Browse Source

forward pkt from ext clients

Abhishek Kondur 2 years ago
parent
commit
30d4a30ce4
4 changed files with 57 additions and 10 deletions
  1. 2 0
      nm-proxy/common/common.go
  2. 8 4
      nm-proxy/manager/manager.go
  3. 40 5
      nm-proxy/packet/packet.go
  4. 7 1
      nm-proxy/peer/peer.go

+ 2 - 0
nm-proxy/common/common.go

@@ -80,6 +80,8 @@ var RelayPeerMap = make(map[string]map[string]RemotePeer)
 
 
 var ExtClientsWaitTh = make(map[string][]context.CancelFunc)
 var ExtClientsWaitTh = make(map[string][]context.CancelFunc)
 
 
+var PeerAddrMap = make(map[string]map[string]*Conn)
+
 // RunCmd - runs a local command
 // RunCmd - runs a local command
 func RunCmd(command string, printerr bool) (string, error) {
 func RunCmd(command string, printerr bool) (string, error) {
 	args := strings.Fields(command)
 	args := strings.Fields(command)

+ 8 - 4
nm-proxy/manager/manager.go

@@ -191,6 +191,7 @@ func cleanUp(iface string) {
 		}
 		}
 	}
 	}
 	delete(common.WgIFaceMap, iface)
 	delete(common.WgIFaceMap, iface)
