Can you entirely re-write this script so that it works as efficiently as possible to…
- User
Can you entirely re-write this script so that it works as efficiently as possible to ensure the most packets per second possible is achieved?
package main import ( "fmt" "log" "net" "os/exec" "sync" "time" "github.com/google/gopacket" "github.com/google/gopacket/layers" "github.com/google/gopacket/pcap" ) const ( packetThreshold = 50 synThreshold = 10 rstThreshold = 10 ackThreshold = 10 timeWindow = 5 * time.Second ipsetMaxElem = 1000000 ipsetResetThreshold = ipsetMaxElem - 1000 ) var ( whitelist = map[string]struct{}{ "144.178.119.44": {}, "141.98.157.11": {}, } packetCounts sync.Map blockedIPs sync.Map resetCountsChan = make(chan struct{}) ) func isWhitelisted(ip net.IP) bool { _, ok := whitelist[ip.String()] return ok } func createMatchSet() { cmd := exec.Command("ipset", "create", "blocked_ips", "hash:ip", "maxelem", fmt.Sprintf("%d", ipsetMaxElem), "-exist") output, err := cmd.CombinedOutput() if err != nil { log.Println("Error creating ipset:", err) log.Println(string(output)) } } func flushMatchSet() { cmd := exec.Command("ipset", "flush", "blocked_ips") output, err := cmd.CombinedOutput() if err != nil { log.Println("Error flushing ipset:", err) log.Println(string(output)) } else { fmt.Println("Flushed ipset 'blocked_ips'") } blockedIPs = sync.Map{} } func addIPToMatchSet(ip string) { if _, loaded := blockedIPs.LoadOrStore(ip, struct{}{}); loaded { return } count, err := getIPSetCount("blocked_ips") if err != nil { log.Println("Error getting ipset count:", err) } else if count >= ipsetResetThreshold { flushMatchSet() } cmd := exec.Command("ipset", "add", "blocked_ips", ip, "-exist") output, err := cmd.CombinedOutput() if err != nil { if string(output) == "Type of set blocked_ips is hash:ip\n" { log.Println("Ipset is full, flushing and recreating the set.") flushMatchSet() cmd = exec.Command("ipset", "add", "blocked_ips", ip, "-exist") output, err = cmd.CombinedOutput() if err != nil { log.Println("Error adding IP to ipset after flush:", err) log.Println(string(output)) return } } else { log.Println("Error adding IP to ipset:", err) log.Println(string(output)) return } } fmt.Printf("Blocked IP address: %s\n", ip) } func blockMatchSet() { cmd := exec.Command("iptables", "-C", "INPUT", "-m", "set", "--match-set", "blocked_ips", "src", "-j", "DROP") err := cmd.Run() if err != nil { cmd = exec.Command("iptables", "-I", "INPUT", "-m", "set", "--match-set", "blocked_ips", "src", "-j", "DROP") output, err := cmd.CombinedOutput() if err != nil { log.Println("Error updating iptables:", err) log.Println(string(output)) } } } func resetPacketCounts() { ticker := time.NewTicker(timeWindow) defer ticker.Stop() for { select { case <-ticker.C: packetCounts = sync.Map{} case <-resetCountsChan: return } } } func main() { handle, err := pcap.OpenLive("ens3", 1600, true, pcap.BlockForever) if err != nil { log.Fatal("Error opening device: ", err) } defer handle.Close() if err := handle.SetBPFFilter("tcp"); err != nil { log.Fatal("Error setting BPF filter: ", err) } createMatchSet() blockMatchSet() go resetPacketCounts() packetSource := gopacket.NewPacketSource(handle, handle.LinkType()) packetChan := make(chan gopacket.Packet, 1000) var wg sync.WaitGroup numWorkers := 4 for i := 0; i < numWorkers; i++ { wg.Add(1) go packetWorker(packetChan, &wg) } for packet := range packetSource.Packets() { packetChan <- packet } close(packetChan) wg.Wait() close(resetCountsChan) } func packetWorker(packetChan <-chan gopacket.Packet, wg *sync.WaitGroup) { defer wg.Done() for packet := range packetChan { processPacket(packet) } } func processPacket(packet gopacket.Packet) { ipLayer := packet.Layer(layers.LayerTypeIPv4) if ipLayer == nil { return } ipAddr := ipLayer.(*layers.IPv4).SrcIP if isWhitelisted(ipAddr) { return } updateCount(ipAddr.String(), "", packetThreshold) tcpLayer := packet.Layer(layers.LayerTypeTCP) if tcpLayer != nil { tcpPacket := tcpLayer.(*layers.TCP) if tcpPacket.SYN { updateCount(ipAddr.String(), "-SYN", synThreshold) } if tcpPacket.RST { updateCount(ipAddr.String(), "-RST", rstThreshold) } if tcpPacket.ACK { updateCount(ipAddr.String(), "-ACK", ackThreshold) } } } func updateCount(ip, suffix string, threshold int) { key := ip + suffix var newCount int = 1 actual, loaded := packetCounts.LoadOrStore(key, &newCount) if loaded { countPtr := actual.(*int) *countPtr++ if *countPtr > threshold { addIPToMatchSet(ip) packetCounts.Delete(key) } } else { if newCount > threshold { addIPToMatchSet(ip) packetCounts.Delete(key) } } } func getIPSetCount(setName string) (int, error) { cmd := exec.Command("ipset", "list", setName) output, err := cmd.Output() if err != nil { return 0, err } var count int fmt.Sscanf(string(output), "Name: %s\nType: hash:ip\nRevision: 4\nHeader: family inet hashsize 1024 maxelem %d\nSize in memory: 88\nReferences: 0\nMembers:", setName, &count) return count, nil } - Assistant