| 1 | // Copyright 2023 CNI authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package main |
| 16 | |
| 17 | import ( |
| 18 | "context" |
| 19 | "fmt" |
| 20 | "net" |
| 21 | "strconv" |
| 22 | |
| 23 | "sigs.k8s.io/knftables" |
| 24 | ) |
| 25 | |
| 26 | const ( |
| 27 | tableName = "cni_hostport" |
| 28 | |
| 29 | // Intermediate chain to jump to both 'hostip_hostports' and 'hostports' |
| 30 | hostPortsAllChain = "hostports_all" |
| 31 | // This chain was used for rules with hostIP, we do not use it anymore, |
| 32 | // but we keep it to make upgrade transparent |
| 33 | hostIPHostPortsChain = "hostip_hostports" |
| 34 | // Chain containing all the rules |
| 35 | hostPortsChain = "hostports" |
| 36 | masqueradingChain = "masquerading" |
| 37 | ) |
| 38 | |
| 39 | // The nftables portmap implementation is fairly similar to the iptables implementation: |
| 40 | // we add a rule for each mapping, with a comment containing a hash of the container ID, |
| 41 | // so that we can later reliably delete the rules we want. (This is important because in |
| 42 | // edge cases, it's possible the plugin might see "ADD container A with IP 192.168.1.3", |
| 43 | // followed by "ADD container B with IP 192.168.1.3" followed by "DEL container A with IP |
| 44 | // 192.168.1.3", and we need to make sure that the DEL causes us to delete the rule for |
| 45 | // container A, and not the rule for container B.) This iptables implementation actually |
| 46 | // uses a separate chain per container but there's not really any need for that... |
| 47 | // |
| 48 | // As with pkg/ip/ipmasq_nftables_linux.go, it would be more nftables-y to have a chain |
| 49 | // with a single rule doing a lookup against a map with an element per mapping, rather |
| 50 | // than having a chain with a rule per mapping. But there's no easy, non-racy way to say |
| 51 | // "delete the element 192.168.1.3 from the map, but only if it was added for container A, |
| 52 | // not if it was added for container B". |
| 53 | |
| 54 | type portMapperNFTables struct { |
| 55 | ipv4 knftables.Interface |
| 56 | ipv6 knftables.Interface |
| 57 | } |
| 58 | |
| 59 | // getPortMapNFT creates an nftables.Interface for port mapping for the IP family of ipn |
| 60 | func (pmNFT *portMapperNFTables) getPortMapNFT(ipv6 bool) (knftables.Interface, error) { |
| 61 | var err error |
| 62 | if ipv6 { |
| 63 | if pmNFT.ipv6 == nil { |
| 64 | pmNFT.ipv6, err = knftables.New(knftables.IPv6Family, tableName) |
| 65 | if err != nil { |
| 66 | return nil, err |
| 67 | } |
| 68 | } |
| 69 | return pmNFT.ipv6, nil |
| 70 | } |
| 71 | |
| 72 | if pmNFT.ipv4 == nil { |
| 73 | pmNFT.ipv4, err = knftables.New(knftables.IPv4Family, tableName) |
| 74 | if err != nil { |
| 75 | return nil, err |
| 76 | } |
| 77 | } |
| 78 | return pmNFT.ipv4, err |
| 79 | } |
| 80 | |
| 81 | // forwardPorts establishes port forwarding to a given container IP. |
| 82 | // containerNet.IP can be either v4 or v6. |
| 83 | func (pmNFT *portMapperNFTables) forwardPorts(config *PortMapConf, containerNet net.IPNet) error { |
| 84 | isV6 := (containerNet.IP.To4() == nil) |
| 85 | nft, err := pmNFT.getPortMapNFT(isV6) |
| 86 | if err != nil { |
| 87 | return err |
| 88 | } |
| 89 | |
| 90 | var ipX string |
| 91 | var conditions []string |
| 92 | if isV6 { |
| 93 | ipX = "ip6" |
| 94 | if config.ConditionsV6 != nil { |
| 95 | conditions = *config.ConditionsV6 |
| 96 | } |
| 97 | } else if !isV6 { |
| 98 | ipX = "ip" |
| 99 | if config.ConditionsV4 != nil { |
| 100 | conditions = *config.ConditionsV4 |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | tx := nft.NewTransaction() |
| 105 | |
| 106 | // Ensure basic rule structure |
| 107 | tx.Add(&knftables.Table{ |
| 108 | Comment: knftables.PtrTo("CNI portmap plugin"), |
| 109 | }) |
| 110 | |
| 111 | tx.Add(&knftables.Chain{ |
| 112 | Name: hostPortsChain, |
| 113 | }) |
| 114 | |
| 115 | tx.Add(&knftables.Chain{ |
| 116 | Name: hostIPHostPortsChain, |
| 117 | }) |
| 118 | |
| 119 | // setup intermediate chain |
| 120 | tx.Add(&knftables.Chain{ |
| 121 | Name: hostPortsAllChain, |
| 122 | }) |
| 123 | |
| 124 | tx.Flush(&knftables.Chain{ |
| 125 | Name: hostPortsAllChain, |
| 126 | }) |
| 127 | |
| 128 | tx.Add(&knftables.Rule{ |
| 129 | Chain: hostPortsAllChain, |
| 130 | Rule: knftables.Concat( |
| 131 | "jump", hostIPHostPortsChain, |
| 132 | ), |
| 133 | }) |
| 134 | |
| 135 | tx.Add(&knftables.Rule{ |
| 136 | Chain: hostPortsAllChain, |
| 137 | Rule: knftables.Concat( |
| 138 | "jump", hostPortsChain, |
| 139 | ), |
| 140 | }) |
| 141 | |
| 142 | tx.Add(&knftables.Chain{ |
| 143 | Name: "prerouting", |
| 144 | Type: knftables.PtrTo(knftables.NATType), |
| 145 | Hook: knftables.PtrTo(knftables.PreroutingHook), |
| 146 | Priority: knftables.PtrTo(knftables.DNATPriority), |
| 147 | }) |
| 148 | tx.Flush(&knftables.Chain{ |
| 149 | Name: "prerouting", |
| 150 | }) |
| 151 | tx.Add(&knftables.Rule{ |
| 152 | Chain: "prerouting", |
| 153 | Rule: knftables.Concat( |
| 154 | conditions, |
| 155 | "fib daddr type local", |
| 156 | "jump", hostPortsAllChain, |
| 157 | ), |
| 158 | }) |
| 159 | |
| 160 | tx.Add(&knftables.Chain{ |
| 161 | Name: "output", |
| 162 | Type: knftables.PtrTo(knftables.NATType), |
| 163 | Hook: knftables.PtrTo(knftables.OutputHook), |
| 164 | Priority: knftables.PtrTo(knftables.DNATPriority), |
| 165 | }) |
| 166 | tx.Flush(&knftables.Chain{ |
| 167 | Name: "output", |
| 168 | }) |
| 169 | tx.Add(&knftables.Rule{ |
| 170 | Chain: "output", |
| 171 | Rule: knftables.Concat( |
| 172 | conditions, |
| 173 | "fib daddr type local", |
| 174 | "jump", hostPortsAllChain, |
| 175 | ), |
| 176 | }) |
| 177 | |
| 178 | if *config.SNAT { |
| 179 | tx.Add(&knftables.Chain{ |
| 180 | Name: masqueradingChain, |
| 181 | Type: knftables.PtrTo(knftables.NATType), |
| 182 | Hook: knftables.PtrTo(knftables.PostroutingHook), |
| 183 | Priority: knftables.PtrTo(knftables.SNATPriority), |
| 184 | }) |
| 185 | } |
| 186 | |
| 187 | // Set up this container |
| 188 | for _, e := range config.RuntimeConfig.PortMaps { |
| 189 | useHostIP := false |
| 190 | if e.HostIP != "" { |
| 191 | hostIP := net.ParseIP(e.HostIP) |
| 192 | isHostV6 := (hostIP.To4() == nil) |
| 193 | // Ignore wrong-IP-family HostIPs |
| 194 | if isV6 != isHostV6 { |
| 195 | continue |
| 196 | } |
| 197 | |
| 198 | // Unspecified addresses cannot be used as destination |
| 199 | useHostIP = !hostIP.IsUnspecified() |
| 200 | } |
| 201 | |
| 202 | if useHostIP { |
| 203 | // we add the rule to 'hostports' instead of 'hostip_hostports' |
| 204 | // as we want to remove 'hostip_hostports' long-term |
| 205 | tx.Add(&knftables.Rule{ |
| 206 | Chain: hostPortsChain, |
| 207 | Rule: knftables.Concat( |
| 208 | ipX, "daddr", e.HostIP, |
| 209 | e.Protocol, "dport", e.HostPort, |
| 210 | "dnat to", net.JoinHostPort(containerNet.IP.String(), strconv.Itoa(e.ContainerPort)), |
| 211 | ), |
| 212 | Comment: &config.ContainerID, |
| 213 | }) |
| 214 | } else { |
| 215 | tx.Add(&knftables.Rule{ |
| 216 | Chain: hostPortsChain, |
| 217 | Rule: knftables.Concat( |
| 218 | e.Protocol, "dport", e.HostPort, |
| 219 | "dnat to", net.JoinHostPort(containerNet.IP.String(), strconv.Itoa(e.ContainerPort)), |
| 220 | ), |
| 221 | Comment: &config.ContainerID, |
| 222 | }) |
| 223 | } |
| 224 | } |
| 225 | |
| 226 | if *config.SNAT { |
| 227 | // Add mark-to-masquerade rules for hairpin and localhost |
| 228 | // In theory we should validate that the original dst IP and port are as |
| 229 | // expected, but *any* traffic matching one of these patterns would need |
| 230 | // to be masqueraded to be able to work correctly anyway. |
| 231 | tx.Add(&knftables.Rule{ |
| 232 | Chain: masqueradingChain, |
| 233 | Rule: knftables.Concat( |
| 234 | ipX, "saddr", containerNet.IP, |
| 235 | ipX, "daddr", containerNet.IP, |
| 236 | "masquerade", |
| 237 | ), |
| 238 | Comment: &config.ContainerID, |
| 239 | }) |
| 240 | if !isV6 { |
| 241 | tx.Add(&knftables.Rule{ |
| 242 | Chain: masqueradingChain, |
| 243 | Rule: knftables.Concat( |
| 244 | ipX, "saddr 127.0.0.1", |
| 245 | ipX, "daddr", containerNet.IP, |
| 246 | "masquerade", |
| 247 | ), |
| 248 | Comment: &config.ContainerID, |
| 249 | }) |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | err = nft.Run(context.TODO(), tx) |
| 254 | if err != nil { |
| 255 | return fmt.Errorf("unable to set up nftables rules for port mappings: %v", err) |
| 256 | } |
| 257 | |
| 258 | return nil |
| 259 | } |
| 260 | |
| 261 | func (pmNFT *portMapperNFTables) checkPorts(config *PortMapConf, containerNet net.IPNet) error { |
| 262 | isV6 := (containerNet.IP.To4() == nil) |
| 263 | |
| 264 | var hostPorts, masqueradings int |
| 265 | for _, e := range config.RuntimeConfig.PortMaps { |
| 266 | if e.HostIP != "" { |
| 267 | hostIP := net.ParseIP(e.HostIP) |
| 268 | isHostV6 := (hostIP.To4() == nil) |
| 269 | // Ignore wrong-IP-family HostIPs |
| 270 | if isV6 != isHostV6 { |
| 271 | continue |
| 272 | } |
| 273 | } |
| 274 | hostPorts++ |
| 275 | } |
| 276 | if *config.SNAT { |
| 277 | masqueradings = 1 |
| 278 | if !isV6 { |
| 279 | masqueradings *= 2 |
| 280 | } |
| 281 | } |
| 282 | |
| 283 | nft, err := pmNFT.getPortMapNFT(isV6) |
| 284 | if err != nil { |
| 285 | return err |
| 286 | } |
| 287 | if hostPorts > 0 { |
| 288 | err := checkPortsAgainstRules(nft, hostPortsChain, config.ContainerID, hostPorts) |
| 289 | if err != nil { |
| 290 | return err |
| 291 | } |
| 292 | } |
| 293 | if masqueradings > 0 { |
| 294 | err := checkPortsAgainstRules(nft, masqueradingChain, config.ContainerID, masqueradings) |
| 295 | if err != nil { |
| 296 | return err |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | return nil |
| 301 | } |
| 302 | |
| 303 | func checkPortsAgainstRules(nft knftables.Interface, chain, comment string, nPorts int) error { |
| 304 | rules, err := nft.ListRules(context.TODO(), chain) |
| 305 | if err != nil { |
| 306 | return err |
| 307 | } |
| 308 | |
| 309 | found := 0 |
| 310 | for _, r := range rules { |
| 311 | if r.Comment != nil && *r.Comment == comment { |
| 312 | found++ |
| 313 | } |
| 314 | } |
| 315 | if found < nPorts { |
| 316 | return fmt.Errorf("missing hostport rules in %q chain", chain) |
| 317 | } |
| 318 | |
| 319 | return nil |
| 320 | } |
| 321 | |
| 322 | // unforwardPorts deletes any nftables rules created by this plugin. |
| 323 | // It should be idempotent - it will not error if the chain does not exist. |
| 324 | func (pmNFT *portMapperNFTables) unforwardPorts(config *PortMapConf) error { |
| 325 | // Always clear both IPv4 and IPv6, just to be sure |
| 326 | for _, family := range []knftables.Family{knftables.IPv4Family, knftables.IPv6Family} { |
| 327 | nft, err := pmNFT.getPortMapNFT(family == knftables.IPv6Family) |
| 328 | if err != nil { |
| 329 | continue |
| 330 | } |
| 331 | |
| 332 | tx := nft.NewTransaction() |
| 333 | for _, chain := range []string{hostPortsChain, hostIPHostPortsChain, masqueradingChain} { |
| 334 | rules, err := nft.ListRules(context.TODO(), chain) |
| 335 | if err != nil { |
| 336 | if knftables.IsNotFound(err) { |
| 337 | continue |
| 338 | } |
| 339 | return fmt.Errorf("could not list rules in table %s: %w", tableName, err) |
| 340 | } |
| 341 | |
| 342 | for _, r := range rules { |
| 343 | if r.Comment != nil && *r.Comment == config.ContainerID { |
| 344 | tx.Delete(r) |
| 345 | } |
| 346 | } |
| 347 | } |
| 348 | |
| 349 | err = nft.Run(context.TODO(), tx) |
| 350 | if err != nil { |
| 351 | return fmt.Errorf("error deleting nftables rules: %w", err) |
| 352 | } |
| 353 | } |
| 354 | |
| 355 | return nil |
| 356 | } |