+	delete(common.PeerAddrMap, iface)
 	if waitThs, ok := common.ExtClientsWaitTh[iface]; ok {
 	if waitThs, ok := common.ExtClientsWaitTh[iface]; ok {
 		for _, cancelF := range waitThs {
 		for _, cancelF := range waitThs {
 			cancelF()
 			cancelF()
@@ -257,7 +258,9 @@ func (m *ManagerAction) AddInterfaceToProxy() error {
 			shouldProceed = true
 			shouldProceed = true
 		}
 		}
 		if peerConf.IsExtClient && peerConf.IsAttachedExtClient && shouldProceed {
 		if peerConf.IsExtClient && peerConf.IsAttachedExtClient && shouldProceed {
-			go packet.StartSniffer(wgInterface.Name, peerConf.Address)
+			ctx, cancel := context.WithCancel(context.Background())
+			common.ExtClientsWaitTh[wgInterface.Name] = append(common.ExtClientsWaitTh[wgInterface.Name], cancel)
+			go packet.StartSniffer(ctx, wgInterface.Name, peerConf.Address, wgInterface.Port)
 		}
 		}
 
 
 		if peerConf.IsExtClient && !peerConf.IsAttachedExtClient {
 		if peerConf.IsExtClient && !peerConf.IsAttachedExtClient {
@@ -294,7 +297,7 @@ func (m *ManagerAction) AddInterfaceToProxy() error {
 				defer func() {
 				defer func() {
 					if addExtClient {
 					if addExtClient {
 						log.Println("GOT ENDPOINT for Extclient adding peer...")
 						log.Println("GOT ENDPOINT for Extclient adding peer...")
-						go packet.StartSniffer(wgInterface.Name, peerConf.Address)
+						go packet.StartSniffer(ctx, wgInterface.Name, peerConf.Address, wgInterface.Port)
 						common.PeerKeyHashMap[fmt.Sprintf("%x", md5.Sum([]byte(peer.PublicKey.String())))] = common.RemotePeer{
 						common.PeerKeyHashMap[fmt.Sprintf("%x", md5.Sum([]byte(peer.PublicKey.String())))] = common.RemotePeer{
 							Interface:           wgInterface.Name,
 							Interface:           wgInterface.Name,
 							PeerKey:             peer.PublicKey.String(),
 							PeerKey:             peer.PublicKey.String(),
@@ -302,7 +305,8 @@ func (m *ManagerAction) AddInterfaceToProxy() error {
 							IsAttachedExtClient: peerConf.IsAttachedExtClient,
 							IsAttachedExtClient: peerConf.IsAttachedExtClient,
 							Endpoint:            peer.Endpoint,
 							Endpoint:            peer.Endpoint,
 						}
 						}
-						peerpkg.AddNewPeer(wgInterface, peer, isRelayed,
+
+						peerpkg.AddNewPeer(wgInterface, peer, peerConf.Address, isRelayed,
 							peerConf.IsExtClient, peerConf.IsAttachedExtClient, relayedTo)
 							peerConf.IsExtClient, peerConf.IsAttachedExtClient, relayedTo)
 					}
 					}
 				}()
 				}()
@@ -333,7 +337,7 @@ func (m *ManagerAction) AddInterfaceToProxy() error {
 			continue
 			continue
 		}
 		}
 
 
-		peerpkg.AddNewPeer(wgInterface, &peerI, isRelayed,
+		peerpkg.AddNewPeer(wgInterface, &peerI, peerConf.Address, isRelayed,
 			peerConf.IsExtClient, peerConf.IsAttachedExtClient, relayedTo)
 			peerConf.IsExtClient, peerConf.IsAttachedExtClient, relayedTo)
 	}
 	}
 	log.Printf("------> PEERHASHMAP: %+v\n", common.PeerKeyHashMap)
 	log.Printf("------> PEERHASHMAP: %+v\n", common.PeerKeyHashMap)

+ 40 - 5
nm-proxy/packet/packet.go

@@ -1,6 +1,7 @@
 package packet
 package packet
 
 
 import (
 import (
+	"context"
 	"crypto/md5"
 	"crypto/md5"
 	"fmt"
 	"fmt"
 	"log"
 	"log"
@@ -9,6 +10,7 @@ import (
 	"github.com/google/gopacket"
 	"github.com/google/gopacket"
 	"github.com/google/gopacket/layers"
 	"github.com/google/gopacket/layers"
 	"github.com/google/gopacket/pcap"
 	"github.com/google/gopacket/pcap"
+	"github.com/gravitl/netmaker/nm-proxy/common"
 )
 )
 
 
 var udpHeaderLen = 8
 var udpHeaderLen = 8
@@ -41,7 +43,7 @@ func ExtractInfo(buffer []byte, n int) (int, string, string) {
 	return n, fmt.Sprintf("%x", srcKeyHash), fmt.Sprintf("%x", dstKeyHash)
 	return n, fmt.Sprintf("%x", srcKeyHash), fmt.Sprintf("%x", dstKeyHash)
 }
 }
 
 
-func StartSniffer(ifaceName string, extClient string) {
+func StartSniffer(ctx context.Context, ifaceName, extClientAddr string, port int) {
 	log.Println("Starting Packet Sniffer for iface: ", ifaceName)
 	log.Println("Starting Packet Sniffer for iface: ", ifaceName)
 	var (
 	var (
 		snapshotLen int32 = 1024
 		snapshotLen int32 = 1024
@@ -56,6 +58,10 @@ func StartSniffer(ifaceName string, extClient string) {
 		log.Println("failed to start sniffer for iface: ", ifaceName, err)
 		log.Println("failed to start sniffer for iface: ", ifaceName, err)
 		return
 		return
 	}
 	}
+	if err := handle.SetBPFFilter(fmt.Sprintf("src %s and port %d", extClientAddr, port)); err != nil {
+		log.Println("failed to set bpf filter: ", err)
+		return
+	}
 	defer handle.Close()
 	defer handle.Close()
 
 
 	// var tcp layers.TCP
 	// var tcp layers.TCP
@@ -65,15 +71,43 @@ func StartSniffer(ifaceName string, extClient string) {
 
 
 	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
 	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
 	for {
 	for {
-		packet, err := packetSource.NextPacket()
-		if err == nil {
-			printPacketInfo(packet)
+		select {
+		case <-ctx.Done():
+			log.Println("Stopping packet sniffer for iface: ", ifaceName, " port: ", port)
+			return
+		default:
+			packet, err := packetSource.NextPacket()
+			if err == nil {
+				//processPkt(ifaceName, packet)
+				ipLayer := packet.Layer(layers.LayerTypeIPv4)
+				if ipLayer != nil {
+					fmt.Println("IPv4 layer detected.")
+					ip, _ := ipLayer.(*layers.IPv4)
+
+					// IP layer variables:
+					// Version (Either 4 or 6)
+					// IHL (IP Header Length in 32-bit words)
+					// TOS, Length, Id, Flags, FragOffset, TTL, Protocol (TCP?),
+					// Checksum, SrcIP, DstIP
+					fmt.Println("#########################")
+					fmt.Printf("From %s to %s\n", ip.SrcIP, ip.DstIP)
+					fmt.Println("Protocol: ", ip.Protocol)
+
+					if ifacePeers, ok := common.PeerAddrMap[ifaceName]; ok {
+						if peerConf, ok := ifacePeers[ip.DstIP.String()]; ok {
+							log.Println("-----> Fowarding PKT From ExtClient: ", extClientAddr, " to: ", peerConf.Config.RemoteProxyIP)
+						}
+
+					}
+					fmt.Println("#########################")
+				}
+			}
 		}
 		}
 
 
 	}
 	}
 }
 }
 
 
-func printPacketInfo(packet gopacket.Packet) {
+func processPkt(iface string, packet gopacket.Packet) {
 	// Let's see if the packet is an ethernet packet
 	// Let's see if the packet is an ethernet packet
 	// ethernetLayer := packet.Layer(layers.LayerTypeEthernet)
 	// ethernetLayer := packet.Layer(layers.LayerTypeEthernet)
 	// if ethernetLayer != nil {
 	// if ethernetLayer != nil {
@@ -100,6 +134,7 @@ func printPacketInfo(packet gopacket.Packet) {
 		fmt.Printf("From %s to %s\n", ip.SrcIP, ip.DstIP)
 		fmt.Printf("From %s to %s\n", ip.SrcIP, ip.DstIP)
 		fmt.Println("Protocol: ", ip.Protocol)
 		fmt.Println("Protocol: ", ip.Protocol)
 		fmt.Println()
 		fmt.Println()
+
 	}
 	}
 
 
 	// udpLayer := packet.Layer(layers.LayerTypeUDP)
 	// udpLayer := packet.Layer(layers.LayerTypeUDP)

+ 7 - 1
nm-proxy/peer/peer.go

@@ -33,7 +33,7 @@ type ConnConfig struct {
 	RemoteProxyPort int
 	RemoteProxyPort int
 }
 }
 
 
-func AddNewPeer(wgInterface *wg.WGIface, peer *wgtypes.PeerConfig,
+func AddNewPeer(wgInterface *wg.WGIface, peer *wgtypes.PeerConfig, peerAddr string,
 	isRelayed, isExtClient, isAttachedExtClient bool, relayTo *net.UDPAddr) error {
 	isRelayed, isExtClient, isAttachedExtClient bool, relayTo *net.UDPAddr) error {
 
 
 	c := proxy.Config{
 	c := proxy.Config{
@@ -104,6 +104,12 @@ func AddNewPeer(wgInterface *wg.WGIface, peer *wgtypes.PeerConfig,
 		common.WgIFaceMap[wgInterface.Name] = make(map[string]*common.Conn)
 		common.WgIFaceMap[wgInterface.Name] = make(map[string]*common.Conn)
 		common.WgIFaceMap[wgInterface.Name][peer.PublicKey.String()] = &peerConn
 		common.WgIFaceMap[wgInterface.Name][peer.PublicKey.String()] = &peerConn
 	}
 	}
+	if _, ok := common.PeerAddrMap[wgInterface.Name]; ok {
+		common.PeerAddrMap[wgInterface.Name][peerAddr] = &peerConn
+	} else {
+		common.PeerAddrMap[wgInterface.Name] = make(map[string]*common.Conn)
+		common.PeerAddrMap[wgInterface.Name][peerAddr] = &peerConn
+	}
 
 
 	return nil
 	return nil
 }
 }