mirror of
https://github.com/tailscale/tailscale.git
synced 2026-12-06 23:36:34 +09:00
* k8s-operator/api-proxy: reject cross-origin browser requests in auth mode
In auth mode the API server proxy sets the caller's identity from their
tailnet address and does not check Origin. Browsers do not apply the
same-origin policy to WebSocket, so a page a tailnet user opened could
open exec, attach or watch WebSockets through the proxy and have them run
as that user.
This fixes this by rejecting cross-origin browser requests on every
route, as browsers also send simple cross-site POSTs without a
preflight. Requests with an Origin are checked on Sec-Fetch-Site first,
where same-origin and none pass and any other value is rejected, and if
the browser does not send it the Origin host must match Host. kubectl
and client-go send no Origin and the Python and fabric8 clients send one
that matches Host, so they still work, as do web UIs whose own proxy
rewrites Host, such as kubectl proxy, Headlamp and Backstage. Headlamp
desktop, whose file:// page is cross-site to its backend, now gets 403
for writes and WebSockets. noauth mode is unchanged as it has no
identity to borrow.
Updates tailscale/corp#51482
* k8s-operator/api-proxy: add test for cross-origin requests in auth mode
Adds a test that sends exec, attach and watch WebSocket upgrades and a
plain POST through the proxy with and without a foreign Origin and
Sec-Fetch-Site, and checks that in auth mode only requests with no Origin,
the proxy's own origin or Sec-Fetch-Site same-origin reach the API server.
Updates tailscale/corp#51482
---------
Change-Id: Ibd73d59912aa98b81f00d0f6c868ae1149bb5d20
(cherry picked from commit 001e91f5b4)
Signed-off-by: chaosinthecrd <tom@tmlabs.co.uk>
Co-authored-by: Tom Meadows <tom@tmlabs.co.uk>
Signed-off-by: Guy J Grigsby <guy@tailscale.com>
This commit is contained in:
1 parent
0093765a90
commit
73e5b75280
2 files changed
+230
No files matched your search
@@ -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
|
||||
|
||||
@@ -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{},
|
||||
|
||||
Reference in new issue
Block a user