utils.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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 util
  14. import (
  15. "context"
  16. "errors"
  17. "fmt"
  18. "net"
  19. "k8s.io/api/core/v1"
  20. "k8s.io/apimachinery/pkg/types"
  21. "k8s.io/apimachinery/pkg/util/sets"
  22. "k8s.io/client-go/tools/record"
  23. helper "k8s.io/kubernetes/pkg/apis/core/v1/helper"
  24. utilnet "k8s.io/utils/net"
  25. "k8s.io/klog"
  26. )
  27. const (
  28. // IPv4ZeroCIDR is the CIDR block for the whole IPv4 address space
  29. IPv4ZeroCIDR = "0.0.0.0/0"
  30. // IPv6ZeroCIDR is the CIDR block for the whole IPv6 address space
  31. IPv6ZeroCIDR = "::/0"
  32. )
  33. var (
  34. // ErrAddressNotAllowed indicates the address is not allowed
  35. ErrAddressNotAllowed = errors.New("address not allowed")
  36. // ErrNoAddresses indicates there are no addresses for the hostname
  37. ErrNoAddresses = errors.New("No addresses for hostname")
  38. )
  39. // IsZeroCIDR checks whether the input CIDR string is either
  40. // the IPv4 or IPv6 zero CIDR
  41. func IsZeroCIDR(cidr string) bool {
  42. if cidr == IPv4ZeroCIDR || cidr == IPv6ZeroCIDR {
  43. return true
  44. }
  45. return false
  46. }
  47. // IsProxyableIP checks if a given IP address is permitted to be proxied
  48. func IsProxyableIP(ip string) error {
  49. netIP := net.ParseIP(ip)
  50. if netIP == nil {
  51. return ErrAddressNotAllowed
  52. }
  53. return isProxyableIP(netIP)
  54. }
  55. func isProxyableIP(ip net.IP) error {
  56. if ip.IsLoopback() || ip.IsLinkLocalUnicast() || ip.IsLinkLocalMulticast() || ip.IsInterfaceLocalMulticast() {
  57. return ErrAddressNotAllowed
  58. }
  59. return nil
  60. }
  61. // Resolver is an interface for net.Resolver
  62. type Resolver interface {
  63. LookupIPAddr(ctx context.Context, host string) ([]net.IPAddr, error)
  64. }
  65. // IsProxyableHostname checks if the IP addresses for a given hostname are permitted to be proxied
  66. func IsProxyableHostname(ctx context.Context, resolv Resolver, hostname string) error {
  67. resp, err := resolv.LookupIPAddr(ctx, hostname)
  68. if err != nil {
  69. return err
  70. }
  71. if len(resp) == 0 {
  72. return ErrNoAddresses
  73. }
  74. for _, host := range resp {
  75. if err := isProxyableIP(host.IP); err != nil {
  76. return err
  77. }
  78. }
  79. return nil
  80. }
  81. // IsLocalIP checks if a given IP address is bound to an interface
  82. // on the local system
  83. func IsLocalIP(ip string) (bool, error) {
  84. addrs, err := net.InterfaceAddrs()
  85. if err != nil {
  86. return false, err
  87. }
  88. for i := range addrs {
  89. intf, _, err := net.ParseCIDR(addrs[i].String())
  90. if err != nil {
  91. return false, err
  92. }
  93. if net.ParseIP(ip).Equal(intf) {
  94. return true, nil
  95. }
  96. }
  97. return false, nil
  98. }
  99. // ShouldSkipService checks if a given service should skip proxying
  100. func ShouldSkipService(svcName types.NamespacedName, service *v1.Service) bool {
  101. // if ClusterIP is "None" or empty, skip proxying
  102. if !helper.IsServiceIPSet(service) {
  103. klog.V(3).Infof("Skipping service %s due to clusterIP = %q", svcName, service.Spec.ClusterIP)
  104. return true
  105. }
  106. // Even if ClusterIP is set, ServiceTypeExternalName services don't get proxied
  107. if service.Spec.Type == v1.ServiceTypeExternalName {
  108. klog.V(3).Infof("Skipping service %s due to Type=ExternalName", svcName)
  109. return true
  110. }
  111. return false
  112. }
  113. // GetNodeAddresses return all matched node IP addresses based on given cidr slice.
  114. // Some callers, e.g. IPVS proxier, need concrete IPs, not ranges, which is why this exists.
  115. // NetworkInterfacer is injected for test purpose.
  116. // We expect the cidrs passed in is already validated.
  117. // Given an empty input `[]`, it will return `0.0.0.0/0` and `::/0` directly.
  118. // If multiple cidrs is given, it will return the minimal IP sets, e.g. given input `[1.2.0.0/16, 0.0.0.0/0]`, it will
  119. // only return `0.0.0.0/0`.
  120. // NOTE: GetNodeAddresses only accepts CIDRs, if you want concrete IPs, e.g. 1.2.3.4, then the input should be 1.2.3.4/32.
  121. func GetNodeAddresses(cidrs []string, nw NetworkInterfacer) (sets.String, error) {
  122. uniqueAddressList := sets.NewString()
  123. if len(cidrs) == 0 {
  124. uniqueAddressList.Insert(IPv4ZeroCIDR)
  125. uniqueAddressList.Insert(IPv6ZeroCIDR)
  126. return uniqueAddressList, nil
  127. }
  128. // First round of iteration to pick out `0.0.0.0/0` or `::/0` for the sake of excluding non-zero IPs.
  129. for _, cidr := range cidrs {
  130. if IsZeroCIDR(cidr) {
  131. uniqueAddressList.Insert(cidr)
  132. }
  133. }
  134. // Second round of iteration to parse IPs based on cidr.
  135. for _, cidr := range cidrs {
  136. if IsZeroCIDR(cidr) {
  137. continue
  138. }
  139. _, ipNet, _ := net.ParseCIDR(cidr)
  140. itfs, err := nw.Interfaces()
  141. if err != nil {
  142. return nil, fmt.Errorf("error listing all interfaces from host, error: %v", err)
  143. }
  144. for _, itf := range itfs {
  145. addrs, err := nw.Addrs(&itf)
  146. if err != nil {
  147. return nil, fmt.Errorf("error getting address from interface %s, error: %v", itf.Name, err)
  148. }
  149. for _, addr := range addrs {
  150. if addr == nil {
  151. continue
  152. }
  153. ip, _, err := net.ParseCIDR(addr.String())
  154. if err != nil {
  155. return nil, fmt.Errorf("error parsing CIDR for interface %s, error: %v", itf.Name, err)
  156. }
  157. if ipNet.Contains(ip) {
  158. if utilnet.IsIPv6(ip) && !uniqueAddressList.Has(IPv6ZeroCIDR) {
  159. uniqueAddressList.Insert(ip.String())
  160. }
  161. if !utilnet.IsIPv6(ip) && !uniqueAddressList.Has(IPv4ZeroCIDR) {
  162. uniqueAddressList.Insert(ip.String())
  163. }
  164. }
  165. }
  166. }
  167. }
  168. return uniqueAddressList, nil
  169. }
  170. // LogAndEmitIncorrectIPVersionEvent logs and emits incorrect IP version event.
  171. func LogAndEmitIncorrectIPVersionEvent(recorder record.EventRecorder, fieldName, fieldValue, svcNamespace, svcName string, svcUID types.UID) {
  172. errMsg := fmt.Sprintf("%s in %s has incorrect IP version", fieldValue, fieldName)
  173. klog.Errorf("%s (service %s/%s).", errMsg, svcNamespace, svcName)
  174. if recorder != nil {
  175. recorder.Eventf(
  176. &v1.ObjectReference{
  177. Kind: "Service",
  178. Name: svcName,
  179. Namespace: svcNamespace,
  180. UID: svcUID,
  181. }, v1.EventTypeWarning, "KubeProxyIncorrectIPVersion", errMsg)
  182. }
  183. }
  184. // FilterIncorrectIPVersion filters out the incorrect IP version case from a slice of IP strings.
  185. func FilterIncorrectIPVersion(ipStrings []string, isIPv6Mode bool) ([]string, []string) {
  186. return filterWithCondition(ipStrings, isIPv6Mode, utilnet.IsIPv6String)
  187. }
  188. // FilterIncorrectCIDRVersion filters out the incorrect IP version case from a slice of CIDR strings.
  189. func FilterIncorrectCIDRVersion(ipStrings []string, isIPv6Mode bool) ([]string, []string) {
  190. return filterWithCondition(ipStrings, isIPv6Mode, utilnet.IsIPv6CIDRString)
  191. }
  192. func filterWithCondition(strs []string, expectedCondition bool, conditionFunc func(string) bool) ([]string, []string) {
  193. var corrects, incorrects []string
  194. for _, str := range strs {
  195. if conditionFunc(str) != expectedCondition {
  196. incorrects = append(incorrects, str)
  197. } else {
  198. corrects = append(corrects, str)
  199. }
  200. }
  201. return corrects, incorrects
  202. }
  203. // AppendPortIfNeeded appends the given port to IP address unless it is already in
  204. // "ipv4:port" or "[ipv6]:port" format.
  205. func AppendPortIfNeeded(addr string, port int32) string {
  206. // Return if address is already in "ipv4:port" or "[ipv6]:port" format.
  207. if _, _, err := net.SplitHostPort(addr); err == nil {
  208. return addr
  209. }
  210. // Simply return for invalid case. This should be caught by validation instead.
  211. ip := net.ParseIP(addr)
  212. if ip == nil {
  213. return addr
  214. }
  215. // Append port to address.
  216. if ip.To4() != nil {
  217. return fmt.Sprintf("%s:%d", addr, port)
  218. }
  219. return fmt.Sprintf("[%s]:%d", addr, port)
  220. }