Closed greenpau closed 4 years ago
Relevant issue: https://github.com/sbezverk/nftableslib/issues/56
Here is how to add he above rule in Go:
// Add rule for inbound traffic
// nft add rule oifname "dummy0" ip daddr 192.168.100.100 ct state established,related counter packets 0 bytes 0 accept
inboundInterfaceRule := &nftables.Rule{
Table: addr.table,
Chain: chain,
Exprs: []expr.Any{},
}
// meta load oifname => reg 1
// cmp eq reg 1 0x6d6d7564 0x00003079 0x00000000 0x00000000
inboundInterfaceRule.Exprs = append(inboundInterfaceRule.Exprs, &expr.Meta{
Key: expr.MetaKeyOIFNAME,
Register: 1,
})
inboundInterfaceRule.Exprs = append(inboundInterfaceRule.Exprs, &expr.Cmp{
Op: expr.CmpOpEq,
Register: 1,
Data: getNftInterfaceName(intfName),
})
if addr.conf.Version == "6" {
inboundInterfaceRule.Exprs = append(inboundInterfaceRule.Exprs, &expr.Payload{
DestRegister: 1,
Base: expr.PayloadBaseNetworkHeader,
Offset: 64,
Len: 16,
})
inboundInterfaceRule.Exprs = append(inboundInterfaceRule.Exprs, &expr.Cmp{
Op: expr.CmpOpEq,
Register: 1,
Data: addr.conf.Address.IP.To16(),
})
} else {
// payload load 4b @ network header + 16 => reg 1
// cmp eq reg 1 0x6464a8c0 ]
inboundInterfaceRule.Exprs = append(inboundInterfaceRule.Exprs, &expr.Payload{
DestRegister: 1,
Base: expr.PayloadBaseNetworkHeader,
Offset: 16,
Len: 4,
})
inboundInterfaceRule.Exprs = append(inboundInterfaceRule.Exprs, &expr.Cmp{
Op: expr.CmpOpEq,
Register: 1,
Data: addr.conf.Address.IP.To4(),
})
}
// ct load state => reg 1 ]
// bitwise reg 1 = (reg=1 & 0x00000006 ) ^ 0x00000000
// cmp neq reg 1 0x00000000
inboundInterfaceRule.Exprs = append(inboundInterfaceRule.Exprs, &expr.Ct{
Register: 1,
Key: expr.CtKeySTATE,
})
inboundInterfaceRule.Exprs = append(inboundInterfaceRule.Exprs, &expr.Bitwise{
SourceRegister: 1,
DestRegister: 1,
Xor: []byte{0x0, 0x0, 0x0, 0x0},
Mask: []byte("\x06\x00\x00\x00"),
Len: 4,
})
inboundInterfaceRule.Exprs = append(inboundInterfaceRule.Exprs, &expr.Cmp{
Op: expr.CmpOpNeq,
Register: 1,
Data: []byte{0x0, 0x0, 0x0, 0x0},
})
// counter pkts 0 bytes 0
inboundInterfaceRule.Exprs = append(inboundInterfaceRule.Exprs, &expr.Counter{})
// immediate reg 0 accept
inboundInterfaceRule.Exprs = append(inboundInterfaceRule.Exprs, &expr.Verdict{
Kind: expr.VerdictAccept,
})
nb.conn.AddRule(inboundInterfaceRule)
if err := nb.conn.Flush(); err != nil {
return fmt.Errorf(
"failed adding outbound traffic rule in table %s chain %s for address %v of interface %s",
addr.table.Name, chainName, addr.conf, intfName,
)
}
All, and @rwhelan , @sbezverk,
In a nutshell, I want to validate the existence of the following
nftables
rule:The
Rule
object looks like this:Is there a way to convert
Rule
struct to text representation (i.e. the output ofnft list chain ip filter FORWARD -a
? I did not find an existing method to do so for theRule
.