| 1 | // Copyright 2017 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 | // This is a post-setup plugin that establishes port forwarding - using iptables, |
| 16 | // from the host's network interface(s) to a pod's network interface. |
| 17 | // |
| 18 | // It is intended to be used as a chained CNI plugin, and determines the container |
| 19 | // IP from the previous result. If the result includes an IPv6 address, it will |
| 20 | // also be configured. (IPTables will not forward cross-family). |
| 21 | // |
| 22 | // This has one notable limitation: it does not perform any kind of reservation |
| 23 | // of the actual host port. If there is a service on the host, it will have all |
| 24 | // its traffic captured by the container. If another container also claims a given |
| 25 | // port, it will caputure the traffic - it is last-write-wins. |
| 26 | package main |
| 27 | |
| 28 | import ( |
| 29 | "encoding/json" |
| 30 | "fmt" |
| 31 | "log" |
| 32 | "net" |
| 33 | |
| 34 | "golang.org/x/sys/unix" |
| 35 | |
| 36 | "github.com/containernetworking/cni/pkg/skel" |
| 37 | "github.com/containernetworking/cni/pkg/types" |
| 38 | current "github.com/containernetworking/cni/pkg/types/100" |
| 39 | "github.com/containernetworking/cni/pkg/version" |
| 40 | "github.com/containernetworking/plugins/pkg/utils" |
| 41 | bv "github.com/containernetworking/plugins/pkg/utils/buildversion" |
| 42 | ) |
| 43 | |
| 44 | type PortMapper interface { |
| 45 | forwardPorts(config *PortMapConf, containerNet net.IPNet) error |
| 46 | checkPorts(config *PortMapConf, containerNet net.IPNet) error |
| 47 | unforwardPorts(config *PortMapConf) error |
| 48 | } |
| 49 | |
| 50 | // These are vars rather than consts so we can "&" them |
| 51 | var ( |
| 52 | iptablesBackend = "iptables" |
| 53 | nftablesBackend = "nftables" |
| 54 | ) |
| 55 | |
| 56 | // PortMapEntry corresponds to a single entry in the port_mappings argument, |
| 57 | // see CONVENTIONS.md |
| 58 | type PortMapEntry struct { |
| 59 | HostPort int `json:"hostPort"` |
| 60 | ContainerPort int `json:"containerPort"` |
| 61 | Protocol string `json:"protocol"` |
| 62 | HostIP string `json:"hostIP,omitempty"` |
| 63 | } |
| 64 | |
| 65 | type PortMapConf struct { |
| 66 | types.NetConf |
| 67 | |
| 68 | mapper PortMapper |
| 69 | |
| 70 | // Generic config |
| 71 | Backend *string `json:"backend,omitempty"` |
| 72 | SNAT *bool `json:"snat,omitempty"` |
| 73 | ConditionsV4 *[]string `json:"conditionsV4"` |
| 74 | ConditionsV6 *[]string `json:"conditionsV6"` |
| 75 | MasqAll bool `json:"masqAll,omitempty"` |
| 76 | MarkMasqBit *int `json:"markMasqBit"` |
| 77 | RuntimeConfig struct { |
| 78 | PortMaps []PortMapEntry `json:"portMappings,omitempty"` |
| 79 | } `json:"runtimeConfig,omitempty"` |
| 80 | |
| 81 | // iptables-backend-specific config |
| 82 | ExternalSetMarkChain *string `json:"externalSetMarkChain"` |
| 83 | |
| 84 | // These are fields parsed out of the config or the environment; |
| 85 | // included here for convenience |
| 86 | ContainerID string `json:"-"` |
| 87 | ContIPv4 net.IPNet `json:"-"` |
| 88 | ContIPv6 net.IPNet `json:"-"` |
| 89 | } |
| 90 | |
| 91 | // The default mark bit to signal that masquerading is required |
| 92 | // Kubernetes uses 14 and 15, Calico uses 20-31. |
| 93 | const DefaultMarkBit = 13 |
| 94 | |
| 95 | func cmdAdd(args *skel.CmdArgs) error { |
| 96 | netConf, _, err := parseConfig(args.StdinData, args.IfName) |
| 97 | if err != nil { |
| 98 | return fmt.Errorf("failed to parse config: %v", err) |
| 99 | } |
| 100 | |
| 101 | if netConf.PrevResult == nil { |
| 102 | return fmt.Errorf("must be called as chained plugin") |
| 103 | } |
| 104 | |
| 105 | if len(netConf.RuntimeConfig.PortMaps) == 0 { |
| 106 | return types.PrintResult(netConf.PrevResult, netConf.CNIVersion) |
| 107 | } |
| 108 | |
| 109 | netConf.ContainerID = args.ContainerID |
| 110 | |
| 111 | if netConf.ContIPv4.IP != nil { |
| 112 | if err := netConf.mapper.forwardPorts(netConf, netConf.ContIPv4); err != nil { |
| 113 | return err |
| 114 | } |
| 115 | // Delete conntrack entries for UDP to avoid conntrack blackholing traffic |
| 116 | // due to stale connections. We do that after the iptables rules are set, so |
| 117 | // the new traffic uses them. Failures are informative only. |
| 118 | if err := deletePortmapStaleConnections(netConf.RuntimeConfig.PortMaps, unix.AF_INET); err != nil { |
| 119 | log.Printf("failed to delete stale UDP conntrack entries for %s: %v", netConf.ContIPv4.IP, err) |
| 120 | } |
| 121 | |
| 122 | if *netConf.SNAT { |
| 123 | // Set the route_localnet bit on the host interface, so that |
| 124 | // 127/8 can cross a routing boundary. |
| 125 | hostIfName := getRoutableHostIF(netConf.ContIPv4.IP) |
| 126 | if hostIfName != "" { |
| 127 | if err := enableLocalnetRouting(hostIfName); err != nil { |
| 128 | return fmt.Errorf("unable to enable route_localnet: %v", err) |
| 129 | } |
| 130 | } |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | if netConf.ContIPv6.IP != nil { |
| 135 | if err := netConf.mapper.forwardPorts(netConf, netConf.ContIPv6); err != nil { |
| 136 | return err |
| 137 | } |
| 138 | // Delete conntrack entries for UDP to avoid conntrack blackholing traffic |
| 139 | // due to stale connections. We do that after the iptables rules are set, so |
| 140 | // the new traffic uses them. Failures are informative only. |
| 141 | if err := deletePortmapStaleConnections(netConf.RuntimeConfig.PortMaps, unix.AF_INET6); err != nil { |
| 142 | log.Printf("failed to delete stale UDP conntrack entries for %s: %v", netConf.ContIPv6.IP, err) |
| 143 | } |
| 144 | } |
| 145 | |
| 146 | // Pass through the previous result |
| 147 | return types.PrintResult(netConf.PrevResult, netConf.CNIVersion) |
| 148 | } |
| 149 | |
| 150 | func cmdDel(args *skel.CmdArgs) error { |
| 151 | netConf, _, err := parseConfig(args.StdinData, args.IfName) |
| 152 | if err != nil { |
| 153 | return fmt.Errorf("failed to parse config: %v", err) |
| 154 | } |
| 155 | |
| 156 | if len(netConf.RuntimeConfig.PortMaps) == 0 { |
| 157 | return nil |
| 158 | } |
| 159 | |
| 160 | netConf.ContainerID = args.ContainerID |
| 161 | |
| 162 | // We don't need to parse out whether or not we're using v6 or snat, |
| 163 | // deletion is idempotent |
| 164 | return netConf.mapper.unforwardPorts(netConf) |
| 165 | } |
| 166 | |
| 167 | func main() { |
| 168 | skel.PluginMainFuncs(skel.CNIFuncs{ |
| 169 | Add: cmdAdd, |
| 170 | Check: cmdCheck, |
| 171 | Del: cmdDel, |
| 172 | /* FIXME GC */ |
| 173 | /* FIXME Status */ |
| 174 | }, version.All, bv.BuildString("portmap")) |
| 175 | } |
| 176 | |
| 177 | func cmdCheck(args *skel.CmdArgs) error { |
| 178 | conf, result, err := parseConfig(args.StdinData, args.IfName) |
| 179 | if err != nil { |
| 180 | return err |
| 181 | } |
| 182 | |
| 183 | // Ensure we have previous result. |
| 184 | if result == nil { |
| 185 | return fmt.Errorf("Required prevResult missing") |
| 186 | } |
| 187 | |
| 188 | if len(conf.RuntimeConfig.PortMaps) == 0 { |
| 189 | return nil |
| 190 | } |
| 191 | |
| 192 | conf.ContainerID = args.ContainerID |
| 193 | |
| 194 | if conf.ContIPv4.IP != nil { |
| 195 | if err := conf.mapper.checkPorts(conf, conf.ContIPv4); err != nil { |
| 196 | return err |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | if conf.ContIPv6.IP != nil { |
| 201 | if err := conf.mapper.checkPorts(conf, conf.ContIPv6); err != nil { |
| 202 | return err |
| 203 | } |
| 204 | } |
| 205 | |
| 206 | return nil |
| 207 | } |
| 208 | |
| 209 | // parseConfig parses the supplied configuration (and prevResult) from stdin. |
| 210 | func parseConfig(stdin []byte, ifName string) (*PortMapConf, *current.Result, error) { |
| 211 | conf := PortMapConf{} |
| 212 | |
| 213 | if err := json.Unmarshal(stdin, &conf); err != nil { |
| 214 | return nil, nil, fmt.Errorf("failed to parse network configuration: %v", err) |
| 215 | } |
| 216 | |
| 217 | // Parse previous result. |
| 218 | var result *current.Result |
| 219 | if conf.RawPrevResult != nil { |
| 220 | var err error |
| 221 | if err = version.ParsePrevResult(&conf.NetConf); err != nil { |
| 222 | return nil, nil, fmt.Errorf("could not parse prevResult: %v", err) |
| 223 | } |
| 224 | |
| 225 | result, err = current.NewResultFromResult(conf.PrevResult) |
| 226 | if err != nil { |
| 227 | return nil, nil, fmt.Errorf("could not convert result to current version: %v", err) |
| 228 | } |
| 229 | } |
| 230 | |
| 231 | conf.mapper = &portMapperIPTables{} |
| 232 | |
| 233 | if conf.SNAT == nil { |
| 234 | tvar := true |
| 235 | conf.SNAT = &tvar |
| 236 | } |
| 237 | |
| 238 | if conf.MarkMasqBit != nil && conf.ExternalSetMarkChain != nil { |
| 239 | return nil, nil, fmt.Errorf("Cannot specify externalSetMarkChain and markMasqBit") |
| 240 | } |
| 241 | |
| 242 | if conf.MarkMasqBit == nil { |
| 243 | bvar := DefaultMarkBit // go constants are "special" |
| 244 | conf.MarkMasqBit = &bvar |
| 245 | } |
| 246 | |
| 247 | if *conf.MarkMasqBit < 0 || *conf.MarkMasqBit > 31 { |
| 248 | return nil, nil, fmt.Errorf("MasqMarkBit must be between 0 and 31") |
| 249 | } |
| 250 | |
| 251 | err := ensureBackend(&conf) |
| 252 | if err != nil { |
| 253 | return nil, nil, err |
| 254 | } |
| 255 | switch *conf.Backend { |
| 256 | case iptablesBackend: |
| 257 | conf.mapper = &portMapperIPTables{} |
| 258 | |
| 259 | case nftablesBackend: |
| 260 | conf.mapper = &portMapperNFTables{} |
| 261 | |
| 262 | default: |
| 263 | return nil, nil, fmt.Errorf("unrecognized backend %q", *conf.Backend) |
| 264 | } |
| 265 | |
| 266 | // Reject invalid port numbers |
| 267 | for _, pm := range conf.RuntimeConfig.PortMaps { |
| 268 | if pm.ContainerPort <= 0 { |
| 269 | return nil, nil, fmt.Errorf("Invalid container port number: %d", pm.ContainerPort) |
| 270 | } |
| 271 | if pm.HostPort <= 0 { |
| 272 | return nil, nil, fmt.Errorf("Invalid host port number: %d", pm.HostPort) |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | if conf.PrevResult != nil { |
| 277 | for _, ip := range result.IPs { |
| 278 | isIPv4 := ip.Address.IP.To4() != nil |
| 279 | if !isIPv4 && conf.ContIPv6.IP != nil { |
| 280 | continue |
| 281 | } else if isIPv4 && conf.ContIPv4.IP != nil { |
| 282 | continue |
| 283 | } |
| 284 | |
| 285 | // Skip known non-sandbox interfaces |
| 286 | if ip.Interface != nil { |
| 287 | intIdx := *ip.Interface |
| 288 | if intIdx >= 0 && |
| 289 | intIdx < len(result.Interfaces) && |
| 290 | (result.Interfaces[intIdx].Name != ifName || |
| 291 | result.Interfaces[intIdx].Sandbox == "") { |
| 292 | continue |
| 293 | } |
| 294 | } |
| 295 | if ip.Address.IP.To4() != nil { |
| 296 | conf.ContIPv4 = ip.Address |
| 297 | } else { |
| 298 | conf.ContIPv6 = ip.Address |
| 299 | } |
| 300 | } |
| 301 | } |
| 302 | |
| 303 | return &conf, result, nil |
| 304 | } |
| 305 | |
| 306 | // ensureBackend validates and/or sets conf.Backend |
| 307 | func ensureBackend(conf *PortMapConf) error { |
| 308 | backendConfig := make(map[string][]string) |
| 309 | |
| 310 | if conf.ExternalSetMarkChain != nil { |
| 311 | backendConfig[iptablesBackend] = append(backendConfig[iptablesBackend], "externalSetMarkChain") |
| 312 | } |
| 313 | if conditionsBackend := detectBackendOfConditions(conf.ConditionsV4); conditionsBackend != "" { |
| 314 | backendConfig[conditionsBackend] = append(backendConfig[conditionsBackend], "conditionsV4") |
| 315 | } |
| 316 | if conditionsBackend := detectBackendOfConditions(conf.ConditionsV6); conditionsBackend != "" { |
| 317 | backendConfig[conditionsBackend] = append(backendConfig[conditionsBackend], "conditionsV6") |
| 318 | } |
| 319 | |
| 320 | // If backend wasn't requested explicitly, default to iptables, unless it is not |
| 321 | // available (and nftables is). FIXME: flip this default at some point. |
| 322 | if conf.Backend == nil { |
| 323 | if !utils.SupportsIPTables() && utils.SupportsNFTables() { |
| 324 | conf.Backend = &nftablesBackend |
| 325 | } else { |
| 326 | conf.Backend = &iptablesBackend |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | // Make sure we dont have config for the wrong backend |
| 331 | var wrongBackend string |
| 332 | if *conf.Backend == iptablesBackend { |
| 333 | wrongBackend = nftablesBackend |
| 334 | } else { |
| 335 | wrongBackend = iptablesBackend |
| 336 | } |
| 337 | if len(backendConfig[wrongBackend]) > 0 { |
| 338 | return fmt.Errorf("%s backend was requested but configuration contains %s-specific options %v", *conf.Backend, wrongBackend, backendConfig[wrongBackend]) |
| 339 | } |
| 340 | |
| 341 | // OK |
| 342 | return nil |
| 343 | } |
| 344 | |
| 345 | // detectBackendOfConditions returns "iptables" if conditions contains iptables |
| 346 | // conditions, "nftables" if it contains nftables conditions, and "" if it is empty. |
| 347 | func detectBackendOfConditions(conditions *[]string) string { |
| 348 | if conditions == nil || len(*conditions) == 0 || (*conditions)[0] == "" { |
| 349 | return "" |
| 350 | } |
| 351 | |
| 352 | // The first character of any iptables condition would either be an hyphen |
| 353 | // (e.g. "-d", "--sport", "-m") or an exclamation mark. |
| 354 | // No nftables condition would start that way. (An nftables condition might |
| 355 | // include a negative number, but not as the first token.) |
| 356 | if (*conditions)[0][0] == '-' || (*conditions)[0][0] == '!' { |
| 357 | return iptablesBackend |
| 358 | } |
| 359 | return nftablesBackend |
| 360 | } |