Can you completely re-write & re-format this go script so that it is efficient as…
- User
Can you completely re-write & re-format this go script so that it is efficient as possible while doing the same thing? It can be completely different, it just has to do the same exact thing it does now.
package main import ( "bufio" "fmt" "log" "net" "os/exec" "strings" "sync" "sync/atomic" "time" "github.com/google/gopacket" "github.com/google/gopacket/layers" "github.com/google/gopacket/pcap" ) const ( PACKET_THRESHOLD = 50 SYN_THRESHOLD = 10 RST_THRESHOLD = 5 ACK_THRESHOLD = 50 FIN_THRESHOLD = 10 TIME_WINDOW = 5 * time.Second IPSET_MAX_ELEM = 1000000 IPSET_RESET_THRESHOLD = IPSET_MAX_ELEM ) var ( whitelist = map[string]struct{}{ "141.98.157.11": {}, "144.178.119.44": {}, } 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", IPSET_MAX_ELEM), "-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 >= IPSET_RESET_THRESHOLD { flushMatchSet() } cmd := exec.Command("ipset", "add", "blocked_ips", ip, "-exist") output, err := cmd.CombinedOutput() if err != nil { if strings.Contains(string(output), "full") || strings.Contains(string(output), "cannot add to the set") { 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(TIME_WINDOW) 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 // GOOD SERVER = GOOD 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(), "", PACKET_THRESHOLD) tcpLayer := packet.Layer(layers.LayerTypeTCP) if tcpLayer != nil { tcpPacket := tcpLayer.(*layers.TCP) if tcpPacket.SYN { updateCount(ipAddr.String(), "-SYN", SYN_THRESHOLD) } if tcpPacket.RST { updateCount(ipAddr.String(), "-RST", RST_THRESHOLD) } if tcpPacket.ACK { updateCount(ipAddr.String(), "-ACK", ACK_THRESHOLD) } if tcpPacket.FIN { updateCount(ipAddr.String(), "-FIN", FIN_THRESHOLD) } } } func updateCount(ip, suffix string, threshold int32) { key := ip + suffix var newCount int32 = 1 actual, loaded := packetCounts.LoadOrStore(key, &newCount) if loaded { countPtr := actual.(*int32) newVal := atomic.AddInt32(countPtr, 1) if newVal > 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 } scanner := bufio.NewScanner(strings.NewReader(string(output))) for scanner.Scan() { line := scanner.Text() if strings.HasPrefix(line, "Number of entries:") { parts := strings.Fields(line) if len(parts) >= 4 { count := parts[3] var num int fmt.Sscanf(count, "%d", &num) return num, nil } } } if err := scanner.Err(); err != nil { return 0, err } return 0, fmt.Errorf("Could not find ipset count") } - Assistant