Add changesets, bandwidth limits and quotas; generic examples

Changesets, as in Jarl: configuration changes are operations that can be
staged in a changeset, checked as they are added (validation and nft -c),
reviewed with the diff of the ruleset, and applied together as one
history entry, then on probation like any change made over the network.
The web UI collects edits for review by default (pending rows, a bar with
Review and Apply now, a Changes page, a switch for live edits); hc stages
with -C ID or HOUSECARL_CHANGESET (checked like JARL_CHANGESET) and has
hc changeset create/list/show/diff/apply/discard/remove. Undo, import and
takeover refuse a changeset. --dry-run shows the ruleset's diff.

Bandwidth and quotas: rate limits in bytes, per source or destination;
quotas per rule or per address that reset daily, weekly, monthly on a
day, or by hand, with their usage carried across reloads, saved for
reboots, shown by hc quotas and on the rules page, and reset with hc rule
reset-quota. Rules that count traffic are checked before established
connections are accepted (so they see every packet) and can't accept.
Per-address limits group IPv6 by /64 by default (--group-v4/-v6).
Per-source rate meters use update. The importer turns meters, byte rates
and quotas into these fields.

The examples in the web UI, hc's help and the docs use documentation
addresses and generic names instead of the maintainer's network.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
abrown38andClaude Opus 5.5 committed 2026-10-19 11:18:54 +01:00
1 parent ebec2cfcca
commit 2880f7ddc9
63 files changed
+4018 -385

No files matched your search

