netexec.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. /*
  2. Copyright 2014 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 netexec
  14. import (
  15. "encoding/json"
  16. "fmt"
  17. "io"
  18. "io/ioutil"
  19. "log"
  20. "net"
  21. "net/http"
  22. "net/url"
  23. "os"
  24. "os/exec"
  25. "strconv"
  26. "strings"
  27. "sync/atomic"
  28. "time"
  29. "github.com/spf13/cobra"
  30. utilnet "k8s.io/apimachinery/pkg/util/net"
  31. )
  32. var (
  33. httpPort = 8080
  34. udpPort = 8081
  35. shellPath = "/bin/sh"
  36. serverReady = &atomicBool{0}
  37. )
  38. // CmdNetexec is used by agnhost Cobra.
  39. var CmdNetexec = &cobra.Command{
  40. Use: "netexec",
  41. Short: "Creates a HTTP / UDP server with various endpoints",
  42. Long: `Starts a HTTP server on given TCP / UDP ports with the following endpoints:
  43. - /: Returns the request's timestamp.
  44. - /clientip: Returns the request's IP address.
  45. - /dial: Creates a given number of requests to the given host and port using the given protocol,
  46. and returns a JSON with the fields "responses" (successful request responses) and "errors" (
  47. failed request responses). Returns "200 OK" status code if the last request succeeded,
  48. "417 Expectation Failed" if it did not, or "400 Bad Request" if any of the endpoint's parameters
  49. is invalid. The endpoint's parameters are:
  50. - "host": The host that will be dialed.
  51. - "port": The port that will be dialed.
  52. - "request": The HTTP endpoint or data to be sent through UDP. If not specified, it will result
  53. in a "400 Bad Request" status code being returned.
  54. - "protocol": The protocol which will be used when making the request. Default value: "http".
  55. Acceptable values: "http", "udp".
  56. - "tries": The number of times the request will be performed. Default value: "1".
  57. - "/echo": Returns the given "msg" ("/echo?msg=echoed_msg")
  58. - "/exit": Closes the server with the given code ("/exit?code=some-code"). The "code"
  59. is expected to be an integer [0-127] or empty; if it is not, it will return an error message.
  60. - "/healthz": Returns "200 OK" if the server is ready, "412 Status Precondition Failed"
  61. otherwise. The server is considered not ready if the UDP server did not start yet or
  62. it exited.
  63. - "/hostname": Returns the server's hostname.
  64. - "/hostName": Returns the server's hostname.
  65. - "/shell": Executes the given "shellCommand" or "cmd" ("/shell?cmd=some-command") and
  66. returns a JSON containing the fields "output" (command's output) and "error" (command's
  67. error message). Returns "200 OK" if the command succeeded, "417 Expectation Failed" if not.
  68. - "/shutdown": Closes the server with the exit code 0.
  69. - "/upload": Accepts a file to be uploaded, writing it in the "/uploads" folder on the host.
  70. Returns a JSON with the fields "output" (containing the file's name on the server) and
  71. "error" containing any potential server side errors.`,
  72. Args: cobra.MaximumNArgs(0),
  73. Run: main,
  74. }
  75. func init() {
  76. CmdNetexec.Flags().IntVar(&httpPort, "http-port", 8080, "HTTP Listen Port")
  77. CmdNetexec.Flags().IntVar(&udpPort, "udp-port", 8081, "UDP Listen Port")
  78. }
  79. // atomicBool uses load/store operations on an int32 to simulate an atomic boolean.
  80. type atomicBool struct {
  81. v int32
  82. }
  83. // set sets the int32 to the given boolean.
  84. func (a *atomicBool) set(value bool) {
  85. if value {
  86. atomic.StoreInt32(&a.v, 1)
  87. return
  88. }
  89. atomic.StoreInt32(&a.v, 0)
  90. }
  91. // get returns true if the int32 == 1
  92. func (a *atomicBool) get() bool {
  93. return atomic.LoadInt32(&a.v) == 1
  94. }
  95. func main(cmd *cobra.Command, args []string) {
  96. go startUDPServer(udpPort)
  97. startHTTPServer(httpPort)
  98. }
  99. func startHTTPServer(httpPort int) {
  100. http.HandleFunc("/", rootHandler)
  101. http.HandleFunc("/clientip", clientIPHandler)
  102. http.HandleFunc("/echo", echoHandler)
  103. http.HandleFunc("/exit", exitHandler)
  104. http.HandleFunc("/hostname", hostnameHandler)
  105. http.HandleFunc("/shell", shellHandler)
  106. http.HandleFunc("/upload", uploadHandler)
  107. http.HandleFunc("/dial", dialHandler)
  108. http.HandleFunc("/healthz", healthzHandler)
  109. // older handlers
  110. http.HandleFunc("/hostName", hostNameHandler)
  111. http.HandleFunc("/shutdown", shutdownHandler)
  112. log.Fatal(http.ListenAndServe(fmt.Sprintf(":%d", httpPort), nil))
  113. }
  114. func rootHandler(w http.ResponseWriter, r *http.Request) {
  115. log.Printf("GET /")
  116. fmt.Fprintf(w, "NOW: %v", time.Now())
  117. }
  118. func echoHandler(w http.ResponseWriter, r *http.Request) {
  119. log.Printf("GET /echo?msg=%s", r.FormValue("msg"))
  120. fmt.Fprintf(w, "%s", r.FormValue("msg"))
  121. }
  122. func clientIPHandler(w http.ResponseWriter, r *http.Request) {
  123. log.Printf("GET /clientip")
  124. fmt.Fprintf(w, r.RemoteAddr)
  125. }
  126. func exitHandler(w http.ResponseWriter, r *http.Request) {
  127. log.Printf("GET /exit?code=%s", r.FormValue("code"))
  128. code, err := strconv.Atoi(r.FormValue("code"))
  129. if err == nil || r.FormValue("code") == "" {
  130. os.Exit(code)
  131. }
  132. fmt.Fprintf(w, "argument 'code' must be an integer [0-127] or empty, got %q", r.FormValue("code"))
  133. }
  134. func hostnameHandler(w http.ResponseWriter, r *http.Request) {
  135. log.Printf("GET /hostname")
  136. fmt.Fprint(w, getHostName())
  137. }
  138. // healthHandler response with a 200 if the UDP server is ready. It also serves
  139. // as a health check of the HTTP server by virtue of being a HTTP handler.
  140. func healthzHandler(w http.ResponseWriter, r *http.Request) {
  141. log.Printf("GET /healthz")
  142. if serverReady.get() {
  143. w.WriteHeader(200)
  144. return
  145. }
  146. w.WriteHeader(http.StatusPreconditionFailed)
  147. }
  148. func shutdownHandler(w http.ResponseWriter, r *http.Request) {
  149. log.Printf("GET /shutdown")
  150. os.Exit(0)
  151. }
  152. func dialHandler(w http.ResponseWriter, r *http.Request) {
  153. values, err := url.Parse(r.URL.RequestURI())
  154. if err != nil {
  155. http.Error(w, fmt.Sprintf("%v", err), http.StatusBadRequest)
  156. return
  157. }
  158. host := values.Query().Get("host")
  159. port := values.Query().Get("port")
  160. request := values.Query().Get("request") // hostName
  161. protocol := values.Query().Get("protocol")
  162. tryParam := values.Query().Get("tries")
  163. log.Printf("GET /dial?host=%s&protocol=%s&port=%s&request=%s&tries=%s", host, protocol, port, request, tryParam)
  164. tries := 1
  165. if len(tryParam) > 0 {
  166. tries, err = strconv.Atoi(tryParam)
  167. }
  168. if err != nil {
  169. http.Error(w, fmt.Sprintf("tries parameter is invalid. %v", err), http.StatusBadRequest)
  170. return
  171. }
  172. if len(request) == 0 {
  173. http.Error(w, fmt.Sprintf("request parameter not specified. %v", err), http.StatusBadRequest)
  174. return
  175. }
  176. if len(protocol) == 0 {
  177. protocol = "http"
  178. } else {
  179. protocol = strings.ToLower(protocol)
  180. }
  181. if protocol != "http" && protocol != "udp" {
  182. http.Error(w, fmt.Sprintf("unsupported protocol. %s", protocol), http.StatusBadRequest)
  183. return
  184. }
  185. hostPort := net.JoinHostPort(host, port)
  186. var udpAddress *net.UDPAddr
  187. if protocol == "udp" {
  188. udpAddress, err = net.ResolveUDPAddr("udp", hostPort)
  189. if err != nil {
  190. http.Error(w, fmt.Sprintf("host and/or port param are invalid. %v", err), http.StatusBadRequest)
  191. return
  192. }
  193. } else {
  194. _, err = net.ResolveTCPAddr("tcp", hostPort)
  195. if err != nil {
  196. http.Error(w, fmt.Sprintf("host and/or port param are invalid. %v", err), http.StatusBadRequest)
  197. return
  198. }
  199. }
  200. errors := make([]string, 0)
  201. responses := make([]string, 0)
  202. var response string
  203. for i := 0; i < tries; i++ {
  204. if protocol == "udp" {
  205. response, err = dialUDP(request, udpAddress)
  206. } else {
  207. response, err = dialHTTP(request, hostPort)
  208. }
  209. if err != nil {
  210. errors = append(errors, fmt.Sprintf("%v", err))
  211. } else {
  212. responses = append(responses, response)
  213. }
  214. }
  215. output := map[string][]string{}
  216. if len(response) > 0 {
  217. output["responses"] = responses
  218. }
  219. if len(errors) > 0 {
  220. output["errors"] = errors
  221. }
  222. bytes, err := json.Marshal(output)
  223. if err == nil {
  224. fmt.Fprint(w, string(bytes))
  225. } else {
  226. http.Error(w, fmt.Sprintf("response could not be serialized. %v", err), http.StatusExpectationFailed)
  227. }
  228. }
  229. func dialHTTP(request, hostPort string) (string, error) {
  230. transport := utilnet.SetTransportDefaults(&http.Transport{})
  231. httpClient := createHTTPClient(transport)
  232. resp, err := httpClient.Get(fmt.Sprintf("http://%s/%s", hostPort, request))
  233. defer transport.CloseIdleConnections()
  234. if err == nil {
  235. defer resp.Body.Close()
  236. body, err := ioutil.ReadAll(resp.Body)
  237. if err == nil {
  238. return string(body), nil
  239. }
  240. }
  241. return "", err
  242. }
  243. func createHTTPClient(transport *http.Transport) *http.Client {
  244. client := &http.Client{
  245. Transport: transport,
  246. Timeout: 5 * time.Second,
  247. }
  248. return client
  249. }
  250. func dialUDP(request string, remoteAddress *net.UDPAddr) (string, error) {
  251. Conn, err := net.DialUDP("udp", nil, remoteAddress)
  252. if err != nil {
  253. return "", fmt.Errorf("udp dial failed. err:%v", err)
  254. }
  255. defer Conn.Close()
  256. buf := []byte(request)
  257. _, err = Conn.Write(buf)
  258. if err != nil {
  259. return "", fmt.Errorf("udp connection write failed. err:%v", err)
  260. }
  261. udpResponse := make([]byte, 2048)
  262. Conn.SetReadDeadline(time.Now().Add(5 * time.Second))
  263. count, err := Conn.Read(udpResponse)
  264. if err != nil || count == 0 {
  265. return "", fmt.Errorf("reading from udp connection failed. err:'%v'", err)
  266. }
  267. return string(udpResponse[0:count]), nil
  268. }
  269. func shellHandler(w http.ResponseWriter, r *http.Request) {
  270. cmd := r.FormValue("shellCommand")
  271. if cmd == "" {
  272. cmd = r.FormValue("cmd")
  273. }
  274. log.Printf("GET /shell?cmd=%s", cmd)
  275. cmdOut, err := exec.Command(shellPath, "-c", cmd).CombinedOutput()
  276. output := map[string]string{}
  277. if len(cmdOut) > 0 {
  278. output["output"] = string(cmdOut)
  279. }
  280. if err != nil {
  281. output["error"] = fmt.Sprintf("%v", err)
  282. }
  283. log.Printf("Output: %s", output)
  284. bytes, err := json.Marshal(output)
  285. if err == nil {
  286. fmt.Fprint(w, string(bytes))
  287. } else {
  288. http.Error(w, fmt.Sprintf("response could not be serialized. %v", err), http.StatusExpectationFailed)
  289. }
  290. }
  291. func uploadHandler(w http.ResponseWriter, r *http.Request) {
  292. log.Printf("GET /upload")
  293. result := map[string]string{}
  294. file, _, err := r.FormFile("file")
  295. if err != nil {
  296. result["error"] = "Unable to upload file."
  297. bytes, err := json.Marshal(result)
  298. if err == nil {
  299. fmt.Fprint(w, string(bytes))
  300. } else {
  301. http.Error(w, fmt.Sprintf("%s. Also unable to serialize output. %v", result["error"], err), http.StatusInternalServerError)
  302. }
  303. log.Printf("Unable to upload file: %s", err)
  304. return
  305. }
  306. defer file.Close()
  307. f, err := ioutil.TempFile("/uploads", "upload")
  308. if err != nil {
  309. result["error"] = "Unable to open file for write"
  310. bytes, err := json.Marshal(result)
  311. if err == nil {
  312. fmt.Fprint(w, string(bytes))
  313. } else {
  314. http.Error(w, fmt.Sprintf("%s. Also unable to serialize output. %v", result["error"], err), http.StatusInternalServerError)
  315. }
  316. log.Printf("Unable to open file for write: %s", err)
  317. return
  318. }
  319. defer f.Close()
  320. if _, err = io.Copy(f, file); err != nil {
  321. result["error"] = "Unable to write file."
  322. bytes, err := json.Marshal(result)
  323. if err == nil {
  324. fmt.Fprint(w, string(bytes))
  325. } else {
  326. http.Error(w, fmt.Sprintf("%s. Also unable to serialize output. %v", result["error"], err), http.StatusInternalServerError)
  327. }
  328. log.Printf("Unable to write file: %s", err)
  329. return
  330. }
  331. UploadFile := f.Name()
  332. if err := os.Chmod(UploadFile, 0700); err != nil {
  333. result["error"] = "Unable to chmod file."
  334. bytes, err := json.Marshal(result)
  335. if err == nil {
  336. fmt.Fprint(w, string(bytes))
  337. } else {
  338. http.Error(w, fmt.Sprintf("%s. Also unable to serialize output. %v", result["error"], err), http.StatusInternalServerError)
  339. }
  340. log.Printf("Unable to chmod file: %s", err)
  341. return
  342. }
  343. log.Printf("Wrote upload to %s", UploadFile)
  344. result["output"] = UploadFile
  345. w.WriteHeader(http.StatusCreated)
  346. bytes, err := json.Marshal(result)
  347. if err != nil {
  348. http.Error(w, fmt.Sprintf("%s. Also unable to serialize output. %v", result["error"], err), http.StatusInternalServerError)
  349. return
  350. }
  351. fmt.Fprint(w, string(bytes))
  352. }
  353. func hostNameHandler(w http.ResponseWriter, r *http.Request) {
  354. log.Printf("GET /hostName")
  355. fmt.Fprint(w, getHostName())
  356. }
  357. // udp server supports the hostName, echo and clientIP commands.
  358. func startUDPServer(udpPort int) {
  359. serverAddress, err := net.ResolveUDPAddr("udp", fmt.Sprintf(":%d", udpPort))
  360. assertNoError(err)
  361. serverConn, err := net.ListenUDP("udp", serverAddress)
  362. assertNoError(err)
  363. defer serverConn.Close()
  364. buf := make([]byte, 2048)
  365. log.Printf("Started UDP server")
  366. // Start responding to readiness probes.
  367. serverReady.set(true)
  368. defer func() {
  369. log.Printf("UDP server exited")
  370. serverReady.set(false)
  371. }()
  372. for {
  373. n, clientAddress, err := serverConn.ReadFromUDP(buf)
  374. assertNoError(err)
  375. receivedText := strings.ToLower(strings.TrimSpace(string(buf[0:n])))
  376. if receivedText == "hostname" {
  377. log.Println("Sending udp hostName response")
  378. _, err = serverConn.WriteToUDP([]byte(getHostName()), clientAddress)
  379. assertNoError(err)
  380. } else if strings.HasPrefix(receivedText, "echo ") {
  381. parts := strings.SplitN(receivedText, " ", 2)
  382. resp := ""
  383. if len(parts) == 2 {
  384. resp = parts[1]
  385. }
  386. log.Printf("Echoing %v\n", resp)
  387. _, err = serverConn.WriteToUDP([]byte(resp), clientAddress)
  388. assertNoError(err)
  389. } else if receivedText == "clientip" {
  390. log.Printf("Sending back clientip to %s", clientAddress.String())
  391. _, err = serverConn.WriteToUDP([]byte(clientAddress.String()), clientAddress)
  392. assertNoError(err)
  393. } else if len(receivedText) > 0 {
  394. log.Printf("Unknown udp command received: %v\n", receivedText)
  395. }
  396. }
  397. }
  398. func getHostName() string {
  399. hostName, err := os.Hostname()
  400. assertNoError(err)
  401. return hostName
  402. }
  403. func assertNoError(err error) {
  404. if err != nil {
  405. log.Fatal("Error occurred. error:", err)
  406. }
  407. }