package server import ( "fmt" "io" "net/http" "net/http/httptest" "net/url" "strings" "testing" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/fed" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" ) const ( utok = "user-token-0123456789-abcdefghijklmnop" ptok = "peer-token-0123456789-abcdefghijklmnopq" ) func bearerGet(h http.Handler, path string) (int, string) { r := httptest.NewRequest("GET", path, nil) r.RemoteAddr = "198.51.100.9:1" r.Header.Set("Authorization", "Bearer "+utok) w := httptest.NewRecorder() h.ServeHTTP(w, r) b, _ := io.ReadAll(w.Body) return w.Code, string(b) } // A hostile peer cannot inject lines, private or zoned addresses, or absurd // scores into the blocklist; every row is revalidated by the writer. func TestBlocklistRevalidatesPeerRowsAndAdmins(t *testing.T) { exp := store.PeerExport{V: 1} exp.Summary.IPs = []store.IPSummary{ {IP: "2001:db8::1%a\n8.8.8.8", Score: 99, Strong: true}, {IP: "0.0.0.0", Score: 99, Strong: true}, {IP: "::ffff:10.0.0.1", Score: 99, Strong: true}, {IP: "192.168.1.1", Score: 99, Strong: true}, {IP: "100.64.0.9", Score: 99, Strong: true}, {IP: "203.0.113.7", Score: 99, Strong: true}, {IP: "1.2.3.4", Score: 1e300, Strong: true}, {IP: "9.9.9.9", Score: 99, Strong: true, Admin: true}, {IP: "8.8.4.4", Score: 99, Strong: true}, {IP: "2606:4700:0:7::/64", Score: 80, Strong: true}, {IP: "5.6.7.8", Score: 99, Strong: false}, } hub := fed.NewHub(func() []fed.Backend { return []fed.Backend{fakeBackend{name: "p", exp: exp}} }) st := store.New(store.Config{Name: "me", Version: "t"}) h := New(Options{Token: utok, Store: st, Hub: hub, Ignore: mustPrefixes("8.8.4.4/32")}) code, body := bearerGet(h, "/api/v1/blocklist.txt") if code != 200 { t.Fatal(code) } lines := strings.Split(strings.TrimSpace(body), "\n") // 9.9.9.9 claims Admin, but admin immunity is never taken from a peer // (a compromised peer could shield any address), so it is listed. want := map[string]bool{"1.2.3.4": true, "2606:4700:0:7::/64": true, "9.9.9.9": true} if len(lines) != len(want) { t.Fatalf("blocklist lines %q", lines) } for _, l := range lines { if !want[l] { t.Fatalf("unexpected blocklist entry %q in %q", l, lines) } } code, js := bearerGet(h, "/api/v1/blocklist.json") if code != 200 || strings.Contains(js, "%a") || strings.Contains(js, "10.0.0.1") || strings.Contains(js, "1e+") { t.Fatalf("json: %s", js) } } func TestAnAdminWithSuccessfulLoginsNeverEntersTheBlocklist(t *testing.T) { st := store.New(store.Config{Name: "me", AdminUsers: []string{"admin"}}) now := time.Now() st.Ingest(core.Event{Time: now, IP: "203.0.113.50", Cat: core.SSHOK, Source: "ssh", User: "admin"}) for i := 0; i < 30; i++ { st.Ingest(core.Event{Time: now, IP: "45.45.45.45", Cat: core.SSHOK, Source: "ssh", User: "admin"}) st.Ingest(core.Event{Time: now, IP: "45.45.45.45", Cat: core.SSHFail, Source: "ssh", User: "admin"}) st.Ingest(core.Event{Time: now, IP: "45.45.45.45", Cat: core.SSHProbe, Source: "ssh"}) } h := New(Options{Token: utok, Store: st}) if _, b := bearerGet(h, "/api/v1/blocklist.txt?min_score=1"); strings.TrimSpace(b) != "" { t.Fatalf("blocklist with an admin address: %q", b) } _, b := bearerGet(h, "/api/v1/ip/45.45.45.45") if !strings.Contains(b, `"admin":true`) || strings.Contains(b, `"level":"hostile"`) { t.Fatalf("the admin must not be hostile: %s", b) } } func TestHugePageNumbersDoNotPanic(t *testing.T) { st := store.New(store.Config{Name: "me"}) st.Ingest(core.Event{Time: time.Now(), IP: "1.2.3.4", Cat: core.Exploit, Source: "traefik", Path: "/x", Method: "GET"}) h := New(Options{Token: utok, Store: st}) for _, pg := range []string{"184467440737095517", "184467440737095516", "9223372036854775807", "-1", "99999999999999999999", "abc"} { if c, _ := bearerGet(h, "/api/v1/ips?page="+pg); c != 200 { t.Errorf("page=%s: %d", pg, c) } } } func TestIPv6DetailAndBlocklistUseThe64(t *testing.T) { st := store.New(store.Config{Name: "me"}) now := time.Now() for i := 0; i < 30; i++ { st.Ingest(core.Event{Time: now, IP: fmt.Sprintf("2606:4700:0:7:%x::1", i+1), Cat: core.Exploit, Strong: true, Source: "traefik", Path: "/x", Method: "GET"}) } h := New(Options{Token: utok, Store: st}) if _, b := bearerGet(h, "/api/v1/blocklist.txt"); strings.TrimSpace(b) != "2606:4700:0:7::/64" { t.Fatalf("blocklist %q", b) } if c, b := bearerGet(h, "/api/v1/ip/2606:4700:0:7:ffff::9"); c != 200 || !strings.Contains(b, `"ip":"2606:4700:0:7::/64"`) { t.Fatalf("%d %s", c, b) } if c, _ := bearerGet(h, "/api/v1/ip/fe80::1%25eth0"); c != 400 { t.Fatalf("a zoned address is refused: %d", c) } } func TestSSEClosesWhenTheSessionIsRevoked(t *testing.T) { old := sseHeartbeat sseHeartbeat = 50 * time.Millisecond defer func() { sseHeartbeat = old }() loginBlockedDelay = 0 ts := httptest.NewServer(federated(t, nil)) defer ts.Close() cl := &http.Client{CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} resp, err := cl.PostForm(ts.URL+"/login", url.Values{"token": {utok}}) if err != nil { t.Fatal(err) } cookie := resp.Cookies()[0] req, _ := http.NewRequest("GET", ts.URL+"/api/v1/events/stream", nil) req.AddCookie(cookie) stream, err := cl.Do(req) if err != nil || stream.StatusCode != 200 { t.Fatalf("stream: %v %v", err, stream) } defer stream.Body.Close() out := make(chan error, 1) go func() { _, err := io.Copy(io.Discard, stream.Body); out <- err }() lr, _ := http.NewRequest("POST", ts.URL+"/logout", nil) lr.AddCookie(cookie) if r, err := cl.Do(lr); err != nil || r.StatusCode != 303 { t.Fatal(err, r) } select { case <-out: case <-time.After(3 * time.Second): t.Fatal("a revoked session must close its live stream at the next heartbeat") } } func TestClientIPVectors(t *testing.T) { trusted := mustPrefixes("10.0.0.0/8,172.16.0.0/12") for xff, want := range map[string]string{ "1.1.1.1, 2.2.2.2": "2.2.2.2", "1.1.1.1,2.2.2.2:80": "172.18.0.2", // not an address: fall back to the proxy "1.1.1.1, 203.0.113.5 ,172.18.0.1": "203.0.113.5", "::ffff:1.2.3.4": "1.2.3.4", "fe80::1%eth0": "172.18.0.2", "1.1.1.1, , 2.2.2.2": "2.2.2.2", "172.18.0.9": "172.18.0.2", } { r := httptest.NewRequest("GET", "/", nil) r.RemoteAddr = "172.18.0.2:5555" r.Header.Set("X-Forwarded-For", xff) if got := clientIP(r, trusted); got != want { t.Errorf("XFF=%q -> %q, want %q", xff, got, want) } } r := httptest.NewRequest("GET", "/", nil) r.RemoteAddr = "[fd00::5]:5555" r.Header.Set("X-Forwarded-For", "1.1.1.1") if clientIP(r, trusted) != "fd00::5" { t.Fatal("a peer outside the trusted list is the client") } }