main.go 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  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 nosnat
  14. import (
  15. "fmt"
  16. "io/ioutil"
  17. "net"
  18. "net/http"
  19. "os"
  20. "strings"
  21. "github.com/spf13/cobra"
  22. "k8s.io/component-base/logs"
  23. )
  24. // CmdNoSnatTest is used by agnhost Cobra.
  25. var CmdNoSnatTest = &cobra.Command{
  26. Use: "no-snat-test",
  27. Short: "Creates the /checknosnat and /whoami endpoints",
  28. Long: `Serves the following endpoints on the given port (defaults to "8080").
  29. - /whoami - returns the request's IP address.
  30. - /checknosnat - queries "ip/whoami" for each provided IP ("/checknosnat?ips=ip1,ip2"),
  31. and if all the response bodies match the "POD_IP" environment variable, it will return a 200 response, 500 otherwise.`,
  32. Args: cobra.MaximumNArgs(0),
  33. Run: main,
  34. }
  35. var port string
  36. func init() {
  37. CmdNoSnatTest.Flags().StringVar(&port, "port", "8080", "The port to serve /checknosnat and /whoami endpoints on.")
  38. }
  39. // ip = target for /whoami query
  40. // rip = returned ip
  41. // pip = this pod's ip
  42. // nip = this node's ip
  43. type masqTester struct {
  44. Port string
  45. }
  46. func main(cmd *cobra.Command, args []string) {
  47. m := &masqTester{
  48. Port: port,
  49. }
  50. logs.InitLogs()
  51. defer logs.FlushLogs()
  52. if err := m.Run(); err != nil {
  53. fmt.Fprintf(os.Stderr, "%v\n", err)
  54. os.Exit(1)
  55. }
  56. }
  57. func (m *masqTester) Run() error {
  58. // pip is the current pod's IP and nip is the current node's IP
  59. // pull the pip and nip out of the env
  60. pip, ok := os.LookupEnv("POD_IP")
  61. if !ok {
  62. return fmt.Errorf("POD_IP env var was not present in the environment")
  63. }
  64. nip, ok := os.LookupEnv("NODE_IP")
  65. if !ok {
  66. return fmt.Errorf("NODE_IP env var was not present in the environment")
  67. }
  68. // validate that pip and nip are ip addresses.
  69. if net.ParseIP(pip) == nil {
  70. return fmt.Errorf("POD_IP env var contained %q, which is not an IP address", pip)
  71. }
  72. if net.ParseIP(nip) == nil {
  73. return fmt.Errorf("NODE_IP env var contained %q, which is not an IP address", nip)
  74. }
  75. // register handlers
  76. http.HandleFunc("/whoami", whoami)
  77. http.HandleFunc("/checknosnat", mkChecknosnat(pip, nip))
  78. // spin up the server
  79. return http.ListenAndServe(":"+m.Port, nil)
  80. }
  81. type handler func(http.ResponseWriter, *http.Request)
  82. func joinErrors(errs []error, sep string) string {
  83. strs := make([]string, len(errs))
  84. for i, err := range errs {
  85. strs[i] = err.Error()
  86. }
  87. return strings.Join(strs, sep)
  88. }
  89. // Builds checknosnat handler, using pod and node ip of current location
  90. func mkChecknosnat(pip string, nip string) handler {
  91. // Queries /whoami for each provided ip, resp 200 if all resp bodies match this Pod's ip, 500 otherwise
  92. return func(w http.ResponseWriter, req *http.Request) {
  93. errs := []error{}
  94. ips := strings.Split(req.URL.Query().Get("ips"), ",")
  95. for _, ip := range ips {
  96. if err := check(ip, pip, nip); err != nil {
  97. errs = append(errs, err)
  98. }
  99. }
  100. if len(errs) > 0 {
  101. w.WriteHeader(500)
  102. fmt.Fprintf(w, "%s", joinErrors(errs, ", "))
  103. return
  104. }
  105. w.WriteHeader(200)
  106. }
  107. }
  108. // Writes the req.RemoteAddr into the response, req.RemoteAddr is the address of the incoming connection
  109. func whoami(w http.ResponseWriter, req *http.Request) {
  110. fmt.Fprintf(w, "%s", req.RemoteAddr)
  111. }
  112. // Queries ip/whoami and compares response to pip, uses nip to differentiate SNAT from other potential failure modes
  113. func check(ip string, pip string, nip string) error {
  114. url := fmt.Sprintf("http://%s/whoami", ip)
  115. resp, err := http.Get(url)
  116. if err != nil {
  117. return err
  118. }
  119. defer resp.Body.Close()
  120. body, err := ioutil.ReadAll(resp.Body)
  121. if err != nil {
  122. return err
  123. }
  124. rips := strings.Split(string(body), ":")
  125. if rips == nil || len(rips) == 0 {
  126. return fmt.Errorf("Invalid returned ip %q from %q", string(body), url)
  127. }
  128. rip := rips[0]
  129. if rip != pip {
  130. if rip == nip {
  131. return fmt.Errorf("Returned ip %q != my Pod ip %q, == my Node ip %q - SNAT", rip, pip, nip)
  132. }
  133. return fmt.Errorf("Returned ip %q != my Pod ip %q or my Node ip %q - SNAT to unexpected ip (possible SNAT through unexpected interface on the way into another node)", rip, pip, nip)
  134. }
  135. return nil
  136. }