cloudflare/cloudflared

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
2020.9.2

Branches

Tags

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

Clone

HTTPS

Download ZIP

dbconnect/proxy.go

278lines · modeblame

759cd019Ashcon Partovi6 years ago1package dbconnect
2
3import (
4"context"
5"encoding/json"
6"fmt"
7"io"
8"net"
9"net/http"
10"net/url"
11"time"
12
13"github.com/cloudflare/cloudflared/hello"
046be632Dalton6 years ago14"github.com/cloudflare/cloudflared/logger"
759cd019Ashcon Partovi6 years ago15"github.com/cloudflare/cloudflared/validation"
16"github.com/gorilla/mux"
17"github.com/pkg/errors"
18)
19
20// Proxy is an HTTP server that proxies requests to a Client.
21type Proxy struct {
22client Client
23accessValidator *validation.Access
046be632Dalton6 years ago24logger logger.Service
759cd019Ashcon Partovi6 years ago25}
26
27// NewInsecureProxy creates a Proxy that talks to a Client at an origin.
28//
29// In insecure mode, the Proxy will allow all Command requests.
30func NewInsecureProxy(ctx context.Context, origin string) (*Proxy, error) {
31originURL, err := url.Parse(origin)
32if err != nil {
33return nil, errors.Wrap(err, "must provide a valid database url")
34}
35
36client, err := NewClient(ctx, originURL)
37if err != nil {
38return nil, err
39}
40
41err = client.Ping(ctx)
42if err != nil {
43return nil, errors.Wrap(err, "could not connect to the database")
44}
45
046be632Dalton6 years ago46logger, err := logger.New()
47if err != nil {
48return nil, errors.Wrap(err, "error setting up logger")
49}
50
51return &Proxy{client, nil, logger}, nil
759cd019Ashcon Partovi6 years ago52}
53
54// NewSecureProxy creates a Proxy that talks to a Client at an origin.
55//
56// In secure mode, the Proxy will reject any Command requests that are
57// not authenticated by Cloudflare Access with a valid JWT.
58func NewSecureProxy(ctx context.Context, origin, authDomain, applicationAUD string) (*Proxy, error) {
59proxy, err := NewInsecureProxy(ctx, origin)
60if err != nil {
61return nil, err
62}
63
64validator, err := validation.NewAccessValidator(ctx, authDomain, authDomain, applicationAUD)
65if err != nil {
66return nil, err
67}
68
69proxy.accessValidator = validator
70
71return proxy, err
72}
73
74// IsInsecure gets whether the Proxy will accept a Command from any source.
75func (proxy *Proxy) IsInsecure() bool {
76return proxy.accessValidator == nil
77}
78
79// IsAllowed checks whether a http.Request is allowed to receive data.
80//
81// By default, requests must pass through Cloudflare Access for authentication.
82// If the proxy is explcitly set to insecure mode, all requests will be allowed.
83func (proxy *Proxy) IsAllowed(r *http.Request, verbose ...bool) bool {
84if proxy.IsInsecure() {
85return true
86}
87
88// Access and Tunnel should prevent bad JWTs from even reaching the origin,
89// but validate tokens anyway as an abundance of caution.
90err := proxy.accessValidator.ValidateRequest(r.Context(), r)
91if err == nil {
92return true
93}
94
95// Warn administrators that invalid JWTs are being rejected. This is indicative
96// of either a misconfiguration of the CLI or a massive failure of upstream systems.
97if len(verbose) > 0 {
046be632Dalton6 years ago98cfRay := proxy.getRayHeader(r)
99proxy.logger.Infof("dbproxy: Failed JWT authentication: cf-ray: %s %s", cfRay, err)
759cd019Ashcon Partovi6 years ago100}
101
102return false
103}
104
105// Start the Proxy at a given address and notify the listener channel when the server is online.
106func (proxy *Proxy) Start(ctx context.Context, addr string, listenerC chan<- net.Listener) error {
107// STOR-611: use a seperate listener and consider web socket support.
108httpListener, err := hello.CreateTLSListener(addr)
109if err != nil {
110return errors.Wrapf(err, "could not create listener at %s", addr)
111}
112
113errC := make(chan error)
114defer close(errC)
115
116// Starts the HTTP server and begins to serve requests.
117go func() {
118errC <- proxy.httpListen(ctx, httpListener)
119}()
120
121// Continually ping the server until it comes online or 10 attempts fail.
122go func() {
123var err error
124for i := 0; i < 10; i++ {
125_, err = http.Get("http://" + httpListener.Addr().String())
126
127// Once no error was detected, notify the listener channel and return.
128if err == nil {
129listenerC <- httpListener
130return
131}
132
133// Backoff between requests to ping the server.
134<-time.After(1 * time.Second)
135}
136errC <- errors.Wrap(err, "took too long for the http server to start")
137}()
138
139return <-errC
140}
141
142// httpListen starts the httpServer and blocks until the context closes.
143func (proxy *Proxy) httpListen(ctx context.Context, listener net.Listener) error {
144httpServer := &http.Server{
145Addr: listener.Addr().String(),
146Handler: proxy.httpRouter(),
147ReadTimeout: 10 * time.Second,
148WriteTimeout: 60 * time.Second,
149IdleTimeout: 60 * time.Second,
150}
151
152go func() {
153<-ctx.Done()
154httpServer.Close()
155listener.Close()
156}()
157
158return httpServer.Serve(listener)
159}
160
161// httpRouter creates a mux.Router for the Proxy.
162func (proxy *Proxy) httpRouter() *mux.Router {
163router := mux.NewRouter()
164
165router.HandleFunc("/ping", proxy.httpPing()).Methods("GET", "HEAD")
166router.HandleFunc("/submit", proxy.httpSubmit()).Methods("POST")
167
168return router
169}
170
171// httpPing tests the connection to the database.
172//
173// By default, this endpoint is unauthenticated to allow for health checks.
174// To enable authentication, Cloudflare Access must be enabled on this route.
175func (proxy *Proxy) httpPing() http.HandlerFunc {
176return func(w http.ResponseWriter, r *http.Request) {
177ctx := r.Context()
178err := proxy.client.Ping(ctx)
179
180if err == nil {
181proxy.httpRespond(w, r, http.StatusOK, "")
182} else {
183proxy.httpRespondErr(w, r, http.StatusInternalServerError, err)
184}
185}
186}
187
188// httpSubmit sends a command to the database and returns its response.
189//
190// By default, this endpoint will reject requests that do not pass through Cloudflare Access.
191// To disable authentication, the --insecure flag must be specified in the command line.
192func (proxy *Proxy) httpSubmit() http.HandlerFunc {
193return func(w http.ResponseWriter, r *http.Request) {
194if !proxy.IsAllowed(r, true) {
195proxy.httpRespondErr(w, r, http.StatusForbidden, fmt.Errorf(""))
196return
197}
198
199var cmd Command
200err := json.NewDecoder(r.Body).Decode(&cmd)
201if err != nil {
202proxy.httpRespondErr(w, r, http.StatusBadRequest, err)
203return
204}
205
206ctx := r.Context()
207data, err := proxy.client.Submit(ctx, &cmd)
208
209if err != nil {
210proxy.httpRespondErr(w, r, http.StatusUnprocessableEntity, err)
211return
212}
213
214w.Header().Set("Content-type", "application/json")
215err = json.NewEncoder(w).Encode(data)
216if err != nil {
217proxy.httpRespondErr(w, r, http.StatusInternalServerError, err)
218}
219}
220}
221
222// httpRespond writes a status code and string response to the response writer.
223func (proxy *Proxy) httpRespond(w http.ResponseWriter, r *http.Request, status int, message string) {
224w.WriteHeader(status)
225
226// Only expose the message detail of the reponse if the request is not HEAD
227// and the user is authenticated. For example, this prevents an unauthenticated
228// failed health check from accidentally leaking sensitive information about the Client.
229if r.Method != http.MethodHead && proxy.IsAllowed(r) {
230if message == "" {
231message = http.StatusText(status)
232}
233fmt.Fprint(w, message)
234}
235}
236
237// httpRespondErr is similar to httpRespond, except it formats errors to be more friendly.
238func (proxy *Proxy) httpRespondErr(w http.ResponseWriter, r *http.Request, defaultStatus int, err error) {
239status, err := httpError(defaultStatus, err)
240
241proxy.httpRespond(w, r, status, err.Error())
242if len(err.Error()) > 0 {
046be632Dalton6 years ago243cfRay := proxy.getRayHeader(r)
244proxy.logger.Infof("dbproxy: Database proxy error: cf-ray: %s %s", cfRay, err)
759cd019Ashcon Partovi6 years ago245}
246}
247
046be632Dalton6 years ago248// getRayHeader returns the request's Cf-ray header.
249func (proxy *Proxy) getRayHeader(r *http.Request) string {
250return r.Header.Get("Cf-ray")
759cd019Ashcon Partovi6 years ago251}
252
253// httpError extracts common errors and returns an status code and friendly error.
254func httpError(defaultStatus int, err error) (int, error) {
255if err == nil {
256return http.StatusNotImplemented, fmt.Errorf("error expected but found none")
257}
258
259if err == io.EOF {
260return http.StatusBadRequest, fmt.Errorf("request body cannot be empty")
261}
262
263if err == context.DeadlineExceeded {
264return http.StatusRequestTimeout, err
265}
266
267_, ok := err.(net.Error)
268if ok {
269return http.StatusRequestTimeout, err
270}
271
272if err == context.Canceled {
273// Does not exist in Golang, but would be: http.StatusClientClosedWithoutResponse
274return 444, err
275}
276
277return defaultStatus, err
278}