diff --git a/k8s-operator/api-proxy/proxy.go b/k8s-operator/api-proxy/proxy.go index 7e72d09a4..beada6709 100644 --- a/k8s-operator/api-proxy/proxy.go +++ b/k8s-operator/api-proxy/proxy.go @@ -207,6 +207,11 @@ type APIServerProxy struct { // serveDefault is the default handler for Kubernetes API server requests. func (ap *APIServerProxy) serveDefault(w http.ResponseWriter, r *http.Request) { + if err := ap.checkOrigin(r); err != nil { + ap.originError(w, r, err) + return + } + who, err := ap.whoIs(r) if err != nil { ap.authError(w, err) @@ -276,6 +281,11 @@ func (ap *APIServerProxy) sessionForProto(w http.ResponseWriter, r *http.Request upgradeHeaderKey = "Upgrade" ) + if err := ap.checkOrigin(r); err != nil { + ap.originError(w, r, err) + return + } + who, err := ap.whoIs(r) if err != nil { ap.authError(w, err) @@ -480,6 +490,43 @@ func (ap *APIServerProxy) authError(w http.ResponseWriter, err error) { http.Error(w, "failed to authenticate caller", http.StatusInternalServerError) } +// checkOrigin rejects browser requests from other origins, which in auth mode +// would run as the caller. Sec-Fetch-Site is checked first, as a web UI's own +// proxy forwards it but rewrites Host. kubectl sends no Origin and the Python +// and fabric8 clients send one that matches Host. +func (ap *APIServerProxy) checkOrigin(r *http.Request) error { + if !ap.authMode { + return nil + } + // TODO(ChaosInTheCRD): a plain-HTTP listener on the tailnet would also need + // a Host allowlist, as without TLS DNS rebinding makes a page same-origin. + origin := r.Header.Get("Origin") + if origin == "" { + return nil + } + switch sfs := r.Header.Get("Sec-Fetch-Site"); sfs { + case "": + // Older browsers and non-browser clients do not send it. + case "same-origin", "none": + return nil + default: + return fmt.Errorf("origin %q with Sec-Fetch-Site %q", origin, sfs) + } + u, err := url.Parse(origin) + if err != nil { + return fmt.Errorf("invalid origin %q: %w", origin, err) + } + if !strings.EqualFold(u.Host, r.Host) { + return fmt.Errorf("origin %q does not match host %q", origin, r.Host) + } + return nil +} + +func (ap *APIServerProxy) originError(w http.ResponseWriter, r *http.Request, err error) { + ap.log.With("remote", r.RemoteAddr).Warnf("rejecting cross-origin request: %v", err) + http.Error(w, "forbidden: cross-origin request", http.StatusForbidden) +} + const ( // oldCapabilityName is a legacy form of // tailfcg.PeerCapabilityKubernetes capability. The only capability rule diff --git a/k8s-operator/api-proxy/proxy_test.go b/k8s-operator/api-proxy/proxy_test.go index ade993acd..9fa0b68a0 100644 --- a/k8s-operator/api-proxy/proxy_test.go +++ b/k8s-operator/api-proxy/proxy_test.go @@ -7,9 +7,12 @@ package apiproxy import ( "encoding/json" + "net" "net/http" "net/http/httptest" + "net/http/httputil" "net/netip" + "net/url" "reflect" "testing" @@ -273,6 +276,186 @@ func TestWhoIs(t *testing.T) { } } +// TestCrossOriginRequests checks that in auth mode the proxy rejects browser +// requests from other origins, including exec WebSocket upgrades, and still +// forwards requests with no Origin (kubectl), with an Origin that matches +// Host (the Python client) or marked same-origin by the browser (a web UI's +// own proxy). +func TestCrossOriginRequests(t *testing.T) { + lal := memnet.Listen("local-tailscaled.sock:80") + defer lal.Close() + localAPI := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + json.NewEncoder(w).Encode(&apitype.WhoIsResponse{ + Node: &tailcfg.Node{Name: "user-node.ts.net."}, + UserProfile: &tailcfg.UserProfile{LoginName: "user@example.com"}, + }) + })} + defer localAPI.Close() + go localAPI.Serve(lal) + + tests := []struct { + name string + method string // empty means a GET WebSocket upgrade + path string + origin string + fetchSite string // Sec-Fetch-Site + sameOrigin bool + otherPort bool + noAuth bool + wantStatus int + }{ + { + name: "exec_ws_no_origin", + path: "/api/v1/namespaces/default/pods/foo/exec?command=sh", + wantStatus: http.StatusSwitchingProtocols, + }, + { + name: "exec_ws_origin_matches_host", + path: "/api/v1/namespaces/default/pods/foo/exec?command=sh", + sameOrigin: true, + wantStatus: http.StatusSwitchingProtocols, + }, + { + name: "exec_ws_origin_other_port", + path: "/api/v1/namespaces/default/pods/foo/exec?command=sh", + otherPort: true, + wantStatus: http.StatusForbidden, + }, + { + name: "exec_ws_cross_origin", + path: "/api/v1/namespaces/default/pods/foo/exec?command=sh", + origin: "https://evil.example", + wantStatus: http.StatusForbidden, + }, + { + name: "exec_ws_null_origin", + path: "/api/v1/namespaces/default/pods/foo/exec?command=sh", + origin: "null", + wantStatus: http.StatusForbidden, + }, + { + name: "exec_ws_via_ui_proxy", + path: "/api/v1/namespaces/default/pods/foo/exec?command=sh", + origin: "http://127.0.0.1:4466", + fetchSite: "same-origin", + wantStatus: http.StatusSwitchingProtocols, + }, + { + name: "exec_ws_cross_site", + path: "/api/v1/namespaces/default/pods/foo/exec?command=sh", + origin: "https://evil.example", + fetchSite: "cross-site", + wantStatus: http.StatusForbidden, + }, + { + name: "attach_ws_cross_origin", + path: "/api/v1/namespaces/default/pods/foo/attach", + origin: "https://evil.example", + wantStatus: http.StatusForbidden, + }, + { + name: "watch_ws_cross_origin", + path: "/api/v1/secrets?watch=true", + origin: "https://evil.example", + wantStatus: http.StatusForbidden, + }, + { + name: "nodes_proxy_post_cross_origin", + method: "POST", + path: "/api/v1/nodes/foo/proxy/run/default/bar/baz?cmd=id", + origin: "https://evil.example", + wantStatus: http.StatusForbidden, + }, + { + name: "noauth_exec_ws_cross_origin", + path: "/api/v1/namespaces/default/pods/foo/exec?command=sh", + origin: "https://evil.example", + noAuth: true, + wantStatus: http.StatusSwitchingProtocols, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + gotUser := make(chan string, 1) + upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotUser <- r.Header.Get("Impersonate-User") + if r.Header.Get("Upgrade") == "" { + return + } + w.Header().Set("Connection", "Upgrade") + w.Header().Set("Upgrade", "websocket") + w.WriteHeader(http.StatusSwitchingProtocols) + })) + defer upstream.Close() + + ap := &APIServerProxy{ + log: zap.NewNop().Sugar(), + lc: &local.Client{Dial: lal.Dial}, + authMode: !tt.noAuth, + upstreamURL: must.Get(url.Parse(upstream.URL)), + } + ap.rp = &httputil.ReverseProxy{ + Rewrite: func(pr *httputil.ProxyRequest) { + ap.addImpersonationHeadersAsRequired(pr.Out) + }, + } + mux := http.NewServeMux() + mux.HandleFunc("/", ap.serveDefault) + mux.HandleFunc("GET /api/v1/namespaces/{namespace}/pods/{pod}/exec", ap.serveExecWS) + mux.HandleFunc("GET /api/v1/namespaces/{namespace}/pods/{pod}/attach", ap.serveAttachWS) + srv := httptest.NewServer(mux) + defer srv.Close() + + method := tt.method + if method == "" { + method = "GET" + } + req := must.Get(http.NewRequestWithContext(t.Context(), method, srv.URL+tt.path, nil)) + if method == "GET" { + req.Header.Set("Connection", "Upgrade") + req.Header.Set("Upgrade", "websocket") + req.Header.Set("Sec-WebSocket-Version", "13") + req.Header.Set("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==") + req.Header.Set("Sec-WebSocket-Protocol", "v5.channel.k8s.io") + } + switch { + case tt.sameOrigin: + req.Header.Set("Origin", srv.URL) + case tt.otherPort: + host, _, _ := net.SplitHostPort(srv.Listener.Addr().String()) + req.Header.Set("Origin", "http://"+net.JoinHostPort(host, "1")) + case tt.origin != "": + req.Header.Set("Origin", tt.origin) + } + if tt.fetchSite != "" { + req.Header.Set("Sec-Fetch-Site", tt.fetchSite) + } + resp, err := srv.Client().Do(req) + if err != nil { + t.Fatal(err) + } + resp.Body.Close() + + if resp.StatusCode != tt.wantStatus { + t.Fatalf("status = %d, want %d", resp.StatusCode, tt.wantStatus) + } + select { + case user := <-gotUser: + if tt.wantStatus == http.StatusForbidden { + t.Fatalf("rejected request reached the API server as %q", user) + } + if want := "user@example.com"; !tt.noAuth && user != want { + t.Errorf("Impersonate-User = %q, want %q", user, want) + } + default: + if tt.wantStatus != http.StatusForbidden { + t.Fatal("request was not forwarded to the API server") + } + } + }) + } +} + func whoResp(capMap map[string][]string) *apitype.WhoIsResponse { resp := &apitype.WhoIsResponse{ CapMap: tailcfg.PeerCapMap{},