mirror of
https://github.com/tailscale/tailscale.git
synced 2026-12-01 06:02:32 -08: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 <[email protected]>
Co-authored-by: Tom Meadows <[email protected]>
476 lines
14 KiB
Go
476 lines
14 KiB
Go
// Copyright (c) Tailscale Inc & contributors
|
|
// SPDX-License-Identifier: BSD-3-Clause
|
|
|
|
//go:build !plan9
|
|
|
|
package apiproxy
|
|
|
|
import (
|
|
"encoding/json"
|
|
"net"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"net/http/httputil"
|
|
"net/netip"
|
|
"net/url"
|
|
"reflect"
|
|
"testing"
|
|
|
|
"github.com/google/go-cmp/cmp"
|
|
"go.uber.org/zap"
|
|
"tailscale.com/client/local"
|
|
"tailscale.com/client/tailscale/apitype"
|
|
"tailscale.com/net/memnet"
|
|
"tailscale.com/tailcfg"
|
|
"tailscale.com/tailcfg/peercap"
|
|
"tailscale.com/util/must"
|
|
)
|
|
|
|
func TestImpersonationHeaders(t *testing.T) {
|
|
zl, err := zap.NewDevelopment()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
tests := []struct {
|
|
name string
|
|
emailish string
|
|
tags []string
|
|
capMap tailcfg.PeerCapMap
|
|
|
|
wantHeaders http.Header
|
|
}{
|
|
{
|
|
name: "user",
|
|
emailish: "[email protected]",
|
|
wantHeaders: http.Header{
|
|
"Impersonate-User": {"[email protected]"},
|
|
},
|
|
},
|
|
{
|
|
name: "tagged",
|
|
emailish: "tagged-device",
|
|
tags: []string{"tag:foo", "tag:bar"},
|
|
wantHeaders: http.Header{
|
|
"Impersonate-User": {"node.ts.net"},
|
|
"Impersonate-Group": {"tag:foo", "tag:bar"},
|
|
},
|
|
},
|
|
{
|
|
name: "user-with-cap",
|
|
emailish: "[email protected]",
|
|
capMap: tailcfg.PeerCapMap{
|
|
peercap.Kubernetes: {
|
|
tailcfg.RawMessage(`{"impersonate":{"groups":["group1","group2"]}}`),
|
|
tailcfg.RawMessage(`{"impersonate":{"groups":["group1","group3"]}}`), // One group is duplicated.
|
|
tailcfg.RawMessage(`{"impersonate":{"groups":["group4"]}}`),
|
|
tailcfg.RawMessage(`{"impersonate":{"groups":["group2"]}}`), // duplicate
|
|
|
|
// These should be ignored, but should parse correctly.
|
|
tailcfg.RawMessage(`{}`),
|
|
tailcfg.RawMessage(`{"impersonate":{}}`),
|
|
tailcfg.RawMessage(`{"impersonate":{"groups":[]}}`),
|
|
},
|
|
},
|
|
wantHeaders: http.Header{
|
|
"Impersonate-Group": {"group1", "group2", "group3", "group4"},
|
|
"Impersonate-User": {"[email protected]"},
|
|
},
|
|
},
|
|
{
|
|
name: "tagged-with-cap",
|
|
emailish: "tagged-device",
|
|
tags: []string{"tag:foo", "tag:bar"},
|
|
capMap: tailcfg.PeerCapMap{
|
|
peercap.Kubernetes: {
|
|
tailcfg.RawMessage(`{"impersonate":{"groups":["group1"]}}`),
|
|
},
|
|
},
|
|
wantHeaders: http.Header{
|
|
"Impersonate-Group": {"group1"},
|
|
"Impersonate-User": {"node.ts.net"},
|
|
},
|
|
},
|
|
{
|
|
name: "mix-of-caps",
|
|
emailish: "tagged-device",
|
|
tags: []string{"tag:foo", "tag:bar"},
|
|
capMap: tailcfg.PeerCapMap{
|
|
peercap.Kubernetes: {
|
|
tailcfg.RawMessage(`{"impersonate":{"groups":["group1"]},"recorder":["tag:foo"],"enforceRecorder":true}`),
|
|
},
|
|
},
|
|
wantHeaders: http.Header{
|
|
"Impersonate-Group": {"group1"},
|
|
"Impersonate-User": {"node.ts.net"},
|
|
},
|
|
},
|
|
{
|
|
name: "bad-cap",
|
|
emailish: "tagged-device",
|
|
tags: []string{"tag:foo", "tag:bar"},
|
|
capMap: tailcfg.PeerCapMap{
|
|
peercap.Kubernetes: {
|
|
tailcfg.RawMessage(`[]`),
|
|
},
|
|
},
|
|
wantHeaders: http.Header{},
|
|
},
|
|
}
|
|
|
|
for _, tc := range tests {
|
|
r := must.Get(http.NewRequest("GET", "https://op.ts.net/api/foo", nil))
|
|
r = r.WithContext(whoIsKey.WithValue(r.Context(), &apitype.WhoIsResponse{
|
|
Node: &tailcfg.Node{
|
|
Name: "node.ts.net",
|
|
Tags: tc.tags,
|
|
},
|
|
UserProfile: &tailcfg.UserProfile{
|
|
LoginName: tc.emailish,
|
|
},
|
|
CapMap: tc.capMap,
|
|
}))
|
|
addImpersonationHeaders(r, zl.Sugar())
|
|
|
|
if d := cmp.Diff(tc.wantHeaders, r.Header); d != "" {
|
|
t.Errorf("unexpected header (-want +got):\n%s", d)
|
|
}
|
|
}
|
|
}
|
|
|
|
func Test_determineRecorderConfig(t *testing.T) {
|
|
addr1, addr2 := netip.MustParseAddrPort("[fd7a:115c:a1e0:ab12:4843:cd96:626b:628b]:80"), netip.MustParseAddrPort("100.99.99.99:80")
|
|
tests := []struct {
|
|
name string
|
|
wantFailOpen bool
|
|
wantRecorderAddresses []netip.AddrPort
|
|
who *apitype.WhoIsResponse
|
|
}{
|
|
{
|
|
name: "two_ips_fail_closed",
|
|
who: whoResp(map[string][]string{string(peercap.Kubernetes): {`{"recorderAddrs":["[fd7a:115c:a1e0:ab12:4843:cd96:626b:628b]:80","100.99.99.99:80"],"enforceRecorder":true}`}}),
|
|
wantRecorderAddresses: []netip.AddrPort{addr1, addr2},
|
|
},
|
|
{
|
|
name: "two_ips_fail_open",
|
|
who: whoResp(map[string][]string{string(peercap.Kubernetes): {`{"recorderAddrs":["[fd7a:115c:a1e0:ab12:4843:cd96:626b:628b]:80","100.99.99.99:80"]}`}}),
|
|
wantRecorderAddresses: []netip.AddrPort{addr1, addr2},
|
|
wantFailOpen: true,
|
|
},
|
|
{
|
|
name: "odd_rule_combination_fail_closed",
|
|
who: whoResp(map[string][]string{string(peercap.Kubernetes): {`{"recorderAddrs":["100.99.99.99:80"],"enforceRecorder":false}`, `{"recorderAddrs":["[fd7a:115c:a1e0:ab12:4843:cd96:626b:628b]:80"]}`, `{"enforceRecorder":true,"impersonate":{"groups":["system:masters"]}}`}}),
|
|
wantRecorderAddresses: []netip.AddrPort{addr2, addr1},
|
|
},
|
|
{
|
|
name: "no_caps",
|
|
who: whoResp(map[string][]string{}),
|
|
wantFailOpen: true,
|
|
},
|
|
{
|
|
name: "no_recorder_caps",
|
|
who: whoResp(map[string][]string{"foo": {`{"x":"y"}`}, string(peercap.Kubernetes): {`{"impersonate":{"groups":["system:masters"]}}`}}),
|
|
wantFailOpen: true,
|
|
},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
c, err := determineRecorderConfig(tt.who)
|
|
if err != nil {
|
|
t.Fatalf("unexpected error: %v", err)
|
|
}
|
|
if c.failOpen != tt.wantFailOpen {
|
|
t.Errorf("determineRecorderConfig() gotFailOpen = %v, want %v", c.failOpen, tt.wantFailOpen)
|
|
}
|
|
if !reflect.DeepEqual(c.recorderAddresses, tt.wantRecorderAddresses) {
|
|
t.Errorf("determineRecorderConfig() gotRecorderAddresses = %v, want %v", c.recorderAddresses, tt.wantRecorderAddresses)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// TestWhoIs checks that whoIs resolves the caller from the request's remote
|
|
// address and ignores the X-Forwarded-For header.
|
|
func TestWhoIs(t *testing.T) {
|
|
zl, err := zap.NewDevelopment()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
|
|
nodes := map[string]*apitype.WhoIsResponse{
|
|
"100.64.0.1:1234": {
|
|
Node: &tailcfg.Node{Name: "user-node.ts.net."},
|
|
UserProfile: &tailcfg.UserProfile{LoginName: "[email protected]"},
|
|
},
|
|
"100.64.0.2": {
|
|
Node: &tailcfg.Node{Name: "admin-node.ts.net."},
|
|
UserProfile: &tailcfg.UserProfile{LoginName: "[email protected]"},
|
|
},
|
|
}
|
|
lal := memnet.Listen("local-tailscaled.sock:80")
|
|
defer lal.Close()
|
|
localAPI := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
who, ok := nodes[r.URL.Query().Get("addr")]
|
|
if !ok {
|
|
http.Error(w, "no match for IP:port", http.StatusNotFound)
|
|
return
|
|
}
|
|
json.NewEncoder(w).Encode(who)
|
|
})}
|
|
defer localAPI.Close()
|
|
go localAPI.Serve(lal)
|
|
|
|
ap := &APIServerProxy{
|
|
log: zl.Sugar(),
|
|
lc: &local.Client{Dial: lal.Dial},
|
|
}
|
|
|
|
tests := []struct {
|
|
name string
|
|
remoteAddr string
|
|
xForwardedFor string
|
|
wantLogin string // empty if whoIs should fail
|
|
}{
|
|
{
|
|
name: "tailnet_node",
|
|
remoteAddr: "100.64.0.1:1234",
|
|
wantLogin: "[email protected]",
|
|
},
|
|
{
|
|
name: "not_a_tailnet_node",
|
|
remoteAddr: "10.0.0.5:1234",
|
|
},
|
|
{
|
|
name: "x_forwarded_for_ignored",
|
|
remoteAddr: "10.0.0.5:1234",
|
|
xForwardedFor: "100.64.0.2",
|
|
},
|
|
{
|
|
name: "x_forwarded_for_ignored_for_tailnet_node",
|
|
remoteAddr: "100.64.0.1:1234",
|
|
xForwardedFor: "100.64.0.2",
|
|
wantLogin: "[email protected]",
|
|
},
|
|
}
|
|
for _, tt := range tests {
|
|
t.Run(tt.name, func(t *testing.T) {
|
|
r := httptest.NewRequest("GET", "/api/v1/namespaces/kube-system/secrets", nil)
|
|
r.RemoteAddr = tt.remoteAddr
|
|
if tt.xForwardedFor != "" {
|
|
r.Header.Set("X-Forwarded-For", tt.xForwardedFor)
|
|
}
|
|
|
|
who, err := ap.whoIs(r)
|
|
if tt.wantLogin == "" {
|
|
if err == nil {
|
|
t.Fatalf("whoIs() = %q, want error", who.UserProfile.LoginName)
|
|
}
|
|
return
|
|
}
|
|
if err != nil {
|
|
t.Fatalf("whoIs() unexpected error: %v", err)
|
|
}
|
|
if got := who.UserProfile.LoginName; got != tt.wantLogin {
|
|
t.Errorf("whoIs() = %q, want %q", got, tt.wantLogin)
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
// 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: "[email protected]"},
|
|
})
|
|
})}
|
|
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 := "[email protected]"; !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{},
|
|
}
|
|
for cap, rules := range capMap {
|
|
resp.CapMap[peercap.Cap(cap)] = raw(rules...)
|
|
}
|
|
return resp
|
|
}
|
|
|
|
func raw(in ...string) []tailcfg.RawMessage {
|
|
var out []tailcfg.RawMessage
|
|
for _, i := range in {
|
|
out = append(out, tailcfg.RawMessage(i))
|
|
}
|
|
return out
|
|
}
|