carrier.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. // Package carrier provides a WebSocket proxy to carry or proxy a connection
  2. // from the local client to the edge. See it as a wrapper around any protocol
  3. // that it packages up in a WebSocket connection to the edge.
  4. package carrier
  5. import (
  6. "crypto/tls"
  7. "fmt"
  8. "io"
  9. "net"
  10. "net/http"
  11. "net/url"
  12. "os"
  13. "strings"
  14. "github.com/pkg/errors"
  15. "github.com/rs/zerolog"
  16. "github.com/cloudflare/cloudflared/token"
  17. )
  18. const (
  19. LogFieldOriginURL = "originURL"
  20. CFAccessTokenHeader = "Cf-Access-Token"
  21. cfJumpDestinationHeader = "Cf-Access-Jump-Destination"
  22. )
  23. type StartOptions struct {
  24. AppInfo *token.AppInfo
  25. OriginURL string
  26. Headers http.Header
  27. Host string
  28. TLSClientConfig *tls.Config
  29. }
  30. // Connection wraps up all the needed functions to forward over the tunnel
  31. type Connection interface {
  32. // ServeStream is used to forward data from the client to the edge
  33. ServeStream(*StartOptions, io.ReadWriter) error
  34. }
  35. // StdinoutStream is empty struct for wrapping stdin/stdout
  36. // into a single ReadWriter
  37. type StdinoutStream struct{}
  38. // Read will read from Stdin
  39. func (c *StdinoutStream) Read(p []byte) (int, error) {
  40. return os.Stdin.Read(p)
  41. }
  42. // Write will write to Stdout
  43. func (c *StdinoutStream) Write(p []byte) (int, error) {
  44. return os.Stdout.Write(p)
  45. }
  46. // Helper to allow deferring the response close with a check that the resp is not nil
  47. func closeRespBody(resp *http.Response) {
  48. if resp != nil {
  49. _ = resp.Body.Close()
  50. }
  51. }
  52. // StartForwarder will setup a listener on a specified address/port and then
  53. // forward connections to the origin by calling `Serve()`.
  54. func StartForwarder(conn Connection, address string, shutdownC <-chan struct{}, options *StartOptions) error {
  55. listener, err := net.Listen("tcp", address)
  56. if err != nil {
  57. return errors.Wrap(err, "failed to start forwarding server")
  58. }
  59. return Serve(conn, listener, shutdownC, options)
  60. }
  61. // StartClient will copy the data from stdin/stdout over a WebSocket connection
  62. // to the edge (originURL)
  63. func StartClient(conn Connection, stream io.ReadWriter, options *StartOptions) error {
  64. return conn.ServeStream(options, stream)
  65. }
  66. // Serve accepts incoming connections on the specified net.Listener.
  67. // Each connection is handled in a new goroutine: its data is copied over a
  68. // WebSocket connection to the edge (originURL).
  69. // `Serve` always closes `listener`.
  70. func Serve(remoteConn Connection, listener net.Listener, shutdownC <-chan struct{}, options *StartOptions) error {
  71. defer listener.Close()
  72. errChan := make(chan error)
  73. go func() {
  74. for {
  75. conn, err := listener.Accept()
  76. if err != nil {
  77. // don't block if parent goroutine quit early
  78. select {
  79. case errChan <- err:
  80. default:
  81. }
  82. return
  83. }
  84. go serveConnection(remoteConn, conn, options)
  85. }
  86. }()
  87. select {
  88. case <-shutdownC:
  89. return nil
  90. case err := <-errChan:
  91. return err
  92. }
  93. }
  94. // serveConnection handles connections for the Serve() call
  95. func serveConnection(remoteConn Connection, c net.Conn, options *StartOptions) {
  96. defer c.Close()
  97. _ = remoteConn.ServeStream(options, c)
  98. }
  99. // IsAccessResponse checks the http Response to see if the url location
  100. // contains the Access structure.
  101. func IsAccessResponse(resp *http.Response) bool {
  102. if resp == nil || resp.StatusCode != http.StatusFound {
  103. return false
  104. }
  105. location, err := resp.Location()
  106. if err != nil || location == nil {
  107. return false
  108. }
  109. if strings.HasPrefix(location.Path, token.AccessLoginWorkerPath) {
  110. return true
  111. }
  112. return false
  113. }
  114. // BuildAccessRequest builds an HTTP request with the Access token set
  115. func BuildAccessRequest(options *StartOptions, log *zerolog.Logger) (*http.Request, error) {
  116. req, err := http.NewRequest(http.MethodGet, options.OriginURL, nil)
  117. if err != nil {
  118. return nil, err
  119. }
  120. token, err := token.FetchTokenWithRedirect(req.URL, options.AppInfo, log)
  121. if err != nil {
  122. return nil, err
  123. }
  124. // We need to create a new request as FetchToken will modify req (boo mutable)
  125. // as it has to follow redirect on the API and such, so here we init a new one
  126. originRequest, err := http.NewRequest(http.MethodGet, options.OriginURL, nil)
  127. if err != nil {
  128. return nil, err
  129. }
  130. originRequest.Header.Set(CFAccessTokenHeader, token)
  131. for k, v := range options.Headers {
  132. if len(v) >= 1 {
  133. originRequest.Header.Set(k, v[0])
  134. }
  135. }
  136. return originRequest, nil
  137. }
  138. func SetBastionDest(header http.Header, destination string) {
  139. if destination != "" {
  140. header.Set(cfJumpDestinationHeader, destination)
  141. }
  142. }
  143. func ResolveBastionDest(r *http.Request) (string, error) {
  144. jumpDestination := r.Header.Get(cfJumpDestinationHeader)
  145. if jumpDestination == "" {
  146. return "", fmt.Errorf("Did not receive final destination from client. The --destination flag is likely not set on the client side")
  147. }
  148. // Strip scheme and path set by client. Without a scheme
  149. // Parsing a hostname and path without scheme might not return an error due to parsing ambiguities
  150. if jumpURL, err := url.Parse(jumpDestination); err == nil && jumpURL.Host != "" {
  151. return removePath(jumpURL.Host), nil
  152. }
  153. return removePath(jumpDestination), nil
  154. }
  155. func removePath(dest string) string {
  156. return strings.SplitN(dest, "/", 2)[0]
  157. }