| 1 | # knftables: a golang nftables library |
| 2 | |
| 3 | This is a library for using nftables from Go. |
| 4 | |
| 5 | It is not intended to support arbitrary use cases, but instead |
| 6 | specifically focuses on supporting Kubernetes components which are |
| 7 | using nftables in the way that nftables is supposed to be used (as |
| 8 | opposed to using nftables in a naively-translated-from-iptables way, |
| 9 | or using nftables to do totally valid things that aren't the sorts of |
| 10 | things Kubernetes components are likely to need to do; see the |
| 11 | "[iptables porting](./docs/iptables-porting.md)" doc for more thoughts |
| 12 | on porting old iptables-based components to nftables.) |
| 13 | |
| 14 | knftables is still under development and is not yet API stable. (See the |
| 15 | section on "Possible future changes" below.) |
| 16 | |
| 17 | The library is implemented as a wrapper around the `nft` CLI, because |
| 18 | the CLI API is the only well-documented interface to nftables. |
| 19 | Although it would be possible to use netlink directly (and some other |
| 20 | golang-based nftables libraries do this), that would result in an API |
| 21 | that is quite different from all documented examples of nftables usage |
| 22 | (e.g. the man pages and the [nftables wiki](http://wiki.nftables.org/)) |
| 23 | because there is no easy way to convert the "standard" representation |
| 24 | of nftables rules into the netlink form. |
| 25 | |
| 26 | (Actually, it's not quite true that there's no other usable API: the |
| 27 | `nft` CLI is just a thin wrapper around `libnftables`, and it would be |
| 28 | possible for knftables to use cgo to invoke that library instead of |
| 29 | using an external binary. However, this would be harder to build and |
| 30 | ship, so I'm not bothering with that for now. But this could be done |
| 31 | in the future without needing to change knftables's API.) |
| 32 | |
| 33 | knftables requires nft version 1.0.1 or later, because earlier |
| 34 | versions would download and process the entire ruleset regardless of |
| 35 | what you were doing, which, besides being pointlessly inefficient, |
| 36 | means that in some cases, other people using new features in _their_ |
| 37 | tables could prevent you from modifying _your_ table. (In particular, |
| 38 | a change in how some rules are generated starting in nft 1.0.3 |
| 39 | triggers a crash in nft 0.9.9 and earlier, _even if you aren't looking |
| 40 | at the table containing that rule_.) |
| 41 | |
| 42 | ## Usage |
| 43 | |
| 44 | Create an `Interface` object to manage operations on a single nftables |
| 45 | table: |
| 46 | |
| 47 | ```golang |
| 48 | nft, err := knftables.New(knftables.IPv4Family, "my-table") |
| 49 | if err != nil { |
| 50 | return fmt.Errorf("no nftables support: %v", err) |
| 51 | } |
| 52 | ``` |
| 53 | |
| 54 | (If you want to operate on multiple tables or multiple nftables |
| 55 | families, you will need separate `Interface` objects for each. If you |
| 56 | need to check whether the system supports an nftables feature as with |
| 57 | `nft --check`, use `nft.Check()`, which works the same as `nft.Run()` |
| 58 | below.) |
| 59 | |
| 60 | You can use the `List`, `ListRules`, and `ListElements` methods on the |
| 61 | `Interface` to check if objects exist. `List` returns the names of |
| 62 | `"chains"`, `"sets"`, or `"maps"` in the table, while `ListElements` |
| 63 | returns `Element` objects and `ListRules` returns *partial* `Rule` |
| 64 | objects. |
| 65 | |
| 66 | ```golang |
| 67 | chains, err := nft.List(ctx, "chains") |
| 68 | if err != nil { |
| 69 | return fmt.Errorf("could not list chains: %v", err) |
| 70 | } |
| 71 | |
| 72 | FIXME |
| 73 | |
| 74 | elements, err := nft.ListElements(ctx, "map", "mymap") |
| 75 | if err != nil { |
| 76 | return fmt.Errorf("could not list map elements: %v", err) |
| 77 | } |
| 78 | |
| 79 | FIXME |
| 80 | ``` |
| 81 | |
| 82 | To make changes, create a `Transaction`, add the appropriate |
| 83 | operations to the transaction, and then call `nft.Run` on it: |
| 84 | |
| 85 | ```golang |
| 86 | tx := nft.NewTransaction() |
| 87 | |
| 88 | tx.Add(&knftables.Chain{ |
| 89 | Name: "mychain", |
| 90 | Comment: knftables.PtrTo("this is my chain"), |
| 91 | }) |
| 92 | tx.Flush(&knftables.Chain{ |
| 93 | Name: "mychain", |
| 94 | }) |
| 95 | |
| 96 | var destIP net.IP |
| 97 | var destPort uint16 |
| 98 | ... |
| 99 | tx.Add(&knftables.Rule{ |
| 100 | Chain: "mychain", |
| 101 | Rule: knftables.Concat( |
| 102 | "ip daddr", destIP, |
| 103 | "ip protocol", "tcp", |
| 104 | "th port", destPort, |
| 105 | "jump", destChain, |
| 106 | ) |
| 107 | }) |
| 108 | |
| 109 | err := nft.Run(context, tx) |
| 110 | ``` |
| 111 | |
| 112 | If any operation in the transaction would fail, then `Run()` will |
| 113 | return an error and the entire transaction will be ignored. You can |
| 114 | use the `knftables.IsNotFound()` and `knftables.IsAlreadyExists()` |
| 115 | methods to check for those well-known error types. In a large |
| 116 | transaction, there is no supported way to determine exactly which |
| 117 | operation failed. |
| 118 | |
| 119 | ## `knftables.Transaction` operations |
| 120 | |
| 121 | `knftables.Transaction` operations correspond to the top-level commands |
| 122 | in the `nft` binary. Currently-supported operations are: |
| 123 | |
| 124 | - `tx.Add()`: adds an object, which may already exist, as with `nft add` |
| 125 | - `tx.Create()`: creates an object, which must not already exist, as with `nft create` |
| 126 | - `tx.Flush()`: flushes the contents of a table/chain/set/map, as with `nft flush` |
| 127 | - `tx.Delete()`: deletes an object, as with `nft delete` |
| 128 | - `tx.Insert()`: inserts a rule before another rule, as with `nft insert rule` |
| 129 | - `tx.Replace()`: replaces a rule, as with `nft replace rule` |
| 130 | |
| 131 | ## Objects |
| 132 | |
| 133 | The `Transaction` methods take arguments of type `knftables.Object`. |
| 134 | The currently-supported objects are: |
| 135 | |
| 136 | - `Table` |
| 137 | - `Flowtable` |
| 138 | - `Chain` |
| 139 | - `Rule` |
| 140 | - `Set` |
| 141 | - `Map` |
| 142 | - `Element` |
| 143 | |
| 144 | Optional fields in objects can be filled in with the help of the |
| 145 | `PtrTo()` function, which just returns a pointer to its argument. |
| 146 | |
| 147 | `Concat()` can be used to concatenate a series of strings, `[]string` |
| 148 | arrays, and other arguments (including numbers, `net.IP`s / |
| 149 | `net.IPNet`s, and anything else that can be formatted usefully via |
| 150 | `fmt.Sprintf("%s")`) together into a single string. This is often |
| 151 | useful when constructing `Rule`s. |
| 152 | |
| 153 | ## `knftables.Fake` |
| 154 | |
| 155 | There is a fake (in-memory) implementation of `knftables.Interface` |
| 156 | for use in unit tests. Use `knftables.NewFake()` instead of |
| 157 | `knftables.New()` to create it, and then it should work mostly the |
| 158 | same. See `fake.go` for more details of the public APIs for examining |
| 159 | the current state of the fake nftables database. |
| 160 | |
| 161 | ## Missing APIs |
| 162 | |
| 163 | Various top-level object types are not yet supported (notably the |
| 164 | "stateful objects" like `counter`). |
| 165 | |
| 166 | Most IPTables libraries have an API for "add this rule only if it |
| 167 | doesn't already exist", but that does not seem as useful in nftables |
| 168 | (or at least "in nftables as used by Kubernetes-ish components that |
| 169 | aren't just blindly copying over old iptables APIs"), because chains |
| 170 | tend to have static rules and dynamic sets/maps, rather than having |
| 171 | dynamic rules. If you aren't sure if a chain has the correct rules, |
| 172 | you can just `Flush` it and recreate all of the rules. |
| 173 | |
| 174 | The "destroy" (delete-without-ENOENT) command that exists in newer |
| 175 | versions of `nft` is not currently supported because it would be |
| 176 | unexpectedly heavyweight to emulate on systems that don't have it, so |
| 177 | it is better (for now) to force callers to implement it by hand. |
| 178 | |
| 179 | `ListRules` returns `Rule` objects without the `Rule` field filled in, |
| 180 | because it uses the JSON API to list the rules, but there is no easy |
| 181 | way to convert the JSON rule representation back into plaintext form. |
| 182 | This means that it is only useful when either (a) you know the order |
| 183 | of the rules in the chain, but want to know their handles, or (b) you |
| 184 | can recognize the rules you are looking for by their comments, rather |
| 185 | than the rule bodies. |
| 186 | |
| 187 | ## Possible future changes |
| 188 | |
| 189 | ### `nft` output parsing |
| 190 | |
| 191 | `nft`'s output is documented and standardized, so it ought to be |
| 192 | possible for us to extract better error messages in the event of a |
| 193 | transaction failure. |
| 194 | |
| 195 | Additionally, if we used the `--echo` (`-e`) and `--handle` (`-a`) |
| 196 | flags, we could learn the handles associated with newly-created |
| 197 | objects in a transaction, and return these to the caller somehow. |
| 198 | (E.g., by setting the `Handle` field in the object that had been |
| 199 | passed to `tx.Add` when the transaction is run.) |
| 200 | |
| 201 | (For now, `ListRules` fills in the handles of the rules it returns, so |
| 202 | it's possible to find out a rule's handle after the fact that way. For |
| 203 | other supported object types, either handles don't exist (`Element`) |
| 204 | or you don't really need to know their handles because it's possible |
| 205 | to delete by name instead (`Table`, `Chain`, `Set`, `Map`).) |
| 206 | |
| 207 | ### List APIs |
| 208 | |
| 209 | The fact that `List` works completely differently from `ListRules` and |
| 210 | `ListElements` is a historical artifact. |
| 211 | |
| 212 | I would like to have a single function |
| 213 | |
| 214 | ```golang |
| 215 | List[T Object](ctx context.Context, template T) ([]T, error) |
| 216 | ``` |
| 217 | |
| 218 | So you could say |
| 219 | |
| 220 | ```golang |
| 221 | elements, err := nft.List(ctx, &knftables.Element{Set: "myset"}) |
| 222 | ``` |
| 223 | |
| 224 | to list the elements of "myset". But this doesn't actually compile |
| 225 | ("`syntax error: method must have no type parameters`") because |
| 226 | allowing that would apparently introduce extremely complicated edge |
| 227 | cases in Go generics. |
| 228 | |
| 229 | ### Set/map type representation |
| 230 | |
| 231 | There is currently an annoying asymmetry in the representation of |
| 232 | concatenated types between `Set`/`Map` and `Element`, where the former |
| 233 | uses a string containing `nft` syntax, and the latter uses an array: |
| 234 | |
| 235 | ```golang |
| 236 | tx.Add(&knftables.Set{ |
| 237 | Name: "firewall", |
| 238 | Type: "ipv4_addr . inet_proto . inet_service", |
| 239 | }) |
| 240 | tx.Add(&knftables.Element{ |
| 241 | Set: "firewall", |
| 242 | Key: []string{"10.1.2.3", "tcp", "80"}, |
| 243 | }) |
| 244 | ``` |
| 245 | |
| 246 | This will probably be fixed at some point, which may result in a |
| 247 | change to how the `type` vs `typeof` distinction is handled as well. |
| 248 | |
| 249 | ### Optimization and rule representation |
| 250 | |
| 251 | We will need to optimize the performance of large transactions. One |
| 252 | change that is likely is to avoid pre-concatenating rule elements in |
| 253 | cases like: |
| 254 | |
| 255 | ```golang |
| 256 | tx.Add(&knftables.Rule{ |
| 257 | Chain: "mychain", |
| 258 | Rule: knftables.Concat( |
| 259 | "ip daddr", destIP, |
| 260 | "ip protocol", "tcp", |
| 261 | "th port", destPort, |
| 262 | "jump", destChain, |
| 263 | ) |
| 264 | }) |
| 265 | ``` |
| 266 | |
| 267 | This will presumably require a change to `knftables.Rule` and/or |
| 268 | `knftables.Concat()` but I'm not sure exactly what it will be. |
| 269 | |
| 270 | ## Community, discussion, contribution, and support |
| 271 | |
| 272 | knftables is maintained by [Kubernetes SIG Network](https://github.com/kubernetes/community/tree/master/sig-network). |
| 273 | |
| 274 | - [sig-network slack channel](https://kubernetes.slack.com/messages/sig-network) |
| 275 | - [kubernetes-sig-network mailing list](https://groups.google.com/forum/#!forum/kubernetes-sig-network) |
| 276 | |
| 277 | See [`CONTRIBUTING.md`](CONTRIBUTING.md) for more information about |
| 278 | contributing. Participation in the Kubernetes community is governed by |
| 279 | the [Kubernetes Code of Conduct](code-of-conduct.md). |