| 1 | /* |
| 2 | Copyright 2023 The Kubernetes Authors. |
| 3 | |
| 4 | Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | you may not use this file except in compliance with the License. |
| 6 | You may obtain a copy of the License at |
| 7 | |
| 8 | http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | |
| 10 | Unless required by applicable law or agreed to in writing, software |
| 11 | distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | See the License for the specific language governing permissions and |
| 14 | limitations under the License. |
| 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 | // Interface is an interface for running nftables commands against a given family and table. |
| 30 | type Interface interface { |
| 31 | // NewTransaction returns a new (empty) Transaction |
| 32 | NewTransaction() *Transaction |
| 33 | |
| 34 | // Run runs a Transaction and returns the result. The IsNotFound and |
| 35 | // IsAlreadyExists methods can be used to test the result. |
| 36 | Run(ctx context.Context, tx *Transaction) error |
| 37 | |
| 38 | // Check does a dry-run of a Transaction (as with `nft --check`) and returns the |
| 39 | // result. The IsNotFound and IsAlreadyExists methods can be used to test the |
| 40 | // result. |
| 41 | Check(ctx context.Context, tx *Transaction) error |
| 42 | |
| 43 | // List returns a list of the names of the objects of objectType ("chain", "set", |
| 44 | // or "map") in the table. If there are no such objects, this will return an empty |
| 45 | // list and no error. |
| 46 | List(ctx context.Context, objectType string) ([]string, error) |
| 47 | |
| 48 | // ListRules returns a list of the rules in a chain, in order. If no chain name is |
| 49 | // specified, then all rules within the table will be returned. Note that at the |
| 50 | // present time, the Rule objects will have their `Comment` and `Handle` fields |
| 51 | // filled in, but *not* the actual `Rule` field. So this can only be used to find |
| 52 | // the handles of rules if they have unique comments to recognize them by, or if |
| 53 | // you know the order of the rules within the chain. If the chain exists but |
| 54 | // contains no rules, this will return an empty list and no error. |
| 55 | ListRules(ctx context.Context, chain string) ([]*Rule, error) |
| 56 | |
| 57 | // ListElements returns a list of the elements in a set or map. (objectType should |
| 58 | // be "set" or "map".) If the set/map exists but contains no elements, this will |
| 59 | // return an empty list and no error. |
| 60 | ListElements(ctx context.Context, objectType, name string) ([]*Element, error) |
| 61 | } |
| 62 | |
| 63 | type nftContext struct { |
| 64 | family Family |
| 65 | table string |
| 66 | |
| 67 | // noObjectComments is true if comments on Table/Chain/Set/Map are not supported. |
| 68 | // (Comments on Rule and Element are always supported.) |
| 69 | noObjectComments bool |
| 70 | } |
| 71 | |
| 72 | // realNFTables is an implementation of Interface |
| 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 | // newInternal creates a new nftables.Interface for interacting with the given table; this |
| 84 | // is split out from New() so it can be used from unit tests with a fakeExec. |
| 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 | // Check that (a) nft works, (b) we have permission, (c) the kernel is new enough |
| 112 | // to support object comments. |
| 113 | tx := nft.NewTransaction() |
| 114 | tx.Add(&Table{ |
| 115 | Comment: PtrTo("test"), |
| 116 | }) |
| 117 | if err := nft.Check(context.TODO(), tx); err != nil { |
| 118 | // Try again, checking just that (a) nft works, (b) we have permission. |
| 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 | // New creates a new nftables.Interface for interacting with the given table. If nftables |
| 132 | // is not available/usable on the current host, it will return an error. |
| 133 | func New(family Family, table string) (Interface, error) { |
| 134 | return newInternal(family, table, realExec{}) |
| 135 | } |
| 136 | |
| 137 | // NewTransaction is part of Interface |
| 138 | func (nft *realNFTables) NewTransaction() *Transaction { |
| 139 | return &Transaction{nftContext: &nft.nftContext} |
| 140 | } |
| 141 | |
| 142 | // Run is part of Interface |
| 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 | // Check is part of Interface |
| 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 | // jsonVal looks up key in json; if it exists and is of type T, it returns (json[key], true). |
| 185 | // Otherwise it returns (_, false). |
| 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 | // getJSONObjects takes the output of "nft -j list", validates it, and returns an array |
| 196 | // of just the objects of objectType. |
| 197 | func getJSONObjects(listOutput, objectType string) ([]map[string]interface{}, error) { |
| 198 | // listOutput should contain JSON looking like: |
| 199 | // |
| 200 | // { |
| 201 | // "nftables": [ |
| 202 | // { |
| 203 | // "metainfo": { |
| 204 | // "json_schema_version": 1, |
| 205 | // ... |
| 206 | // } |
| 207 | // }, |
| 208 | // { |
| 209 | // "chain": { |
| 210 | // "family": "ip", |
| 211 | // "table": "kube-proxy", |
| 212 | // "name": "KUBE-SERVICES", |
| 213 | // "handle": 3 |
| 214 | // } |
| 215 | // }, |
| 216 | // { |
| 217 | // "chain": { |
| 218 | // "family": "ip", |
| 219 | // "table": "kube-proxy", |
| 220 | // "name": "KUBE-NODEPORTS", |
| 221 | // "handle": 4 |
| 222 | // } |
| 223 | // }, |
| 224 | // ... |
| 225 | // ] |
| 226 | // } |
| 227 | // |
| 228 | // In this case, given objectType "chain", we would return |
| 229 | // |
| 230 | // [ |
| 231 | // { |
| 232 | // "family": "ip", |
| 233 | // "table": "kube-proxy", |
| 234 | // "name": "KUBE-SERVICES", |
| 235 | // "handle": 3 |
| 236 | // }, |
| 237 | // { |
| 238 | // "family": "ip", |
| 239 | // "table": "kube-proxy", |
| 240 | // "name": "KUBE-NODEPORTS", |
| 241 | // "handle": 4 |
| 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 | // json_schema_version is an integer but `json.Unmarshal()` will have parsed it as |
| 260 | // a float64 since we didn't tell it otherwise. |
| 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 | // List is part of Interface. |
| 276 | func (nft *realNFTables) List(ctx context.Context, objectType string) ([]string, error) { |
| 277 | // All currently-existing nftables object types have plural forms that are just |
| 278 | // the singular form plus 's'. |
| 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 | // ListRules is part of Interface |
| 314 | func (nft *realNFTables) ListRules(ctx context.Context, chain string) ([]*Rule, error) { |
| 315 | // If no chain is given, return all rules from within the table. |
| 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 | // handle is written as an integer in nft's output, but json.Unmarshal |
| 343 | // will have parsed it as a float64. (Handles are uint64s, but they are |
| 344 | // assigned consecutively starting from 1, so as long as fewer than 2**53 |
| 345 | // nftables objects have been created since boot time, we won't run into |
| 346 | // float64-vs-uint64 precision issues.) |
| 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 | // ListElements is part of Interface |
| 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 | // If the element has a comment, then key will be a compound object like: |
| 394 | // |
| 395 | // { |
| 396 | // "elem": { |
| 397 | // "val": "192.168.0.1", |
| 398 | // "comment": "this is a comment" |
| 399 | // } |
| 400 | // } |
| 401 | // |
| 402 | // (Where "val" contains the value that key would have held if there was no |
| 403 | // comment.) |
| 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 | // parseElementValue parses a JSON element key/value, handling concatenations, prefixes, and |
| 432 | // converting numeric or "verdict" values to strings. |
| 433 | func parseElementValue(json interface{}) ([]string, error) { |
| 434 | // json can be: |
| 435 | // |
| 436 | // - a single string, e.g. "192.168.1.3" |
| 437 | // |
| 438 | // - a single number, e.g. 80 |
| 439 | // |
| 440 | // - a prefix, expressed as an object: |
| 441 | // { |
| 442 | // "prefix": { |
| 443 | // "addr": "192.168.0.0", |
| 444 | // "len": 16, |
| 445 | // } |
| 446 | // } |
| 447 | // |
| 448 | // - a concatenation, expressed as an object containing an array of simple |
| 449 | // values: |
| 450 | // { |
| 451 | // "concat": [ |
| 452 | // "192.168.1.3", |
| 453 | // "tcp", |
| 454 | // 80 |
| 455 | // ] |
| 456 | // } |
| 457 | // |
| 458 | // - a verdict (for a vmap value), expressed as an object: |
| 459 | // { |
| 460 | // "drop": null |
| 461 | // } |
| 462 | // |
| 463 | // { |
| 464 | // "goto": { |
| 465 | // "target": "destchain" |
| 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 | // For prefix-type elements, return the element in CIDR representation. |
| 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 | // We just checked that len(val) == 1, so this loop body will only |
| 501 | // run once |
| 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 | } |