package server import ( "context" "fmt" "net/http" "net/http/httptest" "net/netip" "net/url" "strings" "testing" "time" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core" "git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store" ) func setup(t *testing.T) (http.Handler, *store.Store) { st := store.New(store.Config{Name: "oracle", Version: "test"}) st.Ingest(core.Event{Time: time.Now(), IP: "45.94.31.4", Cat: core.Exploit, Strong: true, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/"}) h := New(Options{Token: "user-token-0123456789-abcdefghijklmnop", Version: "test", Store: st}) return h, st } func do(h http.Handler, method, path string, hdr map[string]string, form url.Values) *httptest.ResponseRecorder { var body *strings.Reader if form != nil { body = strings.NewReader(form.Encode()) } else { body = strings.NewReader("") } r := httptest.NewRequest(method, path, body) r.RemoteAddr = "198.51.100.1:1234" if v, ok := hdr["X-Remote"]; ok { r.RemoteAddr = v delete(hdr, "X-Remote") } if form != nil { r.Header.Set("Content-Type", "application/x-www-form-urlencoded") } for k, v := range hdr { r.Header.Set(k, v) } w := httptest.NewRecorder() h.ServeHTTP(w, r) return w } func TestHealthOpenAndAPIClosed(t *testing.T) { h, _ := setup(t) if w := do(h, "GET", "/api/health", nil, nil); w.Code != 200 || !strings.Contains(w.Body.String(), `"status":"ok"`) { t.Fatalf("health %d %s", w.Code, w.Body) } wrongN := 0 for _, p := range []string{"/api/v1/summary", "/api/v1/ips", "/api/v1/ip/45.94.31.4", "/api/v1/blocklist.txt", "/api/v1/events/stream"} { if w := do(h, "GET", p, nil, nil); w.Code != 401 { t.Errorf("%s without auth: %d", p, w.Code) } wrongN++ if w := do(h, "GET", p, map[string]string{"Authorization": "Bearer wrong", "X-Remote": fmt.Sprintf("198.51.100.%d:1", wrongN)}, nil); w.Code != 401 { t.Errorf("%s wrong token: %d", p, w.Code) } } if w := do(h, "GET", "/", nil, nil); w.Code != 303 || w.Header().Get("Location") != "/login" { t.Fatalf("index unauth: %d", w.Code) } w := do(h, "GET", "/api/health", nil, nil) csp := w.Header().Get("Content-Security-Policy") if !strings.Contains(csp, "default-src 'self'") || strings.Contains(csp, "unsafe-inline") || !strings.Contains(csp, "frame-ancestors 'none'") || w.Header().Get("X-Content-Type-Options") != "nosniff" || w.Header().Get("Referrer-Policy") == "" { t.Fatalf("headers: %v", w.Header()) } } func TestBearerAndPeerToken(t *testing.T) { h, _ := setup(t) auth := map[string]string{"Authorization": "Bearer user-token-0123456789-abcdefghijklmnop"} if w := do(h, "GET", "/api/v1/summary?range=1h", auth, nil); w.Code != 200 || !strings.Contains(w.Body.String(), "45.94.31.4") { t.Fatalf("summary %d %s", w.Code, w.Body) } if w := do(h, "GET", "/api/v1/ip/45.94.31.4", auth, nil); w.Code != 200 || !strings.Contains(w.Body.String(), `"level":"low"`) { t.Fatalf("ip %d %s", w.Code, w.Body) } if w := do(h, "GET", "/api/v1/ip/not-an-ip", auth, nil); w.Code != 400 { t.Fatal("bad ip") } if w := do(h, "GET", "/api/v1/ip/198.18.0.1", auth, nil); w.Code != 404 { t.Fatal("unknown ip") } if w := do(h, "GET", "/api/v1/blocklist.txt?min_score=5", auth, nil); w.Code != 200 || strings.TrimSpace(w.Body.String()) != "45.94.31.4" { t.Fatalf("blocklist %q", w.Body) } if w := do(h, "GET", "/api/v1/blocklist.txt", auth, nil); strings.TrimSpace(w.Body.String()) != "" { t.Fatalf("score 8 must not pass min 50: %q", w.Body) } if w := do(h, "GET", "/api/v1/summary?host=nope", auth, nil); w.Code != 404 { t.Fatalf("unknown host %d", w.Code) } } func TestLoginCookieAndRateLimit(t *testing.T) { loginBlockedDelay = 0 h, _ := setup(t) bad := url.Values{"token": {"nope"}} for i := 0; i < 5; i++ { if w := do(h, "POST", "/login", nil, bad); w.Code != 303 || !strings.Contains(w.Header().Get("Location"), "e=bad") { t.Fatalf("try %d: %d %s", i, w.Code, w.Header().Get("Location")) } } // blocked: a wrong token gets 429 ... w := do(h, "POST", "/login", nil, bad) if w.Code != http.StatusTooManyRequests || w.Header().Get("Retry-After") == "" || w.Header().Get("Set-Cookie") != "" { t.Fatalf("blocked client with a wrong token: %d %v", w.Code, w.Header()) } // ... but the correct token still signs the administrator in w = do(h, "POST", "/login", nil, url.Values{"token": {"user-token-0123456789-abcdefghijklmnop"}}) if w.Code != 303 || w.Header().Get("Location") != "/" || w.Header().Get("Set-Cookie") == "" { t.Fatalf("the admin must not be locked out by an attacker burning the limit: %d %v", w.Code, w.Header()) } // another IP is not affected; HTTPS via proxy header sets Secure r := httptest.NewRequest("POST", "/login", strings.NewReader("token=user-token-0123456789-abcdefghijklmnop")) r.RemoteAddr = "198.51.100.77:1" r.Header.Set("Content-Type", "application/x-www-form-urlencoded") r.Header.Set("X-Forwarded-Proto", "https") rec := httptest.NewRecorder() h.ServeHTTP(rec, r) if rec.Code != 303 || rec.Header().Get("Location") != "/" { t.Fatalf("login %d %s", rec.Code, rec.Header().Get("Location")) } ck := rec.Result().Cookies() if len(ck) != 1 || !ck[0].HttpOnly || !ck[0].Secure || ck[0].SameSite != http.SameSiteStrictMode || ck[0].MaxAge != 12*3600 { t.Fatalf("cookie %+v", ck) } c := ck[0].Name + "=" + ck[0].Value if w := do(h, "GET", "/api/v1/summary", map[string]string{"Cookie": c}, nil); w.Code != 200 { t.Fatalf("cookie auth %d", w.Code) } if w := do(h, "GET", "/", map[string]string{"Cookie": c}, nil); w.Code != 200 { t.Fatalf("index with cookie %d", w.Code) } tampered := ck[0].Name + "=" + ck[0].Value[:len(ck[0].Value)-3] + "xxx" if w := do(h, "GET", "/api/v1/summary", map[string]string{"Cookie": tampered}, nil); w.Code != 401 { t.Fatalf("tampered cookie accepted: %d", w.Code) } // logout revokes the session server side: the stolen cookie stops working if w := do(h, "POST", "/logout", map[string]string{"Cookie": c}, url.Values{}); w.Code != 303 { t.Fatalf("logout %d", w.Code) } if w := do(h, "GET", "/api/v1/summary", map[string]string{"Cookie": c}, nil); w.Code != 401 { t.Fatalf("a logged out cookie must be dead: %d", w.Code) } } func TestSessionsAreRevocableAndExpire(t *testing.T) { s := newSessions() now := time.Now() id, _ := s.issue(now) if !s.valid(id, now.Add(11*time.Hour)) || s.valid(id, now.Add(13*time.Hour)) { t.Fatal("12h expiry") } id2, _ := s.issue(now) if id == id2 || len(id2) < 40 { t.Fatal("ids must be long and random") } s.revoke(id2) if s.valid(id2, now) { t.Fatal("a revoked session must stop working") } if newSessions().valid(id, now) { t.Fatal("a cookie from another process (restart) is not valid") } for i := 0; i < maxSessions*3; i++ { s.issue(now) } if len(s.ids) > maxSessions { t.Fatalf("session table is bounded: %d", len(s.ids)) } if tokenEqual("a", "ab") || !tokenEqual("abc", "abc") { t.Fatal("tokenEqual") } } func TestClientIP(t *testing.T) { trusted := mustPrefixes("172.16.0.0/12,10.0.0.0/8,127.0.0.0/8") r := httptest.NewRequest("GET", "/", nil) r.RemoteAddr = "198.51.100.1:5" r.Header.Set("X-Forwarded-For", "1.2.3.4") if clientIP(r, trusted) != "198.51.100.1" { t.Fatal("XFF must be ignored from an untrusted peer") } r.RemoteAddr = "172.18.0.2:5" r.Header.Set("X-Forwarded-For", "9.9.9.9, 203.0.113.9") if clientIP(r, trusted) != "203.0.113.9" { t.Fatal("the hop added by the trusted proxy is the client; the left side is attacker controlled") } r.Header.Set("X-Forwarded-For", "203.0.113.9, 172.18.0.7") if clientIP(r, trusted) != "203.0.113.9" { t.Fatal("chained trusted proxies are skipped") } r.Header.Set("X-Forwarded-For", "garbage") if clientIP(r, trusted) != "172.18.0.2" { t.Fatal("garbage falls back to the proxy address") } if clientIP(r, nil) != "172.18.0.2" { t.Fatal("no trusted proxy: never believe the header") } } func TestTrafficEndpointAndPrivacy(t *testing.T) { h, st := setup(t) st.Traffic(core.Event{Time: time.Now(), IP: "200.1.2.3", Cat: core.OK, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/", Status: 200, UA: "Mozilla", E: core.Enrich{CC: "BR", Browser: "Firefox", OS: "Linux", Device: "desktop"}}) auth := map[string]string{"Authorization": "Bearer user-token-0123456789-abcdefghijklmnop"} if w := do(h, "GET", "/api/v1/traffic", nil, nil); w.Code != 401 { t.Fatalf("traffic needs auth: %d", w.Code) } w := do(h, "GET", "/api/v1/traffic?range=24h&domain=a.example", auth, nil) if w.Code != 200 || !strings.Contains(w.Body.String(), `"visitors":1`) || !strings.Contains(w.Body.String(), `"BR"`) { t.Fatalf("traffic %d %s", w.Code, w.Body) } if strings.Contains(w.Body.String(), "200.1.2.3") { t.Fatal("visitor IP in the traffic API") } if w := do(h, "GET", "/api/v1/traffic?host=nope", auth, nil); w.Code != 404 { t.Fatal("unknown host") } if w := do(h, "GET", "/world.js", nil, nil); w.Code != 200 || !strings.Contains(w.Header().Get("Content-Type"), "javascript") { t.Fatalf("world.js %d", w.Code) } } func mustPrefixes(l string) []netip.Prefix { p, err := core.ParseCIDRs(l) if err != nil { panic(err) } return p } func federated(t *testing.T, mod func(*Options)) http.Handler { st := store.New(store.Config{Name: "oracle", Version: "test"}) st.Ingest(core.Event{Time: time.Now(), IP: "45.94.31.4", Cat: core.Exploit, Strong: true, Source: "traefik", Method: "GET", Path: "/x"}) o := Options{Token: "user-token-0123456789-abcdefghijklmnop", Version: "test", Store: st, TrustedProxy: mustPrefixes("172.16.0.0/12")} if mod != nil { mod(&o) } return New(o) } func TestLoginRateLimitUsesRealClientBehindProxy(t *testing.T) { loginBlockedDelay = 0 h := federated(t, nil) bad := url.Values{"token": {"nope"}} post := func(xff string, form url.Values) *httptest.ResponseRecorder { return do(h, "POST", "/login", map[string]string{"X-Remote": "172.18.0.2:5000", "X-Forwarded-For": xff}, form) } for i := 0; i < 5; i++ { post("203.0.113.1", bad) } if w := post("203.0.113.1", bad); w.Code != http.StatusTooManyRequests { t.Fatalf("the attacker is rate limited: %d", w.Code) } // everyone else behind the same Traefik can still fail and succeed if w := post("203.0.113.2", bad); w.Code != 303 { t.Fatalf("another client behind the same proxy must not be blocked: %d", w.Code) } // a fake hop on the left (attacker controlled) does not reset the limit if w := post("1.1.1.1, 203.0.113.1", bad); w.Code != http.StatusTooManyRequests { t.Fatalf("spoofed left hop must not reset the limit: %d", w.Code) } } func TestLimiterAggregatesIPv6By64AndFailsClosedWhenFull(t *testing.T) { l := newLimiter() for i := 0; i < 5; i++ { l.failure(fmt.Sprintf("2001:db8:0:9:%x::1", i+1)) // five addresses of one /64 } if l.blocked("2001:db8:0:9:ffff::7") == 0 { t.Fatal("the whole /64 must share one budget") } if l.blocked("2001:db8:0:a::1") != 0 { t.Fatal("another /64 is unaffected") } // a full table evicts the oldest entry, not everything l2 := newLimiter() base := time.Now() l2.now = func() time.Time { base = base.Add(time.Millisecond); return base } for i := 0; i < 5; i++ { l2.failure("9.9.9.9") } for i := 0; i < maxLimiterIP+50; i++ { l2.failure(fmt.Sprintf("10.%d.%d.%d", i>>16, i>>8&255, i&255)) } if len(l2.fail) > maxLimiterIP { t.Fatalf("limiter table unbounded: %d", len(l2.fail)) } if l2.blocked("10.0.1.200") != 0 && len(l2.fail) == 0 { t.Fatal("never forget everybody at once") } } func TestBearerGuessingOnTheAPICountsAndBlocks(t *testing.T) { h := federated(t, nil) var last int for i := 0; i < 8; i++ { last = do(h, "GET", "/api/v1/summary", map[string]string{"Authorization": "Bearer guess" + fmt.Sprint(i)}, nil).Code } if last != http.StatusTooManyRequests { t.Fatalf("guessing the token on the API must end in 429, got %d", last) } if w := do(h, "GET", "/api/v1/summary", map[string]string{"Authorization": "Bearer user-token-0123456789-abcdefghijklmnop"}, nil); w.Code != 200 { t.Fatalf("the right token still works from a blocked address: %d", w.Code) } } func TestCrossSiteFormPostsAreRefused(t *testing.T) { h := federated(t, nil) form := url.Values{"token": {"user-token-0123456789-abcdefghijklmnop"}} for name, hd := range map[string]map[string]string{ "sec-fetch-site": {"Sec-Fetch-Site": "cross-site"}, "foreign origin": {"Origin": "https://evil.example"}, "null origin": {"Origin": "null"}, } { for _, p := range []string{"/login", "/logout"} { if w := do(h, "POST", p, hd, form); w.Code != http.StatusForbidden || w.Header().Get("Set-Cookie") != "" { t.Errorf("%s %s: %d", name, p, w.Code) } } } r := httptest.NewRequest("POST", "/login", strings.NewReader(form.Encode())) r.Host = "urutau.example.org" r.RemoteAddr = "198.51.100.5:1" r.Header.Set("Content-Type", "application/x-www-form-urlencoded") r.Header.Set("Origin", "https://urutau.example.org") r.Header.Set("Sec-Fetch-Site", "same-origin") w := httptest.NewRecorder() h.ServeHTTP(w, r) if w.Code != 303 || w.Header().Get("Location") != "/" { t.Fatalf("same-origin login must work: %d %s", w.Code, w.Header().Get("Location")) } // Chrome sends "Origin: null" for a same-origin POST under some referrer policies r2 := httptest.NewRequest("POST", "/login", strings.NewReader(form.Encode())) r2.RemoteAddr = "198.51.100.6:1" r2.Header.Set("Content-Type", "application/x-www-form-urlencoded") r2.Header.Set("Origin", "null") r2.Header.Set("Sec-Fetch-Site", "same-origin") w2 := httptest.NewRecorder() h.ServeHTTP(w2, r2) if w2.Code != 303 || w2.Header().Get("Location") != "/" { t.Fatalf("same-origin POST with a null Origin must work: %d", w2.Code) } } func TestInsecureNoAuthRefusesForeignHostHeaders(t *testing.T) { st := store.New(store.Config{Name: "x"}) h := New(Options{NoAuth: true, Store: st, AllowHosts: []string{"127.0.0.1"}}) get := func(host string) int { r := httptest.NewRequest("GET", "/api/v1/summary", nil) r.Host = host w := httptest.NewRecorder() h.ServeHTTP(w, r) return w.Code } for _, ok := range []string{"localhost", "localhost:8790", "127.0.0.1:8790", "[::1]:8790", "127.0.0.1"} { if c := get(ok); c != 200 { t.Errorf("%s: %d", ok, c) } } for _, bad := range []string{"evil.example", "evil.example:8790", "127.0.0.1.evil.example", "192.168.1.5"} { if c := get(bad); c != 403 { t.Errorf("DNS rebinding host %q accepted: %d", bad, c) } } } func TestLoginBodyLimitAndServerLimits(t *testing.T) { h := federated(t, nil) big := url.Values{"token": {strings.Repeat("a", 20000)}} if w := do(h, "POST", "/login", nil, big); w.Code != http.StatusBadRequest { t.Fatalf("oversized login body: %d", w.Code) } if w := do(h, "GET", "/api/health", nil, nil); strings.Contains(w.Body.String(), "version") { t.Fatal("/api/health must not expose the version") } srv := HTTPServer(h, context.Background()) if srv.ReadHeaderTimeout <= 0 || srv.ReadTimeout <= 0 || srv.WriteTimeout <= 0 || srv.IdleTimeout <= 0 || srv.MaxHeaderBytes <= 0 || srv.MaxHeaderBytes > 64<<10 { t.Fatalf("server limits not set: %+v", srv) } } func TestSSEClientLimit(t *testing.T) { ts := httptest.NewServer(federated(t, nil)) defer ts.Close() var open []*http.Response defer func() { for _, r := range open { r.Body.Close() } }() get := func() *http.Response { req, _ := http.NewRequest("GET", ts.URL+"/api/v1/events/stream", nil) req.Header.Set("Authorization", "Bearer user-token-0123456789-abcdefghijklmnop") resp, err := http.DefaultClient.Do(req) if err != nil { t.Fatal(err) } return resp } for i := 0; i < maxSSE; i++ { r := get() if r.StatusCode != 200 { t.Fatalf("stream %d: %d", i, r.StatusCode) } open = append(open, r) } over := get() over.Body.Close() if over.StatusCode != http.StatusServiceUnavailable { t.Fatalf("stream over the limit: %d", over.StatusCode) } open[0].Body.Close() deadline := time.Now().Add(3 * time.Second) for time.Now().Before(deadline) { r := get() if r.StatusCode == 200 { open = append(open, r) return } r.Body.Close() time.Sleep(50 * time.Millisecond) } t.Fatal("a closed stream must free its slot") }