cloudflare/cloudflared

Public

mirrored from https://github.com/cloudflare/cloudflaredAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
2023.8.1

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

carrier/carrier.go

185lines · modecode

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