Troubleshooting NFTables Table Creation with Go

77 views Asked by At

I've been working on a Go script that interacts with NFTables to create and manage firewall rules. However, I'm facing a persistent issue when attempting to create a new table. Despite trying various approaches and checking for common pitfalls (like table name conflicts and ensuring proper privileges), the script consistently fails to create a new table.

Here's the core part of my script:

package main

import (
    "fmt"
    "log"
    "os"

    "github.com/google/nftables"
)

func main() {
    conn, err := nftables.New()
    if err != nil {
        log.Fatalf("Error creating NFTables connection: %v", err)
    }

    // Attempting to create a new table with a unique name
    tableName := "test_nft_table"

    // Check if the table already exists
    tables, err := conn.ListTables()
    if err != nil {
        log.Fatalf("Error listing tables: %v", err)
    }
    exists := false
    for _, t := range tables {
        if t.Name == tableName {
            exists = true
            break
        }
    }

    if exists {
        fmt.Printf("Table '%s' already exists.\n", tableName)
    } else {
        // Create the table
        table := &nftables.Table{
            Family: nftables.TableFamilyIPv4,
            Name:   tableName,
        }
        if err := conn.AddTable(table); err != nil {
            log.Fatalf("Error adding table '%s': %v", tableName, err)
        }
        fmt.Printf("Table '%s' created successfully.\n", tableName)
    }

    if err := conn.Flush(); err != nil {
        log.Fatalf("Error applying changes: %v", err)
    }
}

The error message I receive is: Error adding table 'test_nft_table': &{test_nft_table 0 0 2}. This message is quite generic and doesn't provide much insight into what might be going wrong.

I've tried the following to diagnose and resolve the issue:

  • Checked for any table name conflicts.
  • Ensured that the script is run with superuser privileges.
  • Tested with different table families (IPv4 and INet).
  • Simplified the script to its most basic form to isolate the problem.
  • I'm currently running this on (inserir detalhes do seu ambiente, como a versão do sistema operacional, versão do kernel Linux, e versão do NFTables).

I would greatly appreciate any insights or suggestions you might have on what could be causing this issue or any additional diagnostic steps I could take.

Thank you in advance for your time and help!

1

There are 1 answers

0
yi yang On

conclusion: the successful return value of conn.AddTable() is not nil but instance of type *table.

replace

    if err := conn.AddTable(table); err != nil {

        log.Fatalf("Error adding table '%s': %v", tableName, err)

    }

with

conn.AddTable(table)

the table will be added successfully.


debug with dlv: enter image description here