firewall.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. /*
  2. Copyright 2016 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 gce
  14. import (
  15. "fmt"
  16. "net/http"
  17. "strconv"
  18. "strings"
  19. "time"
  20. compute "google.golang.org/api/compute/v1"
  21. "k8s.io/api/core/v1"
  22. "k8s.io/apimachinery/pkg/util/sets"
  23. "k8s.io/apimachinery/pkg/util/wait"
  24. cloudprovider "k8s.io/cloud-provider"
  25. "k8s.io/kubernetes/test/e2e/framework"
  26. gcecloud "k8s.io/legacy-cloud-providers/gce"
  27. )
  28. // MakeFirewallNameForLBService return the expected firewall name for a LB service.
  29. // This should match the formatting of makeFirewallName() in pkg/cloudprovider/providers/gce/gce_loadbalancer.go
  30. func MakeFirewallNameForLBService(name string) string {
  31. return fmt.Sprintf("k8s-fw-%s", name)
  32. }
  33. // ConstructFirewallForLBService returns the expected GCE firewall rule for a loadbalancer type service
  34. func ConstructFirewallForLBService(svc *v1.Service, nodeTag string) *compute.Firewall {
  35. if svc.Spec.Type != v1.ServiceTypeLoadBalancer {
  36. framework.Failf("can not construct firewall rule for non-loadbalancer type service")
  37. }
  38. fw := compute.Firewall{}
  39. fw.Name = MakeFirewallNameForLBService(cloudprovider.DefaultLoadBalancerName(svc))
  40. fw.TargetTags = []string{nodeTag}
  41. if svc.Spec.LoadBalancerSourceRanges == nil {
  42. fw.SourceRanges = []string{"0.0.0.0/0"}
  43. } else {
  44. fw.SourceRanges = svc.Spec.LoadBalancerSourceRanges
  45. }
  46. for _, sp := range svc.Spec.Ports {
  47. fw.Allowed = append(fw.Allowed, &compute.FirewallAllowed{
  48. IPProtocol: strings.ToLower(string(sp.Protocol)),
  49. Ports: []string{strconv.Itoa(int(sp.Port))},
  50. })
  51. }
  52. return &fw
  53. }
  54. // MakeHealthCheckFirewallNameForLBService returns the firewall name used by the GCE load
  55. // balancers for performing health checks.
  56. func MakeHealthCheckFirewallNameForLBService(clusterID, name string, isNodesHealthCheck bool) string {
  57. return gcecloud.MakeHealthCheckFirewallName(clusterID, name, isNodesHealthCheck)
  58. }
  59. // ConstructHealthCheckFirewallForLBService returns the expected GCE firewall rule for a loadbalancer type service
  60. func ConstructHealthCheckFirewallForLBService(clusterID string, svc *v1.Service, nodeTag string, isNodesHealthCheck bool) *compute.Firewall {
  61. if svc.Spec.Type != v1.ServiceTypeLoadBalancer {
  62. framework.Failf("can not construct firewall rule for non-loadbalancer type service")
  63. }
  64. fw := compute.Firewall{}
  65. fw.Name = MakeHealthCheckFirewallNameForLBService(clusterID, cloudprovider.DefaultLoadBalancerName(svc), isNodesHealthCheck)
  66. fw.TargetTags = []string{nodeTag}
  67. fw.SourceRanges = gcecloud.L4LoadBalancerSrcRanges()
  68. healthCheckPort := gcecloud.GetNodesHealthCheckPort()
  69. if !isNodesHealthCheck {
  70. healthCheckPort = svc.Spec.HealthCheckNodePort
  71. }
  72. fw.Allowed = []*compute.FirewallAllowed{
  73. {
  74. IPProtocol: "tcp",
  75. Ports: []string{fmt.Sprintf("%d", healthCheckPort)},
  76. },
  77. }
  78. return &fw
  79. }
  80. // GetInstancePrefix returns the INSTANCE_PREFIX env we set for e2e cluster.
  81. // From cluster/gce/config-test.sh, master name is set up using below format:
  82. // MASTER_NAME="${INSTANCE_PREFIX}-master"
  83. func GetInstancePrefix(masterName string) (string, error) {
  84. if !strings.HasSuffix(masterName, "-master") {
  85. return "", fmt.Errorf("unexpected master name format: %v", masterName)
  86. }
  87. return masterName[:len(masterName)-7], nil
  88. }
  89. // GetClusterName returns the CLUSTER_NAME env we set for e2e cluster.
  90. // From cluster/gce/config-test.sh, cluster name is set up using below format:
  91. // CLUSTER_NAME="${CLUSTER_NAME:-${INSTANCE_PREFIX}}"
  92. func GetClusterName(instancePrefix string) string {
  93. return instancePrefix
  94. }
  95. // GetE2eFirewalls returns all firewall rules we create for an e2e cluster.
  96. // From cluster/gce/util.sh, all firewall rules should be consistent with the ones created by startup scripts.
  97. func GetE2eFirewalls(masterName, masterTag, nodeTag, network, clusterIPRange string) []*compute.Firewall {
  98. instancePrefix, err := GetInstancePrefix(masterName)
  99. framework.ExpectNoError(err)
  100. clusterName := GetClusterName(instancePrefix)
  101. fws := []*compute.Firewall{}
  102. fws = append(fws, &compute.Firewall{
  103. Name: clusterName + "-default-internal-master",
  104. SourceRanges: []string{"10.0.0.0/8"},
  105. TargetTags: []string{masterTag},
  106. Allowed: []*compute.FirewallAllowed{
  107. {
  108. IPProtocol: "tcp",
  109. Ports: []string{"1-2379"},
  110. },
  111. {
  112. IPProtocol: "tcp",
  113. Ports: []string{"2382-65535"},
  114. },
  115. {
  116. IPProtocol: "udp",
  117. Ports: []string{"1-65535"},
  118. },
  119. {
  120. IPProtocol: "icmp",
  121. },
  122. },
  123. })
  124. fws = append(fws, &compute.Firewall{
  125. Name: clusterName + "-default-internal-node",
  126. SourceRanges: []string{"10.0.0.0/8"},
  127. TargetTags: []string{nodeTag},
  128. Allowed: []*compute.FirewallAllowed{
  129. {
  130. IPProtocol: "tcp",
  131. Ports: []string{"1-65535"},
  132. },
  133. {
  134. IPProtocol: "udp",
  135. Ports: []string{"1-65535"},
  136. },
  137. {
  138. IPProtocol: "icmp",
  139. },
  140. },
  141. })
  142. fws = append(fws, &compute.Firewall{
  143. Name: network + "-default-ssh",
  144. SourceRanges: []string{"0.0.0.0/0"},
  145. Allowed: []*compute.FirewallAllowed{
  146. {
  147. IPProtocol: "tcp",
  148. Ports: []string{"22"},
  149. },
  150. },
  151. })
  152. fws = append(fws, &compute.Firewall{
  153. Name: masterName + "-etcd",
  154. SourceTags: []string{masterTag},
  155. TargetTags: []string{masterTag},
  156. Allowed: []*compute.FirewallAllowed{
  157. {
  158. IPProtocol: "tcp",
  159. Ports: []string{"2380"},
  160. },
  161. {
  162. IPProtocol: "tcp",
  163. Ports: []string{"2381"},
  164. },
  165. },
  166. })
  167. fws = append(fws, &compute.Firewall{
  168. Name: masterName + "-https",
  169. SourceRanges: []string{"0.0.0.0/0"},
  170. TargetTags: []string{masterTag},
  171. Allowed: []*compute.FirewallAllowed{
  172. {
  173. IPProtocol: "tcp",
  174. Ports: []string{"443"},
  175. },
  176. },
  177. })
  178. fws = append(fws, &compute.Firewall{
  179. Name: nodeTag + "-all",
  180. SourceRanges: []string{clusterIPRange},
  181. TargetTags: []string{nodeTag},
  182. Allowed: []*compute.FirewallAllowed{
  183. {
  184. IPProtocol: "tcp",
  185. },
  186. {
  187. IPProtocol: "udp",
  188. },
  189. {
  190. IPProtocol: "icmp",
  191. },
  192. {
  193. IPProtocol: "esp",
  194. },
  195. {
  196. IPProtocol: "ah",
  197. },
  198. {
  199. IPProtocol: "sctp",
  200. },
  201. },
  202. })
  203. fws = append(fws, &compute.Firewall{
  204. Name: nodeTag + "-http-alt",
  205. SourceRanges: []string{"0.0.0.0/0"},
  206. TargetTags: []string{nodeTag},
  207. Allowed: []*compute.FirewallAllowed{
  208. {
  209. IPProtocol: "tcp",
  210. Ports: []string{"80"},
  211. },
  212. {
  213. IPProtocol: "tcp",
  214. Ports: []string{"8080"},
  215. },
  216. },
  217. })
  218. fws = append(fws, &compute.Firewall{
  219. Name: nodeTag + "-nodeports",
  220. SourceRanges: []string{"0.0.0.0/0"},
  221. TargetTags: []string{nodeTag},
  222. Allowed: []*compute.FirewallAllowed{
  223. {
  224. IPProtocol: "tcp",
  225. Ports: []string{"30000-32767"},
  226. },
  227. {
  228. IPProtocol: "udp",
  229. Ports: []string{"30000-32767"},
  230. },
  231. },
  232. })
  233. return fws
  234. }
  235. // PackProtocolsPortsFromFirewall packs protocols and ports in an unified way for verification.
  236. func PackProtocolsPortsFromFirewall(alloweds []*compute.FirewallAllowed) []string {
  237. protocolPorts := []string{}
  238. for _, allowed := range alloweds {
  239. for _, port := range allowed.Ports {
  240. protocolPorts = append(protocolPorts, strings.ToLower(allowed.IPProtocol+"/"+port))
  241. }
  242. }
  243. return protocolPorts
  244. }
  245. type portRange struct {
  246. protocol string
  247. min, max int
  248. }
  249. func toPortRange(s string) (pr portRange, err error) {
  250. protoPorts := strings.Split(s, "/")
  251. // Set protocol
  252. pr.protocol = strings.ToUpper(protoPorts[0])
  253. if len(protoPorts) != 2 {
  254. return pr, fmt.Errorf("expected a single '/' in %q", s)
  255. }
  256. ports := strings.Split(protoPorts[1], "-")
  257. switch len(ports) {
  258. case 1:
  259. v, err := strconv.Atoi(ports[0])
  260. if err != nil {
  261. return pr, err
  262. }
  263. pr.min, pr.max = v, v
  264. case 2:
  265. start, err := strconv.Atoi(ports[0])
  266. if err != nil {
  267. return pr, err
  268. }
  269. end, err := strconv.Atoi(ports[1])
  270. if err != nil {
  271. return pr, err
  272. }
  273. pr.min, pr.max = start, end
  274. default:
  275. return pr, fmt.Errorf("unexpected range value %q", protoPorts[1])
  276. }
  277. return pr, nil
  278. }
  279. // isPortsSubset asserts that the "requiredPorts" are covered by the "coverage" ports.
  280. // requiredPorts - must be single-port, examples: 'tcp/50', 'udp/80'.
  281. // coverage - single or port-range values, example: 'tcp/50', 'udp/80-1000'.
  282. // Returns true if every requiredPort exists in the list of coverage rules.
  283. func isPortsSubset(requiredPorts, coverage []string) error {
  284. for _, reqPort := range requiredPorts {
  285. rRange, err := toPortRange(reqPort)
  286. if err != nil {
  287. return err
  288. }
  289. if rRange.min != rRange.max {
  290. return fmt.Errorf("requiring a range is not supported: %q", reqPort)
  291. }
  292. var covered bool
  293. for _, c := range coverage {
  294. cRange, err := toPortRange(c)
  295. if err != nil {
  296. return err
  297. }
  298. if rRange.protocol != cRange.protocol {
  299. continue
  300. }
  301. if rRange.min >= cRange.min && rRange.min <= cRange.max {
  302. covered = true
  303. break
  304. }
  305. }
  306. if !covered {
  307. return fmt.Errorf("%q is not covered by %v", reqPort, coverage)
  308. }
  309. }
  310. return nil
  311. }
  312. // SameStringArray verifies whether two string arrays have the same strings, return error if not.
  313. // Order does not matter.
  314. // When `include` is set to true, verifies whether result includes all elements from expected.
  315. func SameStringArray(result, expected []string, include bool) error {
  316. res := sets.NewString(result...)
  317. exp := sets.NewString(expected...)
  318. if !include {
  319. diff := res.Difference(exp)
  320. if len(diff) != 0 {
  321. return fmt.Errorf("found differences: %v", diff)
  322. }
  323. } else {
  324. if !res.IsSuperset(exp) {
  325. return fmt.Errorf("some elements are missing: expected %v, got %v", expected, result)
  326. }
  327. }
  328. return nil
  329. }
  330. // VerifyFirewallRule verifies whether the result firewall is consistent with the expected firewall.
  331. // When `portsSubset` is false, match given ports exactly. Otherwise, only check ports are included.
  332. func VerifyFirewallRule(res, exp *compute.Firewall, network string, portsSubset bool) error {
  333. if res == nil || exp == nil {
  334. return fmt.Errorf("res and exp must not be nil")
  335. }
  336. if res.Name != exp.Name {
  337. return fmt.Errorf("incorrect name: %v, expected %v", res.Name, exp.Name)
  338. }
  339. // Sample Network value: https://www.googleapis.com/compute/v1/projects/{project-id}/global/networks/e2e
  340. if !strings.HasSuffix(res.Network, "/"+network) {
  341. return fmt.Errorf("incorrect network: %v, expected ends with: %v", res.Network, "/"+network)
  342. }
  343. actualPorts := PackProtocolsPortsFromFirewall(res.Allowed)
  344. expPorts := PackProtocolsPortsFromFirewall(exp.Allowed)
  345. if portsSubset {
  346. if err := isPortsSubset(expPorts, actualPorts); err != nil {
  347. return fmt.Errorf("incorrect allowed protocol ports: %v", err)
  348. }
  349. } else {
  350. if err := SameStringArray(actualPorts, expPorts, false); err != nil {
  351. return fmt.Errorf("incorrect allowed protocols ports: %v", err)
  352. }
  353. }
  354. if err := SameStringArray(res.SourceRanges, exp.SourceRanges, false); err != nil {
  355. return fmt.Errorf("incorrect source ranges %v, expected %v: %v", res.SourceRanges, exp.SourceRanges, err)
  356. }
  357. if err := SameStringArray(res.SourceTags, exp.SourceTags, false); err != nil {
  358. return fmt.Errorf("incorrect source tags %v, expected %v: %v", res.SourceTags, exp.SourceTags, err)
  359. }
  360. if err := SameStringArray(res.TargetTags, exp.TargetTags, false); err != nil {
  361. return fmt.Errorf("incorrect target tags %v, expected %v: %v", res.TargetTags, exp.TargetTags, err)
  362. }
  363. return nil
  364. }
  365. // WaitForFirewallRule waits for the specified firewall existence
  366. func WaitForFirewallRule(gceCloud *gcecloud.Cloud, fwName string, exist bool, timeout time.Duration) (*compute.Firewall, error) {
  367. framework.Logf("Waiting up to %v for firewall %v exist=%v", timeout, fwName, exist)
  368. var fw *compute.Firewall
  369. var err error
  370. condition := func() (bool, error) {
  371. fw, err = gceCloud.GetFirewall(fwName)
  372. if err != nil && exist ||
  373. err == nil && !exist ||
  374. err != nil && !exist && !IsGoogleAPIHTTPErrorCode(err, http.StatusNotFound) {
  375. return false, nil
  376. }
  377. return true, nil
  378. }
  379. if err := wait.PollImmediate(5*time.Second, timeout, condition); err != nil {
  380. return nil, fmt.Errorf("error waiting for firewall %v exist=%v", fwName, exist)
  381. }
  382. return fw, nil
  383. }