why is there a iptable input drop rule and a ipset in this?
please rewrite i this script so that it does the exact same thing it currently does (but block the IP's with ipset, remove iptables), but way more efficiently.:
code
Assistant
package main
import (
"fmt"
"log"
"os/exec"
"sync"
"time"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/google/gopacket/pcap"
)
const (
PACKET_THRESHOLD = 50
SYN_THRESHOLD = 10
RST_THRESHOLD = 10
ACK_THRESHOLD = 10
TIME_WINDOW = 5 * time.Second
)
var whitelist = map[string]bool{
"IP": true,
"IP": true,
}
var mu sync.Mutex
var packetCounts = make(map[string]int)
var blockedIPs = make(map[string]bool)
func createMatchSet() {
cmd := exec.Command("ipset", "create", "blocked_ips", "hash:ip")
output, err := cmd.CombinedOutput()
if err != nil {
log.Println("Error creating ipset:", err)
log.Println(string(output))
}
}
func addIPToMatchSet(ip string) {
if blockedIPs[ip] {
return
}
cmd := exec.Command("ipset", "add", "blocked_ips", ip, "-exist")
output, err := cmd.CombinedOutput()
if err != nil {
if string(output) != "ipset v7.19: Element cannot be added to the set: it's already added\n" {
log.Println("Error adding IP to match set:", err)
log.Println(string(output))
}
} else {
blockedIPs[ip] = true
fmt.Printf("Blocked IP address: %s\n", ip)
}
}
func blockMatchSet() {
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 blocking match set:", err)
log.Println(string(output))
}
}
func main() {
handle, err := pcap.OpenLive("ens3", 1600, true, pcap.BlockForever)
if err != nil {
log.Fatal(err)
}
defer handle.Close()
createMatchSet()
go func() {
ticker := time.NewTicker(TIME_WINDOW)
defer ticker.Stop()
for range ticker.C {
mu.Lock()
packetCounts = make(map[string]int)
mu.Unlock()
}
}()
packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
for packet := range packetSource.Packets() {
ipLayer := packet.Layer(layers.LayerTypeIPv4)
if ipLayer == nil {
continue
}
ipAddr := ipLayer.(*layers.IPv4).SrcIP
// Skip whitelisted IPs
if whitelist[ipAddr.String()] {
continue
}
mu.Lock()
packetCounts[ipAddr.String()]++
if packetCounts[ipAddr.String()] > PACKET_THRESHOLD {
addIPToMatchSet(ipAddr.String())
}
mu.Unlock()
tcpLayer := packet.Layer(layers.LayerTypeTCP)
if tcpLayer != nil {
tcpPacket := tcpLayer.(*layers.TCP)
if tcpPacket.SYN {
mu.Lock()
packetCounts[ipAddr.String()+"-SYN"]++
if packetCounts[ipAddr.String()+"-SYN"] > SYN_THRESHOLD {
addIPToMatchSet(ipAddr.String())
}
mu.Unlock()
} else if tcpPacket.RST {
mu.Lock()
packetCounts[ipAddr.String()+"-RST"]++
if packetCounts[ipAddr.String()+"-RST"] > RST_THRESHOLD {
addIPToMatchSet(ipAddr.String())
}
mu.Unlock()
} else if tcpPacket.ACK {
mu.Lock()
packetCounts[ipAddr.String()+"-ACK"]++
if packetCounts[ipAddr.String()+"-ACK"] > ACK_THRESHOLD {
addIPToMatchSet(ipAddr.String())
}
mu.Unlock()
}
}
}
}
Sure, I'd be happy to help explain and rewrite your script.
Why is there an iptables input drop rule and an ipset in this script?
In your script, ipset is used to maintain a set of IP addresses that should be blocked. However, ipset itself doesn't enforce any packet filtering or blocking. It simply manages sets of IP addresses efficiently.
To actually drop packets from these IP addresses, you need to use a firewall tool like iptables or nftables to define rules that specify what action to take for packets matching certain criteria. In your script, the iptables rule is used to tell the kernel to drop any incoming packets from IPs that are in the blocked_ips ipset.
So, both ipset and iptables are used together:
ipset: Efficiently manages the set of IP addresses to block.
iptables: Enforces the actual blocking by matching packets against the ipset and dropping them.
Rewriting the script for efficiency and removing iptables:
Since you want to remove iptables and still block IPs using ipset, one efficient way is to use nftables, which is the modern replacement for iptables. nftables integrates sets (like ipset) directly and can be managed via the Netlink interface, allowing for efficient updates without invoking external commands.
Below is the rewritten script that:
Removes external command executions (no exec.Command calls).
Uses the nftables Go library to manage the firewall rules and sets directly via Netlink.
Blocks IPs using a set in nftables without the need for iptables.
go
package main
import (
"log"
"net"
"sync"
"time"
"github.com/google/nftables"
"github.com/google/nftables/expr"
"github.com/google/gopacket"
"github.com/google/gopacket/layers"
"github.com/google/gopacket/pcap"
"golang.org/x/sys/unix"
)
const (
PACKET_THRESHOLD = 50
SYN_THRESHOLD = 10
RST_THRESHOLD = 10
ACK_THRESHOLD = 10
TIME_WINDOW = 5 * time.Second
)
var whitelist = map[string]bool{
"IP1": true,
"IP2": true,
}
var mu sync.Mutex
var packetCounts = make(map[string]int)
var blockedIPs = make(map[string]bool)
var nftConn *nftables.Conn
var blockedSet *nftables.Set
func createNftablesSet() error {
nftConn = &nftables.Conn{}
// Define a new table
table := &nftables.Table{
Family: nftables.TableFamilyIPv4,
Name: "filter",
}
// Add the table
nftConn.AddTable(table)
// Define the set to hold blocked IPs
blockedSet = &nftables.Set{
Table: table,
Name: "blocked_ips",
KeyType: nftables.TypeIPAddr, // For IPv4 addresses
DataType: nftables.TypeNone,
}
// Add the set
nftConn.AddSet(blockedSet, nil)
// Define a chain
chain := &nftables.Chain{
Name: "input_chain",
Table: table,
Type: nftables.ChainTypeFilter,
Hooknum: nftables.ChainHookInput,
Priority: nftables.ChainPriorityFilter,
}
// Add the chain
nftConn.AddChain(chain)
// Create a rule to drop packets from IPs in the set
nftConn.AddRule(&nftables.Rule{
Table: table,
Chain: chain,
Exprs: []expr.Any{
// Payload load (network header)
&expr.Payload{
DestRegister: 1,
Base: expr.PayloadBaseNetworkHeader,
Offset: 12, // Source IP offset in IPv4 header
Len: 4, // IPv4 address length
},
// Lookup in set
&expr.Lookup{
SourceRegister: 1,
SetName: blockedSet.Name,
SetID: blockedSet.ID,
Invert: false,
},
// Immediate verdict (drop)
&expr.Verdict{
Kind: expr.VerdictDrop,
},
},
})
// Flush changes
return nftConn.Flush()
}
func addIPToNftablesSet(ip string) error {
if blockedIPs[ip] {
return nil
}
parsedIP := net.ParseIP(ip).To4()
if parsedIP == nil {
return nil // invalid IP
}
// Add the IP to the set
err := nftConn.SetAddElements(blockedSet, []nftables.SetElement{{Key: parsedIP}})
if err != nil {
return err
}
blockedIPs[ip] = true
log.Printf("Blocked IP address: %s\n", ip)
return nil
}
func main() {
handle, err := pcap.OpenLive("ens3", 1600, true, pcap.BlockForever)
if err != nil {
log.Fatal(err)
}
defer handle.Close()
// Initialize nftables set and rules
if err := createNftablesSet(); err != nil {
log.Fatalf("Failed to set up nftables: %v", err)
}
// Periodically reset packet counts
go func() {
ticker := time.NewTicker(TIME_WINDOW)
defer ticker.Stop()
for range ticker.C {
mu.Lock()
packetCounts = make(map[string]int)
mu.Unlock()
}
}()
packetSource := gopacket.NewPacketSource(handle, handle.LinkType())
for packet := range packetSource.Packets() {
ipLayer := packet.Layer(layers.LayerTypeIPv4)
if ipLayer == nil {
continue
}
ipAddr := ipLayer.(*layers.IPv4).SrcIP
// Skip whitelisted IPs
if whitelist[ipAddr.String()] {
continue
}
mu.Lock()
packetCounts[ipAddr.String()]++
if packetCounts[ipAddr.String()] > PACKET_THRESHOLD {
if err := addIPToNftablesSet(ipAddr.String()); err != nil {
log.Printf("Failed to add IP to nftables set: %v", err)
}
}
mu.Unlock()
tcpLayer := packet.Layer(layers.LayerTypeTCP)
if tcpLayer != nil {
tcpPacket := tcpLayer.(*layers.TCP)
if tcpPacket.SYN {
mu.Lock()
packetCounts[ipAddr.String()+"-SYN"]++
if packetCounts[ipAddr.String()+"-SYN"] > SYN_THRESHOLD {
if err := addIPToNftablesSet(ipAddr.String()); err != nil {
log.Printf("Failed to add IP to nftables set: %v", err)
}
}
mu.Unlock()
} else if tcpPacket.RST {
mu.Lock()
packetCounts[ipAddr.String()+"-RST"]++
if packetCounts[ipAddr.String()+"-RST"] > RST_THRESHOLD {
if err := addIPToNftablesSet(ipAddr.String()); err != nil {
log.Printf("Failed to add IP to nftables set: %v", err)
}
}
mu.Unlock()
} else if tcpPacket.ACK {
mu.Lock()
packetCounts[ipAddr.String()+"-ACK"]++
if packetCounts[ipAddr.String()+"-ACK"] > ACK_THRESHOLD {
if err := addIPToNftablesSet(ipAddr.String()); err != nil {
log.Printf("Failed to add IP to nftables set: %v", err)
}
}
mu.Unlock()
}
}
}
}
Explanation of modifications:
Removed exec.Command Calls: Instead of executing external commands (ipset and iptables), we use the nftables Go library to interact with the firewall directly via Netlink. This reduces overhead and increases efficiency.
Using nftables Library:
Create a Table and Chain: We create a new table (filter) and a chain (input_chain) in nftables.
Define a Set (blocked_ips): We create a set to store the blocked IP addresses.
Add a Rule: We add a rule to the input_chain that drops packets if the source IP is in the blocked_ips set.
Efficient IP Blocking: When an IP exceeds the thresholds, it's added to the blocked_ips set using nftConn.SetAddElements(). The firewall rule automatically starts dropping packets from any IPs in this set without the need for additional rules or commands.
Error Handling: The code checks and logs any errors encountered during firewall setup or when adding IPs to the set.
Note:
Privileges: Modifying firewall rules requires root privileges. Ensure the program is run with sufficient permissions.
Compatibility: The nftables library interacts with the kernel's Netlink interface and requires a Linux kernel that supports nftables (generally kernel 3.13 and newer).
Benefits of this Approach:
Efficiency: Interacting directly with the Netlink interface is more efficient than invoking external commands.
Atomic Updates: Using Netlink allows for atomic updates to firewall rules, reducing the chance of inconsistencies.
Modern Firewalling:nftables is the modern replacement for iptables, offering better performance and flexibility.
This rewritten script should achieve the same functionality but in a more efficient manner, and it doesn't rely on iptables.