mirror of
https://github.com/tailscale/tailscale.git
synced 2026-12-02 14:42:34 -08:00
net/captivedetection,feature/captiveportal: add the portal URL to the health warning
The captive portal warning told the user to log in using a web browser, but not where. Have the detector return the URL the captive portal redirected its request to, or the URL of the intercepted endpoint if the portal didn't redirect, and offer it as the warning's PrimaryAction. Signed-off-by: Nick Khyl <[email protected]>
This commit is contained in:
1 parent
ee2d0604dc
commit
8a45d69f31
4 files changed
+109
-32
No files matched your search
@@ -48,8 +48,17 @@ var captivePortalWarnable = health.Register(&health.Warnable{
|
||||
Severity: health.SeverityHigh,
|
||||
Text: health.StaticMessage("This network requires you to log in using your web browser."),
|
||||
ImpactsConnectivity: true,
|
||||
PrimaryAction: func(args health.Args) *health.UnhealthyStateAction {
|
||||
if args[argPortalURL] == "" {
|
||||
return nil
|
||||
}
|
||||
return &health.UnhealthyStateAction{URL: args[argPortalURL], Label: "Open login page"}
|
||||
},
|
||||
})
|
||||
|
||||
// argPortalURL provides captivePortalWarnable with the URL to log in to the captive portal.
|
||||
const argPortalURL health.Arg = "portal-url"
|
||||
|
||||
// Extension is the captive portal detection extension.
|
||||
// There is one per [ipnext.Host] (and hence per LocalBackend).
|
||||
type Extension struct {
|
||||
@@ -169,11 +178,11 @@ func (e *Extension) maybeDetectCaptivePortal() {
|
||||
}
|
||||
|
||||
e.logf("health: connectivity impacted; running captive portal detection")
|
||||
if e.detectCaptivePortal(e.ctx) {
|
||||
if found, portalURL := e.detectCaptivePortal(e.ctx); found {
|
||||
if !e.health.IsUnhealthy(captivePortalWarnable) {
|
||||
metricCaptivePortalDetected.Add(1)
|
||||
}
|
||||
e.health.SetUnhealthy(captivePortalWarnable, health.Args{})
|
||||
e.health.SetUnhealthy(captivePortalWarnable, health.Args{argPortalURL: portalURL})
|
||||
} else {
|
||||
e.health.SetHealthy(captivePortalWarnable)
|
||||
}
|
||||
@@ -188,8 +197,9 @@ func (e *Extension) captiveDetectionEnabled() bool {
|
||||
e.host.Profiles().CurrentPrefs().WantRunning()
|
||||
}
|
||||
|
||||
// detectCaptivePortal reports whether a captive portal is detected.
|
||||
func (e *Extension) detectCaptivePortal(ctx context.Context) (found bool) {
|
||||
// detectCaptivePortal reports whether a captive portal is detected
|
||||
// and, if so, the URL to log in to it.
|
||||
func (e *Extension) detectCaptivePortal(ctx context.Context) (found bool, portalURL string) {
|
||||
d := captivedetection.NewDetector(e.logf)
|
||||
dm := e.host.NodeBackend().DERPMap()
|
||||
var preferredDERP tailcfg.DERPRegionID
|
||||
|
||||
@@ -41,7 +41,7 @@ func startCaptivePortalDetection(ctx context.Context, c *netcheck.Client, dm *ta
|
||||
tmr := time.AfterFunc(captivePortalDelay, func() {
|
||||
defer close(ch)
|
||||
d := captivedetection.NewDetector(logf)
|
||||
found := d.Detect(ctx, c.NetMon, dm, preferredDERP)
|
||||
found, _ := d.Detect(ctx, c.NetMon, dm, preferredDERP)
|
||||
setCaptivePortal(found)
|
||||
})
|
||||
|
||||
|
||||
@@ -71,17 +71,21 @@ const Timeout = 3 * time.Second
|
||||
// or body that looks like a captive portal, Detect returns true. It returns false in all other cases, including when any
|
||||
// error occurs during a detection attempt.
|
||||
//
|
||||
// If a captive portal is found, portalURL is a URL to open in a browser to log in to it: the URL the captive portal
|
||||
// redirected the request to or, if it didn't redirect, the URL of the Endpoint it intercepted. It is controlled by
|
||||
// the network, and is only guaranteed to be an http or https URL.
|
||||
//
|
||||
// This function might take a while to return, as it will attempt to detect a captive portal on all available interfaces
|
||||
// by performing multiple HTTP requests. It should be called in a separate goroutine if you want to avoid blocking.
|
||||
func (d *Detector) Detect(ctx context.Context, netMon *netmon.Monitor, derpMap *tailcfg.DERPMap, preferredDERPRegionID tailcfg.DERPRegionID) (found bool) {
|
||||
func (d *Detector) Detect(ctx context.Context, netMon *netmon.Monitor, derpMap *tailcfg.DERPMap, preferredDERPRegionID tailcfg.DERPRegionID) (found bool, portalURL string) {
|
||||
return d.detectCaptivePortalWithGOOS(ctx, netMon, derpMap, preferredDERPRegionID, runtime.GOOS)
|
||||
}
|
||||
|
||||
func (d *Detector) detectCaptivePortalWithGOOS(ctx context.Context, netMon *netmon.Monitor, derpMap *tailcfg.DERPMap, preferredDERPRegionID tailcfg.DERPRegionID, goos string) (found bool) {
|
||||
func (d *Detector) detectCaptivePortalWithGOOS(ctx context.Context, netMon *netmon.Monitor, derpMap *tailcfg.DERPMap, preferredDERPRegionID tailcfg.DERPRegionID, goos string) (found bool, portalURL string) {
|
||||
ifState := netMon.InterfaceState()
|
||||
if !ifState.AnyInterfaceUp() {
|
||||
d.logf("[v2] DetectCaptivePortal: no interfaces up, returning false")
|
||||
return false
|
||||
return false, ""
|
||||
}
|
||||
|
||||
endpoints := availableEndpoints(derpMap, preferredDERPRegionID, d.logf, goos)
|
||||
@@ -105,15 +109,14 @@ func (d *Detector) detectCaptivePortalWithGOOS(ctx context.Context, netMon *netm
|
||||
continue
|
||||
}
|
||||
d.logf("[v2] attempting to do captive portal detection on interface %s", ifName)
|
||||
res := d.detectOnInterface(ctx, i.Index, endpoints)
|
||||
if res {
|
||||
if found, portalURL := d.detectOnInterface(ctx, i.Index, endpoints); found {
|
||||
d.logf("DetectCaptivePortal(found=true,ifName=%s)", ifName)
|
||||
return true
|
||||
return true, portalURL
|
||||
}
|
||||
}
|
||||
|
||||
d.logf("DetectCaptivePortal(found=false)")
|
||||
return false
|
||||
return false, ""
|
||||
}
|
||||
|
||||
// interfaceNameDoesNotNeedCaptiveDetection returns true if an interface does not require captive portal detection
|
||||
@@ -142,8 +145,9 @@ func interfaceNameDoesNotNeedCaptiveDetection(ifName string, goos string) bool {
|
||||
// captive portal, detected by making a request to a URL that we know should
|
||||
// return a "204 No Content" response and checking if that's what we get.
|
||||
//
|
||||
// The boolean return is whether we think we have a captive portal.
|
||||
func (d *Detector) detectOnInterface(ctx context.Context, ifIndex int, endpoints []Endpoint) bool {
|
||||
// It reports whether we think we have a captive portal and, if so, the URL
|
||||
// to log in to it.
|
||||
func (d *Detector) detectOnInterface(ctx context.Context, ifIndex int, endpoints []Endpoint) (found bool, portalURL string) {
|
||||
defer d.httpClient.CloseIdleConnections()
|
||||
|
||||
use := min(len(endpoints), 5)
|
||||
@@ -152,7 +156,7 @@ func (d *Detector) detectOnInterface(ctx context.Context, ifIndex int, endpoints
|
||||
|
||||
// We try to detect the captive portal more quickly by making requests to multiple endpoints concurrently.
|
||||
var wg sync.WaitGroup
|
||||
resultCh := make(chan bool, len(endpoints))
|
||||
resultCh := make(chan string, len(endpoints))
|
||||
|
||||
// Once any goroutine detects a captive portal, we shut down the others.
|
||||
ctx, cancel := context.WithCancel(ctx)
|
||||
@@ -162,7 +166,7 @@ func (d *Detector) detectOnInterface(ctx context.Context, ifIndex int, endpoints
|
||||
wg.Add(1)
|
||||
go func(endpoint Endpoint) {
|
||||
defer wg.Done()
|
||||
found, err := d.verifyCaptivePortalEndpoint(ctx, endpoint, ifIndex)
|
||||
found, portalURL, err := d.verifyCaptivePortalEndpoint(ctx, endpoint, ifIndex)
|
||||
if err != nil {
|
||||
if ctx.Err() == nil {
|
||||
d.logf("[v1] checkCaptivePortalEndpoint failed with endpoint %v: %v", endpoint, err)
|
||||
@@ -171,7 +175,7 @@ func (d *Detector) detectOnInterface(ctx context.Context, ifIndex int, endpoints
|
||||
}
|
||||
if found {
|
||||
cancel() // one match is good enough
|
||||
resultCh <- true
|
||||
resultCh <- portalURL
|
||||
}
|
||||
}(e)
|
||||
}
|
||||
@@ -181,19 +185,18 @@ func (d *Detector) detectOnInterface(ctx context.Context, ifIndex int, endpoints
|
||||
close(resultCh)
|
||||
}()
|
||||
|
||||
for result := range resultCh {
|
||||
if result {
|
||||
// If any of the endpoints seems to be a captive portal, we consider the system to be behind one.
|
||||
return true
|
||||
}
|
||||
for portalURL := range resultCh {
|
||||
// If any of the endpoints seems to be a captive portal, we consider the system to be behind one.
|
||||
return true, portalURL
|
||||
}
|
||||
|
||||
return false
|
||||
return false, ""
|
||||
}
|
||||
|
||||
// verifyCaptivePortalEndpoint checks if the given Endpoint is a captive portal by making an HTTP request to the
|
||||
// given Endpoint URL using the interface with index ifIndex, and checking if the response looks like a captive portal.
|
||||
func (d *Detector) verifyCaptivePortalEndpoint(ctx context.Context, e Endpoint, ifIndex int) (found bool, err error) {
|
||||
// If it does, portalURL is the URL the response redirects to, or the Endpoint URL if it's not a redirect.
|
||||
func (d *Detector) verifyCaptivePortalEndpoint(ctx context.Context, e Endpoint, ifIndex int) (found bool, portalURL string, err error) {
|
||||
ctx, cancel := context.WithTimeout(ctx, Timeout)
|
||||
defer cancel()
|
||||
|
||||
@@ -204,7 +207,7 @@ func (d *Detector) verifyCaptivePortalEndpoint(ctx context.Context, e Endpoint,
|
||||
|
||||
req, err := http.NewRequestWithContext(ctx, "GET", u.String(), nil)
|
||||
if err != nil {
|
||||
return false, err
|
||||
return false, "", err
|
||||
}
|
||||
req.Header.Set("Cache-Control", "no-cache, no-store, must-revalidate, no-transform, max-age=0")
|
||||
|
||||
@@ -225,10 +228,16 @@ func (d *Detector) verifyCaptivePortalEndpoint(ctx context.Context, e Endpoint,
|
||||
// Make the actual request, and check if the response looks like a captive portal or not.
|
||||
r, err := d.httpClient.Do(req)
|
||||
if err != nil {
|
||||
return false, err
|
||||
return false, "", err
|
||||
}
|
||||
|
||||
return e.responseLooksLikeCaptive(r, d.logf), nil
|
||||
if !e.responseLooksLikeCaptive(r, d.logf) {
|
||||
return false, "", nil
|
||||
}
|
||||
if loc, err := r.Location(); err == nil && (loc.Scheme == "http" || loc.Scheme == "https") {
|
||||
return true, loc.String(), nil
|
||||
}
|
||||
return true, e.URL.String(), nil
|
||||
}
|
||||
|
||||
func (d *Detector) dialContext(ctx context.Context, network, addr string) (net.Conn, error) {
|
||||
|
||||
@@ -6,6 +6,7 @@ package captivedetection
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -78,7 +79,7 @@ func TestDetectCaptivePortalReturnsFalse(t *testing.T) {
|
||||
ok := derpserver.ServeNoContent
|
||||
dm, hits := localDERPMap(t, ok, ok, ok, ok, ok)
|
||||
d := NewDetector(t.Logf)
|
||||
found := d.Detect(t.Context(), netmon.NewStatic(), dm, 0)
|
||||
found, _ := d.Detect(t.Context(), netmon.NewStatic(), dm, 0)
|
||||
if found {
|
||||
t.Errorf("DetectCaptivePortal returned true, expected false.")
|
||||
}
|
||||
@@ -94,7 +95,7 @@ func TestDetectCaptivePortalReturnsTrue(t *testing.T) {
|
||||
ok := derpserver.ServeNoContent
|
||||
dm, hits := localDERPMap(t, ok, ok, ok, ok, notFound)
|
||||
d := NewDetector(t.Logf)
|
||||
found := d.Detect(t.Context(), netmon.NewStatic(), dm, 0)
|
||||
found, _ := d.Detect(t.Context(), netmon.NewStatic(), dm, 0)
|
||||
if hits.Load() == 0 {
|
||||
t.Skip("no endpoint was reached; no usable non-loopback interface?")
|
||||
}
|
||||
@@ -126,7 +127,7 @@ func TestEndpointsAreUpAndReturnExpectedResponse(t *testing.T) {
|
||||
}
|
||||
defer sem.Release()
|
||||
|
||||
found, err := d.verifyCaptivePortalEndpoint(ctx, endpoint, 0)
|
||||
found, _, err := d.verifyCaptivePortalEndpoint(ctx, endpoint, 0)
|
||||
if err != nil && ctx.Err() == nil {
|
||||
t.Logf("verifyCaptivePortalEndpoint failed with endpoint %v: %v", endpoint, err)
|
||||
}
|
||||
@@ -178,7 +179,7 @@ func TestCaptivePortalRequest(t *testing.T) {
|
||||
SupportsTailscaleChallenge: true,
|
||||
}
|
||||
|
||||
found, err := d.verifyCaptivePortalEndpoint(ctx, e, 0)
|
||||
found, _, err := d.verifyCaptivePortalEndpoint(ctx, e, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("verifyCaptivePortalEndpoint = %v, %v", found, err)
|
||||
}
|
||||
@@ -200,7 +201,7 @@ func TestAgainstDERPHandler(t *testing.T) {
|
||||
ExpectedContent: "",
|
||||
SupportsTailscaleChallenge: true,
|
||||
}
|
||||
found, err := d.verifyCaptivePortalEndpoint(ctx, e, 0)
|
||||
found, _, err := d.verifyCaptivePortalEndpoint(ctx, e, 0)
|
||||
if err != nil {
|
||||
t.Fatalf("verifyCaptivePortalEndpoint = %v, %v", found, err)
|
||||
}
|
||||
@@ -208,3 +209,60 @@ func TestAgainstDERPHandler(t *testing.T) {
|
||||
t.Errorf("verifyCaptivePortalEndpoint = %v, want false", found)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPortalURL(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
location string // if non-empty, the portal redirects to it
|
||||
want func(endpoint string) string
|
||||
}{
|
||||
{
|
||||
name: "redirect",
|
||||
location: "https://portal.example.com/login?id=1",
|
||||
want: func(string) string { return "https://portal.example.com/login?id=1" },
|
||||
},
|
||||
{
|
||||
name: "relative-redirect",
|
||||
location: "/login",
|
||||
want: func(endpoint string) string {
|
||||
return must.Get(url.Parse(endpoint)).ResolveReference(&url.URL{Path: "/login"}).String()
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "non-http-redirect",
|
||||
location: "javascript:alert(1)",
|
||||
want: func(endpoint string) string { return endpoint },
|
||||
},
|
||||
{
|
||||
name: "no-redirect",
|
||||
want: func(endpoint string) string { return endpoint },
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
s := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if tt.location != "" {
|
||||
w.Header().Set("Location", tt.location)
|
||||
w.WriteHeader(http.StatusFound)
|
||||
return
|
||||
}
|
||||
io.WriteString(w, "<html>Please log in.</html>")
|
||||
}))
|
||||
defer s.Close()
|
||||
e := Endpoint{
|
||||
URL: must.Get(url.Parse(s.URL + "/generate_204")),
|
||||
StatusCode: 204,
|
||||
SupportsTailscaleChallenge: true,
|
||||
}
|
||||
|
||||
d := NewDetector(t.Logf)
|
||||
found, got, err := d.verifyCaptivePortalEndpoint(t.Context(), e, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := tt.want(e.URL.String()); !found || got != want {
|
||||
t.Errorf("got %v, %q; want true, %q", found, got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user