hostport.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. /*
  2. Copyright 2017 The Kubernetes Authors.
  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. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package hostport
  14. import (
  15. "fmt"
  16. "net"
  17. "strings"
  18. "k8s.io/klog"
  19. "k8s.io/api/core/v1"
  20. utiliptables "k8s.io/kubernetes/pkg/util/iptables"
  21. )
  22. const (
  23. // the hostport chain
  24. kubeHostportsChain utiliptables.Chain = "KUBE-HOSTPORTS"
  25. // prefix for hostport chains
  26. kubeHostportChainPrefix string = "KUBE-HP-"
  27. )
  28. // PortMapping represents a network port in a container
  29. type PortMapping struct {
  30. Name string
  31. HostPort int32
  32. ContainerPort int32
  33. Protocol v1.Protocol
  34. HostIP string
  35. }
  36. // PodPortMapping represents a pod's network state and associated container port mappings
  37. type PodPortMapping struct {
  38. Namespace string
  39. Name string
  40. PortMappings []*PortMapping
  41. HostNetwork bool
  42. IP net.IP
  43. }
  44. type hostport struct {
  45. port int32
  46. protocol string
  47. }
  48. type hostportOpener func(*hostport) (closeable, error)
  49. type closeable interface {
  50. Close() error
  51. }
  52. func openLocalPort(hp *hostport) (closeable, error) {
  53. // For ports on node IPs, open the actual port and hold it, even though we
  54. // use iptables to redirect traffic.
  55. // This ensures a) that it's safe to use that port and b) that (a) stays
  56. // true. The risk is that some process on the node (e.g. sshd or kubelet)
  57. // is using a port and we give that same port out to a Service. That would
  58. // be bad because iptables would silently claim the traffic but the process
  59. // would never know.
  60. // NOTE: We should not need to have a real listen()ing socket - bind()
  61. // should be enough, but I can't figure out a way to e2e test without
  62. // it. Tools like 'ss' and 'netstat' do not show sockets that are
  63. // bind()ed but not listen()ed, and at least the default debian netcat
  64. // has no way to avoid about 10 seconds of retries.
  65. var socket closeable
  66. switch hp.protocol {
  67. case "tcp":
  68. listener, err := net.Listen("tcp", fmt.Sprintf(":%d", hp.port))
  69. if err != nil {
  70. return nil, err
  71. }
  72. socket = listener
  73. case "udp":
  74. addr, err := net.ResolveUDPAddr("udp", fmt.Sprintf(":%d", hp.port))
  75. if err != nil {
  76. return nil, err
  77. }
  78. conn, err := net.ListenUDP("udp", addr)
  79. if err != nil {
  80. return nil, err
  81. }
  82. socket = conn
  83. default:
  84. return nil, fmt.Errorf("unknown protocol %q", hp.protocol)
  85. }
  86. klog.V(3).Infof("Opened local port %s", hp.String())
  87. return socket, nil
  88. }
  89. // portMappingToHostport creates hostport structure based on input portmapping
  90. func portMappingToHostport(portMapping *PortMapping) hostport {
  91. return hostport{
  92. port: portMapping.HostPort,
  93. protocol: strings.ToLower(string(portMapping.Protocol)),
  94. }
  95. }
  96. // ensureKubeHostportChains ensures the KUBE-HOSTPORTS chain is setup correctly
  97. func ensureKubeHostportChains(iptables utiliptables.Interface, natInterfaceName string) error {
  98. klog.V(4).Info("Ensuring kubelet hostport chains")
  99. // Ensure kubeHostportChain
  100. if _, err := iptables.EnsureChain(utiliptables.TableNAT, kubeHostportsChain); err != nil {
  101. return fmt.Errorf("Failed to ensure that %s chain %s exists: %v", utiliptables.TableNAT, kubeHostportsChain, err)
  102. }
  103. tableChainsNeedJumpServices := []struct {
  104. table utiliptables.Table
  105. chain utiliptables.Chain
  106. }{
  107. {utiliptables.TableNAT, utiliptables.ChainOutput},
  108. {utiliptables.TableNAT, utiliptables.ChainPrerouting},
  109. }
  110. args := []string{"-m", "comment", "--comment", "kube hostport portals",
  111. "-m", "addrtype", "--dst-type", "LOCAL",
  112. "-j", string(kubeHostportsChain)}
  113. for _, tc := range tableChainsNeedJumpServices {
  114. // KUBE-HOSTPORTS chain needs to be appended to the system chains.
  115. // This ensures KUBE-SERVICES chain gets processed first.
  116. // Since rules in KUBE-HOSTPORTS chain matches broader cases, allow the more specific rules to be processed first.
  117. if _, err := iptables.EnsureRule(utiliptables.Append, tc.table, tc.chain, args...); err != nil {
  118. return fmt.Errorf("Failed to ensure that %s chain %s jumps to %s: %v", tc.table, tc.chain, kubeHostportsChain, err)
  119. }
  120. }
  121. // Need to SNAT traffic from localhost
  122. args = []string{"-m", "comment", "--comment", "SNAT for localhost access to hostports", "-o", natInterfaceName, "-s", "127.0.0.0/8", "-j", "MASQUERADE"}
  123. if _, err := iptables.EnsureRule(utiliptables.Append, utiliptables.TableNAT, utiliptables.ChainPostrouting, args...); err != nil {
  124. return fmt.Errorf("Failed to ensure that %s chain %s jumps to MASQUERADE: %v", utiliptables.TableNAT, utiliptables.ChainPostrouting, err)
  125. }
  126. return nil
  127. }