+131 -18
View File
@@ -12,6 +12,7 @@ package render
import (
"fmt"
"net/netip"
"sort"
"strings"
@@ -33,14 +34,25 @@ type Options struct {
// Elements are dynamic sets' current entries, re-added in the same
// transaction so a reload keeps them: set name → entries.
Elements map[string][]Element
// Quotas are the rules' quotas' used bytes (quota name, quota_r12),
// and QuotaSets the per-address quotas' entries (set name,
// quota_r12_v4), so a reload keeps what was used.
Quotas map[string]int64
QuotaSets map[string][]Element
}
// Element is a dynamic set's entry with its remaining lifetime.
// Element is a dynamic set's entry with its remaining lifetime, or a
// per-address quota's entry with what it used.
type Element struct {
Addr string `json:"address"`
Timeout int `json:"timeout,omitempty"` // seconds left (0: none)
Used int64 `json:"used,omitempty"` // bytes
}
// QuotaName is the name of a rule's quota: the named quota of a total
// quota, and (with _v4, _v6) the sets of a per-address one.
func QuotaName(ruleID int64) string { return fmt.Sprintf("quota_r%d", ruleID) }
// Ruleset is the rendered nftables script.
type Ruleset struct {
Text string
@@ -86,7 +98,8 @@ type renderer struct {
st *model.State
opt Options
w *writer
// meters are the per-source limit and connection sets the rules need.
// meters are the per-address limit, connection and quota sets, and
// the named quotas, the rules need.
meters []string
}
@@ -238,7 +251,8 @@ func (r *renderer) early() {
r.builtin("antispoof6", "iifname %s ip6 saddr { %s } counter drop", ifaces(ext), strings.Join(v6, ", "))
}
}
r.rules(model.ChainEarly)
r.rules(model.ChainEarly, true)
r.rules(model.ChainEarly, false)
r.end()
}
@@ -265,6 +279,9 @@ func (r *renderer) input() {
if b.Loopback {
r.builtin("loopback", "iifname \"lo\" accept")
}
// Rules that count traffic see every packet: before the established
// connections are accepted.
r.rules(model.ChainInput, true)
r.connBuiltins()
ext := st.ExternalInterfaces()
if b.ICMPv6 {
@@ -282,7 +299,7 @@ func (r *renderer) input() {
if b.DHCPv6Client && len(ext) > 0 {
r.builtin("dhcpv6-client", "iifname %s ip6 saddr fe80::/10 udp dport 546 counter accept", ifaces(ext))
}
r.rules(model.ChainInput)
r.rules(model.ChainInput, false)
r.policyTail("input", st.Settings.InputPolicy)
r.end()
}
@@ -295,6 +312,7 @@ func (r *renderer) forward(flowtable bool) {
if b.MSSClamp && len(ext) > 0 {
r.builtin("mss-clamp", "oifname %s tcp flags syn tcp option maxseg size set rt mtu", ifaces(ext))
}
r.rules(model.ChainForward, true)
if flowtable {
r.builtin("flowtable", "meta l4proto { tcp, udp } flow add @ft")
}
@@ -303,7 +321,7 @@ func (r *renderer) forward(flowtable bool) {
r.builtin("icmpv6", "icmpv6 type { %s } counter accept", icmpv6Errors)
}
r.forwardAccepts()
r.rules(model.ChainForward)
r.rules(model.ChainForward, false)
r.policyTail("forward", st.Settings.ForwardPolicy)
r.end()
}
@@ -311,6 +329,7 @@ func (r *renderer) forward(flowtable bool) {
func (r *renderer) output() {
st := r.st
r.chain("output", "output", "filter", st.Settings.OutputPolicy)
r.rules(model.ChainOutput, true)
if st.Settings.OutputPolicy == model.PolicyDrop {
if st.Settings.Builtins.Loopback {
r.builtin("loopback", "oifname \"lo\" accept")
@@ -322,7 +341,7 @@ func (r *renderer) output() {
r.builtin("icmpv6", "icmpv6 type { %s, echo-request, echo-reply, %s, %s } counter accept", icmpv6Errors, icmpv6ND, icmpv6MLD)
}
}
r.rules(model.ChainOutput)
r.rules(model.ChainOutput, false)
r.policyTail("output", st.Settings.OutputPolicy)
r.end()
}
@@ -341,9 +360,11 @@ func (r *renderer) policyTail(chain, policy string) {
// ---- rules
func (r *renderer) rules(chain string) {
// rules writes a chain's rules: those that count traffic (traffic true),
// or the others.
func (r *renderer) rules(chain string, traffic bool) {
for _, rule := range r.st.Rules {
if rule.Chain != chain || rule.Disabled {
if rule.Chain != chain || rule.Disabled || rule.CountsTraffic() != traffic {
continue
}
obj := rule.Label()
@@ -370,8 +391,8 @@ func (r *renderer) rules(chain string) {
tail = append(tail, hours(rule.HourFrom, rule.HourTo))
}
verdict := r.verdict(rule, mark)
perSource := rule.ConnLimit > 0 || rule.Limit != nil && rule.Limit.PerSource
for _, line := range r.expand(rule.Match, perSource) {
perAddress := rule.ConnLimit > 0 || rule.Limit.PerAddress() != "" || rule.Quota.PerAddress() != ""
for _, line := range r.expand(rule.Match, perAddress) {
parts := append([]string{}, line.parts...)
parts = append(parts, tail...)
if l := rule.Limit; l != nil {
@@ -380,6 +401,9 @@ func (r *renderer) rules(chain string) {
if rule.ConnLimit > 0 {
parts = append(parts, r.connLimit(rule, line))
}
if rule.Quota != nil {
parts = append(parts, r.quota(rule, line))
}
parts = append(parts, verdict)
r.w.emit(obj, "\t\t%s", strings.Join(nonEmpty(parts), " "))
}
@@ -410,20 +434,51 @@ func (r *renderer) verdict(rule *model.Rule, mark string) string {
return strings.Join(v, " ")
}
// limit renders a rate limit, per source with a meter set per family.
// limit renders a rate limit: of packets or bytes; per source or
// destination with a meter set per family, whose entries are refreshed
// by each packet (update) and forgotten once a source is quiet.
func (r *renderer) limit(rule *model.Rule, line expanded, l *model.Limit) string {
rate := fmt.Sprintf("limit rate %s%d/%s", map[bool]string{true: "over ", false: ""}[l.Over], l.Rate, l.Per)
if l.Burst > 0 {
rate += fmt.Sprintf(" burst %d packets", l.Burst)
unit := ""
if _, ok := model.ByteUnits[l.Unit]; ok {
unit = " " + l.Unit
}
if !l.PerSource {
rate := fmt.Sprintf("limit rate %s%d%s/%s", map[bool]string{true: "over ", false: ""}[l.Over], l.Rate, unit, l.Per)
if l.Burst > 0 {
burstUnit := " packets"
if unit != "" {
burstUnit = unit
}
rate += fmt.Sprintf(" burst %d%s", l.Burst, burstUnit)
}
addr := l.PerAddress()
if addr == "" {
return rate
}
name := fmt.Sprintf("meter_r%d_%s", rule.ID, line.fam)
if !r.hasMeter(name) {
r.meters = append(r.meters, fmt.Sprintf("\tset %s { type %s; flags dynamic,timeout; timeout 1%s; }", name, addrType(line.fam == "v6"), map[string]string{"second": "m", "minute": "m", "hour": "h", "day": "d"}[l.Per]))
}
return fmt.Sprintf("add @%s { %s saddr %s }", name, ipKeyword(line.fam), rate)
return fmt.Sprintf("update @%s { %s %s }", name, r.addrKey(rule, line.fam, addr), rate)
}
// addrKey is what a per-address meter counts by: "ip saddr", or grouped
// by a prefix, "ip6 saddr and ffff:ffff:ffff:ffff::".
func (r *renderer) addrKey(rule *model.Rule, fam, addr string) string {
v4, v6 := rule.Groups()
bits, size := v4, 32
if fam == "v6" {
bits, size = v6, 128
}
key := ipKeyword(fam) + " " + addr
if bits >= size {
return key
}
mask := make([]byte, size/8)
for i := 0; i < bits; i++ {
mask[i/8] |= 0x80 >> (i % 8)
}
m, _ := netip.AddrFromSlice(mask)
return key + " and " + m.String()
}
func (r *renderer) connLimit(rule *model.Rule, line expanded) string {
@@ -431,12 +486,70 @@ func (r *renderer) connLimit(rule *model.Rule, line expanded) string {
if !r.hasMeter(name) {
r.meters = append(r.meters, fmt.Sprintf("\tset %s { type %s; flags dynamic; size 65535; }", name, addrType(line.fam == "v6")))
}
return fmt.Sprintf("add @%s { %s saddr ct count over %d }", name, ipKeyword(line.fam), rule.ConnLimit)
return fmt.Sprintf("add @%s { %s ct count over %d }", name, r.addrKey(rule, line.fam, "saddr"), rule.ConnLimit)
}
// quota renders a rule's quota: a named quota shared by the rule's lines
// (both families count against one allowance), or per address a set of
// quotas per family. What was used comes back from Options, so a reload
// doesn't reset it.
func (r *renderer) quota(rule *model.Rule, line expanded) string {
q := rule.Quota
amount := quotaAmount(q)
name := QuotaName(rule.ID)
addr := q.PerAddress()
if addr == "" {
if !r.hasMeter(name) {
used := ""
if u := r.opt.Quotas[name]; u > 0 {
used = fmt.Sprintf(" used %d bytes", u)
}
r.meters = append(r.meters, fmt.Sprintf("\tquota %s { %s%s }", name, amount, used))
}
return fmt.Sprintf("quota name %s", quote(name))
}
set := name + "_" + line.fam
if !r.hasMeter(set) {
var elems []string
for _, e := range r.opt.QuotaSets[set] {
a, err := netip.ParseAddr(e.Addr)
if err != nil || a.Is6() != (line.fam == "v6") {
continue
}
used := ""
if e.Used > 0 {
used = fmt.Sprintf(" used %d bytes", e.Used)
}
elems = append(elems, fmt.Sprintf("%s quota %s%s", a, amount, used))
}
list := ""
if len(elems) > 0 {
list = " elements = { " + strings.Join(elems, ", ") + " }"
}
r.meters = append(r.meters, fmt.Sprintf("\tset %s { type %s; flags dynamic; size 65535;%s }", set, addrType(line.fam == "v6"), list))
}
return fmt.Sprintf("add @%s { %s quota %s }", set, r.addrKey(rule, line.fam, addr), amount)
}
// quotaAmount writes a quota: "over 5000 mbytes" (nftables 1.1.3 has no
// gbytes).
func quotaAmount(q *model.Quota) string {
n, unit := q.Bytes, "bytes"
for _, u := range []string{"mbytes", "kbytes"} {
if n >= model.ByteUnits[u] && n%model.ByteUnits[u] == 0 {
n, unit = n/model.ByteUnits[u], u
break
}
}
if q.Over {
return fmt.Sprintf("over %d %s", n, unit)
}
return fmt.Sprintf("until %d %s", n, unit)
}
func (r *renderer) hasMeter(name string) bool {
for _, m := range r.meters {
if strings.Contains(m, "set "+name+" ") {
if strings.Contains(m, "set "+name+" ") || strings.Contains(m, "quota "+name+" ") {
return true
}
}