Browse Source

use additional port for ext client

Abhishek Kondur 2 years ago
parent
commit
ddabbcd8ea
5 changed files with 158 additions and 155 deletions
  1. 2 3
      nm-proxy/manager/manager.go
  2. 0 135
      nm-proxy/packet/packet.go
  3. 10 4
      nm-proxy/peer/peer.go
  4. 133 0
      nm-proxy/proxy/proxy.go
  5. 13 13
      nm-proxy/server/server.go

+ 2 - 3
nm-proxy/manager/manager.go

@@ -11,7 +11,6 @@ import (
 	"time"
 	"time"
 
 
 	"github.com/gravitl/netmaker/nm-proxy/common"
 	"github.com/gravitl/netmaker/nm-proxy/common"
-	"github.com/gravitl/netmaker/nm-proxy/packet"
 	peerpkg "github.com/gravitl/netmaker/nm-proxy/peer"
 	peerpkg "github.com/gravitl/netmaker/nm-proxy/peer"
 	"github.com/gravitl/netmaker/nm-proxy/proxy"
 	"github.com/gravitl/netmaker/nm-proxy/proxy"
 	"github.com/gravitl/netmaker/nm-proxy/wg"
 	"github.com/gravitl/netmaker/nm-proxy/wg"
@@ -260,7 +259,7 @@ func (m *ManagerAction) AddInterfaceToProxy() error {
 		if peerConf.IsExtClient && peerConf.IsAttachedExtClient && shouldProceed {
 		if peerConf.IsExtClient && peerConf.IsAttachedExtClient && shouldProceed {
 			ctx, cancel := context.WithCancel(context.Background())
 			ctx, cancel := context.WithCancel(context.Background())
 			common.ExtClientsWaitTh[wgInterface.Name] = append(common.ExtClientsWaitTh[wgInterface.Name], cancel)
 			common.ExtClientsWaitTh[wgInterface.Name] = append(common.ExtClientsWaitTh[wgInterface.Name], cancel)
-			go packet.StartSniffer(ctx, wgInterface.Name, peerConf.Address, wgInterface.Port)
+			go proxy.StartSniffer(ctx, wgInterface.Name, peerConf.Address, wgInterface.Port)
 		}
 		}
 
 
 		if peerConf.IsExtClient && !peerConf.IsAttachedExtClient {
 		if peerConf.IsExtClient && !peerConf.IsAttachedExtClient {
@@ -297,7 +296,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(ctx, wgInterface.Name, peerConf.Address, wgInterface.Port)
+						go proxy.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(),

+ 0 - 135
nm-proxy/packet/packet.go

@@ -1,16 +1,8 @@
 package packet
 package packet
 
 
 import (
 import (
-	"context"
 	"crypto/md5"
 	"crypto/md5"
 	"fmt"
 	"fmt"
-	"log"
-	"time"
-
-	"github.com/google/gopacket"
-	"github.com/google/gopacket/layers"
-	"github.com/google/gopacket/pcap"
-	"github.com/gravitl/netmaker/nm-proxy/common"
 )
 )
 
 
 var udpHeaderLen = 8
 var udpHeaderLen = 8
@@ -42,130 +34,3 @@ func ExtractInfo(buffer []byte, n int) (int, string, string) {
 	n -= 32
 	n -= 32
 	return n, fmt.Sprintf("%x", srcKeyHash), fmt.Sprintf("%x", dstKeyHash)
 	return n, fmt.Sprintf("%x", srcKeyHash), fmt.Sprintf("%x", dstKeyHash)
 }
 }
-
-func StartSniffer(ctx context.Context, ifaceName, extClientAddr string, port int) {
-	log.Println("Starting Packet Sniffer for iface: ", ifaceName)
-	var (
-		snapshotLen int32 = 1024
-		promiscuous bool  = false
-		err         error
-		timeout     time.Duration = 1 * time.Microsecond
-		handle      *pcap.Handle
-	)
-	// Open device
-	handle, err = pcap.OpenLive(ifaceName, snapshotLen, promiscuous, timeout)
-	if err != nil {
-		log.Println("failed to start sniffer for iface: ", ifaceName, err)
-		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()
-
-	// var tcp layers.TCP
-	// var icmp layers.ICMPv4
-	// var udp layers.UDP
-	// parser := gopacket.NewDecodingLayerParser(layers.LayerTypeIPv4, &udp, &tcp, &icmp)
-
-	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
-	for {
-		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 processPkt(iface string, packet gopacket.Packet) {
-	// Let's see if the packet is an ethernet packet
-	// ethernetLayer := packet.Layer(layers.LayerTypeEthernet)
-	// if ethernetLayer != nil {
-	// 	fmt.Println("Ethernet layer detected.")
-	// 	ethernetPacket, _ := ethernetLayer.(*layers.Ethernet)
-	// 	fmt.Println("Source MAC: ", ethernetPacket.SrcMAC)
-	// 	fmt.Println("Destination MAC: ", ethernetPacket.DstMAC)
-	// 	// Ethernet type is typically IPv4 but could be ARP or other
-	// 	fmt.Println("Ethernet type: ", ethernetPacket.EthernetType)
-	// 	fmt.Println()
-	// }
-
-	// Let's see if the packet is IP (even though the ether type told us)
-	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.Printf("From %s to %s\n", ip.SrcIP, ip.DstIP)
-		fmt.Println("Protocol: ", ip.Protocol)
-		fmt.Println()
-
-	}
-
-	// udpLayer := packet.Layer(layers.LayerTypeUDP)
-	// if udpLayer != nil {
-	// 	udp, _ := udpLayer.(*layers.UDP)
-	// 	fmt.Printf("UDP: From port %d to %d\n", udp.SrcPort, udp.DstPort)
-	// 	fmt.Println()
-	// }
-
-	// // Iterate over all layers, printing out each layer type
-	// fmt.Println("All packet layers:")
-	// for _, layer := range packet.Layers() {
-	// 	fmt.Println("- ", layer.LayerType())
-	// }
-
-	// When iterating through packet.Layers() above,
-	// if it lists Payload layer then that is the same as
-	// this applicationLayer. applicationLayer contains the payload
-	// applicationLayer := packet.ApplicationLayer()
-	// if applicationLayer != nil {
-	// 	fmt.Println("Application layer/Payload found.")
-	// 	fmt.Printf("%s\n", applicationLayer.Payload())
-
-	// 	// Search for a string inside the payload
-	// 	if strings.Contains(string(applicationLayer.Payload()), "HTTP") {
-	// 		fmt.Println("HTTP found!")
-	// 	}
-	// }
-
-	// Check for errors
-	if err := packet.ErrorLayer(); err != nil {
-		fmt.Println("Error decoding some part of the packet:", err)
-	}
-}

+ 10 - 4
nm-proxy/peer/peer.go

@@ -63,11 +63,17 @@ func AddNewPeer(wgInterface *wg.WGIface, peer *wgtypes.PeerConfig, peerAddr stri
 		return err
 		return err
 	}
 	}
 	log.Printf("----> Established Remote Conn with RPeer: %s, ----> RAddr: %s", peer.PublicKey, remoteConn.String())
 	log.Printf("----> Established Remote Conn with RPeer: %s, ----> RAddr: %s", peer.PublicKey, remoteConn.String())
-	log.Printf("Starting proxy for Peer: %s\n", peer.PublicKey.String())
-	err = p.Start(remoteConn)
-	if err != nil {
-		return err
+
+	if !(isExtClient && isAttachedExtClient) {
+		log.Printf("Starting proxy for Peer: %s\n", peer.PublicKey.String())
+		err = p.Start(remoteConn)
+		if err != nil {
+			return err
+		}
+	} else {
+		log.Println("Not Starting Proxy for Attached ExtClient...")
 	}
 	}
+
 	connConf := common.ConnConfig{
 	connConf := common.ConnConfig{
 		Key:             peer.PublicKey.String(),
 		Key:             peer.PublicKey.String(),
 		LocalKey:        wgInterface.Device.PublicKey.String(),
 		LocalKey:        wgInterface.Device.PublicKey.String(),

+ 133 - 0
nm-proxy/proxy/proxy.go

@@ -4,8 +4,13 @@ import (
 	"context"
 	"context"
 	"errors"
 	"errors"
 	"fmt"
 	"fmt"
+	"log"
 	"net"
 	"net"
+	"time"
 
 
+	"github.com/google/gopacket"
+	"github.com/google/gopacket/layers"
+	"github.com/google/gopacket/pcap"
 	"github.com/gravitl/netmaker/nm-proxy/common"
 	"github.com/gravitl/netmaker/nm-proxy/common"
 	"github.com/gravitl/netmaker/nm-proxy/wg"
 	"github.com/gravitl/netmaker/nm-proxy/wg"
 	"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
 	"golang.zx2c4.com/wireguard/wgctrl/wgtypes"
@@ -102,3 +107,131 @@ func getBoardCastAddress() ([]net.Addr, error) {
 	}
 	}
 	return nil, errors.New("couldn't obtain the broadcast addr")
 	return nil, errors.New("couldn't obtain the broadcast addr")
 }
 }
+
+func StartSniffer(ctx context.Context, ifaceName, extClientAddr string, port int) {
+	log.Println("Starting Packet Sniffer for iface: ", ifaceName)
+	var (
+		snapshotLen int32 = 1024
+		promiscuous bool  = false
+		err         error
+		timeout     time.Duration = 1 * time.Microsecond
+		handle      *pcap.Handle
+	)
+	// Open device
+	handle, err = pcap.OpenLive(ifaceName, snapshotLen, promiscuous, timeout)
+	if err != nil {
+		log.Println("failed to start sniffer for iface: ", ifaceName, err)
+		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()
+
+	// var tcp layers.TCP
+	// var icmp layers.ICMPv4
+	// var udp layers.UDP
+	// parser := gopacket.NewDecodingLayerParser(layers.LayerTypeIPv4, &udp, &tcp, &icmp)
+
+	packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
+	for {
+		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)
+							//server.NmProxyServer.Server.WriteTo(packet.Data(),  )
+						}
+
+					}
+					fmt.Println("#########################")
+				}
+			}
+		}
+
+	}
+}
+
+func processPkt(iface string, packet gopacket.Packet) {
+	// Let's see if the packet is an ethernet packet
+	// ethernetLayer := packet.Layer(layers.LayerTypeEthernet)
+	// if ethernetLayer != nil {
+	// 	fmt.Println("Ethernet layer detected.")
+	// 	ethernetPacket, _ := ethernetLayer.(*layers.Ethernet)
+	// 	fmt.Println("Source MAC: ", ethernetPacket.SrcMAC)
+	// 	fmt.Println("Destination MAC: ", ethernetPacket.DstMAC)
+	// 	// Ethernet type is typically IPv4 but could be ARP or other
+	// 	fmt.Println("Ethernet type: ", ethernetPacket.EthernetType)
+	// 	fmt.Println()
+	// }
+
+	// Let's see if the packet is IP (even though the ether type told us)
+	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.Printf("From %s to %s\n", ip.SrcIP, ip.DstIP)
+		fmt.Println("Protocol: ", ip.Protocol)
+		fmt.Println()
+
+	}
+
+	// udpLayer := packet.Layer(layers.LayerTypeUDP)
+	// if udpLayer != nil {
+	// 	udp, _ := udpLayer.(*layers.UDP)
+	// 	fmt.Printf("UDP: From port %d to %d\n", udp.SrcPort, udp.DstPort)
+	// 	fmt.Println()
+	// }
+
+	// // Iterate over all layers, printing out each layer type
+	// fmt.Println("All packet layers:")
+	// for _, layer := range packet.Layers() {
+	// 	fmt.Println("- ", layer.LayerType())
+	// }
+
+	// When iterating through packet.Layers() above,
+	// if it lists Payload layer then that is the same as
+	// this applicationLayer. applicationLayer contains the payload
+	// applicationLayer := packet.ApplicationLayer()
+	// if applicationLayer != nil {
+	// 	fmt.Println("Application layer/Payload found.")
+	// 	fmt.Printf("%s\n", applicationLayer.Payload())
+
+	// 	// Search for a string inside the payload
+	// 	if strings.Contains(string(applicationLayer.Payload()), "HTTP") {
+	// 		fmt.Println("HTTP found!")
+	// 	}
+	// }
+
+	// Check for errors
+	if err := packet.ErrorLayer(); err != nil {
+		fmt.Println("Error decoding some part of the packet:", err)
+	}
+}

