diff --git a/go.mod b/go.mod index 2782f31bf..78c19a420 100644 --- a/go.mod +++ b/go.mod @@ -40,7 +40,7 @@ require ( github.com/projectdiscovery/rod v0.116.3-0.20261113214723-dd0abeca2a24 github.com/projectdiscovery/tlsx v1.5.0 github.com/projectdiscovery/useragent v0.0.110 - github.com/projectdiscovery/utils v0.11.13 + github.com/projectdiscovery/utils v0.11.17-0.20261122142141-bb5b328c030e github.com/projectdiscovery/wappalyzergo v0.3.8 github.com/rs/xid v1.6.0 github.com/seh-msft/burpxml v1.0.1 @@ -122,7 +122,7 @@ require ( github.com/projectdiscovery/govaluate v0.0.0-20260504230327-80320480bb6e // indirect github.com/projectdiscovery/jarm-go v0.0.0-20260910160638-430e2bae86f6 // indirect github.com/projectdiscovery/machineid v0.0.0-20250715113114-c77eb3567582 // indirect - github.com/projectdiscovery/retryabledns v1.0.118 // indirect + github.com/projectdiscovery/retryabledns v1.0.119 // indirect github.com/refraction-networking/utls v1.8.2 // indirect github.com/rivo/uniseg v0.4.7 // indirect github.com/rogpeppe/go-internal v1.12.0 // indirect diff --git a/go.sum b/go.sum index e673d859e..e76bda8f1 100644 --- a/go.sum +++ b/go.sum @@ -263,8 +263,8 @@ github.com/projectdiscovery/ratelimit v0.0.95 h1:/vwnXSuVz9di/nJ2x/ebX9d1Hd320nU github.com/projectdiscovery/ratelimit v0.0.95/go.mod h1:QCzQMpdcjlXZNhfy1UJFp6vdPk2E3DaGKxKhFZ3dI48= github.com/projectdiscovery/rawhttp v0.3.1 h1:utudlS3qCAZYa+DU+WK0Q0uuiUxgYXfLwxWIs9dd1Bc= github.com/projectdiscovery/rawhttp v0.3.1/go.mod h1:ezbLgLuzFC3EunY4OqptRunQb6QUM7z78gOBL8DrWYY= -github.com/projectdiscovery/retryabledns v1.0.118 h1:vrWzUgjRyD5fg2QiPF0boDuSL/QYuoxPftgpYQv2MiQ= -github.com/projectdiscovery/retryabledns v1.0.118/go.mod h1:qHuxflnN8BWWqQ+N+TIe9OTqmaMpE/G2+36chAcFQhg= +github.com/projectdiscovery/retryabledns v1.0.119 h1:QljvfDIQ9qw3qtsgyl3g5dkW87RcpNwIv/tKPvBGgjQ= +github.com/projectdiscovery/retryabledns v1.0.119/go.mod h1:DzJqF5OpIgjSm4fR087gHSDYC05JsTRi1RTbbpvrJo8= github.com/projectdiscovery/retryablehttp-go v1.3.35 h1:u4ZnTMh7ZE46buZRBrFL3Yyk0uCrDudcVOlT/VkDWGU= github.com/projectdiscovery/retryablehttp-go v1.3.35/go.mod h1:+UvjTjyTxKJRfPgm023lb84MjAjpDT3jjs1ZO5KuAIE= github.com/projectdiscovery/rod v0.116.3-0.20261113214723-dd0abeca2a24 h1:Hot/bpOreHagjzK10d939dAzEuiDsbScyz/JQ4OTolA= @@ -275,8 +275,8 @@ github.com/projectdiscovery/tlsx v1.5.0 h1:uYHx4qUdLueWJATbFg2Zw5dVxxFdVwKumAFnW github.com/projectdiscovery/tlsx v1.5.0/go.mod h1:w77xx09yOu6Vsz1q8CKabIMvid4o6rAwahXkNlNnTPY= github.com/projectdiscovery/useragent v0.0.110 h1:hoKpQssbFLSSmK/Vxf/fG/a+PToEYdzLafG7HHbvCAc= github.com/projectdiscovery/useragent v0.0.110/go.mod h1:fOeQ2+nlOJHYuPpnWWrBz5q5dUo7efe/AmvWQdNsLUM= -github.com/projectdiscovery/utils v0.11.13 h1:Mn3/rtyQvtn8XZy0UnVkxbAmn0afbHtWuMHUEztwWSw= -github.com/projectdiscovery/utils v0.11.13/go.mod h1:TJgsyVjB02CavwZVFzUzPg6YOSJXQxLhL808JCiQKlU= +github.com/projectdiscovery/utils v0.11.17-0.20261122142141-bb5b328c030e h1:r7kW/SSqI7w3Y2t7zVMOLsv2nad6Rc21kG6p1beXUWs= +github.com/projectdiscovery/utils v0.11.17-0.20261122142141-bb5b328c030e/go.mod h1:xi8KJ+NENlIk4sgfnvihJdcR+4qnEO5Z67fvN5Md33w= github.com/projectdiscovery/wappalyzergo v0.3.8 h1:bjQ99Lanzj8l+2ENwt24/LdZ09uR9IxkamXssBXahIQ= github.com/projectdiscovery/wappalyzergo v0.3.8/go.mod h1:7gTNIjQSXsVmFDJJ3PT8+FhYE+dv6hZLGZSsRAEjVSw= github.com/refraction-networking/utls v1.8.2 h1:j4Q1gJj0xngdeH+Ox/qND11aEfhpgoEvV+S9iJ2IdQo= diff --git a/runner/headless.go b/runner/headless.go index fbe821cef..b155fb2d4 100644 --- a/runner/headless.go +++ b/runner/headless.go @@ -1,21 +1,27 @@ package runner import ( + "context" "fmt" + "maps" "net/url" "os" "path/filepath" + "slices" "strconv" "strings" "time" "github.com/pkg/errors" "github.com/projectdiscovery/fastdialer/fastdialer" + "github.com/projectdiscovery/gologger" "github.com/projectdiscovery/networkpolicy" "github.com/projectdiscovery/rod" "github.com/projectdiscovery/rod/lib/launcher" "github.com/projectdiscovery/rod/lib/launcher/flags" "github.com/projectdiscovery/rod/lib/proto" + rodutils "github.com/projectdiscovery/rod/lib/utils" + "github.com/projectdiscovery/utils/chromeshell" fileutil "github.com/projectdiscovery/utils/file" iputil "github.com/projectdiscovery/utils/ip" mapsutil "github.com/projectdiscovery/utils/maps" @@ -103,6 +109,12 @@ func pathGlobExists(root string, patterns []string) bool { } func NewBrowser(proxy string, useLocal bool, optionalArgs map[string]string) (*Browser, error) { + return newBrowser(proxy, proxy, useLocal, optionalArgs) +} + +// newBrowser is NewBrowser with a separate proxy for the chrome-headless-shell +// download. An empty downloadProxy uses the environment proxy. +func newBrowser(proxy, downloadProxy string, useLocal bool, optionalArgs map[string]string) (*Browser, error) { dataStore, err := os.MkdirTemp("", "nuclei-*") if err != nil { return nil, errors.Wrap(err, "could not create temporary directory") @@ -121,7 +133,31 @@ func NewBrowser(proxy string, useLocal bool, optionalArgs map[string]string) (*B Set("window-size", fmt.Sprintf("%d,%d", 1080, 1920)). Set("mute-audio", "true"). Set("incognito", "true"). + // Performance: keep background/occluded tabs running at full speed so + // many concurrent screenshot pages don't get render-throttled. + Set("disable-background-timer-throttling", "true"). + Set("disable-backgrounding-occluded-windows", "true"). + Set("disable-renderer-backgrounding", "true"). + Set("disable-hang-monitor", "true"). + // Performance: strip background chrome services we never use. + Set("disable-background-networking", "true"). + Set("disable-client-side-phishing-detection", "true"). + Set("disable-component-update", "true"). + Set("disable-default-apps", "true"). + Set("disable-domain-reliability", "true"). + Set("disable-extensions", "true"). + Set("disable-sync", "true"). + Set("no-first-run", "true"). + Set("no-default-browser-check", "true"). + Set("metrics-recording-only", "true"). + Set("safebrowsing-disable-auto-update", "true"). + // site-per-process stays enabled: screenshots render untrusted pages, so + // Chromium's cross-origin renderer isolation is worth the extra processes. + Set("disable-features", "Translate,BackForwardCache,AcceptCHFrame,MediaRouter,OptimizationHints"). Delete("use-mock-keychain"). + // rod disables IPC flooding protection by default; keep it on because + // untrusted pages share one browser process and must not starve each other. + Delete("disable-ipc-flooding-protection"). Headless(true). UserDataDir(dataStore) @@ -130,12 +166,22 @@ func NewBrowser(proxy string, useLocal bool, optionalArgs map[string]string) (*B } // go-rod downloads a glibc Chromium, which cannot run on a musl host. + usingChromeShell := false if preferSystemBrowser(useLocal) { if chromePath, hasChrome := launcher.LookPath(); hasChrome { chromeLauncher.Bin(chromePath) } else { return nil, errors.New("the chrome browser is not installed") } + } else if chromeshell.Supported() { + // Prefer chrome-headless-shell on linux/amd64: smaller download and + // faster headless screenshots than full Chromium snapshots. + if shellPath, err := ensureChromeShell(downloadProxy); err == nil { + chromeLauncher.Bin(shellPath) + usingChromeShell = true + } else { + gologger.Warning().Msgf("Could not prepare chrome-headless-shell, using the default browser: %s\n", err) + } } if proxy == "" { @@ -155,6 +201,13 @@ func NewBrowser(proxy string, useLocal bool, optionalArgs map[string]string) (*B } launcherURL, err := chromeLauncher.Launch() + if err != nil && usingChromeShell { + // A damaged cached shell must not disable screenshots: retry once with + // the rod default browser and the same flags. + gologger.Warning().Msgf("Could not launch chrome-headless-shell, using the default browser: %s\n", err) + chromeLauncher = defaultBrowserLauncher(chromeLauncher) + launcherURL, err = chromeLauncher.Launch() + } if err != nil { return nil, err } @@ -181,7 +234,7 @@ func (b *Browser) SetNetworkPolicy(np *networkpolicy.NetworkPolicy, dialer *fast } func (b *Browser) ScreenshotWithBody(url string, timeout time.Duration, idle time.Duration, headers []string, fullPage bool, jsCodes []string) ([]byte, string, []NetworkRequest, error) { - page, router, networkRequests, err := b.setupPageAndNavigate(url, timeout, headers, jsCodes) + page, router, networkRequests, err := b.setupPageAndNavigate(url, timeout, idle, headers, jsCodes) if router != nil { defer func() { _ = router.Stop() }() } @@ -190,7 +243,7 @@ func (b *Browser) ScreenshotWithBody(url string, timeout time.Duration, idle tim } defer b.closePage(page) - screenshot, body, err := b.takeScreenshotAndGetBody(page, idle, fullPage) + screenshot, body, err := b.takeScreenshotAndGetBody(page, fullPage) if err != nil { return nil, "", networkRequests, err } @@ -199,7 +252,7 @@ func (b *Browser) ScreenshotWithBody(url string, timeout time.Duration, idle tim } // setupPageAndNavigate opens a page, performs all adaptive actions including JS injection -func (b *Browser) setupPageAndNavigate(url string, timeout time.Duration, headers []string, jsCodes []string) (*rod.Page, *rod.HijackRouter, []NetworkRequest, error) { +func (b *Browser) setupPageAndNavigate(url string, timeout time.Duration, idle time.Duration, headers []string, jsCodes []string) (*rod.Page, *rod.HijackRouter, []NetworkRequest, error) { page, err := b.engine.Page(proto.TargetCreateTarget{}) if err != nil { return nil, nil, []NetworkRequest{}, err @@ -276,6 +329,17 @@ func (b *Browser) setupPageAndNavigate(url string, timeout time.Duration, header } page = page.Timeout(timeout) + // The readiness waits stop early enough to leave time for the capture, + // so a request that never ends delays the screenshot but does not fail it. + readyCtx, cancelReady := context.WithTimeout(page.GetContext(), timeout-timeout/4) + defer cancelReady() + var waitReqIdle func(context.Context) + if idle > 0 { + // Register before Navigate so the first SPA XHRs are tracked by the + // request-idle waiter. Zero/negative idle skips this (the idle waiter + // and WaitDOMStable reject non-positive durations). + waitReqIdle = waitRequestIdle(page, idle) + } if err := page.Navigate(url); err != nil { return page, router, snapshot(networkRequests), err @@ -288,7 +352,7 @@ func (b *Browser) setupPageAndNavigate(url string, timeout time.Duration, header } } - page.Timeout(5 * time.Second).WaitNavigation(proto.PageLifecycleEventNameFirstMeaningfulPaint)() + b.waitPageReady(page.Context(readyCtx), idle, waitReqIdle) return page, router, snapshot(networkRequests), nil } @@ -439,14 +503,103 @@ func mergeRequestHeaders(existing proto.NetworkHeaders, extra map[string]string) return out } -// takeScreenshotAndGetBody performs the screenshot actions -func (b *Browser) takeScreenshotAndGetBody(page *rod.Page, idle time.Duration, fullPage bool) ([]byte, string, error) { - if err := page.WaitLoad(); err != nil { - return nil, "", err +// waitPageReady blocks until the page is visually settled so we don't capture a +// half-rendered SPA. It gates on three independent signals, each bounded by the +// page timeout: +// - window.onload +// - network request-idle (a quiet network window) +// - DOM stability (the rendered tree stops mutating) +// +// SPAs paint late: the network can briefly go quiet before hydration starts, so +// request-idle alone can fire on the boot screen. Requiring DOM stability on top +// closes that gap. DOM stability is re-checked after the network settles so the +// first snapshot is taken post-hydration rather than on the boot screen. +func (b *Browser) waitPageReady(page *rod.Page, idle time.Duration, waitReqIdle func(context.Context)) { + _ = page.WaitLoad() + if idle <= 0 || waitReqIdle == nil { + return + } + waitReqIdle(page.GetContext()) + _ = page.WaitDOMStable(idle, 0) +} + +// idleIgnoredTypes are the request types that do not delay the screenshot, +// the same as the defaults of rod's WaitRequestIdle. +var idleIgnoredTypes = []proto.NetworkResourceType{ + proto.NetworkResourceTypeWebSocket, + proto.NetworkResourceTypeEventSource, + proto.NetworkResourceTypeMedia, + proto.NetworkResourceTypeImage, + proto.NetworkResourceTypeFont, +} + +// waitRequestIdle starts tracking the page requests and returns a function +// that blocks until no tracked request was pending for d, or until its +// context ends. It is rod's WaitRequestIdle without the requests that have +// no loader: Chrome reports the main script request of a dedicated worker +// on the page session with an empty loader id, but reports its end on the +// worker target, which is not attached. rod would wait for that request +// until the page timeout. +func waitRequestIdle(page *rod.Page, d time.Duration) func(context.Context) { + page, cancel := page.WithCancel() + pending := map[proto.NetworkRequestID]struct{}{} + idle := rodutils.NewIdleCounter(d) + done := func(id proto.NetworkRequestID) { + if _, ok := pending[id]; ok { + delete(pending, id) + idle.Done() + } } - _ = page.WaitIdle(idle) + wait := page.EachEvent(func(e *proto.NetworkRequestWillBeSent) { + if e.LoaderID == "" || slices.Contains(idleIgnoredTypes, e.Type) { + return + } + // a redirect sends the same request id again + if _, ok := pending[e.RequestID]; !ok { + pending[e.RequestID] = struct{}{} + idle.Add() + } + }, func(e *proto.NetworkLoadingFinished) { + done(e.RequestID) + }, func(e *proto.NetworkLoadingFailed) { + done(e.RequestID) + }) + return func(ctx context.Context) { + go func() { + idle.Wait(ctx) + cancel() + }() + wait() + } +} - screenshot, err := page.Screenshot(fullPage, &proto.PageCaptureScreenshot{}) +// defaultBrowserLauncher returns a new launcher with the flags of configured, +// minus the browser binary, so rod launches its default browser. A launcher can +// only be launched once. +func defaultBrowserLauncher(configured *launcher.Launcher) *launcher.Launcher { + fallback := launcher.New() + fallback.Flags = maps.Clone(configured.Flags) + fallback.Delete(flags.Bin) + return fallback +} + +// ensureChromeShell fetches the browser under a deadline. The context has to +// reach the download itself: racing a plain Ensure against a timer would only +// abandon the wait, leaving the transfer running and the shared download lock +// held, so the next caller would block behind it. +func ensureChromeShell(proxy string) (string, error) { + ctx, cancel := context.WithTimeout(context.Background(), chromeshell.DefaultDownloadTimeout) + defer cancel() + return chromeshell.EnsureWithOptions(ctx, chromeshell.Options{Proxy: proxy}) +} + +// takeScreenshotAndGetBody performs the screenshot actions +func (b *Browser) takeScreenshotAndGetBody(page *rod.Page, fullPage bool) ([]byte, string, error) { + _ = page.WaitRepaint() + + screenshot, err := page.Screenshot(fullPage, &proto.PageCaptureScreenshot{ + OptimizeForSpeed: true, + }) if err != nil { return nil, "", err } diff --git a/runner/headless_screenshot_test.go b/runner/headless_screenshot_test.go new file mode 100644 index 000000000..62ffcf351 --- /dev/null +++ b/runner/headless_screenshot_test.go @@ -0,0 +1,161 @@ +package runner + +import ( + "fmt" + "net/http" + "net/http/httptest" + "strings" + "sync" + "testing" + "time" +) + +const spaHydratedMarker = "hydrated-ok" + +// spaHTML is a tiny SPA-style page: it paints a boot screen first, then +// fetches /app.js which hydrates #root after a short delay. Early captures +// only contain "boot"; a correct wait must include spaHydratedMarker. +const spaHTML = ` +