Files

314 lines
10 KiB
Go

package remotebrowser
import (
"context"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strconv"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/dop251/goja"
"github.com/phishingclub/phishingclub/embedded"
"github.com/go-rod/rod/lib/launcher"
"github.com/go-rod/rod/lib/launcher/flags"
)
// TestRequestToMapNil proves a nil Request still yields a fully shaped object so
// a script reading request().country never hits undefined.
func TestRequestToMapNil(t *testing.T) {
m := requestToMap(nil)
for _, k := range []string{"ip", "country", "asns", "ja4", "userAgent", "acceptLanguage", "headers"} {
if _, ok := m[k]; !ok {
t.Fatalf("nil request map missing key %q", k)
}
}
if m["country"] != "" {
t.Fatalf("expected empty country, got %v", m["country"])
}
if got := m["asns"].([]interface{}); len(got) != 0 {
t.Fatalf("expected empty asns, got %v", got)
}
}
// TestRequestToMapValues proves the fields map to the lowercase JS keys.
func TestRequestToMapValues(t *testing.T) {
ri := &RequestInfo{
IP: "1.2.3.4",
Country: "DE",
ASNs: []RequestASN{{Number: 16509, Name: "AMAZON-02"}},
JA4: "t13d1516h2_x",
Headers: map[string]string{"user-agent": "UA"},
}
m := requestToMap(ri)
if m["ip"] != "1.2.3.4" || m["country"] != "DE" || m["ja4"] != "t13d1516h2_x" {
t.Fatalf("scalar fields wrong: %v", m)
}
asn := m["asns"].([]interface{})[0].(map[string]interface{})
if asn["number"] != uint32(16509) || asn["name"] != "AMAZON-02" {
t.Fatalf("asn mapping wrong: %v", asn)
}
if m["headers"].(map[string]interface{})["user-agent"] != "UA" {
t.Fatalf("headers mapping wrong: %v", m["headers"])
}
}
// TestPreludeStateMachine runs the real prelude JS in a goja VM against a
// stubbed session and asserts states() returns a machine whose before/after
// hooks and run loop work, and that present/visible/query were added to the
// session. It checks the mechanic the prelude relies on: reassigning the
// newSession global and augmenting the returned session from JS.
func TestPreludeStateMachine(t *testing.T) {
vm := goja.New()
// stage advances as actions run, simulating page progression:
// 0 password, 1 totp, 2 done.
stage := 0
// badArg records the regression where the prelude wrapper forwards undefined
// to the native newSession for a no-argument call.
badArg := false
newSession := func(call goja.FunctionCall) goja.Value {
if len(call.Arguments) > 0 {
a := call.Argument(0)
if goja.IsUndefined(a) || goja.IsNull(a) {
badArg = true
}
}
s := vm.NewObject()
_ = s.Set("location", func(goja.FunctionCall) goja.Value {
if stage >= 2 {
return vm.ToValue("https://myaccount.example/home")
}
return vm.ToValue("https://login.microsoftonline.com/step")
})
_ = s.Set("getNodeCount", func(call goja.FunctionCall) goja.Value {
sel := call.Argument(0).String()
if stage == 0 && sel == "input[type=password]" {
return vm.ToValue(1)
}
if stage == 1 && sel == "input[name=otc]" {
return vm.ToValue(1)
}
return vm.ToValue(0)
})
_ = s.Set("getText", func(goja.FunctionCall) goja.Value { return vm.ToValue("") })
_ = s.Set("evaluate", func(goja.FunctionCall) goja.Value { return vm.ToValue(false) })
_ = s.Set("wait", func(goja.FunctionCall) goja.Value { return goja.Undefined() })
return s
}
if err := vm.Set("newSession", newSession); err != nil {
t.Fatalf("set newSession: %v", err)
}
var logs []string
_ = vm.Set("log", func(call goja.FunctionCall) goja.Value {
logs = append(logs, call.Argument(0).String())
return goja.Undefined()
})
if _, err := vm.RunString(embedded.RemoteBrowserPreludeJS); err != nil {
t.Fatalf("prelude failed to load: %v", err)
}
script := `
var visited = [];
var beforeSeen = [];
var afterSeen = [];
var s = newSession();
if (typeof s.states !== "function") { throw new Error("s.states missing"); }
if (typeof s.waitForState !== "function") { throw new Error("s.waitForState missing"); }
if (typeof s.present !== "function") { throw new Error("s.present missing"); }
if (typeof s.visible !== "function") { throw new Error("s.visible missing"); }
if (typeof s.query !== "function") { throw new Error("s.query missing"); }
var machine = s.states({
password: function () { return s.present("input[type=password]"); },
totp: function () { return s.present("input[name=otc]"); },
done: function () { return !s.location().includes("microsoftonline.com"); },
});
if (typeof machine.run !== "function") { throw new Error("machine.run missing"); }
if (typeof machine.before !== "function") { throw new Error("machine.before missing"); }
if (typeof machine.after !== "function") { throw new Error("machine.after missing"); }
machine
.before(function (state) { beforeSeen.push(state); })
.after(function (state) { afterSeen.push(state); })
.run({
password: function (loop) { visited.push("password"); advance(); },
totp: function (loop) { visited.push("totp"); advance(); },
done: function (loop) { visited.push("done"); loop.stop(); },
}, { detectTimeout: 1000 });
visited.join(",") + "|" + beforeSeen.join(",") + "|" + afterSeen.join(",");
`
// advance() bumps the Go stage counter so the stub page moves forward.
_ = vm.Set("advance", func(goja.FunctionCall) goja.Value {
stage++
return goja.Undefined()
})
v, err := vm.RunString(script)
if err != nil {
t.Fatalf("script failed: %v", err)
}
if badArg {
t.Fatalf("newSession wrapper forwarded undefined/null opts for a no-argument call")
}
got := v.String()
want := "password,totp,done|password,totp,done|password,totp,done"
if got != want {
t.Fatalf("state walk = %q, want %q (logs: %v)", got, want, logs)
}
}
// TestRunnerEgressGuarded runs a script on a real browser and checks that a
// session without a proxy cannot reach an internal address, here loopback,
// unless the config allows it. Skips without a browser.
func TestRunnerEgressGuarded(t *testing.T) {
bin := findChromeBin()
if bin == "" {
t.Skip("no chrome/chromium binary available")
}
var hits atomic.Int64
victim := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
hits.Add(1)
_, _ = w.Write([]byte("<html><body>REACHED</body></html>"))
}))
defer victim.Close()
script := `
var s = newSession();
try { s.navigate(` + strconv.Quote(victim.URL+"/") + `); } catch (e) { log("navigate failed"); }
s.close();
`
var blockedLogged bool
run := func(allow []string) {
t.Helper()
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
defer cancel()
r := NewRunner(script, Config{Mode: "local", Headless: true, Timeout: 60_000, AllowInternal: allow})
r.ExecPath = bin
done := make(chan error, 1)
go func() { done <- r.Run(ctx) }()
blockedLogged = false
for ev := range r.Events {
if ev.Type == "error" {
t.Logf("runner error: %s", ev.Message)
}
if ev.Type == "log" && strings.Contains(ev.Message, "blocked 127.0.0.1") {
blockedLogged = true
}
}
<-done
}
run(nil)
if n := hits.Load(); n != 0 {
t.Fatalf("loopback was reached %d times without being allowed", n)
}
if !blockedLogged {
t.Fatalf("the blocked address was not logged to the session")
}
run([]string{"127.0.0.1"})
if hits.Load() == 0 {
t.Fatalf("allowed loopback was not reached")
}
if blockedLogged {
t.Fatalf("an allowed address was logged as blocked")
}
}
// TestSystemBrowserPicksOneThatStarts: an installed browser is used only when
// it starts, the names are tried in order, and only in a container may a
// browser run without its sandbox.
func TestSystemBrowserPicksOneThatStarts(t *testing.T) {
was := inContainer
t.Cleanup(func() { inContainer = was; browserProbes.seen = nil })
inContainer = false
dir := t.TempDir()
write := func(name, body string) string {
p := filepath.Join(dir, name)
if err := os.WriteFile(p, []byte("#!/bin/sh\n"+body+"\n"), 0o755); err != nil {
t.Fatal(err)
}
return p
}
t.Setenv("PATH", dir)
if bin := systemBrowser(); bin != "" {
t.Fatalf("found %s on an empty PATH", bin)
}
// the first name does not start, the second has no usable sandbox, the
// third one starts
write("google-chrome", "exit 1")
nosb := write("google-chrome-stable", `echo "No usable sandbox!"; exit 1`)
want := write("chromium", "exit 0")
if bin := systemBrowser(); bin != want {
t.Fatalf("got %q want %q", bin, want)
}
if got, err := ResolveBrowserBin("", t.TempDir()); err != nil || got != want {
t.Fatalf("resolve: %q %v", got, err)
}
if got, _ := ResolveBrowserBin("/opt/own/chrome", t.TempDir()); got != "/opt/own/chrome" {
t.Fatalf("the configured path must win, got %q", got)
}
if sandboxUsable(nosb) {
t.Fatalf("a browser that reports no usable sandbox was probed as usable")
}
if !sandboxUsable(want) {
t.Fatalf("a browser that starts was probed as having no sandbox")
}
// a browser that starts only without its sandbox
only := write("google-chrome", `case "$*" in *--no-sandbox*) exit 0;; esac; echo "No usable sandbox!"; exit 1`)
browserProbes.seen = nil
if bin := systemBrowser(); bin != want {
t.Fatalf("outside a container got %q want %q", bin, want)
}
if l := applySandbox(launcher.New().Set(flags.NoSandbox), only); l.Has(flags.NoSandbox) {
t.Fatalf("outside a container the sandbox was turned off")
}
inContainer = true
browserProbes.seen = nil
if bin := systemBrowser(); bin != only {
t.Fatalf("in a container got %q want %q", bin, only)
}
if l := applySandbox(launcher.New(), only); !l.Has(flags.NoSandbox) {
t.Fatalf("in a container the browser must fall back to no sandbox")
}
if l := applySandbox(launcher.New().Set(flags.NoSandbox), want); l.Has(flags.NoSandbox) {
t.Fatalf("a usable sandbox was turned off")
}
}
// TestBrowserLimit: no more browsers start than the limit, and a place that
// is given back can be taken again.
func TestBrowserLimit(t *testing.T) {
t.Cleanup(func() { maxBrowsers.Store(0); liveBrowsers.Store(0) })
liveBrowsers.Store(0)
SetMaxBrowsers(2)
if !acquireBrowser() || !acquireBrowser() {
t.Fatal("the places under the limit were refused")
}
if acquireBrowser() {
t.Fatal("a browser over the limit was allowed")
}
if liveBrowsers.Load() != 2 {
t.Fatalf("a refused browser was counted: %d", liveBrowsers.Load())
}
releaseBrowser()
if !acquireBrowser() {
t.Fatal("a place that was given back was refused")
}
SetMaxBrowsers(0)
if browserLimit() != DefaultMaxBrowsers {
t.Fatalf("no number in the config must give the default, got %d", browserLimit())
}
}