+ 13 - 13
nm-proxy/server/server.go

@@ -128,19 +128,19 @@ func (p *ProxyServer) Listen(ctx context.Context) {
 				continue
 				continue
 
 
 			}
 			}
-			// forward to all interfaces
-			for _, ifaceCfg := range common.WgIfaceKeyMap {
-				log.Println("###--------> Forwarding Unknown PKT to ", ifaceCfg.Interface)
-				conn, err := net.DialUDP("udp", source, ifaceCfg.Endpoint)
-				if err == nil {
-					_, err := conn.Write(buffer[:n])
-					if err != nil {
-						log.Println("Failed to forward the unknown pkt to ifcace: ", ifaceCfg.Interface, err)
-					}
-					conn.Close()
-				}
-
-			}
+			// // forward to all interfaces
+			// for _, ifaceCfg := range common.WgIfaceKeyMap {
+			// 	log.Println("###--------> Forwarding Unknown PKT to ", ifaceCfg.Interface)
+			// 	conn, err := net.DialUDP("udp", nil, ifaceCfg.Endpoint)
+			// 	if err == nil {
+			// 		_, err := conn.Write(buffer[:n])
+			// 		if err != nil {
+			// 			log.Println("Failed to forward the unknown pkt to ifcace: ", ifaceCfg.Interface, err)
+			// 		}
+			// 		conn.Close()
+			// 	}
+
+			// }
 		}
 		}
 
 
 	}
 	}