| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
package knftables |
| 18 |
|
| 19 |
import ( |
| 20 |
"bytes" |
| 21 |
"context" |
| 22 |
"encoding/json" |
| 23 |
"fmt" |
| 24 |
"os/exec" |
| 25 |
"strings" |
| 26 |
"sync" |
| 27 |
) |
| 28 |
|
| 29 |
|
| 30 |
type Interface interface { |
| 31 |
|
| 32 |
NewTransaction() *Transaction |
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
Run(ctx context.Context, tx *Transaction) error |
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
|
| 41 |
Check(ctx context.Context, tx *Transaction) error |
| 42 |
|
| 43 |
|
| 44 |
|
| 45 |
|
| 46 |
List(ctx context.Context, objectType string) ([]string, error) |
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
|
| 53 |
|
| 54 |
|
| 55 |
ListRules(ctx context.Context, chain string) ([]*Rule, error) |
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
ListElements(ctx context.Context, objectType, name string) ([]*Element, error) |
| 61 |
} |
| 62 |
|
| 63 |
type nftContext struct { |
| 64 |
family Family |
| 65 |
table string |
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
noObjectComments bool |
| 70 |
} |
| 71 |
|
| 72 |
|
| 73 |
type realNFTables struct { |
| 74 |
nftContext |
| 75 |
|
| 76 |
bufferMutex sync.Mutex |
| 77 |
buffer *bytes.Buffer |
| 78 |
|
| 79 |
exec execer |
| 80 |
path string |
| 81 |
} |
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
func newInternal(family Family, table string, execer execer) (Interface, error) { |
| 86 |
var err error |
| 87 |
|
| 88 |
nft := &realNFTables{ |
| 89 |
nftContext: nftContext{ |
| 90 |
family: family, |
| 91 |
table: table, |
| 92 |
}, |
| 93 |
buffer: &bytes.Buffer{}, |
| 94 |
exec: execer, |
| 95 |
} |
| 96 |
|
| 97 |
nft.path, err = nft.exec.LookPath("nft") |
| 98 |
if err != nil { |
| 99 |
return nil, fmt.Errorf("could not find nftables binary: %w", err) |
| 100 |
} |
| 101 |
|
| 102 |
cmd := exec.Command(nft.path, "--version") |
| 103 |
out, err := nft.exec.Run(cmd) |
| 104 |
if err != nil { |
| 105 |
return nil, fmt.Errorf("could not run nftables command: %w", err) |
| 106 |
} |
| 107 |
if strings.HasPrefix(out, "nftables v0.") || strings.HasPrefix(out, "nftables v1.0.0 ") { |
| 108 |
return nil, fmt.Errorf("nft version must be v1.0.1 or later (got %s)", strings.TrimSpace(out)) |
| 109 |
} |
| 110 |
|
| 111 |
|
| 112 |
|
| 113 |
tx := nft.NewTransaction() |
| 114 |
tx.Add(&Table{ |
| 115 |
Comment: PtrTo("test"), |
| 116 |
}) |
| 117 |
if err := nft.Check(context.TODO(), tx); err != nil { |
| 118 |
|
| 119 |
tx := nft.NewTransaction() |
| 120 |
tx.Add(&Table{}) |
| 121 |
if err := nft.Check(context.TODO(), tx); err != nil { |
| 122 |
return nil, fmt.Errorf("could not run nftables command: %w", err) |
| 123 |
} |
| 124 |
|
| 125 |
nft.noObjectComments = true |
| 126 |
} |
| 127 |
|
| 128 |
return nft, nil |
| 129 |
} |
| 130 |
|
| 131 |
|
| 132 |
|
| 133 |
func New(family Family, table string) (Interface, error) { |
| 134 |
return newInternal(family, table, realExec{}) |
| 135 |
} |
| 136 |
|
| 137 |
|
| 138 |
func (nft *realNFTables) NewTransaction() *Transaction { |
| 139 |
return &Transaction{nftContext: &nft.nftContext} |
| 140 |
} |
| 141 |
|
| 142 |
|
| 143 |
func (nft *realNFTables) Run(ctx context.Context, tx *Transaction) error { |
| 144 |
nft.bufferMutex.Lock() |
| 145 |
defer nft.bufferMutex.Unlock() |
| 146 |
|
| 147 |
if tx.err != nil { |
| 148 |
return tx.err |
| 149 |
} |
| 150 |
|
| 151 |
nft.buffer.Reset() |
| 152 |
err := tx.populateCommandBuf(nft.buffer) |
| 153 |
if err != nil { |
| 154 |
return err |
| 155 |
} |
| 156 |
|
| 157 |
cmd := exec.CommandContext(ctx, nft.path, "-f", "-") |
| 158 |
cmd.Stdin = nft.buffer |
| 159 |
_, err = nft.exec.Run(cmd) |
| 160 |
return err |
| 161 |
} |
| 162 |
|
| 163 |
|
| 164 |
func (nft *realNFTables) Check(ctx context.Context, tx *Transaction) error { |
| 165 |
nft.bufferMutex.Lock() |
| 166 |
defer nft.bufferMutex.Unlock() |
| 167 |
|
| 168 |
if tx.err != nil { |
| 169 |
return tx.err |
| 170 |
} |
| 171 |
|
| 172 |
nft.buffer.Reset() |
| 173 |
err := tx.populateCommandBuf(nft.buffer) |
| 174 |
if err != nil { |
| 175 |
return err |
| 176 |
} |
| 177 |
|
| 178 |
cmd := exec.CommandContext(ctx, nft.path, "--check", "-f", "-") |
| 179 |
cmd.Stdin = nft.buffer |
| 180 |
_, err = nft.exec.Run(cmd) |
| 181 |
return err |
| 182 |
} |
| 183 |
|
| 184 |
|
| 185 |
|
| 186 |
func jsonVal[T any](json map[string]interface{}, key string) (T, bool) { |
| 187 |
if ifVal, exists := json[key]; exists { |
| 188 |
tVal, ok := ifVal.(T) |
| 189 |
return tVal, ok |
| 190 |
} |
| 191 |
var zero T |
| 192 |
return zero, false |
| 193 |
} |
| 194 |
|
| 195 |
|
| 196 |
|
| 197 |
func getJSONObjects(listOutput, objectType string) ([]map[string]interface{}, error) { |
| 198 |
|
| 199 |
|
| 200 |
|
| 201 |
|
| 202 |
|
| 203 |
|
| 204 |
|
| 205 |
|
| 206 |
|
| 207 |
|
| 208 |
|
| 209 |
|
| 210 |
|
| 211 |
|
| 212 |
|
| 213 |
|
| 214 |
|
| 215 |
|
| 216 |
|
| 217 |
|
| 218 |
|
| 219 |
|
| 220 |
|
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
|
| 226 |
|
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
|
| 241 |
|
| 242 |
|
| 243 |
|
| 244 |
|
| 245 |
|
| 246 |
jsonResult := map[string][]map[string]map[string]interface{}{} |
| 247 |
if err := json.Unmarshal([]byte(listOutput), &jsonResult); err != nil { |
| 248 |
return nil, fmt.Errorf("could not parse nft output: %w", err) |
| 249 |
} |
| 250 |
|
| 251 |
nftablesResult := jsonResult["nftables"] |
| 252 |
if len(nftablesResult) == 0 { |
| 253 |
return nil, fmt.Errorf("could not find result in nft output %q", listOutput) |
| 254 |
} |
| 255 |
metainfo := nftablesResult[0]["metainfo"] |
| 256 |
if metainfo == nil { |
| 257 |
return nil, fmt.Errorf("could not find metadata in nft output %q", listOutput) |
| 258 |
} |
| 259 |
|
| 260 |
|
| 261 |
if version, ok := jsonVal[float64](metainfo, "json_schema_version"); !ok || version != 1.0 { |
| 262 |
return nil, fmt.Errorf("could not find supported json_schema_version in nft output %q", listOutput) |
| 263 |
} |
| 264 |
|
| 265 |
var objects []map[string]interface{} |
| 266 |
for _, objContainer := range nftablesResult { |
| 267 |
obj := objContainer[objectType] |
| 268 |
if obj != nil { |
| 269 |
objects = append(objects, obj) |
| 270 |
} |
| 271 |
} |
| 272 |
return objects, nil |
| 273 |
} |
| 274 |
|
| 275 |
|
| 276 |
func (nft *realNFTables) List(ctx context.Context, objectType string) ([]string, error) { |
| 277 |
|
| 278 |
|
| 279 |
var typeSingular, typePlural string |
| 280 |
if objectType[len(objectType)-1] == 's' { |
| 281 |
typeSingular = objectType[:len(objectType)-1] |
| 282 |
typePlural = objectType |
| 283 |
} else { |
| 284 |
typeSingular = objectType |
| 285 |
typePlural = objectType + "s" |
| 286 |
} |
| 287 |
|
| 288 |
cmd := exec.CommandContext(ctx, nft.path, "--json", "list", typePlural, string(nft.family)) |
| 289 |
out, err := nft.exec.Run(cmd) |
| 290 |
if err != nil { |
| 291 |
return nil, fmt.Errorf("failed to run nft: %w", err) |
| 292 |
} |
| 293 |
|
| 294 |
objects, err := getJSONObjects(out, typeSingular) |
| 295 |
if err != nil { |
| 296 |
return nil, err |
| 297 |
} |
| 298 |
|
| 299 |
var result []string |
| 300 |
for _, obj := range objects { |
| 301 |
objTable, _ := jsonVal[string](obj, "table") |
| 302 |
if objTable != nft.table { |
| 303 |
continue |
| 304 |
} |
| 305 |
|
| 306 |
if name, ok := jsonVal[string](obj, "name"); ok { |
| 307 |
result = append(result, name) |
| 308 |
} |
| 309 |
} |
| 310 |
return result, nil |
| 311 |
} |
| 312 |
|
| 313 |
|
| 314 |
func (nft *realNFTables) ListRules(ctx context.Context, chain string) ([]*Rule, error) { |
| 315 |
|
| 316 |
var cmd *exec.Cmd |
| 317 |
if chain == "" { |
| 318 |
cmd = exec.CommandContext(ctx, nft.path, "--json", "list", "table", string(nft.family), nft.table) |
| 319 |
} else { |
| 320 |
cmd = exec.CommandContext(ctx, nft.path, "--json", "list", "chain", string(nft.family), nft.table, chain) |
| 321 |
} |
| 322 |
out, err := nft.exec.Run(cmd) |
| 323 |
if err != nil { |
| 324 |
return nil, fmt.Errorf("failed to run nft: %w", err) |
| 325 |
} |
| 326 |
|
| 327 |
jsonRules, err := getJSONObjects(out, "rule") |
| 328 |
if err != nil { |
| 329 |
return nil, fmt.Errorf("unable to parse JSON output: %w", err) |
| 330 |
} |
| 331 |
|
| 332 |
rules := make([]*Rule, 0, len(jsonRules)) |
| 333 |
for _, jsonRule := range jsonRules { |
| 334 |
parentChain, ok := jsonVal[string](jsonRule, "chain") |
| 335 |
if !ok { |
| 336 |
return nil, fmt.Errorf("unexpected JSON output from nft (rule with no chain)") |
| 337 |
} |
| 338 |
rule := &Rule{ |
| 339 |
Chain: parentChain, |
| 340 |
} |
| 341 |
|
| 342 |
|
| 343 |
|
| 344 |
|
| 345 |
|
| 346 |
|
| 347 |
if handle, ok := jsonVal[float64](jsonRule, "handle"); ok { |
| 348 |
rule.Handle = PtrTo(int(handle)) |
| 349 |
} |
| 350 |
if comment, ok := jsonVal[string](jsonRule, "comment"); ok { |
| 351 |
rule.Comment = &comment |
| 352 |
} |
| 353 |
|
| 354 |
rules = append(rules, rule) |
| 355 |
} |
| 356 |
return rules, nil |
| 357 |
} |
| 358 |
|
| 359 |
|
| 360 |
func (nft *realNFTables) ListElements(ctx context.Context, objectType, name string) ([]*Element, error) { |
| 361 |
cmd := exec.CommandContext(ctx, nft.path, "--json", "list", objectType, string(nft.family), nft.table, name) |
| 362 |
out, err := nft.exec.Run(cmd) |
| 363 |
if err != nil { |
| 364 |
return nil, fmt.Errorf("failed to run nft: %w", err) |
| 365 |
} |
| 366 |
|
| 367 |
jsonSetsOrMaps, err := getJSONObjects(out, objectType) |
| 368 |
if err != nil { |
| 369 |
return nil, fmt.Errorf("unable to parse JSON output: %w", err) |
| 370 |
} |
| 371 |
if len(jsonSetsOrMaps) != 1 { |
| 372 |
return nil, fmt.Errorf("unexpected JSON output from nft (multiple results)") |
| 373 |
} |
| 374 |
|
| 375 |
jsonElements, _ := jsonVal[[]interface{}](jsonSetsOrMaps[0], "elem") |
| 376 |
elements := make([]*Element, 0, len(jsonElements)) |
| 377 |
for _, jsonElement := range jsonElements { |
| 378 |
var key, value interface{} |
| 379 |
|
| 380 |
elem := &Element{} |
| 381 |
if objectType == "set" { |
| 382 |
elem.Set = name |
| 383 |
key = jsonElement |
| 384 |
} else { |
| 385 |
elem.Map = name |
| 386 |
tuple, ok := jsonElement.([]interface{}) |
| 387 |
if !ok || len(tuple) != 2 { |
| 388 |
return nil, fmt.Errorf("unexpected JSON output from nft (elem is not [key,val]: %q)", jsonElement) |
| 389 |
} |
| 390 |
key, value = tuple[0], tuple[1] |
| 391 |
} |
| 392 |
|
| 393 |
|
| 394 |
|
| 395 |
|
| 396 |
|
| 397 |
|
| 398 |
|
| 399 |
|
| 400 |
|
| 401 |
|
| 402 |
|
| 403 |
|
| 404 |
if obj, ok := key.(map[string]interface{}); ok { |
| 405 |
if compoundElem, ok := jsonVal[map[string]interface{}](obj, "elem"); ok { |
| 406 |
if key, ok = jsonVal[interface{}](compoundElem, "val"); !ok { |
| 407 |
return nil, fmt.Errorf("unexpected JSON output from nft (elem with no val: %q)", jsonElement) |
| 408 |
} |
| 409 |
if comment, ok := jsonVal[string](compoundElem, "comment"); ok { |
| 410 |
elem.Comment = &comment |
| 411 |
} |
| 412 |
} |
| 413 |
} |
| 414 |
|
| 415 |
elem.Key, err = parseElementValue(key) |
| 416 |
if err != nil { |
| 417 |
return nil, err |
| 418 |
} |
| 419 |
if value != nil { |
| 420 |
elem.Value, err = parseElementValue(value) |
| 421 |
if err != nil { |
| 422 |
return nil, err |
| 423 |
} |
| 424 |
} |
| 425 |
|
| 426 |
elements = append(elements, elem) |
| 427 |
} |
| 428 |
return elements, nil |
| 429 |
} |
| 430 |
|
| 431 |
|
| 432 |
|
| 433 |
func parseElementValue(json interface{}) ([]string, error) { |
| 434 |
|
| 435 |
|
| 436 |
|
| 437 |
|
| 438 |
|
| 439 |
|
| 440 |
|
| 441 |
|
| 442 |
|
| 443 |
|
| 444 |
|
| 445 |
|
| 446 |
|
| 447 |
|
| 448 |
|
| 449 |
|
| 450 |
|
| 451 |
|
| 452 |
|
| 453 |
|
| 454 |
|
| 455 |
|
| 456 |
|
| 457 |
|
| 458 |
|
| 459 |
|
| 460 |
|
| 461 |
|
| 462 |
|
| 463 |
|
| 464 |
|
| 465 |
|
| 466 |
|
| 467 |
|
| 468 |
|
| 469 |
switch val := json.(type) { |
| 470 |
case string: |
| 471 |
return []string{val}, nil |
| 472 |
case float64: |
| 473 |
return []string{fmt.Sprintf("%d", int(val))}, nil |
| 474 |
case map[string]interface{}: |
| 475 |
if concat, _ := jsonVal[[]interface{}](val, "concat"); concat != nil { |
| 476 |
vals := make([]string, len(concat)) |
| 477 |
for i := range concat { |
| 478 |
if str, ok := concat[i].(string); ok { |
| 479 |
vals[i] = str |
| 480 |
} else if num, ok := concat[i].(float64); ok { |
| 481 |
vals[i] = fmt.Sprintf("%d", int(num)) |
| 482 |
} else { |
| 483 |
return nil, fmt.Errorf("could not parse element value %q", concat[i]) |
| 484 |
} |
| 485 |
} |
| 486 |
return vals, nil |
| 487 |
} else if prefix, _ := jsonVal[map[string]interface{}](val, "prefix"); prefix != nil { |
| 488 |
|
| 489 |
addr, ok := jsonVal[string](prefix, "addr") |
| 490 |
if !ok { |
| 491 |
return nil, fmt.Errorf("could not parse 'addr' value as string: %q", prefix) |
| 492 |
} |
| 493 |
length, ok := jsonVal[float64](prefix, "len") |
| 494 |
if !ok { |
| 495 |
return nil, fmt.Errorf("could not parse 'len' value as number: %q", prefix) |
| 496 |
} |
| 497 |
return []string{fmt.Sprintf("%s/%d", addr, int(length))}, nil |
| 498 |
} else if len(val) == 1 { |
| 499 |
var verdict string |
| 500 |
|
| 501 |
|
| 502 |
for k, v := range val { |
| 503 |
if v == nil { |
| 504 |
verdict = k |
| 505 |
} else if target, ok := v.(map[string]interface{}); ok { |
| 506 |
verdict = fmt.Sprintf("%s %s", k, target["target"]) |
| 507 |
} |
| 508 |
} |
| 509 |
return []string{verdict}, nil |
| 510 |
} |
| 511 |
} |
| 512 |
|
| 513 |
return nil, fmt.Errorf("could not parse element value %q", json) |
| 514 |
} |