mirror of
https://github.com/tailscale/tailscale.git
synced 2026-11-24 02:31:18 -08:00
Some HTTP proxies (as seen in ChatGPT Work's sandbox) intercept TLS and refuse DERP's "Upgrade: DERP" request but allow WebSocket upgrades, like browsers use. derphttp could already speak DERP over WebSockets, but only on js/wasm or with the ts_debug_websockets build tag and an envknob, and that path dials with its own http.Client, skipping the DERP node selection, proxy CONNECT, and TLS logic of the normal path. Add derphttp.HookUpgradeWebsocket. When it's set and a client's HTTP upgrade to DERP fails after any TLS handshake succeeded, the client redials and calls the hook to do a WebSocket handshake over the new connection instead. Once that works, the client keeps using WebSockets for its reconnects until they fail, so it doesn't pay for a refused upgrade every time. The new feature/derpwebsocket package sets the hook. Neither tailscaled nor tsnet links it in; programs that want the fallback, like tailcat, import it. Updates #22412 Signed-off-by: Brad Fitzpatrick <[email protected]> Change-Id: I20e4b29f1bca6e7e5e3b33f960ce9d331ec7dac9
57 lines
1.5 KiB
Go
57 lines
1.5 KiB
Go
// Copyright (c) Tailscale Inc & contributors
|
|
// SPDX-License-Identifier: BSD-3-Clause
|
|
|
|
//go:build !js
|
|
|
|
package derpwebsocket
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"net"
|
|
"net/http"
|
|
"sync/atomic"
|
|
|
|
"github.com/coder/websocket"
|
|
"tailscale.com/derp/derphttp"
|
|
"tailscale.com/feature"
|
|
"tailscale.com/net/wsconn"
|
|
)
|
|
|
|
func init() {
|
|
if !feature.Register("derpwebsocket") {
|
|
return
|
|
}
|
|
derphttp.HookUpgradeWebsocket.Set(upgrade)
|
|
}
|
|
|
|
// upgrade does a WebSocket handshake with the DERP server at urlStr over
|
|
// conn, which derphttp has already dialed (via any HTTP proxy) and, for
|
|
// https URLs, TLS-wrapped. It returns a net.Conn that carries DERP frames
|
|
// in binary WebSocket messages.
|
|
func upgrade(ctx context.Context, conn net.Conn, urlStr string) (net.Conn, error) {
|
|
var used atomic.Bool
|
|
dial := func(context.Context, string, string) (net.Conn, error) {
|
|
if used.Swap(true) {
|
|
return nil, errors.New("DERP websocket handshake tried to dial a second connection")
|
|
}
|
|
return conn, nil
|
|
}
|
|
hc := &http.Client{
|
|
Transport: &http.Transport{
|
|
DialContext: dial, // for http URLs
|
|
DialTLSContext: dial, // for https URLs; conn is already TLS
|
|
},
|
|
}
|
|
wc, _, err := websocket.Dial(ctx, urlStr, &websocket.DialOptions{
|
|
HTTPClient: hc,
|
|
Subprotocols: []string{"derp"},
|
|
// WireGuard packets don't compress.
|
|
CompressionMode: websocket.CompressionDisabled,
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return wsconn.NetConn(context.Background(), wc, websocket.MessageBinary, urlStr), nil
|
|
}
|