feat: Urutau 1.0.0, lightweight threat intelligence and web analytics
Release / Plan (reuse the published image?) (push) Successful in 4s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 1m29s
CI / Tests (Linux, race detector) (push) Failing after 1m48s
CI / Dependency audit (push) Successful in 21s
Release / ci (push) Failing after 1m50s
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Skipped
Release / Gitea release (push) Skipped
Release / Plan (reuse the published image?) (push) Successful in 4s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 1m29s
CI / Tests (Linux, race detector) (push) Failing after 1m48s
CI / Dependency audit (push) Successful in 21s
Release / ci (push) Failing after 1m50s
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Skipped
Release / Gitea release (push) Skipped
Always-on Go service (stdlib only) that follows the Traefik JSON access log, the sshd log and the fail2ban log of a host, classifies attacks, scores sources, keeps bounded aggregates with snapshots, and serves an embedded dashboard with live updates, offline geolocation (DB-IP Lite), privacy-friendly traffic analytics, an exportable blocklist and token-authenticated federation between instances. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
b4a2c2c9ec
99 files changed
+15403
No files matched your search
@@ -0,0 +1,236 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"crypto/subtle"
|
||||
"encoding/base64"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
cookieName = "urutau_session"
|
||||
sessionTTL = 12 * time.Hour
|
||||
loginMax = 5
|
||||
loginWindow = 10 * time.Minute
|
||||
maxLimiterIP = 10000
|
||||
)
|
||||
|
||||
// tokenEqual compares in constant time regardless of length.
|
||||
func tokenEqual(a, b string) bool {
|
||||
ha, hb := sha256.Sum256([]byte(a)), sha256.Sum256([]byte(b))
|
||||
return subtle.ConstantTimeCompare(ha[:], hb[:]) == 1
|
||||
}
|
||||
|
||||
const maxSessions = 64
|
||||
|
||||
// sessions is the in-memory registry of signed-in browsers. The cookie carries
|
||||
// a random id; logging out deletes it, so a stolen cookie can be revoked. A
|
||||
// restart signs everybody out.
|
||||
type sessions struct {
|
||||
mu sync.Mutex
|
||||
ids map[string]time.Time
|
||||
}
|
||||
|
||||
func newSessions() *sessions { return &sessions{ids: map[string]time.Time{}} }
|
||||
|
||||
func (s *sessions) issue(now time.Time) (string, time.Time) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
id := base64.RawURLEncoding.EncodeToString(b)
|
||||
exp := now.Add(sessionTTL)
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
for k, e := range s.ids {
|
||||
if now.After(e) {
|
||||
delete(s.ids, k)
|
||||
}
|
||||
}
|
||||
for len(s.ids) >= maxSessions { // drop the oldest
|
||||
var oldK string
|
||||
var oldE time.Time
|
||||
for k, e := range s.ids {
|
||||
if oldK == "" || e.Before(oldE) {
|
||||
oldK, oldE = k, e
|
||||
}
|
||||
}
|
||||
delete(s.ids, oldK)
|
||||
}
|
||||
s.ids[id] = exp
|
||||
return id, exp
|
||||
}
|
||||
|
||||
func (s *sessions) valid(id string, now time.Time) bool {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
exp, ok := s.ids[id]
|
||||
if ok && now.After(exp) {
|
||||
delete(s.ids, id)
|
||||
return false
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
func (s *sessions) revoke(id string) { s.mu.Lock(); delete(s.ids, id); s.mu.Unlock() }
|
||||
|
||||
// limiter allows loginMax failures per client inside loginWindow. IPv6
|
||||
// clients are keyed by their /64.
|
||||
type limiter struct {
|
||||
mu sync.Mutex
|
||||
fail map[string][]time.Time
|
||||
busy map[string]bool // a blocked client gets one wrong attempt in flight at a time
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func newLimiter() *limiter {
|
||||
return &limiter{fail: map[string][]time.Time{}, busy: map[string]bool{}, now: time.Now}
|
||||
}
|
||||
|
||||
// maxFailKept bounds the timestamps kept per client.
|
||||
const maxFailKept = 64
|
||||
|
||||
// maxBlockedDelay caps the progressive delay of a blocked client.
|
||||
var maxBlockedDelay = 30 * time.Second // a var so tests can shorten it
|
||||
|
||||
// penalty is the delay of the next wrong attempt of a blocked client: 1 s,
|
||||
// doubling with every failure past the limit, at most maxBlockedDelay.
|
||||
func (l *limiter) penalty(ip string) time.Duration {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
over := len(l.recent(limiterKey(ip))) - loginMax
|
||||
if over < 0 {
|
||||
return 0
|
||||
}
|
||||
if over > 5 {
|
||||
return maxBlockedDelay
|
||||
}
|
||||
d := loginBlockedDelay << over
|
||||
if d > maxBlockedDelay {
|
||||
d = maxBlockedDelay
|
||||
}
|
||||
return d
|
||||
}
|
||||
|
||||
// acquire marks the client's single slow slot as taken; false means another
|
||||
// wrong attempt of the same client is already waiting.
|
||||
func (l *limiter) acquire(ip string) (release func(), ok bool) {
|
||||
key := limiterKey(ip)
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
if l.busy[key] {
|
||||
return nil, false
|
||||
}
|
||||
l.busy[key] = true
|
||||
return func() { l.mu.Lock(); delete(l.busy, key); l.mu.Unlock() }, true
|
||||
}
|
||||
|
||||
// limiterKey aggregates IPv6 by /64: one subscriber owns the whole prefix.
|
||||
func limiterKey(ip string) string {
|
||||
if a, err := netip.ParseAddr(ip); err == nil {
|
||||
a = a.WithZone("").Unmap()
|
||||
if a.Is6() {
|
||||
return netip.PrefixFrom(a, 64).Masked().String()
|
||||
}
|
||||
return a.String()
|
||||
}
|
||||
return ip
|
||||
}
|
||||
|
||||
func (l *limiter) recent(key string) []time.Time {
|
||||
cut := l.now().Add(-loginWindow)
|
||||
list := l.fail[key]
|
||||
i := 0
|
||||
for i < len(list) && list[i].Before(cut) {
|
||||
i++
|
||||
}
|
||||
list = list[i:]
|
||||
if len(list) == 0 {
|
||||
delete(l.fail, key)
|
||||
} else {
|
||||
l.fail[key] = list
|
||||
}
|
||||
return list
|
||||
}
|
||||
|
||||
// blocked returns how long the client must wait, or 0.
|
||||
func (l *limiter) blocked(ip string) time.Duration {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
list := l.recent(limiterKey(ip))
|
||||
if len(list) < loginMax {
|
||||
return 0
|
||||
}
|
||||
return list[0].Add(loginWindow).Sub(l.now())
|
||||
}
|
||||
|
||||
func (l *limiter) failure(ip string) {
|
||||
l.mu.Lock()
|
||||
defer l.mu.Unlock()
|
||||
key := limiterKey(ip)
|
||||
if _, known := l.fail[key]; !known && len(l.fail) >= maxLimiterIP {
|
||||
// full: expire the stale entries, and if everybody is fresh drop the one
|
||||
// whose latest failure is the oldest (never forget all of them at once)
|
||||
var oldK string
|
||||
var oldT time.Time
|
||||
for k := range l.fail {
|
||||
list := l.recent(k)
|
||||
if len(list) == 0 {
|
||||
continue
|
||||
}
|
||||
if last := list[len(list)-1]; oldK == "" || last.Before(oldT) {
|
||||
oldK, oldT = k, last
|
||||
}
|
||||
}
|
||||
if len(l.fail) >= maxLimiterIP && oldK != "" {
|
||||
delete(l.fail, oldK)
|
||||
}
|
||||
}
|
||||
list := append(l.recent(key), l.now())
|
||||
if len(list) > maxFailKept {
|
||||
list = list[len(list)-maxFailKept:]
|
||||
}
|
||||
l.fail[key] = list
|
||||
}
|
||||
|
||||
func (l *limiter) reset(ip string) { l.mu.Lock(); delete(l.fail, limiterKey(ip)); l.mu.Unlock() }
|
||||
|
||||
// clientIP is the address used for rate limiting and for the peer allow list.
|
||||
// X-Forwarded-For is only believed when the TCP peer is one of the trusted
|
||||
// proxies; the chain is then walked from the right, skipping trusted proxies,
|
||||
// so a client cannot choose its own address by sending the header.
|
||||
func clientIP(r *http.Request, trusted []netip.Prefix) string {
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
host = r.RemoteAddr
|
||||
}
|
||||
a, err := netip.ParseAddr(host)
|
||||
if err != nil || !prefixesContain(trusted, a) {
|
||||
return host
|
||||
}
|
||||
var hops []string
|
||||
for _, h := range r.Header.Values("X-Forwarded-For") {
|
||||
hops = append(hops, strings.Split(h, ",")...)
|
||||
}
|
||||
for i := len(hops) - 1; i >= 0; i-- {
|
||||
hop := strings.TrimSpace(hops[i])
|
||||
ha, err := netip.ParseAddr(hop)
|
||||
if err != nil || ha.Zone() != "" {
|
||||
return host // garbage in the chain: fall back to the proxy itself
|
||||
}
|
||||
if !prefixesContain(trusted, ha) {
|
||||
return ha.Unmap().String()
|
||||
}
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
func isHTTPS(r *http.Request) bool {
|
||||
return r.TLS != nil || strings.EqualFold(r.Header.Get("X-Forwarded-Proto"), "https")
|
||||
}
|
||||
@@ -0,0 +1,243 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"sync"
|
||||
"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},
|
||||
}
|
||||
peer := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(exp) }))
|
||||
defer peer.Close()
|
||||
hub := fed.NewHub([]fed.Peer{{Name: "p", URL: peer.URL}}, ptok)
|
||||
hub.Refresh(context.Background())
|
||||
st := store.New(store.Config{Name: "me", Version: "t"})
|
||||
h := New(Options{Token: utok, PeerTokens: []string{ptok}, 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")
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentHubAndStoreUnderLoad(t *testing.T) {
|
||||
pst := store.New(store.Config{Name: "peer", Version: "t"})
|
||||
ph := New(Options{Token: utok, PeerTokens: []string{ptok}, Store: pst})
|
||||
ps := httptest.NewServer(ph)
|
||||
defer ps.Close()
|
||||
hub := fed.NewHub([]fed.Peer{{Name: "peer", URL: ps.URL}}, ptok)
|
||||
hub.Interval = 20 * time.Millisecond
|
||||
st := store.New(store.Config{Name: "me", Version: "t", MaxIPs: 3000})
|
||||
srv := httptest.NewServer(New(Options{Token: utok, PeerTokens: []string{ptok}, Store: st, Hub: hub}))
|
||||
defer srv.Close()
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
go hub.Run(ctx)
|
||||
var wg sync.WaitGroup
|
||||
stop := make(chan struct{})
|
||||
now := time.Now()
|
||||
for _, s := range []*store.Store{st, pst} {
|
||||
wg.Add(1)
|
||||
go func(s *store.Store) {
|
||||
defer wg.Done()
|
||||
for i := 0; ; i++ {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
}
|
||||
s.Ingest(core.Event{Time: now, IP: fmt.Sprintf("9.%d.%d.%d", i>>16&255, i>>8&255, i&255), Cat: core.Exploit, Source: "traefik", Path: "/x", Method: "GET", Domain: "d"})
|
||||
s.Traffic(core.Event{Time: now, IP: "3.3.3.3", Source: "traefik", Domain: "d", Method: "GET", Path: "/", Status: 200})
|
||||
}
|
||||
}(s)
|
||||
}
|
||||
paths := []string{"/api/v1/summary", "/api/v1/summary?host=peer", "/api/v1/ips?per=200&sort=events", "/api/v1/traffic?domain=d", "/api/v1/blocklist.json", "/api/v1/ip/9.0.0.1"}
|
||||
for g := 0; g < 6; g++ {
|
||||
wg.Add(1)
|
||||
go func(g int) {
|
||||
defer wg.Done()
|
||||
for i := 0; ; i++ {
|
||||
select {
|
||||
case <-stop:
|
||||
return
|
||||
default:
|
||||
}
|
||||
req, _ := http.NewRequest("GET", srv.URL+paths[(g+i)%len(paths)], nil)
|
||||
req.Header.Set("Authorization", "Bearer "+utok)
|
||||
if r, err := http.DefaultClient.Do(req); err == nil {
|
||||
io.Copy(io.Discard, r.Body)
|
||||
r.Body.Close()
|
||||
}
|
||||
}
|
||||
}(g)
|
||||
}
|
||||
time.Sleep(1500 * time.Millisecond)
|
||||
close(stop)
|
||||
wg.Wait()
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/core"
|
||||
"git.lucasrguerra.dev.br/ciberfauna/urutau/internal/store"
|
||||
)
|
||||
|
||||
// Once a client is blocked, parallel wrong attempts must not run at full
|
||||
// speed: only one waits (progressively delayed), the others get 429 at once,
|
||||
// and the correct token still opens the dashboard.
|
||||
func TestBlockedClientIsSerializedAndAdminStillGetsIn(t *testing.T) {
|
||||
old, oldMax := loginBlockedDelay, maxBlockedDelay
|
||||
loginBlockedDelay, maxBlockedDelay = 40*time.Millisecond, 200*time.Millisecond
|
||||
defer func() { loginBlockedDelay, maxBlockedDelay = old, oldMax }()
|
||||
h, _ := setup(t)
|
||||
auth := func(tok string) int {
|
||||
return do(h, "GET", "/api/v1/summary", map[string]string{"Authorization": "Bearer " + tok, "X-Remote": "203.0.113.77:1"}, nil).Code
|
||||
}
|
||||
for i := 0; i < loginMax; i++ {
|
||||
auth("wrong-guess")
|
||||
}
|
||||
var slow atomic.Int32
|
||||
var wg sync.WaitGroup
|
||||
start := time.Now()
|
||||
for i := 0; i < 50; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
t0 := time.Now()
|
||||
if c := auth("wrong-guess"); c != http.StatusTooManyRequests {
|
||||
t.Errorf("blocked wrong attempt: %d", c)
|
||||
}
|
||||
if time.Since(t0) >= loginBlockedDelay/2 {
|
||||
slow.Add(1)
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if n := slow.Load(); n > 3 {
|
||||
t.Fatalf("%d parallel wrong attempts were evaluated slowly; only one at a time should wait", n)
|
||||
}
|
||||
if time.Since(start) > 5*time.Second {
|
||||
t.Fatal("parallel attempts must not pile up delays")
|
||||
}
|
||||
if c := auth(utok); c != 200 {
|
||||
t.Fatalf("the correct token must still be accepted while the client is blocked: %d", c)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPenaltyGrowsAndIsCapped(t *testing.T) {
|
||||
old := loginBlockedDelay
|
||||
loginBlockedDelay = time.Second
|
||||
defer func() { loginBlockedDelay = old }()
|
||||
l := newLimiter()
|
||||
var last time.Duration
|
||||
for i := 0; i < loginMax+20; i++ {
|
||||
l.failure("203.0.113.9")
|
||||
p := l.penalty("203.0.113.9")
|
||||
if p < last {
|
||||
t.Fatalf("penalty must not shrink: %v after %v", p, last)
|
||||
}
|
||||
last = p
|
||||
}
|
||||
if last != maxBlockedDelay {
|
||||
t.Fatalf("penalty cap: %v", last)
|
||||
}
|
||||
if n := len(l.fail[limiterKey("203.0.113.9")]); n > maxFailKept {
|
||||
t.Fatalf("timestamps per client must be bounded: %d", n)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBlocklistFamilyFilter(t *testing.T) {
|
||||
st := store.New(store.Config{Name: "oracle", Version: "test"})
|
||||
now := time.Now()
|
||||
for i := 0; i < 30; i++ {
|
||||
for _, ip := range []string{"45.94.31.4", "2a01:4f8:1:2::99"} {
|
||||
st.Ingest(core.Event{Time: now, IP: ip, Cat: core.Exploit, Strong: true, Source: "traefik", Domain: "a.example", Method: "GET", Path: "/etc/passwd", Status: 404})
|
||||
}
|
||||
}
|
||||
h := New(Options{Token: utok, Version: "test", Store: st})
|
||||
get := func(q string) string {
|
||||
return do(h, "GET", "/api/v1/blocklist.txt"+q, map[string]string{"Authorization": "Bearer " + utok}, nil).Body.String()
|
||||
}
|
||||
all, v4, v6 := get("?min_score=1"), get("?min_score=1&family=4"), get("?min_score=1&family=6")
|
||||
if !strings.Contains(all, "45.94.31.4") || !strings.Contains(all, "::/64") {
|
||||
t.Fatalf("default lists both families: %q", all)
|
||||
}
|
||||
if v4 != "45.94.31.4\n" {
|
||||
t.Fatalf("family=4 must be plain IPv4 only (ipset hash:ip): %q", v4)
|
||||
}
|
||||
if strings.Contains(v6, "45.94.31.4") || !strings.Contains(v6, "::/64") {
|
||||
t.Fatalf("family=6: %q", v6)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,701 @@
|
||||
// Package server exposes the dashboard and the JSON API.
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"embed"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"net/url"
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"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"
|
||||
)
|
||||
|
||||
//go:embed web
|
||||
var webFS embed.FS
|
||||
|
||||
// maxSSE bounds the simultaneous live streams.
|
||||
const maxSSE = 20
|
||||
|
||||
// sseHeartbeat is how often a live stream pings and revalidates its session.
|
||||
var sseHeartbeat = 20 * time.Second
|
||||
|
||||
// loginBlockedDelay is the fixed delay applied to login attempts from a blocked client.
|
||||
var loginBlockedDelay = time.Second
|
||||
|
||||
// HTTPServer wraps a handler with the timeouts and limits of the daemon. The
|
||||
// SSE handler lifts the write deadline of its own connection.
|
||||
func HTTPServer(h http.Handler, base context.Context) *http.Server {
|
||||
return &http.Server{Handler: h, ReadHeaderTimeout: 10 * time.Second, ReadTimeout: 30 * time.Second,
|
||||
WriteTimeout: 30 * time.Second, IdleTimeout: 120 * time.Second, MaxHeaderBytes: 16 << 10,
|
||||
BaseContext: func(net.Listener) context.Context { return base }}
|
||||
}
|
||||
|
||||
// Options configure the handler.
|
||||
type Options struct {
|
||||
Token string
|
||||
// PeerTokens are the federation tokens accepted by /api/v1/peer/export.
|
||||
PeerTokens []string
|
||||
// Ignore lists networks that must never appear in the blocklist (ignore + trusted).
|
||||
Ignore []netip.Prefix
|
||||
// AllowHosts: with NoAuth, only requests whose Host is one of these are served
|
||||
// (anti DNS rebinding).
|
||||
AllowHosts []string
|
||||
// PeerAllow, when not empty, restricts /api/v1/peer/export to these source
|
||||
// networks. TrustedProxy lists the reverse proxies whose X-Forwarded-For is believed.
|
||||
PeerAllow []netip.Prefix
|
||||
TrustedProxy []netip.Prefix
|
||||
NoAuth bool
|
||||
Version string
|
||||
Store *store.Store
|
||||
Hub *fed.Hub
|
||||
Now func() time.Time
|
||||
}
|
||||
|
||||
// Server is the HTTP handler.
|
||||
type Server struct {
|
||||
sse atomic.Int32
|
||||
exp exportCache
|
||||
opt Options
|
||||
ses *sessions
|
||||
lim *limiter
|
||||
mux *http.ServeMux
|
||||
assets fs.FS
|
||||
}
|
||||
|
||||
// New builds the handler.
|
||||
func New(opt Options) http.Handler {
|
||||
if opt.Now == nil {
|
||||
opt.Now = time.Now
|
||||
}
|
||||
sub, _ := fs.Sub(webFS, "web")
|
||||
s := &Server{opt: opt, ses: newSessions(), lim: newLimiter(), mux: http.NewServeMux(), assets: sub}
|
||||
m := s.mux
|
||||
m.HandleFunc("GET /api/health", s.health)
|
||||
m.HandleFunc("GET /login", s.loginPage)
|
||||
m.HandleFunc("POST /login", s.login)
|
||||
m.HandleFunc("POST /logout", s.logout)
|
||||
m.HandleFunc("GET /{$}", s.index)
|
||||
for _, f := range []string{"/style.css", "/app.js", "/i18n.js", "/login.js", "/logo.png", "/favicon.png", "/world.js"} {
|
||||
name := strings.TrimPrefix(f, "/")
|
||||
m.HandleFunc("GET "+f, func(w http.ResponseWriter, r *http.Request) { s.static(w, r, name) })
|
||||
}
|
||||
m.HandleFunc("GET /api/v1/peer/export", s.peerExport)
|
||||
m.HandleFunc("GET /api/v1/summary", s.api(s.summary))
|
||||
m.HandleFunc("GET /api/v1/traffic", s.api(s.traffic))
|
||||
m.HandleFunc("GET /api/v1/ips", s.api(s.ips))
|
||||
m.HandleFunc("GET /api/v1/ip/{ip}", s.api(s.ipDetail))
|
||||
m.HandleFunc("GET /api/v1/events/stream", s.api(s.stream))
|
||||
m.HandleFunc("GET /api/v1/blocklist.txt", s.api(s.blocklist(false)))
|
||||
m.HandleFunc("GET /api/v1/blocklist.json", s.api(s.blocklist(true)))
|
||||
return s.headers(m)
|
||||
}
|
||||
|
||||
func (s *Server) headers(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if s.opt.NoAuth && !hostAllowed(r.Host, s.opt.AllowHosts) {
|
||||
http.Error(w, "host not allowed", http.StatusForbidden) // DNS rebinding guard
|
||||
return
|
||||
}
|
||||
h := w.Header()
|
||||
h.Set("Content-Security-Policy", "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; font-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'")
|
||||
h.Set("X-Content-Type-Options", "nosniff")
|
||||
h.Set("X-Frame-Options", "DENY")
|
||||
h.Set("Referrer-Policy", "same-origin")
|
||||
h.Set("Cross-Origin-Opener-Policy", "same-origin")
|
||||
h.Set("Cross-Origin-Resource-Policy", "same-origin")
|
||||
h.Set("Permissions-Policy", "camera=(), microphone=(), geolocation=()")
|
||||
if isHTTPS(r) {
|
||||
h.Set("Strict-Transport-Security", "max-age=31536000")
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, code int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(code)
|
||||
json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
|
||||
func (s *Server) health(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, 200, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
// authKind returns "session" or "bearer" for a valid user credential (cookie or
|
||||
// URUTAU_TOKEN), "peer" for the federation token, "" otherwise.
|
||||
func (s *Server) authKind(r *http.Request) string {
|
||||
if s.opt.NoAuth {
|
||||
return "session"
|
||||
}
|
||||
if a := r.Header.Get("Authorization"); strings.HasPrefix(a, "Bearer ") {
|
||||
tok := strings.TrimSpace(a[7:])
|
||||
if tokenEqual(tok, s.opt.Token) {
|
||||
return "bearer"
|
||||
}
|
||||
if s.peerTokenOK(tok) {
|
||||
return "peer"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
if c, err := r.Cookie(cookieName); err == nil && s.ses.valid(c.Value, s.opt.Now()) {
|
||||
return "session"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (s *Server) peerTokenOK(tok string) bool {
|
||||
ok := false
|
||||
for _, t := range s.opt.PeerTokens { // no early exit: constant work per token
|
||||
if tokenEqual(tok, t) {
|
||||
ok = true
|
||||
}
|
||||
}
|
||||
return ok
|
||||
}
|
||||
|
||||
// api wraps a user endpoint: only a session or URUTAU_TOKEN opens it. The peer
|
||||
// token is refused with 403 (it is a valid credential, for another route).
|
||||
func (s *Server) api(h http.HandlerFunc) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
switch s.authKind(r) {
|
||||
case "session", "bearer":
|
||||
case "peer":
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "the peer token only opens /api/v1/peer/export"})
|
||||
return
|
||||
default:
|
||||
ip := clientIP(r, s.opt.TrustedProxy)
|
||||
wait := s.lim.blocked(ip)
|
||||
if strings.HasPrefix(r.Header.Get("Authorization"), "Bearer ") {
|
||||
delay := s.lim.penalty(ip) // measured before this failure is counted
|
||||
s.lim.failure(ip) // guessing the token on the API counts like on the login form
|
||||
if wait > 0 {
|
||||
s.slowFail(ip, delay)
|
||||
}
|
||||
}
|
||||
if wait = s.lim.blocked(ip); wait > 0 {
|
||||
w.Header().Set("Retry-After", strconv.Itoa(int(wait.Seconds())+1))
|
||||
writeJSON(w, http.StatusTooManyRequests, map[string]string{"error": "too many attempts"})
|
||||
return
|
||||
}
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="urutau"`)
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
h(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
// slowFail delays a wrong attempt of a blocked client. Only one attempt per
|
||||
// client waits at a time; concurrent ones return at once (and get 429), so
|
||||
// parallel requests do not multiply the guessing rate.
|
||||
func (s *Server) slowFail(ip string, d time.Duration) {
|
||||
release, ok := s.lim.acquire(ip)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
defer release()
|
||||
if d > 0 {
|
||||
time.Sleep(d)
|
||||
}
|
||||
}
|
||||
|
||||
type exportCache struct {
|
||||
mu sync.Mutex
|
||||
at map[string]time.Time
|
||||
v map[string][]byte
|
||||
}
|
||||
|
||||
// peerExport is the only route the peer token opens: GET /api/v1/peer/export.
|
||||
func (s *Server) peerExport(w http.ResponseWriter, r *http.Request) {
|
||||
if len(s.opt.PeerTokens) == 0 && !s.opt.NoAuth {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "federation is not enabled"})
|
||||
return
|
||||
}
|
||||
if len(s.opt.PeerAllow) > 0 {
|
||||
a, err := netip.ParseAddr(clientIP(r, s.opt.TrustedProxy))
|
||||
if err != nil || !prefixesContain(s.opt.PeerAllow, a) {
|
||||
writeJSON(w, http.StatusForbidden, map[string]string{"error": "source not allowed"})
|
||||
return
|
||||
}
|
||||
}
|
||||
if !s.opt.NoAuth && s.authKind(r) != "peer" {
|
||||
if strings.HasPrefix(r.Header.Get("Authorization"), "Bearer ") {
|
||||
s.lim.failure(clientIP(r, s.opt.TrustedProxy))
|
||||
}
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="urutau-peer"`)
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"})
|
||||
return
|
||||
}
|
||||
rg := store.ParseRange(r.URL.Query().Get("range")).Name
|
||||
s.exp.mu.Lock()
|
||||
if s.exp.v == nil {
|
||||
s.exp.v, s.exp.at = map[string][]byte{}, map[string]time.Time{}
|
||||
}
|
||||
b, ok := s.exp.v[rg]
|
||||
if !ok || time.Since(s.exp.at[rg]) > 5*time.Second {
|
||||
b, _ = json.Marshal(s.opt.Store.Export(rg))
|
||||
s.exp.v[rg], s.exp.at[rg] = b, time.Now()
|
||||
}
|
||||
s.exp.mu.Unlock()
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.Write(b)
|
||||
}
|
||||
|
||||
func prefixesContain(ps []netip.Prefix, a netip.Addr) bool {
|
||||
a = a.Unmap()
|
||||
for _, p := range ps {
|
||||
if p.Contains(a) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Server) static(w http.ResponseWriter, r *http.Request, name string) {
|
||||
b, err := fs.ReadFile(s.assets, name)
|
||||
if err != nil {
|
||||
http.NotFound(w, r)
|
||||
return
|
||||
}
|
||||
ct := "application/octet-stream"
|
||||
switch {
|
||||
case strings.HasSuffix(name, ".css"):
|
||||
ct = "text/css; charset=utf-8"
|
||||
case strings.HasSuffix(name, ".js"):
|
||||
ct = "text/javascript; charset=utf-8"
|
||||
case strings.HasSuffix(name, ".png"):
|
||||
ct = "image/png"
|
||||
case strings.HasSuffix(name, ".html"):
|
||||
ct = "text/html; charset=utf-8"
|
||||
}
|
||||
w.Header().Set("Content-Type", ct)
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Write(b)
|
||||
}
|
||||
|
||||
func (s *Server) index(w http.ResponseWriter, r *http.Request) {
|
||||
if s.authKind(r) == "" {
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
s.static(w, r, "index.html")
|
||||
}
|
||||
|
||||
func (s *Server) loginPage(w http.ResponseWriter, r *http.Request) {
|
||||
if s.authKind(r) != "" {
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
s.static(w, r, "login.html")
|
||||
}
|
||||
|
||||
// sameOrigin rejects cross-site form posts: browsers send Sec-Fetch-Site and
|
||||
// Origin; SameSite=Strict on the cookie is the first line, this is the second.
|
||||
func sameOrigin(r *http.Request) bool {
|
||||
switch r.Header.Get("Sec-Fetch-Site") {
|
||||
case "cross-site":
|
||||
return false
|
||||
case "same-origin":
|
||||
return true // browsers that send Fetch Metadata state it reliably
|
||||
}
|
||||
if o := r.Header.Get("Origin"); o != "" {
|
||||
u, err := url.Parse(o)
|
||||
if err != nil || u.Host == "" || !strings.EqualFold(u.Host, r.Host) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s *Server) login(w http.ResponseWriter, r *http.Request) {
|
||||
if !sameOrigin(r) {
|
||||
http.Error(w, "cross-site request refused", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
ip := clientIP(r, s.opt.TrustedProxy)
|
||||
r.Body = http.MaxBytesReader(w, r.Body, 4096)
|
||||
if err := r.ParseForm(); err != nil {
|
||||
http.Error(w, "bad request", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
// The correct token is always accepted at once, so an attacker who burns
|
||||
// the limit cannot lock the administrator out. Guessing stays infeasible:
|
||||
// tokens carry at least 128 bits (checkToken). Wrong attempts of a blocked
|
||||
// client are serialized and progressively delayed (s.slowFail).
|
||||
if s.opt.NoAuth || !tokenEqual(r.PostForm.Get("token"), s.opt.Token) {
|
||||
wait := s.lim.blocked(ip)
|
||||
delay := s.lim.penalty(ip) // measured before this failure is counted
|
||||
s.lim.failure(ip)
|
||||
if wait > 0 {
|
||||
s.slowFail(ip, delay)
|
||||
w.Header().Set("Retry-After", strconv.Itoa(int(wait.Seconds())+1))
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-store")
|
||||
w.WriteHeader(http.StatusTooManyRequests)
|
||||
if b, err := fs.ReadFile(s.assets, "login.html"); err == nil {
|
||||
w.Write(b)
|
||||
}
|
||||
return
|
||||
}
|
||||
http.Redirect(w, r, "/login?e=bad", http.StatusSeeOther)
|
||||
return
|
||||
}
|
||||
s.lim.reset(ip)
|
||||
val, exp := s.ses.issue(s.opt.Now())
|
||||
http.SetCookie(w, &http.Cookie{Name: cookieName, Value: val, Path: "/", Expires: exp, MaxAge: int(sessionTTL.Seconds()),
|
||||
HttpOnly: true, Secure: isHTTPS(r), SameSite: http.SameSiteStrictMode})
|
||||
http.Redirect(w, r, "/", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
func (s *Server) logout(w http.ResponseWriter, r *http.Request) {
|
||||
if !sameOrigin(r) {
|
||||
http.Error(w, "cross-site request refused", http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
if c, err := r.Cookie(cookieName); err == nil {
|
||||
s.ses.revoke(c.Value)
|
||||
}
|
||||
http.SetCookie(w, &http.Cookie{Name: cookieName, Value: "", Path: "/", MaxAge: -1, HttpOnly: true,
|
||||
Secure: isHTTPS(r), SameSite: http.SameSiteStrictMode})
|
||||
http.Redirect(w, r, "/login", http.StatusSeeOther)
|
||||
}
|
||||
|
||||
// hostSel is the "host" query parameter resolved.
|
||||
func (s *Server) parts(rangeName, host string) (parts []store.Summary, all []store.HostInfo) {
|
||||
self := s.opt.Store.Name()
|
||||
local := s.opt.Store.Summary(rangeName)
|
||||
all = append(all, local.Hosts...)
|
||||
if s.opt.Hub != nil {
|
||||
all = append(all, s.opt.Hub.Hosts()...)
|
||||
}
|
||||
if host == "" || host == "all" || host == self {
|
||||
parts = append(parts, local)
|
||||
}
|
||||
if s.opt.Hub != nil && host != self {
|
||||
only := ""
|
||||
if host != "" && host != "all" {
|
||||
only = host
|
||||
}
|
||||
parts = append(parts, s.opt.Hub.Summaries(rangeName, only)...)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Server) summary(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
rg := store.ParseRange(q.Get("range")).Name
|
||||
host := q.Get("host")
|
||||
if host == "" {
|
||||
host = "all"
|
||||
}
|
||||
if host != "all" && host != s.opt.Store.Name() && (s.opt.Hub == nil || !s.opt.Hub.Has(host)) {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
|
||||
return
|
||||
}
|
||||
parts, hosts := s.parts(rg, host)
|
||||
var out store.Summary
|
||||
switch len(parts) {
|
||||
case 0:
|
||||
out = store.Summary{Version: s.opt.Version, Host: host, Range: rg, Generated: s.opt.Now().Unix()}
|
||||
default:
|
||||
out = store.Merge(host, parts)
|
||||
}
|
||||
out.Hosts = hosts
|
||||
// Peers' sources are in the merge; keep a stable order: by host then name.
|
||||
sort.SliceStable(out.Sources, func(i, j int) bool {
|
||||
if out.Sources[i].Host != out.Sources[j].Host {
|
||||
return out.Sources[i].Host < out.Sources[j].Host
|
||||
}
|
||||
return out.Sources[i].Name < out.Sources[j].Name
|
||||
})
|
||||
writeJSON(w, 200, out)
|
||||
}
|
||||
|
||||
// allIPs returns the merged IP table for the requested host selection.
|
||||
func (s *Server) allIPs(rangeName, host string) []store.IPSummary {
|
||||
rg := store.ParseRange(rangeName)
|
||||
var lists [][]store.IPSummary
|
||||
self := s.opt.Store.Name()
|
||||
if host == "" || host == "all" || host == self {
|
||||
lists = append(lists, s.opt.Store.AllIPs(rg, false))
|
||||
}
|
||||
if s.opt.Hub != nil && host != self {
|
||||
only := ""
|
||||
if host != "" && host != "all" {
|
||||
only = host
|
||||
}
|
||||
for _, p := range s.opt.Hub.Summaries(rg.Name, only) {
|
||||
lists = append(lists, p.IPs)
|
||||
}
|
||||
}
|
||||
return store.MergeIPs(lists...)
|
||||
}
|
||||
|
||||
func (s *Server) ips(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
list := s.allIPs(q.Get("range"), q.Get("host"))
|
||||
minScore, _ := strconv.ParseFloat(q.Get("min_score"), 64)
|
||||
level, needle := q.Get("level"), strings.ToLower(strings.TrimSpace(q.Get("q")))
|
||||
banned := q.Get("banned") == "1"
|
||||
filtered := list[:0:0]
|
||||
for _, x := range list {
|
||||
if x.Score < minScore || (level != "" && string(x.Level) != level) || (banned && !x.Banned) {
|
||||
continue
|
||||
}
|
||||
if needle != "" && !strings.Contains(x.IP, needle) && !strings.Contains(strings.ToLower(x.RDNS), needle) {
|
||||
continue
|
||||
}
|
||||
filtered = append(filtered, x)
|
||||
}
|
||||
switch q.Get("sort") {
|
||||
case "score", "last", "first", "events", "ip":
|
||||
store.SortIPs(filtered, q.Get("sort"), q.Get("order") != "asc")
|
||||
}
|
||||
per, _ := strconv.Atoi(q.Get("per"))
|
||||
if per < 1 || per > 200 {
|
||||
per = 50
|
||||
}
|
||||
page, _ := strconv.Atoi(q.Get("page"))
|
||||
if page < 1 {
|
||||
page = 1
|
||||
}
|
||||
if page > 100000 {
|
||||
page = 100000
|
||||
}
|
||||
from := (page - 1) * per
|
||||
if from > len(filtered) {
|
||||
from = len(filtered)
|
||||
}
|
||||
to := from + per
|
||||
if to > len(filtered) {
|
||||
to = len(filtered)
|
||||
}
|
||||
items := filtered[from:to]
|
||||
for i := range items {
|
||||
s.opt.Store.Enrich(&items[i])
|
||||
if items[i].RDNS == "" {
|
||||
items[i].RDNS = s.opt.Store.RDNSOf(items[i].IP)
|
||||
}
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"total": len(filtered), "page": page, "per": per, "items": items})
|
||||
}
|
||||
|
||||
func (s *Server) ipDetail(w http.ResponseWriter, r *http.Request) {
|
||||
raw := r.PathValue("ip")
|
||||
if _, ok := blockAddr(raw); !ok {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid ip"})
|
||||
return
|
||||
}
|
||||
ip := store.KeyOf(raw)
|
||||
var lists [][]store.IPSummary
|
||||
if d, ok := s.opt.Store.IP(ip); ok {
|
||||
lists = append(lists, []store.IPSummary{d})
|
||||
}
|
||||
if s.opt.Hub != nil {
|
||||
lists = append(lists, s.opt.Hub.IPDetail(ip))
|
||||
}
|
||||
m := store.MergeIPs(lists...)
|
||||
if len(m) == 0 {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "not found"})
|
||||
return
|
||||
}
|
||||
writeJSON(w, 200, m[0])
|
||||
}
|
||||
|
||||
func (s *Server) stream(w http.ResponseWriter, r *http.Request) {
|
||||
fl, ok := w.(http.Flusher)
|
||||
if !ok {
|
||||
http.Error(w, "streaming unsupported", 500)
|
||||
return
|
||||
}
|
||||
if s.sse.Add(1) > maxSSE {
|
||||
s.sse.Add(-1)
|
||||
w.Header().Set("Retry-After", "10")
|
||||
http.Error(w, "too many live streams", http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
defer s.sse.Add(-1)
|
||||
rc := http.NewResponseController(w)
|
||||
_ = rc.SetWriteDeadline(time.Time{})
|
||||
h := w.Header()
|
||||
h.Set("Content-Type", "text/event-stream")
|
||||
h.Set("Cache-Control", "no-store")
|
||||
h.Set("X-Accel-Buffering", "no")
|
||||
ch, stop := s.opt.Store.Subscribe()
|
||||
defer stop()
|
||||
fmt.Fprint(w, "retry: 3000\n: connected\n\n")
|
||||
fl.Flush()
|
||||
tick := time.NewTicker(sseHeartbeat)
|
||||
defer tick.Stop()
|
||||
for {
|
||||
select {
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
case <-tick.C:
|
||||
if k := s.authKind(r); k != "session" && k != "bearer" {
|
||||
return // the session expired or was revoked: close the stream
|
||||
}
|
||||
if _, err := fmt.Fprint(w, ": ping\n\n"); err != nil {
|
||||
return
|
||||
}
|
||||
fl.Flush()
|
||||
case e := <-ch:
|
||||
if k := s.authKind(r); k != "session" && k != "bearer" {
|
||||
return
|
||||
}
|
||||
b, _ := json.Marshal(e)
|
||||
if _, err := fmt.Fprintf(w, "event: ev\ndata: %s\n\n", b); err != nil {
|
||||
return
|
||||
}
|
||||
fl.Flush()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) blocklist(asJSON bool) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
min := 50.0
|
||||
if v, err := strconv.ParseFloat(q.Get("min_score"), 64); err == nil && v >= 0 {
|
||||
min = v
|
||||
}
|
||||
rangeName := q.Get("range")
|
||||
if rangeName == "" {
|
||||
rangeName = "7d"
|
||||
}
|
||||
// family=4 gives plain IPv4 addresses only (for ipset hash:ip and similar);
|
||||
// family=6 gives only the IPv6 /64 prefixes; the default lists both.
|
||||
family := q.Get("family")
|
||||
if family != "4" && family != "6" {
|
||||
family = "all"
|
||||
}
|
||||
var out []store.IPSummary
|
||||
for _, x := range s.allIPs(rangeName, q.Get("host")) {
|
||||
if x.Score < min || !x.Strong || x.Admin {
|
||||
continue
|
||||
}
|
||||
// every row is revalidated here, whatever its origin (a peer included)
|
||||
addr, ok := blockAddr(x.IP)
|
||||
if !ok || !core.IsGlobal(addr) || core.Ignored(s.opt.Ignore, addr.String()) {
|
||||
continue
|
||||
}
|
||||
if (family == "4" && !addr.Is4()) || (family == "6" && addr.Is4()) {
|
||||
continue
|
||||
}
|
||||
out = append(out, x)
|
||||
}
|
||||
if q.Get("download") == "1" {
|
||||
ext := "txt"
|
||||
if asJSON {
|
||||
ext = "json"
|
||||
}
|
||||
w.Header().Set("Content-Disposition", `attachment; filename="urutau-blocklist.`+ext+`"`)
|
||||
}
|
||||
if asJSON {
|
||||
type row struct {
|
||||
IP string `json:"ip"`
|
||||
Score float64 `json:"score"`
|
||||
Last int64 `json:"last"`
|
||||
Hosts []string `json:"hosts"`
|
||||
CC string `json:"cc,omitempty"`
|
||||
Country string `json:"country,omitempty"`
|
||||
City string `json:"city,omitempty"`
|
||||
ASN uint32 `json:"asn,omitempty"`
|
||||
ASOrg string `json:"as_org,omitempty"`
|
||||
}
|
||||
rows := make([]row, 0, len(out))
|
||||
for _, x := range out {
|
||||
s.opt.Store.Enrich(&x)
|
||||
rows = append(rows, row{x.IP, x.Score, x.Last, x.Hosts, x.CC, x.Country, x.City, x.ASN, x.ASOrg})
|
||||
}
|
||||
writeJSON(w, 200, map[string]any{"generated": s.opt.Now().Unix(), "min_score": min, "count": len(rows), "ips": rows})
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "text/plain; charset=utf-8")
|
||||
var b strings.Builder
|
||||
for _, x := range out {
|
||||
b.WriteString(x.IP)
|
||||
b.WriteByte('\n')
|
||||
}
|
||||
w.Write([]byte(b.String()))
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) traffic(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query()
|
||||
rg := store.ParseRange(q.Get("range")).Name
|
||||
domain := q.Get("domain")
|
||||
if domain == "" {
|
||||
domain = "all"
|
||||
}
|
||||
host := q.Get("host")
|
||||
if host == "" {
|
||||
host = "all"
|
||||
}
|
||||
self := s.opt.Store.Name()
|
||||
if host != "all" && host != self && (s.opt.Hub == nil || !s.opt.Hub.Has(host)) {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "unknown host"})
|
||||
return
|
||||
}
|
||||
var parts []store.TrafficData
|
||||
if host == "all" || host == self {
|
||||
parts = append(parts, s.opt.Store.TrafficSummary(rg, domain))
|
||||
}
|
||||
if s.opt.Hub != nil && host != self {
|
||||
only := ""
|
||||
if host != "all" {
|
||||
only = host
|
||||
}
|
||||
parts = append(parts, s.opt.Hub.Traffic(rg, domain, only)...)
|
||||
}
|
||||
out := store.MergeTraffic(host, parts)
|
||||
out.Domain = domain
|
||||
writeJSON(w, 200, out)
|
||||
}
|
||||
|
||||
// blockAddr parses a table key (address or IPv6 /64 prefix) into the address
|
||||
// that represents it. Zones and garbage are refused.
|
||||
func blockAddr(key string) (netip.Addr, bool) {
|
||||
if a, err := netip.ParseAddr(key); err == nil {
|
||||
return a, a.Zone() == ""
|
||||
}
|
||||
if p, err := netip.ParsePrefix(key); err == nil && p.Addr().Is6() && p.Bits() == 64 && p.Addr().Zone() == "" {
|
||||
return p.Addr(), true
|
||||
}
|
||||
return netip.Addr{}, false
|
||||
}
|
||||
|
||||
// hostAllowed checks the Host header against loopback names and the extra list.
|
||||
func hostAllowed(host string, extra []string) bool {
|
||||
h := strings.ToLower(host)
|
||||
if i := strings.LastIndexByte(h, ':'); i >= 0 && !strings.HasSuffix(h, "]") {
|
||||
h = h[:i]
|
||||
}
|
||||
h = strings.Trim(h, "[]")
|
||||
switch h {
|
||||
case "localhost", "127.0.0.1", "::1":
|
||||
return true
|
||||
}
|
||||
for _, e := range extra {
|
||||
if h == strings.ToLower(e) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,494 @@
|
||||
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: "/<img src=x onerror=alert(1)>"})
|
||||
h := New(Options{Token: "user-token-0123456789-abcdefghijklmnop", PeerTokens: []string{"peer-token-0123456789-abcdefghijklmnopq"}, 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", PeerTokens: []string{"peer-token-0123456789-abcdefghijklmnopq"}, Version: "test", Store: st,
|
||||
TrustedProxy: mustPrefixes("172.16.0.0/12")}
|
||||
if mod != nil {
|
||||
mod(&o)
|
||||
}
|
||||
return New(o)
|
||||
}
|
||||
|
||||
func TestPeerTokenOnlyOpensExport(t *testing.T) {
|
||||
h, _ := setup(t)
|
||||
peer := map[string]string{"Authorization": "Bearer peer-token-0123456789-abcdefghijklmnopq"}
|
||||
user := map[string]string{"Authorization": "Bearer user-token-0123456789-abcdefghijklmnop"}
|
||||
for _, p := range []string{"/api/v1/summary", "/api/v1/traffic", "/api/v1/ip/45.94.31.4", "/api/v1/ips", "/api/v1/events/stream",
|
||||
"/api/v1/blocklist.txt", "/api/v1/blocklist.json"} {
|
||||
if w := do(h, "GET", p, peer, nil); w.Code != http.StatusForbidden {
|
||||
t.Errorf("peer token on %s: %d (want 403)", p, w.Code)
|
||||
}
|
||||
if w := do(h, "GET", p, nil, nil); w.Code != http.StatusUnauthorized {
|
||||
t.Errorf("no credential on %s: %d (want 401)", p, w.Code)
|
||||
}
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/peer/export", nil, nil); w.Code != 401 {
|
||||
t.Fatalf("export without credential: %d", w.Code)
|
||||
}
|
||||
if w := do(h, "GET", "/api/v1/peer/export", user, nil); w.Code != 401 {
|
||||
t.Fatalf("the user token must not open the export: %d", w.Code)
|
||||
}
|
||||
w := do(h, "GET", "/api/v1/peer/export?range=7d", peer, nil)
|
||||
if w.Code != 200 || !strings.Contains(w.Body.String(), `"v":1`) || !strings.Contains(w.Body.String(), "45.94.31.4") || !strings.Contains(w.Body.String(), `"traffic"`) {
|
||||
t.Fatalf("export %d %.200s", w.Code, w.Body)
|
||||
}
|
||||
// without a peer token configured the route does not exist
|
||||
h2 := federated(t, func(o *Options) { o.PeerTokens = nil })
|
||||
if w := do(h2, "GET", "/api/v1/peer/export", peer, nil); w.Code != 404 {
|
||||
t.Fatalf("federation disabled: %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerAllowAndRealClientIP(t *testing.T) {
|
||||
peer := map[string]string{"Authorization": "Bearer peer-token-0123456789-abcdefghijklmnopq"}
|
||||
h := federated(t, func(o *Options) { o.PeerAllow = mustPrefixes("203.0.113.0/24") })
|
||||
with := func(remote, xff string) *httptest.ResponseRecorder {
|
||||
hd := map[string]string{"Authorization": peer["Authorization"], "X-Remote": remote}
|
||||
if xff != "" {
|
||||
hd["X-Forwarded-For"] = xff
|
||||
}
|
||||
return do(h, "GET", "/api/v1/peer/export", hd, nil)
|
||||
}
|
||||
if w := with("198.51.100.9:1", ""); w.Code != 403 {
|
||||
t.Fatalf("outside the allow list: %d", w.Code)
|
||||
}
|
||||
if w := with("203.0.113.8:1", ""); w.Code != 200 {
|
||||
t.Fatalf("inside the allow list: %d", w.Code)
|
||||
}
|
||||
if w := with("198.51.100.9:1", "203.0.113.8"); w.Code != 403 {
|
||||
t.Fatalf("forged XFF from an untrusted source must not pass: %d", w.Code)
|
||||
}
|
||||
if w := with("172.18.0.2:1", "203.0.113.8"); w.Code != 200 {
|
||||
t.Fatalf("XFF from the trusted proxy is the real client: %d", w.Code)
|
||||
}
|
||||
if w := with("172.18.0.2:1", "198.51.100.77"); w.Code != 403 {
|
||||
t.Fatalf("real client outside the list behind the proxy: %d", w.Code)
|
||||
}
|
||||
if w := with("172.18.0.2:1", "203.0.113.8, 198.51.100.77"); w.Code != 403 {
|
||||
t.Fatalf("the proxy appended the real client on the right: %d", w.Code)
|
||||
}
|
||||
}
|
||||
|
||||
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")
|
||||
}
|
||||
@@ -0,0 +1,714 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
var D = window.URUTAU_I18N;
|
||||
var $ = function (s, r) { return (r || document).querySelector(s); };
|
||||
function lsGet(k) { try { return localStorage.getItem(k); } catch (e) { return null; } }
|
||||
function lsSet(k, v) { try { localStorage.setItem(k, v); } catch (e) { /* ignore */ } }
|
||||
|
||||
var lang = lsGet('urutau.lang') || ((navigator.language || 'en').toLowerCase().indexOf('pt') === 0 ? 'pt-BR' : 'en');
|
||||
if (!D[lang]) lang = 'en';
|
||||
var theme = lsGet('urutau.theme');
|
||||
if (theme === 'light' || theme === 'dark') document.documentElement.setAttribute('data-theme', theme);
|
||||
|
||||
function t(key, n) {
|
||||
var s = D[lang][key] || D.en[key] || key;
|
||||
return n === undefined ? s : s.replace('{n}', n);
|
||||
}
|
||||
function nf(n) { return new Intl.NumberFormat(lang).format(n); }
|
||||
|
||||
var CHART_CATS = ['notfound', 'scanner', 'bruteforce', 'exploit', 'ssh-fail', 'ssh-probe', 'ban'];
|
||||
var state = {
|
||||
host: lsGet('urutau.host') || 'all', range: lsGet('urutau.range') || '24h',
|
||||
sort: 'score', order: 'desc', page: 1, per: 25, q: '', level: '', banned: false,
|
||||
hidden: {}, summary: null, ipsTotal: 0, live: [],
|
||||
tab: lsGet('urutau.tab') === 'traffic' ? 'traffic' : 'threats', domain: 'all', traffic: null
|
||||
};
|
||||
if (['1h', '24h', '7d'].indexOf(state.range) < 0) state.range = '24h';
|
||||
|
||||
// All dynamic text goes through textContent: log data is hostile.
|
||||
function el(tag, cls, text) {
|
||||
var e = document.createElement(tag);
|
||||
if (cls) e.className = cls;
|
||||
if (text !== undefined && text !== null) e.textContent = text;
|
||||
return e;
|
||||
}
|
||||
function svgEl(tag, attrs) {
|
||||
var e = document.createElementNS('http://www.w3.org/2000/svg', tag);
|
||||
for (var k in attrs) e.setAttribute(k, attrs[k]);
|
||||
return e;
|
||||
}
|
||||
function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); }
|
||||
|
||||
function flag(cc) {
|
||||
if (!cc || cc.length !== 2) return '';
|
||||
return cc.toUpperCase().replace(/./g, function (c) { return String.fromCodePoint(127397 + c.charCodeAt(0)); });
|
||||
}
|
||||
var regionNames = null, regionLang = '';
|
||||
function countryName(cc) {
|
||||
try {
|
||||
if (!regionNames || regionLang !== lang) { regionNames = new Intl.DisplayNames([lang], { type: 'region' }); regionLang = lang; }
|
||||
return regionNames.of(cc.toUpperCase()) || cc;
|
||||
} catch (e) { return cc; }
|
||||
}
|
||||
function fmtBytes(n) {
|
||||
var u = ['B', 'KB', 'MB', 'GB', 'TB'], i = 0;
|
||||
while (n >= 1024 && i < u.length - 1) { n /= 1024; i++; }
|
||||
return new Intl.NumberFormat(lang, { maximumFractionDigits: n < 10 && i > 0 ? 1 : 0 }).format(n) + ' ' + u[i];
|
||||
}
|
||||
// Class names are built from whitelists only: peers send these values.
|
||||
var KNOWN_CATS = ['ok', 'notfound', 'scanner', 'exploit', 'bruteforce', 'ssh-fail', 'ssh-probe', 'ssh-ok', 'ban'];
|
||||
var KNOWN_STATES = ['following', 'waiting', 'backfill', 'error', 'disabled'];
|
||||
var KNOWN_LEVELS = ['hostile', 'suspicious', 'low'];
|
||||
function pick(list, v, fallback) { return list.indexOf(v) >= 0 ? v : fallback; }
|
||||
function ago(ts) {
|
||||
if (!ts) return t('never');
|
||||
var s = Math.max(0, Math.floor(Date.now() / 1000 - ts));
|
||||
if (s < 5) return t('ago.now');
|
||||
if (s < 60) return t('ago.s', s);
|
||||
if (s < 3600) return t('ago.m', Math.floor(s / 60));
|
||||
if (s < 86400) return t('ago.h', Math.floor(s / 3600));
|
||||
return t('ago.d', Math.floor(s / 86400));
|
||||
}
|
||||
function clock(ts) { return new Date(ts * 1000).toLocaleTimeString(lang, { hour: '2-digit', minute: '2-digit', second: '2-digit' }); }
|
||||
|
||||
function api(path) {
|
||||
return fetch(path, { credentials: 'same-origin', headers: { Accept: 'application/json' } }).then(function (r) {
|
||||
if (r.status === 401) { location.href = '/login'; throw new Error('unauthorized'); }
|
||||
if (!r.ok) throw new Error('HTTP ' + r.status);
|
||||
return r.json();
|
||||
});
|
||||
}
|
||||
function qs(extra) {
|
||||
var p = new URLSearchParams({ host: state.host, range: state.range });
|
||||
for (var k in extra) p.set(k, extra[k]);
|
||||
return p.toString();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- i18n
|
||||
function applyI18n() {
|
||||
document.documentElement.lang = lang;
|
||||
document.querySelectorAll('[data-i18n]').forEach(function (n) { n.textContent = t(n.getAttribute('data-i18n')); });
|
||||
document.querySelectorAll('[data-i18n-ph]').forEach(function (n) { n.setAttribute('placeholder', t(n.getAttribute('data-i18n-ph'))); });
|
||||
document.querySelectorAll('[data-i18n-aria]').forEach(function (n) { n.setAttribute('aria-label', t(n.getAttribute('data-i18n-aria'))); });
|
||||
document.querySelectorAll('[data-i18n-title]').forEach(function (n) { n.setAttribute('title', t(n.getAttribute('data-i18n-title'))); });
|
||||
$('#lang').textContent = lang === 'en' ? 'PT' : 'EN';
|
||||
renderAll();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- render
|
||||
function kpi(cls, value, label) {
|
||||
var d = el('div', 'panel kpi ' + cls);
|
||||
d.appendChild(el('div', 'v', nf(value)));
|
||||
d.appendChild(el('div', 'l', label));
|
||||
return d;
|
||||
}
|
||||
function renderKpis() {
|
||||
var s = state.summary, box = $('#kpis');
|
||||
clear(box);
|
||||
if (!s) return;
|
||||
var T = s.totals;
|
||||
box.appendChild(kpi('', T.requests, t('kpi.requests')));
|
||||
box.appendChild(kpi('', T.malicious, t('kpi.malicious')));
|
||||
box.appendChild(kpi(T.hostile_ips > 0 ? 'hot' : '', T.hostile_ips, t('kpi.hostile')));
|
||||
box.appendChild(kpi(T.suspicious_ips > 0 ? 'warn' : '', T.suspicious_ips, t('kpi.suspicious')));
|
||||
box.appendChild(kpi('', T.active_bans, t('kpi.bans')));
|
||||
box.appendChild(kpi('', T.unique_ips, t('kpi.ips')));
|
||||
$('#monitoring').textContent = T.monitoring ? t('kpi.monitoring', nf(T.monitoring)) : '';
|
||||
}
|
||||
|
||||
function renderLegend() {
|
||||
var box = $('#legend');
|
||||
clear(box);
|
||||
CHART_CATS.forEach(function (c) {
|
||||
var b = el('button');
|
||||
b.type = 'button';
|
||||
b.setAttribute('aria-pressed', state.hidden[c] ? 'false' : 'true');
|
||||
b.appendChild(el('span', 'sw b-' + c));
|
||||
b.appendChild(el('span', '', t('cat.' + c)));
|
||||
b.addEventListener('click', function () { state.hidden[c] = !state.hidden[c]; renderLegend(); drawChart(); });
|
||||
box.appendChild(b);
|
||||
});
|
||||
}
|
||||
|
||||
function niceMax(v) {
|
||||
var raw = Math.max(v, 4) / 4, p = Math.pow(10, Math.floor(Math.log10(raw))), m = raw / p;
|
||||
return (m <= 1 ? 1 : m <= 2 ? 2 : m <= 5 ? 5 : 10) * p * 4;
|
||||
}
|
||||
function tickLabel(ts) {
|
||||
var d = new Date(ts * 1000);
|
||||
if (state.range === '7d') return d.toLocaleDateString(lang, { month: 'short', day: 'numeric' });
|
||||
return d.toLocaleTimeString(lang, { hour: '2-digit', minute: '2-digit' });
|
||||
}
|
||||
|
||||
function drawChart() {
|
||||
var wrap = $('#chart');
|
||||
clear(wrap);
|
||||
var s = state.summary;
|
||||
if (!s) return;
|
||||
var tl = s.timeline, n = (tl.series.ok || []).length;
|
||||
var W = Math.max(280, wrap.clientWidth), H = 230, L = 38, R = 6, Tp = 8, B = 22;
|
||||
var cats = CHART_CATS.filter(function (c) { return !state.hidden[c]; });
|
||||
var tot = [], max = 0, i;
|
||||
for (i = 0; i < n; i++) {
|
||||
var sum = 0;
|
||||
cats.forEach(function (c) { sum += tl.series[c][i]; });
|
||||
tot.push(sum);
|
||||
if (sum > max) max = sum;
|
||||
}
|
||||
var top = niceMax(max), ph = H - Tp - B, bw = (W - L - R) / n;
|
||||
var svg = svgEl('svg', { viewBox: '0 0 ' + W + ' ' + H, role: 'img', 'aria-label': t('timeline.title') });
|
||||
for (i = 0; i <= 4; i++) {
|
||||
var y = Tp + ph - (ph * i / 4);
|
||||
svg.appendChild(svgEl('line', { x1: L, x2: W - R, y1: y, y2: y, 'class': 'gridline' }));
|
||||
var lab = svgEl('text', { x: L - 5, y: y + 3, 'text-anchor': 'end', 'class': 'axis' });
|
||||
lab.textContent = nf(Math.round(top * i / 4));
|
||||
svg.appendChild(lab);
|
||||
}
|
||||
var nt = W < 520 ? 3 : 5;
|
||||
for (i = 0; i < nt; i++) {
|
||||
var idx = Math.round((n - 1) * i / (nt - 1));
|
||||
var xl = svgEl('text', { x: L + bw * idx + bw / 2, y: H - 6, 'text-anchor': i === 0 ? 'start' : i === nt - 1 ? 'end' : 'middle', 'class': 'axis' });
|
||||
xl.textContent = tickLabel(tl.start + idx * tl.step);
|
||||
svg.appendChild(xl);
|
||||
}
|
||||
var tip = el('div', 'tip');
|
||||
tip.hidden = true;
|
||||
function showTip(ix, x) {
|
||||
clear(tip);
|
||||
tip.appendChild(el('strong', '', new Date((tl.start + ix * tl.step) * 1000).toLocaleString(lang, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })));
|
||||
CHART_CATS.forEach(function (c) {
|
||||
var v = tl.series[c][ix];
|
||||
if (!v) return;
|
||||
var r = el('div');
|
||||
r.appendChild(el('span', '', t('cat.' + c)));
|
||||
r.appendChild(el('span', 'num', nf(v)));
|
||||
tip.appendChild(r);
|
||||
});
|
||||
tip.hidden = false;
|
||||
tip.style.left = Math.max(0, Math.min(x, W - 160)) + 'px';
|
||||
tip.style.top = '4px';
|
||||
}
|
||||
for (i = 0; i < n; i++) {
|
||||
var yb = Tp + ph;
|
||||
for (var k = 0; k < cats.length; k++) {
|
||||
var v = tl.series[cats[k]][i];
|
||||
if (!v) continue;
|
||||
var h = Math.max(1, v / top * ph);
|
||||
yb -= h;
|
||||
svg.appendChild(svgEl('rect', { x: L + bw * i + (bw > 3 ? 0.5 : 0), y: yb, width: Math.max(1, bw - (bw > 3 ? 1 : 0)), height: h, 'class': 'b-' + cats[k] }));
|
||||
}
|
||||
}
|
||||
(function (tl2) {
|
||||
for (var j = 0; j < n; j++) {
|
||||
(function (j) {
|
||||
var r = svgEl('rect', { x: L + bw * j, y: Tp, width: bw, height: ph, 'class': 'hover-col' });
|
||||
r.addEventListener('mouseenter', function () { showTip(j, L + bw * j + 14); });
|
||||
r.addEventListener('click', function () { showTip(j, L + bw * j + 14); });
|
||||
svg.appendChild(r);
|
||||
})(j);
|
||||
}
|
||||
})(tl);
|
||||
svg.addEventListener('mouseleave', function () { tip.hidden = true; });
|
||||
wrap.appendChild(svg);
|
||||
wrap.appendChild(tip);
|
||||
if (max === 0) {
|
||||
var e = svgEl('text', { x: W / 2, y: H / 2, 'text-anchor': 'middle', 'class': 'axis' });
|
||||
e.textContent = t('timeline.empty');
|
||||
svg.appendChild(e);
|
||||
}
|
||||
}
|
||||
|
||||
function levelBadge(l) { l = pick(KNOWN_LEVELS, l, 'low'); return el('span', 'badge lv-' + l, t('level.' + l)); }
|
||||
|
||||
function renderIPs(items) {
|
||||
var tb = $('#ips tbody');
|
||||
clear(tb);
|
||||
if (!items.length) {
|
||||
var tr0 = el('tr'), td0 = el('td', 'empty', t('ips.empty'));
|
||||
td0.colSpan = 7;
|
||||
tr0.appendChild(td0);
|
||||
tb.appendChild(tr0);
|
||||
}
|
||||
items.forEach(function (x) {
|
||||
var tr = el('tr', 'row');
|
||||
tr.tabIndex = 0;
|
||||
tr.setAttribute('role', 'button');
|
||||
function cell(label, node) { var td = el('td'); td.setAttribute('data-label', label); td.appendChild(node); tr.appendChild(td); }
|
||||
var ipc = el('span');
|
||||
ipc.appendChild(el('span', 'mono', x.ip));
|
||||
if (state.summary && state.summary.hosts.length > 1) ipc.appendChild(el('small', '', (x.hosts || []).join(', ')));
|
||||
cell(t('col.ip'), ipc);
|
||||
cell(t('col.score'), el('span', 'num', String(x.score)));
|
||||
cell(t('col.level'), levelBadge(x.level));
|
||||
var chips = el('span');
|
||||
var kinds = Object.keys(x.counts).filter(function (c) { return c !== 'ok' && c !== 'ssh-ok' && KNOWN_CATS.indexOf(c) >= 0; })
|
||||
.sort(function (a, b) { return x.counts[b] - x.counts[a]; });
|
||||
kinds.slice(0, 2).forEach(function (c) { chips.appendChild(el('span', 'chip', t('cat.' + c) + ' ' + nf(x.counts[c]))); });
|
||||
if (kinds.length > 2) chips.appendChild(el('span', 'chip', '+' + (kinds.length - 2)));
|
||||
cell(t('col.cats'), chips);
|
||||
var org = el('span', 'origin');
|
||||
if (x.cc) org.textContent = flag(x.cc) + ' ' + (x.city ? x.city + ', ' : '') + (x.country || countryName(x.cc));
|
||||
else org.textContent = '-';
|
||||
// one line, ellipsis; the rest on hover
|
||||
var tip = [x.asn ? 'AS' + x.asn + (x.as_org ? ' ' + x.as_org : '') : '', x.rdns || ''].filter(Boolean);
|
||||
if (x.cc) tip.unshift(org.textContent);
|
||||
if (tip.length) org.title = tip.join('\n');
|
||||
cell(t('col.origin'), org);
|
||||
cell(t('col.last'), el('span', '', ago(x.last)));
|
||||
cell(t('col.banned'), x.banned ? el('span', 'banned', (x.jails || []).join(', ') || t('yes')) : el('span', '', '-'));
|
||||
tr.addEventListener('click', function () { openDetail(x.ip); });
|
||||
tr.addEventListener('keydown', function (ev) { if (ev.key === 'Enter' || ev.key === ' ') { ev.preventDefault(); openDetail(x.ip); } });
|
||||
tb.appendChild(tr);
|
||||
});
|
||||
$('#count').textContent = t('pager.count', nf(state.ipsTotal));
|
||||
$('#prev').disabled = state.page <= 1;
|
||||
$('#next').disabled = state.page * state.per >= state.ipsTotal;
|
||||
}
|
||||
|
||||
function renderTop(id, rows, mono) {
|
||||
var box = $(id);
|
||||
clear(box);
|
||||
if (!rows || !rows.length) { box.appendChild(el('div', 'empty', t('top.empty'))); return; }
|
||||
var max = rows[0].n || 1;
|
||||
rows.slice(0, 10).forEach(function (r) {
|
||||
var d = el('div', 'bar-row');
|
||||
d.appendChild(el('span', 'k' + (mono ? ' mono' : ''), r.key));
|
||||
d.appendChild(el('span', 'n', nf(r.n)));
|
||||
if (r.label) d.appendChild(el('span', 'sub', r.label));
|
||||
var bar = el('div', 'bar'), i = el('i');
|
||||
i.style.width = Math.max(2, r.n / max * 100) + '%';
|
||||
bar.appendChild(i);
|
||||
d.appendChild(bar);
|
||||
box.appendChild(d);
|
||||
});
|
||||
}
|
||||
|
||||
function eventText(e) {
|
||||
if (e.source === 'traefik') return (e.method || '') + ' ' + (e.domain || '') + (e.path || '') + (e.forged ? ' [' + t('feed.forged') + ']' : '');
|
||||
if (e.source === 'ssh') return e.user ? 'ssh user ' + e.user : 'ssh';
|
||||
if (e.source === 'fail2ban') return 'fail2ban [' + (e.jail || '') + ']';
|
||||
return '';
|
||||
}
|
||||
function renderFeed() {
|
||||
var box = $('#feed');
|
||||
clear(box);
|
||||
var seen = {}, list = [];
|
||||
var rec = state.summary ? state.summary.recent || [] : [];
|
||||
state.live.concat(rec).forEach(function (e) {
|
||||
if (state.host !== 'all' && e.host !== state.host) return;
|
||||
var key = e.t + '|' + e.ip + '|' + e.cat + '|' + (e.path || e.user || e.jail || '');
|
||||
if (seen[key]) return;
|
||||
seen[key] = 1;
|
||||
list.push(e);
|
||||
});
|
||||
list.sort(function (a, b) { return b.t - a.t; });
|
||||
list = list.slice(0, 100);
|
||||
if (!list.length) { box.appendChild(el('li', 'empty', t('feed.empty'))); return; }
|
||||
list.forEach(function (e) {
|
||||
var li = el('li');
|
||||
li.appendChild(el('span', 't', clock(e.t)));
|
||||
if (e.forged) li.title = t('feed.forged');
|
||||
var ecat = pick(KNOWN_CATS, e.cat, 'ok');
|
||||
li.appendChild(el('span', 'cat b-' + ecat, e.unban ? t('feed.unban') : t('cat.' + ecat)));
|
||||
var b = el('button', 'linkish mono', e.ip);
|
||||
b.type = 'button';
|
||||
b.addEventListener('click', function () { openDetail(e.ip); });
|
||||
li.appendChild(b);
|
||||
if (e.cc) b.textContent = flag(e.cc) + ' ' + e.ip;
|
||||
li.appendChild(el('span', 'what', (e.host ? '[' + e.host + '] ' : '') + eventText(e)));
|
||||
box.appendChild(li);
|
||||
});
|
||||
}
|
||||
|
||||
function renderHosts() {
|
||||
var s = state.summary, box = $('#hosts'), sel = $('#host');
|
||||
if (!s) return;
|
||||
clear(box);
|
||||
(s.hosts || []).forEach(function (h) {
|
||||
var c = el('div', 'host');
|
||||
var hd = el('h3');
|
||||
hd.appendChild(el('span', 'dot ' + (h.online ? 'on' : 'off')));
|
||||
hd.appendChild(el('span', '', h.name));
|
||||
c.appendChild(hd);
|
||||
c.appendChild(el('div', 'meta', h.online ? t('host.online') + (h.version ? ' · ' + h.version : '') : t('host.offline') + (h.error ? ' · ' + h.error : '')));
|
||||
var dl = el('dl');
|
||||
[['host.requests', h.requests], ['host.malicious', h.malicious], ['host.hostile', h.hostile_ips], ['host.bans', h.active_bans]].forEach(function (p) {
|
||||
dl.appendChild(el('dt', '', t(p[0])));
|
||||
dl.appendChild(el('dd', '', nf(p[1] || 0)));
|
||||
});
|
||||
if (h.latency_ms) { dl.appendChild(el('dt', '', t('host.latency'))); dl.appendChild(el('dd', '', h.latency_ms + ' ms')); }
|
||||
c.appendChild(dl);
|
||||
box.appendChild(c);
|
||||
});
|
||||
var want = (s.hosts || []).map(function (h) { return h.name; }).join('|');
|
||||
if (sel.getAttribute('data-hosts') !== want + '|' + lang) {
|
||||
clear(sel);
|
||||
var o = el('option', '', t('host.all'));
|
||||
o.value = 'all';
|
||||
sel.appendChild(o);
|
||||
(s.hosts || []).forEach(function (h) { var op = el('option', '', h.name); op.value = h.name; sel.appendChild(op); });
|
||||
sel.setAttribute('data-hosts', want + '|' + lang);
|
||||
}
|
||||
sel.value = state.host;
|
||||
sel.hidden = (s.hosts || []).length < 2;
|
||||
|
||||
var tb = $('#sources tbody');
|
||||
clear(tb);
|
||||
(s.sources || []).forEach(function (r) {
|
||||
var tr = el('tr');
|
||||
function cell(label, text, cls) { var td = el('td'); td.setAttribute('data-label', label); td.appendChild(el('span', cls || '', text)); tr.appendChild(td); }
|
||||
cell(t('col.host'), r.host || '');
|
||||
cell(t('col.source'), r.name);
|
||||
var rs = pick(KNOWN_STATES, r.state, 'error');
|
||||
cell(t('col.state'), t('state.' + rs) + (r.error ? ' (' + r.error + ')' : ''), 'st-' + rs);
|
||||
cell(t('col.lines'), nf(r.lines), 'num');
|
||||
cell(t('col.malformed'), nf(r.malformed), 'num');
|
||||
cell(t('col.lastEvent'), ago(r.last_event));
|
||||
tb.appendChild(tr);
|
||||
});
|
||||
$('#ver').textContent = s.version ? 'v' + s.version : '';
|
||||
$('#attrib').textContent = s.attribution || '';
|
||||
}
|
||||
|
||||
function renderAll() {
|
||||
var s = state.summary;
|
||||
renderKpis(); renderLegend(); drawChart(); renderHosts(); renderFeed();
|
||||
if (s) {
|
||||
renderTop('#top-paths', s.top_paths, true);
|
||||
renderTop('#top-domains', s.top_domains, true);
|
||||
renderTop('#top-uas', s.top_uas, false);
|
||||
renderTop('#top-users', s.top_users, true);
|
||||
renderMap('#map-threats', '#maplist-threats', s.countries, false);
|
||||
}
|
||||
if (state.traffic) renderTraffic();
|
||||
if (state.ipItems) renderIPs(state.ipItems);
|
||||
document.querySelectorAll('#range button').forEach(function (b) { b.setAttribute('aria-pressed', b.getAttribute('data-range') === state.range ? 'true' : 'false'); });
|
||||
updateBlocklistLink();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- data
|
||||
var inflight = false;
|
||||
function refresh() {
|
||||
if (inflight) return;
|
||||
inflight = true;
|
||||
var jobs = [api('/api/v1/summary?' + qs({}))];
|
||||
if (state.tab === 'traffic') {
|
||||
jobs.push(api('/api/v1/traffic?' + qs({ domain: state.domain })));
|
||||
} else {
|
||||
jobs.push(api('/api/v1/ips?' + qs({ sort: state.sort, order: state.order, page: state.page, per: state.per, q: state.q, level: state.level, banned: state.banned ? '1' : '0' })));
|
||||
}
|
||||
Promise.all(jobs).then(function (r) {
|
||||
state.summary = r[0];
|
||||
if (state.tab === 'traffic') state.traffic = r[1];
|
||||
else { state.ipItems = r[1].items; state.ipsTotal = r[1].total; }
|
||||
$('#err').hidden = true;
|
||||
renderAll();
|
||||
}).catch(function (e) {
|
||||
if (String(e.message) === 'unauthorized') return;
|
||||
var b = $('#err');
|
||||
b.textContent = t('error.load');
|
||||
b.hidden = false;
|
||||
}).then(function () { inflight = false; });
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- map
|
||||
var world = window.URUTAU_WORLD;
|
||||
function renderMap(mapSel, listSel, rows, good) {
|
||||
var box = $(mapSel), list = $(listSel);
|
||||
clear(box); clear(list);
|
||||
box.className = 'map' + (good ? ' good' : '');
|
||||
rows = rows || [];
|
||||
var by = {}, max = 1;
|
||||
rows.forEach(function (r) { by[r.key] = r.n; if (r.n > max) max = r.n; });
|
||||
if (world) {
|
||||
var svg = svgEl('svg', { viewBox: '0 0 ' + world.w + ' ' + world.h, role: 'img', 'aria-label': t(good ? 'map.visitors' : 'map.attacks') });
|
||||
Object.keys(world.paths).forEach(function (cc) {
|
||||
var p = svgEl('path', { d: world.paths[cc], 'class': 'mapc' + (by[cc] ? ' hit' : '') });
|
||||
if (by[cc]) {
|
||||
p.setAttribute('fill-opacity', String(0.25 + 0.75 * Math.sqrt(by[cc] / max)));
|
||||
var ti = svgEl('title', {});
|
||||
ti.textContent = flag(cc) + ' ' + countryName(cc) + ': ' + nf(by[cc]);
|
||||
p.appendChild(ti);
|
||||
}
|
||||
svg.appendChild(p);
|
||||
});
|
||||
box.appendChild(svg);
|
||||
}
|
||||
if (!rows.length) { list.appendChild(el('div', 'empty', t('top.empty'))); return; }
|
||||
rows.slice(0, 8).forEach(function (r) {
|
||||
var d = el('div', 'bar-row');
|
||||
d.appendChild(el('span', 'k', flag(r.key) + ' ' + countryName(r.key)));
|
||||
d.appendChild(el('span', 'n', nf(r.n)));
|
||||
var bar = el('div', 'bar'), i = el('i');
|
||||
i.style.width = Math.max(2, r.n / max * 100) + '%';
|
||||
bar.appendChild(i);
|
||||
d.appendChild(bar);
|
||||
list.appendChild(d);
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- traffic
|
||||
function renderTraffic() {
|
||||
var d = state.traffic;
|
||||
if (!d) return;
|
||||
var box = $('#tkpis');
|
||||
clear(box);
|
||||
box.appendChild(kpi('', d.requests, t('traffic.requests')));
|
||||
box.appendChild(kpi('', d.pages, t('traffic.pages')));
|
||||
box.appendChild(kpi('', d.visitors, t('traffic.visitors')));
|
||||
var b = el('div', 'panel kpi');
|
||||
b.appendChild(el('div', 'v', fmtBytes(d.bytes)));
|
||||
b.appendChild(el('div', 'l', t('traffic.bytes')));
|
||||
box.appendChild(b);
|
||||
var l = el('div', 'panel kpi');
|
||||
l.appendChild(el('div', 'v', Math.round(d.p50_ms) + ' / ' + Math.round(d.p95_ms) + ' ms'));
|
||||
l.appendChild(el('div', 'l', t('traffic.latency')));
|
||||
box.appendChild(l);
|
||||
box.appendChild(kpi('', d.bots, t('traffic.bots')));
|
||||
|
||||
var sel = $('#domain'), want = (d.domains || []).map(function (x) { return x.key; }).join('|') + '|' + lang;
|
||||
if (sel.getAttribute('data-doms') !== want) {
|
||||
clear(sel);
|
||||
var o = el('option', '', t('traffic.allDomains'));
|
||||
o.value = 'all';
|
||||
sel.appendChild(o);
|
||||
(d.domains || []).forEach(function (x) { var op = el('option', '', x.key + ' (' + nf(x.n) + ')'); op.value = x.key; sel.appendChild(op); });
|
||||
sel.setAttribute('data-doms', want);
|
||||
}
|
||||
sel.value = state.domain;
|
||||
|
||||
drawTrafficChart();
|
||||
renderMap('#map-traffic', '#maplist-traffic', d.countries, true);
|
||||
renderTop('#t-pages', d.top_pages, true);
|
||||
renderTop('#t-refs', d.referrers, true);
|
||||
renderTop('#t-cities', d.cities, false);
|
||||
renderTop('#t-browsers', d.browsers, false);
|
||||
renderTop('#t-oses', d.oses, false);
|
||||
renderTop('#t-devices', (d.devices || []).map(function (x) { return { key: t('device.' + (['desktop', 'mobile', 'tablet', 'bot', 'tool'].indexOf(x.key) >= 0 ? x.key : 'unknown')), n: x.n }; }), false);
|
||||
renderTop('#t-bots', d.bot_names, false);
|
||||
renderTop('#t-status', ['2xx', '3xx', '4xx', '5xx'].map(function (k, i) { return { key: k, n: d.status[i] }; }).filter(function (x) { return x.n > 0; }), true);
|
||||
}
|
||||
|
||||
function drawTrafficChart() {
|
||||
var wrap = $('#tchart');
|
||||
clear(wrap);
|
||||
var d = state.traffic;
|
||||
if (!d) return;
|
||||
var tl = d.timeline, n = tl.req.length, max = 0, i;
|
||||
for (i = 0; i < n; i++) if (tl.req[i] > max) max = tl.req[i];
|
||||
var W = Math.max(280, wrap.clientWidth), H = 230, L = 38, R = 6, Tp = 8, B = 22;
|
||||
var top = niceMax(max), ph = H - Tp - B, bw = (W - L - R) / n;
|
||||
var svg = svgEl('svg', { viewBox: '0 0 ' + W + ' ' + H, role: 'img', 'aria-label': t('traffic.timeline') });
|
||||
for (i = 0; i <= 4; i++) {
|
||||
var y = Tp + ph - (ph * i / 4);
|
||||
svg.appendChild(svgEl('line', { x1: L, x2: W - R, y1: y, y2: y, 'class': 'gridline' }));
|
||||
var lab = svgEl('text', { x: L - 5, y: y + 3, 'text-anchor': 'end', 'class': 'axis' });
|
||||
lab.textContent = nf(Math.round(top * i / 4));
|
||||
svg.appendChild(lab);
|
||||
}
|
||||
var nt = W < 520 ? 3 : 5;
|
||||
for (i = 0; i < nt; i++) {
|
||||
var idx = Math.round((n - 1) * i / (nt - 1));
|
||||
var xl = svgEl('text', { x: L + bw * idx + bw / 2, y: H - 6, 'text-anchor': i === 0 ? 'start' : i === nt - 1 ? 'end' : 'middle', 'class': 'axis' });
|
||||
xl.textContent = tickLabel(tl.start + idx * tl.step);
|
||||
svg.appendChild(xl);
|
||||
}
|
||||
var tip = el('div', 'tip');
|
||||
tip.hidden = true;
|
||||
for (i = 0; i < n; i++) {
|
||||
var x = L + bw * i + (bw > 3 ? 0.5 : 0), w = Math.max(1, bw - (bw > 3 ? 1 : 0));
|
||||
[['req', 'b-treq'], ['pages', 'b-tpages']].forEach(function (sr) {
|
||||
var v = tl[sr[0]][i];
|
||||
if (!v) return;
|
||||
var h = Math.max(1, v / top * ph);
|
||||
svg.appendChild(svgEl('rect', { x: x, y: Tp + ph - h, width: w, height: h, 'class': sr[1] }));
|
||||
});
|
||||
(function (i) {
|
||||
var r = svgEl('rect', { x: L + bw * i, y: Tp, width: bw, height: ph, 'class': 'hover-col' });
|
||||
r.addEventListener('mouseenter', function () {
|
||||
clear(tip);
|
||||
tip.appendChild(el('strong', '', new Date((tl.start + i * tl.step) * 1000).toLocaleString(lang, { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' })));
|
||||
[['traffic.requests', tl.req[i]], ['traffic.pages', tl.pages[i]]].forEach(function (p) {
|
||||
var rr = el('div');
|
||||
rr.appendChild(el('span', '', t(p[0])));
|
||||
rr.appendChild(el('span', 'num', nf(p[1])));
|
||||
tip.appendChild(rr);
|
||||
});
|
||||
tip.hidden = false;
|
||||
tip.style.left = Math.max(0, Math.min(L + bw * i + 14, W - 160)) + 'px';
|
||||
tip.style.top = '4px';
|
||||
});
|
||||
svg.appendChild(r);
|
||||
})(i);
|
||||
}
|
||||
svg.addEventListener('mouseleave', function () { tip.hidden = true; });
|
||||
wrap.appendChild(svg);
|
||||
wrap.appendChild(tip);
|
||||
}
|
||||
|
||||
function setTab(tab) {
|
||||
state.tab = tab;
|
||||
lsSet('urutau.tab', tab);
|
||||
$('#tab-threats').hidden = tab !== 'threats';
|
||||
$('#tab-traffic').hidden = tab !== 'traffic';
|
||||
$('#domain').hidden = tab !== 'traffic';
|
||||
document.querySelectorAll('.tabs button[role=tab]').forEach(function (b) { b.setAttribute('aria-selected', b.getAttribute('data-tab') === tab ? 'true' : 'false'); });
|
||||
refresh();
|
||||
}
|
||||
|
||||
function connectLive() {
|
||||
if (!window.EventSource) return;
|
||||
var es = new EventSource('/api/v1/events/stream');
|
||||
function setLive(on) {
|
||||
$('#live-dot').className = 'dot' + (on ? ' on' : '');
|
||||
$('#live-text').textContent = t(on ? 'live.on' : 'live.off');
|
||||
$('#live-text').setAttribute('data-i18n', on ? 'live.on' : 'live.off');
|
||||
}
|
||||
es.onopen = function () { setLive(true); };
|
||||
es.onerror = function () { setLive(false); };
|
||||
es.addEventListener('ev', function (m) {
|
||||
try {
|
||||
var e = JSON.parse(m.data);
|
||||
state.live.unshift(e);
|
||||
if (state.live.length > 100) state.live.length = 100;
|
||||
renderFeed();
|
||||
} catch (x) { /* ignore malformed frame */ }
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- detail
|
||||
function row(dl, label, node) {
|
||||
dl.appendChild(el('dt', '', label));
|
||||
var dd = el('dd');
|
||||
dd.appendChild(node);
|
||||
dl.appendChild(dd);
|
||||
}
|
||||
function listOf(items, mono) {
|
||||
if (!items || !items.length) return el('span', '', '-');
|
||||
var ul = el('ul');
|
||||
items.forEach(function (i) { ul.appendChild(el('li', mono ? 'mono' : '', i)); });
|
||||
return ul;
|
||||
}
|
||||
function closeDetail() { $('#detail').hidden = true; $('#scrim').hidden = true; }
|
||||
function openDetail(ip) {
|
||||
var box = $('#detail');
|
||||
clear(box);
|
||||
box.hidden = false;
|
||||
$('#scrim').hidden = false;
|
||||
api('/api/v1/ip/' + encodeURIComponent(ip)).then(function (d) {
|
||||
clear(box);
|
||||
var top = el('div', 'toolbar');
|
||||
var h = el('h2', 'mono', d.ip);
|
||||
h.style.marginRight = 'auto';
|
||||
top.appendChild(h);
|
||||
var cp = el('button', 'btn', t('detail.copyIp'));
|
||||
cp.type = 'button';
|
||||
cp.addEventListener('click', function () { copyText(d.ip); });
|
||||
var cl = el('button', 'btn', t('detail.close'));
|
||||
cl.type = 'button';
|
||||
cl.addEventListener('click', closeDetail);
|
||||
top.appendChild(cp); top.appendChild(cl);
|
||||
box.appendChild(top);
|
||||
var dl = el('dl');
|
||||
row(dl, t('detail.level'), levelBadge(d.level));
|
||||
row(dl, t('detail.score'), el('span', 'num', String(d.score)));
|
||||
row(dl, t('detail.rdns'), el('span', 'mono', d.rdns || '-'));
|
||||
if (d.cc) row(dl, t('detail.country'), el('span', '', flag(d.cc) + ' ' + (d.country || countryName(d.cc))));
|
||||
if (d.city) row(dl, t('detail.city'), el('span', '', d.city));
|
||||
if (d.asn) row(dl, t('detail.network'), el('span', '', 'AS' + d.asn + (d.as_org ? ' ' + d.as_org : '')));
|
||||
row(dl, t('detail.first'), el('span', '', new Date(d.first * 1000).toLocaleString(lang)));
|
||||
row(dl, t('detail.last'), el('span', '', new Date(d.last * 1000).toLocaleString(lang) + ' (' + ago(d.last) + ')'));
|
||||
row(dl, t('detail.hosts'), el('span', '', (d.hosts || []).join(', ')));
|
||||
if (d.banned) row(dl, t('detail.jails'), el('span', 'banned', (d.jails || []).join(', ')));
|
||||
var counts = el('span');
|
||||
Object.keys(d.counts).filter(function (c) { return KNOWN_CATS.indexOf(c) >= 0; }).forEach(function (c) { counts.appendChild(el('span', 'chip', t('cat.' + c) + ' ' + nf(d.counts[c]))); });
|
||||
row(dl, t('detail.counts'), counts);
|
||||
row(dl, t('detail.domains'), listOf(d.domains, true));
|
||||
row(dl, t('detail.uas'), listOf(d.uas, false));
|
||||
if (d.ua_labels && d.ua_labels.length) row(dl, t('detail.uaparsed'), listOf(d.ua_labels, false));
|
||||
row(dl, t('detail.samples'), listOf(d.samples, true));
|
||||
box.appendChild(dl);
|
||||
}).catch(function (e) {
|
||||
if (String(e.message) === 'unauthorized') return;
|
||||
clear(box);
|
||||
box.appendChild(el('p', 'empty', t('detail.notfound')));
|
||||
var cl = el('button', 'btn', t('detail.close'));
|
||||
cl.type = 'button';
|
||||
cl.addEventListener('click', closeDetail);
|
||||
box.appendChild(cl);
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- blocklist
|
||||
function blocklistQuery(extra) {
|
||||
var p = new URLSearchParams({ host: state.host, min_score: String($('#minScore').value || '50') });
|
||||
for (var k in extra) p.set(k, extra[k]);
|
||||
return p.toString();
|
||||
}
|
||||
function updateBlocklistLink() { $('#dlBl').setAttribute('href', '/api/v1/blocklist.txt?' + blocklistQuery({ download: '1' })); }
|
||||
function copyText(text) {
|
||||
if (navigator.clipboard && navigator.clipboard.writeText) return navigator.clipboard.writeText(text);
|
||||
return new Promise(function (ok, fail) {
|
||||
var ta = document.createElement('textarea');
|
||||
ta.value = text;
|
||||
document.body.appendChild(ta);
|
||||
ta.select();
|
||||
var done = false;
|
||||
try { done = document.execCommand('copy'); } catch (e) { done = false; }
|
||||
document.body.removeChild(ta);
|
||||
done ? ok() : fail(new Error('copy'));
|
||||
});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- wiring
|
||||
function resetPage() { state.page = 1; refresh(); }
|
||||
var timer;
|
||||
$('#range').addEventListener('click', function (e) {
|
||||
var r = e.target.getAttribute && e.target.getAttribute('data-range');
|
||||
if (!r) return;
|
||||
state.range = r; lsSet('urutau.range', r); resetPage();
|
||||
});
|
||||
$('#host').addEventListener('change', function (e) { state.host = e.target.value; lsSet('urutau.host', state.host); resetPage(); });
|
||||
$('#lang').addEventListener('click', function () { lang = lang === 'en' ? 'pt-BR' : 'en'; lsSet('urutau.lang', lang); applyI18n(); });
|
||||
$('#theme').addEventListener('click', function () {
|
||||
var cur = document.documentElement.getAttribute('data-theme') || (matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark');
|
||||
var next = cur === 'dark' ? 'light' : 'dark';
|
||||
document.documentElement.setAttribute('data-theme', next);
|
||||
lsSet('urutau.theme', next);
|
||||
});
|
||||
$('#q').addEventListener('input', function (e) { clearTimeout(timer); timer = setTimeout(function () { state.q = e.target.value.trim(); resetPage(); }, 300); });
|
||||
$('#level').addEventListener('change', function (e) { state.level = e.target.value; resetPage(); });
|
||||
$('#bannedOnly').addEventListener('change', function (e) { state.banned = e.target.checked; resetPage(); });
|
||||
$('#prev').addEventListener('click', function () { if (state.page > 1) { state.page--; refresh(); } });
|
||||
$('#next').addEventListener('click', function () { state.page++; refresh(); });
|
||||
document.querySelectorAll('th [data-sort]').forEach(function (b) {
|
||||
b.addEventListener('click', function () {
|
||||
var k = b.getAttribute('data-sort');
|
||||
if (state.sort === k) state.order = state.order === 'desc' ? 'asc' : 'desc'; else { state.sort = k; state.order = 'desc'; }
|
||||
resetPage();
|
||||
});
|
||||
});
|
||||
$('#minScore').addEventListener('input', updateBlocklistLink);
|
||||
$('#copyBl').addEventListener('click', function () {
|
||||
var msg = $('#blMsg');
|
||||
fetch('/api/v1/blocklist.txt?' + blocklistQuery({}), { credentials: 'same-origin' }).then(function (r) { return r.text(); }).then(function (txt) {
|
||||
var n = txt.split('\n').filter(Boolean).length;
|
||||
return copyText(txt).then(function () { msg.textContent = t('blocklist.copied', nf(n)); });
|
||||
}).catch(function () { msg.textContent = t('blocklist.failed'); });
|
||||
});
|
||||
$('#scrim').addEventListener('click', closeDetail);
|
||||
document.addEventListener('keydown', function (e) { if (e.key === 'Escape') closeDetail(); });
|
||||
var rz;
|
||||
window.addEventListener('resize', function () { clearTimeout(rz); rz = setTimeout(function () { drawChart(); drawTrafficChart(); }, 150); });
|
||||
|
||||
document.querySelectorAll('.tabs button[role=tab]').forEach(function (b) { b.addEventListener('click', function () { setTab(b.getAttribute('data-tab')); }); });
|
||||
$('#domain').addEventListener('change', function (e) { state.domain = e.target.value; refresh(); });
|
||||
$('#tab-threats').hidden = state.tab !== 'threats';
|
||||
$('#tab-traffic').hidden = state.tab !== 'traffic';
|
||||
$('#domain').hidden = state.tab !== 'traffic';
|
||||
document.querySelectorAll('.tabs button[role=tab]').forEach(function (b) { b.setAttribute('aria-selected', b.getAttribute('data-tab') === state.tab ? 'true' : 'false'); });
|
||||
applyI18n();
|
||||
refresh();
|
||||
connectLive();
|
||||
setInterval(function () { if (!document.hidden) refresh(); }, 10000);
|
||||
})();
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 7.6 KiB |
@@ -0,0 +1,296 @@
|
||||
/* Urutau UI dictionaries. Every key must exist in both languages:
|
||||
scripts/check-ui-i18n.mjs enforces it. "{n}" is replaced by the caller. */
|
||||
window.URUTAU_I18N = {
|
||||
en: {
|
||||
'tagline': 'Lightweight, always-on threat intelligence for self-hosted servers · local-first · authorized use.',
|
||||
'live.connecting': 'connecting',
|
||||
'live.on': 'live',
|
||||
'live.off': 'reconnecting',
|
||||
'host.label': 'Host',
|
||||
'host.all': 'All hosts',
|
||||
'range.label': 'Time range',
|
||||
'range.1h': '1 h',
|
||||
'range.24h': '24 h',
|
||||
'range.7d': '7 d',
|
||||
'lang.toggle': 'Switch language',
|
||||
'theme.toggle': 'Switch light/dark theme',
|
||||
'logout': 'Sign out',
|
||||
'kpi.requests': 'Requests',
|
||||
'kpi.malicious': 'Malicious events',
|
||||
'kpi.hostile': 'Hostile IPs',
|
||||
'kpi.suspicious': 'Suspicious IPs',
|
||||
'kpi.bans': 'Active bans',
|
||||
'kpi.ips': 'Distinct IPs',
|
||||
'kpi.monitoring': '{n} monitoring requests filtered out.',
|
||||
'feed.forged': 'forged monitor user agent',
|
||||
'timeline.title': 'Activity by category',
|
||||
'timeline.empty': 'No activity in this range.',
|
||||
'ips.title': 'Top IPs',
|
||||
'ips.search': 'Filter by IP or reverse DNS',
|
||||
'ips.level': 'Threat level',
|
||||
'ips.bannedOnly': 'Banned only',
|
||||
'ips.empty': 'No IPs match.',
|
||||
'level.all': 'All levels',
|
||||
'level.hostile': 'Hostile',
|
||||
'level.suspicious': 'Suspicious',
|
||||
'level.low': 'Low',
|
||||
'col.ip': 'IP',
|
||||
'col.score': 'Score',
|
||||
'col.level': 'Level',
|
||||
'col.cats': 'Categories',
|
||||
'col.last': 'Last seen',
|
||||
'col.banned': 'Banned',
|
||||
'col.host': 'Host',
|
||||
'col.source': 'Source',
|
||||
'col.state': 'State',
|
||||
'col.lines': 'Lines',
|
||||
'col.malformed': 'Malformed',
|
||||
'col.lastEvent': 'Last event',
|
||||
'pager.prev': 'Previous',
|
||||
'pager.next': 'Next',
|
||||
'pager.count': '{n} IPs',
|
||||
'feed.title': 'Live feed',
|
||||
'feed.empty': 'Waiting for events.',
|
||||
'top.paths': 'Most attacked paths',
|
||||
'top.domains': 'Most targeted domains',
|
||||
'top.uas': 'Top user agents',
|
||||
'top.users': 'SSH users tried',
|
||||
'top.empty': 'No data.',
|
||||
'blocklist.title': 'Blocklist',
|
||||
'blocklist.help': 'Export the IPs at or above a score as a plain list, one per line, for a firewall or fail2ban.',
|
||||
'blocklist.minScore': 'Minimum score',
|
||||
'blocklist.copy': 'Copy list',
|
||||
'blocklist.download': 'Download',
|
||||
'blocklist.copied': '{n} IPs copied.',
|
||||
'blocklist.failed': 'Could not copy the list.',
|
||||
'hosts.title': 'Hosts',
|
||||
'host.online': 'online',
|
||||
'host.offline': 'offline',
|
||||
'host.requests': 'Requests',
|
||||
'host.malicious': 'Malicious',
|
||||
'host.hostile': 'Hostile IPs',
|
||||
'host.bans': 'Bans',
|
||||
'host.latency': 'Latency',
|
||||
'sources.title': 'Sources',
|
||||
'state.following': 'following',
|
||||
'state.waiting': 'waiting for file',
|
||||
'state.backfill': 'reading history',
|
||||
'state.error': 'error',
|
||||
'state.disabled': 'disabled',
|
||||
'cat.ok': 'ok',
|
||||
'cat.notfound': 'not found',
|
||||
'cat.scanner': 'scanner',
|
||||
'cat.exploit': 'exploit',
|
||||
'cat.bruteforce': 'brute force',
|
||||
'cat.ssh-fail': 'ssh fail',
|
||||
'cat.ssh-probe': 'ssh probe',
|
||||
'cat.ssh-ok': 'ssh login',
|
||||
'cat.ban': 'ban',
|
||||
'feed.unban': 'unban',
|
||||
'ago.now': 'now',
|
||||
'ago.s': '{n}s ago',
|
||||
'ago.m': '{n}m ago',
|
||||
'ago.h': '{n}h ago',
|
||||
'ago.d': '{n}d ago',
|
||||
'never': 'never',
|
||||
'yes': 'yes',
|
||||
'detail.close': 'Close',
|
||||
'detail.copyIp': 'Copy IP',
|
||||
'detail.score': 'Score',
|
||||
'detail.level': 'Level',
|
||||
'detail.first': 'First seen',
|
||||
'detail.last': 'Last seen',
|
||||
'detail.rdns': 'Reverse DNS',
|
||||
'detail.hosts': 'Hosts',
|
||||
'detail.domains': 'Targeted domains',
|
||||
'detail.uas': 'User agents',
|
||||
'detail.samples': 'Recent activity',
|
||||
'detail.jails': 'Active bans',
|
||||
'detail.counts': 'Events',
|
||||
'detail.notfound': 'This IP is no longer in memory.',
|
||||
'error.load': 'Could not load data. Retrying.',
|
||||
'footer': 'Urutau · watches motionless all night.',
|
||||
'tab.threats': 'Threats',
|
||||
'tab.traffic': 'Traffic',
|
||||
'traffic.domain': 'Domain',
|
||||
'traffic.allDomains': 'All domains',
|
||||
'traffic.timeline': 'Requests and page views',
|
||||
'traffic.requests': 'Requests',
|
||||
'traffic.pages': 'Page views',
|
||||
'traffic.visitors': 'Visitors',
|
||||
'traffic.bytes': 'Data sent',
|
||||
'traffic.bots': 'Search and AI bots',
|
||||
'traffic.latency': 'Latency p50 / p95',
|
||||
'traffic.topPages': 'Top pages',
|
||||
'traffic.referrers': 'External referrers',
|
||||
'traffic.cities': 'Cities',
|
||||
'traffic.browsers': 'Browsers',
|
||||
'traffic.oses': 'Operating systems',
|
||||
'traffic.devices': 'Devices',
|
||||
'traffic.status': 'Status codes',
|
||||
'traffic.privacy': 'Visitors are counted with a daily rotating hash kept in memory only. No visitor IP is stored.',
|
||||
'map.attacks': 'Origin of attacks',
|
||||
'map.visitors': 'Visitors by country',
|
||||
'col.origin': 'Origin',
|
||||
'detail.country': 'Country',
|
||||
'detail.city': 'City',
|
||||
'detail.network': 'Network',
|
||||
'detail.uaparsed': 'Clients',
|
||||
'device.desktop': 'desktop',
|
||||
'device.mobile': 'mobile',
|
||||
'device.tablet': 'tablet',
|
||||
'device.bot': 'bot',
|
||||
'device.tool': 'tool',
|
||||
'device.unknown': 'unknown',
|
||||
'login.token': 'Access token',
|
||||
'login.submit': 'Sign in',
|
||||
'login.err.bad': 'Invalid token.',
|
||||
'login.err.rate': 'Too many attempts. Try again in a few minutes.'
|
||||
},
|
||||
'pt-BR': {
|
||||
'tagline': 'Inteligência de ameaças leve e sempre ativa para servidores próprios · local-first · uso autorizado.',
|
||||
'live.connecting': 'conectando',
|
||||
'live.on': 'ao vivo',
|
||||
'live.off': 'reconectando',
|
||||
'host.label': 'Host',
|
||||
'host.all': 'Todos os hosts',
|
||||
'range.label': 'Período',
|
||||
'range.1h': '1 h',
|
||||
'range.24h': '24 h',
|
||||
'range.7d': '7 d',
|
||||
'lang.toggle': 'Trocar idioma',
|
||||
'theme.toggle': 'Alternar tema claro/escuro',
|
||||
'logout': 'Sair',
|
||||
'kpi.requests': 'Requisições',
|
||||
'kpi.malicious': 'Eventos maliciosos',
|
||||
'kpi.hostile': 'IPs hostis',
|
||||
'kpi.suspicious': 'IPs suspeitos',
|
||||
'kpi.bans': 'Bans ativos',
|
||||
'kpi.ips': 'IPs distintos',
|
||||
'kpi.monitoring': '{n} requisições de monitoramento filtradas.',
|
||||
'feed.forged': 'user-agent de monitor forjado',
|
||||
'timeline.title': 'Atividade por categoria',
|
||||
'timeline.empty': 'Nenhuma atividade neste período.',
|
||||
'ips.title': 'Principais IPs',
|
||||
'ips.search': 'Filtrar por IP ou DNS reverso',
|
||||
'ips.level': 'Nível de ameaça',
|
||||
'ips.bannedOnly': 'Só banidos',
|
||||
'ips.empty': 'Nenhum IP corresponde.',
|
||||
'level.all': 'Todos os níveis',
|
||||
'level.hostile': 'Hostil',
|
||||
'level.suspicious': 'Suspeito',
|
||||
'level.low': 'Baixo',
|
||||
'col.ip': 'IP',
|
||||
'col.score': 'Pontos',
|
||||
'col.level': 'Nível',
|
||||
'col.cats': 'Categorias',
|
||||
'col.last': 'Visto por último',
|
||||
'col.banned': 'Banido',
|
||||
'col.host': 'Host',
|
||||
'col.source': 'Fonte',
|
||||
'col.state': 'Estado',
|
||||
'col.lines': 'Linhas',
|
||||
'col.malformed': 'Malformadas',
|
||||
'col.lastEvent': 'Último evento',
|
||||
'pager.prev': 'Anterior',
|
||||
'pager.next': 'Próxima',
|
||||
'pager.count': '{n} IPs',
|
||||
'feed.title': 'Feed ao vivo',
|
||||
'feed.empty': 'Aguardando eventos.',
|
||||
'top.paths': 'Caminhos mais atacados',
|
||||
'top.domains': 'Domínios mais visados',
|
||||
'top.uas': 'Principais user-agents',
|
||||
'top.users': 'Usuários SSH tentados',
|
||||
'top.empty': 'Sem dados.',
|
||||
'blocklist.title': 'Lista de bloqueio',
|
||||
'blocklist.help': 'Exporte os IPs a partir de uma pontuação como lista simples, um por linha, para firewall ou fail2ban.',
|
||||
'blocklist.minScore': 'Pontuação mínima',
|
||||
'blocklist.copy': 'Copiar lista',
|
||||
'blocklist.download': 'Baixar',
|
||||
'blocklist.copied': '{n} IPs copiados.',
|
||||
'blocklist.failed': 'Não foi possível copiar a lista.',
|
||||
'hosts.title': 'Hosts',
|
||||
'host.online': 'online',
|
||||
'host.offline': 'offline',
|
||||
'host.requests': 'Requisições',
|
||||
'host.malicious': 'Maliciosos',
|
||||
'host.hostile': 'IPs hostis',
|
||||
'host.bans': 'Bans',
|
||||
'host.latency': 'Latência',
|
||||
'sources.title': 'Fontes',
|
||||
'state.following': 'acompanhando',
|
||||
'state.waiting': 'aguardando arquivo',
|
||||
'state.backfill': 'lendo histórico',
|
||||
'state.error': 'erro',
|
||||
'state.disabled': 'desativada',
|
||||
'cat.ok': 'ok',
|
||||
'cat.notfound': 'não encontrado',
|
||||
'cat.scanner': 'scanner',
|
||||
'cat.exploit': 'exploit',
|
||||
'cat.bruteforce': 'força bruta',
|
||||
'cat.ssh-fail': 'falha ssh',
|
||||
'cat.ssh-probe': 'sondagem ssh',
|
||||
'cat.ssh-ok': 'login ssh',
|
||||
'cat.ban': 'ban',
|
||||
'feed.unban': 'desbanido',
|
||||
'ago.now': 'agora',
|
||||
'ago.s': 'há {n}s',
|
||||
'ago.m': 'há {n}min',
|
||||
'ago.h': 'há {n}h',
|
||||
'ago.d': 'há {n}d',
|
||||
'never': 'nunca',
|
||||
'yes': 'sim',
|
||||
'detail.close': 'Fechar',
|
||||
'detail.copyIp': 'Copiar IP',
|
||||
'detail.score': 'Pontos',
|
||||
'detail.level': 'Nível',
|
||||
'detail.first': 'Primeira vez visto',
|
||||
'detail.last': 'Visto por último',
|
||||
'detail.rdns': 'DNS reverso',
|
||||
'detail.hosts': 'Hosts',
|
||||
'detail.domains': 'Domínios visados',
|
||||
'detail.uas': 'User-agents',
|
||||
'detail.samples': 'Atividade recente',
|
||||
'detail.jails': 'Bans ativos',
|
||||
'detail.counts': 'Eventos',
|
||||
'detail.notfound': 'Este IP não está mais na memória.',
|
||||
'error.load': 'Não foi possível carregar os dados. Tentando de novo.',
|
||||
'footer': 'Urutau · vigia imóvel a noite toda.',
|
||||
'tab.threats': 'Ameaças',
|
||||
'tab.traffic': 'Tráfego',
|
||||
'traffic.domain': 'Domínio',
|
||||
'traffic.allDomains': 'Todos os domínios',
|
||||
'traffic.timeline': 'Requisições e páginas vistas',
|
||||
'traffic.requests': 'Requisições',
|
||||
'traffic.pages': 'Páginas vistas',
|
||||
'traffic.visitors': 'Visitantes',
|
||||
'traffic.bytes': 'Dados enviados',
|
||||
'traffic.bots': 'Bots de busca e de IA',
|
||||
'traffic.latency': 'Latência p50 / p95',
|
||||
'traffic.topPages': 'Páginas mais vistas',
|
||||
'traffic.referrers': 'Referenciadores externos',
|
||||
'traffic.cities': 'Cidades',
|
||||
'traffic.browsers': 'Navegadores',
|
||||
'traffic.oses': 'Sistemas operacionais',
|
||||
'traffic.devices': 'Dispositivos',
|
||||
'traffic.status': 'Códigos de status',
|
||||
'traffic.privacy': 'Visitantes são contados com um hash que muda todo dia e fica só na memória. Nenhum IP de visitante é guardado.',
|
||||
'map.attacks': 'Origem dos ataques',
|
||||
'map.visitors': 'Visitantes por país',
|
||||
'col.origin': 'Origem',
|
||||
'detail.country': 'País',
|
||||
'detail.city': 'Cidade',
|
||||
'detail.network': 'Rede',
|
||||
'detail.uaparsed': 'Clientes',
|
||||
'device.desktop': 'computador',
|
||||
'device.mobile': 'celular',
|
||||
'device.tablet': 'tablet',
|
||||
'device.bot': 'bot',
|
||||
'device.tool': 'ferramenta',
|
||||
'device.unknown': 'desconhecido',
|
||||
'login.token': 'Token de acesso',
|
||||
'login.submit': 'Entrar',
|
||||
'login.err.bad': 'Token inválido.',
|
||||
'login.err.rate': 'Tentativas demais. Tente de novo em alguns minutos.'
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,165 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="dark light">
|
||||
<title>Urutau</title>
|
||||
<link rel="icon" type="image/png" href="/favicon.png">
|
||||
<link rel="stylesheet" href="/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<div class="wrap">
|
||||
<header class="top">
|
||||
<div class="brand">
|
||||
<img src="/logo.png" alt="Urutau" width="44" height="44">
|
||||
<div><h1>Urutau</h1><small data-i18n="tagline"></small></div>
|
||||
</div>
|
||||
<div class="controls">
|
||||
<span class="live"><span class="dot" id="live-dot"></span><span id="live-text" data-i18n="live.connecting"></span></span>
|
||||
<select id="host" data-i18n-aria="host.label"></select>
|
||||
<div class="seg" id="range" role="group" data-i18n-aria="range.label">
|
||||
<button type="button" data-range="1h" data-i18n="range.1h"></button>
|
||||
<button type="button" data-range="24h" data-i18n="range.24h"></button>
|
||||
<button type="button" data-range="7d" data-i18n="range.7d"></button>
|
||||
</div>
|
||||
<button type="button" class="btn" id="lang" data-i18n-aria="lang.toggle">EN</button>
|
||||
<button type="button" class="btn" id="theme" data-i18n-aria="theme.toggle" data-i18n-title="theme.toggle">◐</button>
|
||||
<form method="post" action="/logout"><button class="btn" type="submit" data-i18n="logout"></button></form>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<nav class="tabs" role="tablist">
|
||||
<button type="button" role="tab" id="tab-btn-threats" data-tab="threats" aria-selected="true" data-i18n="tab.threats"></button>
|
||||
<button type="button" role="tab" id="tab-btn-traffic" data-tab="traffic" aria-selected="false" data-i18n="tab.traffic"></button>
|
||||
<select id="domain" hidden data-i18n-aria="traffic.domain"></select>
|
||||
</nav>
|
||||
|
||||
<div class="err-banner" id="err" hidden></div>
|
||||
|
||||
<div id="tab-threats">
|
||||
|
||||
<section class="grid kpis" id="kpis"></section>
|
||||
|
||||
<p class="empty mono" id="monitoring"></p>
|
||||
|
||||
<section class="panel">
|
||||
<h2 data-i18n="timeline.title"></h2>
|
||||
<div class="chart-wrap" id="chart"></div>
|
||||
<div class="legend" id="legend"></div>
|
||||
</section>
|
||||
|
||||
<section class="panel mt">
|
||||
<h2 data-i18n="map.attacks"></h2>
|
||||
<div class="mapbox"><div class="map" id="map-threats"></div><div class="maplist" id="maplist-threats"></div></div>
|
||||
</section>
|
||||
|
||||
<section class="grid cols-main mt">
|
||||
<div class="panel">
|
||||
<h2 data-i18n="ips.title"></h2>
|
||||
<div class="toolbar">
|
||||
<input type="text" id="q" data-i18n-ph="ips.search" data-i18n-aria="ips.search" autocomplete="off">
|
||||
<select id="level" data-i18n-aria="ips.level">
|
||||
<option value="" data-i18n="level.all"></option>
|
||||
<option value="hostile" data-i18n="level.hostile"></option>
|
||||
<option value="suspicious" data-i18n="level.suspicious"></option>
|
||||
<option value="low" data-i18n="level.low"></option>
|
||||
</select>
|
||||
<label class="live"><input type="checkbox" id="bannedOnly"> <span data-i18n="ips.bannedOnly"></span></label>
|
||||
</div>
|
||||
<table class="stack" id="ips">
|
||||
<thead><tr>
|
||||
<th><button type="button" data-sort="ip" data-i18n="col.ip"></button></th>
|
||||
<th><button type="button" data-sort="score" data-i18n="col.score"></button></th>
|
||||
<th data-i18n="col.level"></th>
|
||||
<th data-i18n="col.cats"></th>
|
||||
<th data-i18n="col.origin"></th>
|
||||
<th><button type="button" data-sort="last" data-i18n="col.last"></button></th>
|
||||
<th data-i18n="col.banned"></th>
|
||||
</tr></thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
<div class="pager">
|
||||
<span id="count"></span>
|
||||
<span><button type="button" class="btn" id="prev" data-i18n="pager.prev"></button> <button type="button" class="btn" id="next" data-i18n="pager.next"></button></span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="panel">
|
||||
<h2 data-i18n="feed.title"></h2>
|
||||
<ul class="feed" id="feed"></ul>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="grid cols-3 mt">
|
||||
<div class="panel"><h2 data-i18n="top.paths"></h2><div id="top-paths"></div></div>
|
||||
<div class="panel"><h2 data-i18n="top.domains"></h2><div id="top-domains"></div></div>
|
||||
<div class="panel"><h2 data-i18n="top.uas"></h2><div id="top-uas"></div></div>
|
||||
</section>
|
||||
|
||||
<section class="grid cols-2 mt">
|
||||
<div class="panel"><h2 data-i18n="top.users"></h2><div id="top-users"></div></div>
|
||||
<div class="panel">
|
||||
<h2 data-i18n="blocklist.title"></h2>
|
||||
<p class="empty" data-i18n="blocklist.help"></p>
|
||||
<div class="toolbar">
|
||||
<label class="live"><span data-i18n="blocklist.minScore"></span> <input type="number" id="minScore" value="50" min="0" step="1"></label>
|
||||
<button type="button" class="btn primary" id="copyBl" data-i18n="blocklist.copy"></button>
|
||||
<a class="btn" id="dlBl" href="/api/v1/blocklist.txt?download=1" data-i18n="blocklist.download"></a>
|
||||
</div>
|
||||
<div class="empty" id="blMsg" role="status"></div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
</div>
|
||||
|
||||
<div id="tab-traffic" hidden>
|
||||
<section class="grid kpis" id="tkpis"></section>
|
||||
<section class="panel">
|
||||
<h2 data-i18n="traffic.timeline"></h2>
|
||||
<div class="chart-wrap" id="tchart"></div>
|
||||
<div class="legend"><span class="live"><span class="sw t-req"></span><span data-i18n="traffic.requests"></span></span> <span class="live"><span class="sw t-pages"></span><span data-i18n="traffic.pages"></span></span></div>
|
||||
</section>
|
||||
<section class="panel mt">
|
||||
<h2 data-i18n="map.visitors"></h2>
|
||||
<div class="mapbox"><div class="map" id="map-traffic"></div><div class="maplist" id="maplist-traffic"></div></div>
|
||||
</section>
|
||||
<section class="grid cols-3 mt">
|
||||
<div class="panel"><h2 data-i18n="traffic.topPages"></h2><div id="t-pages"></div></div>
|
||||
<div class="panel"><h2 data-i18n="traffic.referrers"></h2><div id="t-refs"></div></div>
|
||||
<div class="panel"><h2 data-i18n="traffic.cities"></h2><div id="t-cities"></div></div>
|
||||
</section>
|
||||
<section class="grid cols-3 mt">
|
||||
<div class="panel"><h2 data-i18n="traffic.browsers"></h2><div id="t-browsers"></div></div>
|
||||
<div class="panel"><h2 data-i18n="traffic.oses"></h2><div id="t-oses"></div></div>
|
||||
<div class="panel"><h2 data-i18n="traffic.devices"></h2><div id="t-devices"></div></div>
|
||||
</section>
|
||||
<section class="grid cols-2 mt">
|
||||
<div class="panel"><h2 data-i18n="traffic.bots"></h2><div id="t-bots"></div></div>
|
||||
<div class="panel"><h2 data-i18n="traffic.status"></h2><div id="t-status"></div><p class="empty" data-i18n="traffic.privacy"></p></div>
|
||||
</section>
|
||||
</div>
|
||||
|
||||
<section class="panel mt">
|
||||
<h2 data-i18n="hosts.title"></h2>
|
||||
<div class="hosts" id="hosts"></div>
|
||||
<h2 class="mt" data-i18n="sources.title"></h2>
|
||||
<table class="stack" id="sources">
|
||||
<thead><tr>
|
||||
<th data-i18n="col.host"></th><th data-i18n="col.source"></th><th data-i18n="col.state"></th>
|
||||
<th data-i18n="col.lines"></th><th data-i18n="col.malformed"></th><th data-i18n="col.lastEvent"></th>
|
||||
</tr></thead>
|
||||
<tbody></tbody>
|
||||
</table>
|
||||
</section>
|
||||
|
||||
<footer><span data-i18n="footer"></span> <span id="ver"></span><div id="attrib"></div></footer>
|
||||
</div>
|
||||
|
||||
<div class="scrim" id="scrim" hidden></div>
|
||||
<aside id="detail" hidden aria-live="polite"></aside>
|
||||
|
||||
<script src="/i18n.js"></script>
|
||||
<script src="/world.js"></script>
|
||||
<script src="/app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,31 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="color-scheme" content="dark light">
|
||||
<title>Urutau</title>
|
||||
<link rel="icon" type="image/png" href="/favicon.png">
|
||||
<link rel="stylesheet" href="/style.css">
|
||||
</head>
|
||||
<body>
|
||||
<main class="login">
|
||||
<div class="panel">
|
||||
<img src="/logo.png" alt="Urutau" width="84" height="84">
|
||||
<h1>Urutau</h1>
|
||||
<p data-i18n="tagline"></p>
|
||||
<form method="post" action="/login">
|
||||
<input type="password" name="token" id="token" required autocomplete="current-password" data-i18n-ph="login.token" data-i18n-aria="login.token" autofocus>
|
||||
<button class="btn primary" type="submit" data-i18n="login.submit"></button>
|
||||
<div class="msg" id="msg" role="alert"></div>
|
||||
</form>
|
||||
<div class="controls">
|
||||
<button type="button" class="btn" id="lang" data-i18n-aria="lang.toggle">EN</button>
|
||||
<button type="button" class="btn" id="theme" data-i18n-aria="theme.toggle" data-i18n-title="theme.toggle">◐</button>
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
<script src="/i18n.js"></script>
|
||||
<script src="/login.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,32 @@
|
||||
(function () {
|
||||
'use strict';
|
||||
var D = window.URUTAU_I18N;
|
||||
function get(k) { try { return localStorage.getItem(k); } catch (e) { return null; } }
|
||||
function set(k, v) { try { localStorage.setItem(k, v); } catch (e) { /* ignore */ } }
|
||||
var lang = get('urutau.lang') || ((navigator.language || 'en').toLowerCase().indexOf('pt') === 0 ? 'pt-BR' : 'en');
|
||||
if (!D[lang]) lang = 'en';
|
||||
var theme = get('urutau.theme');
|
||||
if (theme === 'light' || theme === 'dark') document.documentElement.setAttribute('data-theme', theme);
|
||||
function t(k) { return D[lang][k] || D.en[k] || k; }
|
||||
function apply() {
|
||||
document.documentElement.lang = lang;
|
||||
document.querySelectorAll('[data-i18n]').forEach(function (n) { n.textContent = t(n.getAttribute('data-i18n')); });
|
||||
document.querySelectorAll('[data-i18n-ph]').forEach(function (n) { n.setAttribute('placeholder', t(n.getAttribute('data-i18n-ph'))); });
|
||||
document.querySelectorAll('[data-i18n-aria]').forEach(function (n) { n.setAttribute('aria-label', t(n.getAttribute('data-i18n-aria'))); });
|
||||
document.querySelectorAll('[data-i18n-title]').forEach(function (n) { n.setAttribute('title', t(n.getAttribute('data-i18n-title'))); });
|
||||
document.getElementById('lang').textContent = lang === 'en' ? 'PT' : 'EN';
|
||||
var e = new URLSearchParams(location.search).get('e');
|
||||
try {
|
||||
var nav = performance.getEntriesByType('navigation')[0];
|
||||
if (nav && nav.responseStatus === 429) e = 'rate';
|
||||
} catch (x) { /* ignore */ }
|
||||
document.getElementById('msg').textContent = e === 'bad' ? t('login.err.bad') : e === 'rate' ? t('login.err.rate') : '';
|
||||
}
|
||||
document.getElementById('lang').addEventListener('click', function () { lang = lang === 'en' ? 'pt-BR' : 'en'; set('urutau.lang', lang); apply(); });
|
||||
document.getElementById('theme').addEventListener('click', function () {
|
||||
var cur = document.documentElement.getAttribute('data-theme') || (matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark');
|
||||
var next = cur === 'dark' ? 'light' : 'dark';
|
||||
document.documentElement.setAttribute('data-theme', next); set('urutau.theme', next);
|
||||
});
|
||||
apply();
|
||||
})();
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 73 KiB |
@@ -0,0 +1,204 @@
|
||||
:root {
|
||||
--bg: #070d14; --bg-2: #0b1420; --panel: rgba(13, 25, 38, .82); --line: rgba(148, 188, 205, .16);
|
||||
--text: #e8f2f4; --muted: #8ea5b0; --accent: #38bdf8; --accent-2: #f0b35b;
|
||||
--sev-critical: #ef4444; --sev-high: #f97316; --sev-medium: #f59e0b; --sev-low: #10b981; --sev-info: #64748b;
|
||||
--radius: 16px; --field: rgba(148, 188, 205, .08); --shadow: 0 10px 30px rgba(0, 0, 0, .35);
|
||||
--c-ssh-probe: #a5b4fc; color-scheme: dark;
|
||||
}
|
||||
:root[data-theme="light"] {
|
||||
--bg: #f0f4f8; --bg-2: #e2eaf0; --panel: rgba(255, 255, 255, .88); --line: rgba(15, 31, 38, .13);
|
||||
--text: #0f1f26; --muted: #536b75; --accent: #0284c7; --accent-2: #d97706; --field: rgba(15, 31, 38, .05);
|
||||
--shadow: 0 10px 30px rgba(15, 31, 38, .10); --c-ssh-probe: #6366f1; color-scheme: light;
|
||||
}
|
||||
@media (prefers-color-scheme: light) {
|
||||
:root:not([data-theme="dark"]) {
|
||||
--bg: #f0f4f8; --bg-2: #e2eaf0; --panel: rgba(255, 255, 255, .88); --line: rgba(15, 31, 38, .13);
|
||||
--text: #0f1f26; --muted: #536b75; --accent: #0284c7; --accent-2: #d97706; --field: rgba(15, 31, 38, .05);
|
||||
--shadow: 0 10px 30px rgba(15, 31, 38, .10); --c-ssh-probe: #6366f1; color-scheme: light;
|
||||
}
|
||||
}
|
||||
* { box-sizing: border-box; }
|
||||
html { -webkit-text-size-adjust: 100%; min-height: 100%; background: var(--bg-2); }
|
||||
body {
|
||||
margin: 0; min-height: 100vh; color: var(--text); font: 14px/1.45 "Inter", "Segoe UI", system-ui, -apple-system, sans-serif;
|
||||
background: radial-gradient(1100px 500px at 15% 0, color-mix(in srgb, var(--accent) 14%, transparent), transparent 60%) no-repeat,
|
||||
linear-gradient(180deg, var(--bg), var(--bg-2));
|
||||
overflow-x: hidden;
|
||||
}
|
||||
a { color: var(--accent); }
|
||||
button, select, input { font: inherit; color: inherit; }
|
||||
.wrap { max-width: 1280px; margin: 0 auto; padding: 16px; }
|
||||
header.top { display: flex; flex-wrap: wrap; align-items: center; gap: 12px; padding-bottom: 14px; }
|
||||
.brand { display: flex; align-items: center; gap: 12px; margin-right: auto; min-width: 0; }
|
||||
.brand img { width: 44px; height: 44px; border-radius: 12px; flex: none; }
|
||||
.brand h1 { font-size: 20px; margin: 0; letter-spacing: .02em; }
|
||||
.brand small { display: block; color: var(--muted); font-size: 12px; max-width: 46ch; }
|
||||
.controls { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.btn, select, .seg button, input[type="text"], input[type="number"], input[type="password"] {
|
||||
background: var(--field); border: 1px solid var(--line); border-radius: 10px; padding: 7px 12px; min-height: 36px;
|
||||
}
|
||||
.btn, .seg button { cursor: pointer; }
|
||||
.btn:hover, .seg button:hover { border-color: var(--accent); }
|
||||
.btn.primary { background: var(--accent); color: #04121c; border-color: transparent; font-weight: 600; }
|
||||
.seg { display: inline-flex; border-radius: 10px; overflow: hidden; border: 1px solid var(--line); }
|
||||
.seg button { border: 0; border-radius: 0; background: transparent; }
|
||||
.seg button[aria-pressed="true"] { background: var(--accent); color: #04121c; font-weight: 600; }
|
||||
:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.live { display: inline-flex; align-items: center; gap: 6px; color: var(--muted); font-size: 12px; }
|
||||
.dot { width: 8px; height: 8px; border-radius: 50%; background: var(--sev-info); display: inline-block; flex: none; }
|
||||
.dot.on { background: var(--sev-low); box-shadow: 0 0 8px var(--sev-low); }
|
||||
.dot.off { background: var(--sev-critical); }
|
||||
.grid { display: grid; gap: 14px; }
|
||||
.kpis { grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); margin-bottom: 14px; }
|
||||
.panel {
|
||||
background: var(--panel); border: 1px solid var(--line); border-radius: var(--radius); padding: 14px 16px;
|
||||
box-shadow: var(--shadow); backdrop-filter: blur(10px); min-width: 0;
|
||||
}
|
||||
.panel h2 { font-size: 13px; text-transform: uppercase; letter-spacing: .08em; color: var(--muted); margin: 0 0 10px; font-weight: 600; }
|
||||
.kpi .v { font-size: 28px; font-weight: 700; line-height: 1.1; font-variant-numeric: tabular-nums; }
|
||||
.kpi .l { color: var(--muted); font-size: 12px; margin-top: 4px; }
|
||||
.kpi.hot .v { color: var(--sev-critical); }
|
||||
.kpi.warn .v { color: var(--sev-high); }
|
||||
.cols-2 { grid-template-columns: 1fr 1fr; }
|
||||
.cols-3 { grid-template-columns: repeat(3, 1fr); }
|
||||
.cols-main { grid-template-columns: minmax(0, 2fr) minmax(0, 1fr); }
|
||||
.mt { margin-top: 14px; }
|
||||
.chart-wrap { position: relative; }
|
||||
.chart-wrap svg { width: 100%; height: 230px; display: block; }
|
||||
.chart-wrap .tip {
|
||||
position: absolute; pointer-events: none; background: var(--bg-2); border: 1px solid var(--line); border-radius: 10px;
|
||||
padding: 8px 10px; font-size: 12px; z-index: 5; min-width: 130px; box-shadow: var(--shadow);
|
||||
}
|
||||
.tip[hidden] { display: none; }
|
||||
.tip div { display: flex; justify-content: space-between; gap: 12px; }
|
||||
.axis { fill: var(--muted); font-size: 10px; }
|
||||
.gridline { stroke: var(--line); stroke-width: 1; }
|
||||
.hover-col { fill: transparent; }
|
||||
.hover-col:hover { fill: color-mix(in srgb, var(--text) 8%, transparent); }
|
||||
.b-notfound { fill: var(--sev-info); } .b-scanner { fill: var(--sev-medium); } .b-bruteforce { fill: var(--sev-high); }
|
||||
.b-exploit { fill: var(--sev-critical); } .b-ssh-fail { fill: var(--accent); } .b-ssh-probe { fill: var(--c-ssh-probe); }
|
||||
.b-ban { fill: var(--accent-2); }
|
||||
.legend { display: flex; flex-wrap: wrap; gap: 6px 14px; margin-top: 8px; }
|
||||
.legend button { background: none; border: 0; padding: 2px 0; display: inline-flex; align-items: center; gap: 6px; cursor: pointer; color: var(--text); font-size: 12px; }
|
||||
.legend button[aria-pressed="false"] { opacity: .4; text-decoration: line-through; }
|
||||
.sw { width: 10px; height: 10px; border-radius: 3px; display: inline-block; }
|
||||
.sw.b-notfound { background: var(--sev-info); } .sw.b-scanner { background: var(--sev-medium); } .sw.b-bruteforce { background: var(--sev-high); }
|
||||
.sw.b-exploit { background: var(--sev-critical); } .sw.b-ssh-fail { background: var(--accent); } .sw.b-ssh-probe { background: var(--c-ssh-probe); }
|
||||
.sw.b-ban { background: var(--accent-2); }
|
||||
table { width: 100%; border-collapse: collapse; }
|
||||
th { text-align: left; font-size: 11px; text-transform: uppercase; letter-spacing: .06em; color: var(--muted); font-weight: 600; padding: 6px 8px; white-space: nowrap; }
|
||||
th button { background: none; border: 0; padding: 0; cursor: pointer; color: inherit; font: inherit; text-transform: inherit; letter-spacing: inherit; }
|
||||
td { padding: 8px; border-top: 1px solid var(--line); vertical-align: top; overflow-wrap: anywhere; }
|
||||
tr.row { cursor: pointer; }
|
||||
tr.row:hover td, tr.row:focus-visible td { background: var(--field); }
|
||||
.num { font-variant-numeric: tabular-nums; }
|
||||
.mono { font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; font-size: 12.5px; }
|
||||
.badge { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: 11px; font-weight: 600; border: 1px solid transparent; white-space: nowrap; }
|
||||
.lv-hostile { background: color-mix(in srgb, var(--sev-critical) 22%, transparent); color: var(--sev-critical); border-color: var(--sev-critical); }
|
||||
.lv-suspicious { background: color-mix(in srgb, var(--sev-medium) 20%, transparent); color: var(--sev-medium); border-color: var(--sev-medium); }
|
||||
.lv-low { background: color-mix(in srgb, var(--sev-low) 16%, transparent); color: var(--sev-low); border-color: var(--sev-low); }
|
||||
.chip { display: inline-block; margin: 0 4px 2px 0; padding: 0 6px; border-radius: 6px; background: var(--field); font-size: 11px; white-space: nowrap; }
|
||||
.banned { color: var(--accent-2); font-weight: 600; }
|
||||
.bar-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 2px 10px; padding: 5px 0; border-top: 1px solid var(--line); }
|
||||
.bar-row:first-of-type { border-top: 0; }
|
||||
.bar-row .k { overflow-wrap: anywhere; }
|
||||
.bar-row .n { color: var(--muted); font-variant-numeric: tabular-nums; }
|
||||
.bar-row .bar { grid-column: 1 / -1; height: 3px; border-radius: 2px; background: var(--field); overflow: hidden; }
|
||||
.bar-row .bar i { display: block; height: 100%; background: var(--accent); }
|
||||
.empty { color: var(--muted); padding: 8px 0; }
|
||||
.feed { list-style: none; margin: 0; padding: 0; max-height: 380px; overflow-y: auto; }
|
||||
.feed li { padding: 6px 0; border-top: 1px solid var(--line); display: grid; grid-template-columns: auto auto minmax(0, 1fr); gap: 2px 8px; align-items: baseline; }
|
||||
.feed li:first-child { border-top: 0; }
|
||||
.feed .t { color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; }
|
||||
.feed .what { grid-column: 1 / -1; color: var(--muted); font-size: 12.5px; overflow-wrap: anywhere; }
|
||||
.feed a, .linkish { color: var(--accent); cursor: pointer; background: none; border: 0; padding: 0; text-decoration: underline; text-underline-offset: 2px; }
|
||||
.cat { display: inline-block; padding: 0 7px; border-radius: 6px; font-size: 11px; font-weight: 600; color: #04121c; }
|
||||
.cat.b-notfound { background: var(--sev-info); color: #fff; } .cat.b-scanner { background: var(--sev-medium); } .cat.b-bruteforce { background: var(--sev-high); }
|
||||
.cat.b-exploit { background: var(--sev-critical); color: #fff; } .cat.b-ssh-fail { background: var(--accent); } .cat.b-ssh-probe { background: var(--c-ssh-probe); }
|
||||
.cat.b-ban { background: var(--accent-2); } .cat.b-ssh-ok { background: var(--sev-low); } .cat.b-ok { background: var(--sev-low); }
|
||||
.toolbar { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-bottom: 10px; }
|
||||
.toolbar input[type="text"] { flex: 1 1 140px; min-width: 0; }
|
||||
.toolbar input[type="number"] { width: 84px; }
|
||||
.pager { display: flex; justify-content: space-between; align-items: center; gap: 8px; margin-top: 10px; color: var(--muted); font-size: 12px; }
|
||||
.hosts { display: grid; gap: 10px; grid-template-columns: repeat(auto-fit, minmax(220px, 1fr)); }
|
||||
.host { border: 1px solid var(--line); border-radius: 12px; padding: 10px 12px; }
|
||||
.host h3 { margin: 0 0 4px; font-size: 14px; display: flex; align-items: center; gap: 8px; }
|
||||
.host .meta { color: var(--muted); font-size: 12px; }
|
||||
.host dl { display: grid; grid-template-columns: 1fr auto; gap: 2px 8px; margin: 8px 0 0; font-size: 12.5px; }
|
||||
.host dd { margin: 0; font-variant-numeric: tabular-nums; text-align: right; }
|
||||
.host dt { color: var(--muted); }
|
||||
.st-following, .st-ok { color: var(--sev-low); } .st-waiting, .st-backfill { color: var(--sev-medium); } .st-error { color: var(--sev-critical); }
|
||||
aside#detail {
|
||||
position: fixed; top: 0; right: 0; bottom: 0; width: min(460px, 100vw); background: var(--bg-2); border-left: 1px solid var(--line);
|
||||
box-shadow: var(--shadow); z-index: 20; padding: 18px 16px; overflow-y: auto; overflow-x: hidden;
|
||||
}
|
||||
aside#detail[hidden] { display: none; }
|
||||
aside#detail h2 { font-size: 18px; text-transform: none; letter-spacing: 0; color: var(--text); margin: 0; overflow-wrap: anywhere; }
|
||||
aside#detail dl { display: grid; grid-template-columns: 110px minmax(0, 1fr); gap: 6px 10px; margin: 14px 0; }
|
||||
aside#detail dt { color: var(--muted); }
|
||||
aside#detail dd { margin: 0; overflow-wrap: anywhere; }
|
||||
aside#detail ul { margin: 0; padding-left: 16px; }
|
||||
.scrim { position: fixed; inset: 0; background: rgba(0, 0, 0, .45); z-index: 15; }
|
||||
.scrim[hidden] { display: none; }
|
||||
footer { color: var(--muted); font-size: 12px; text-align: center; padding: 20px 0 6px; }
|
||||
.err-banner { background: color-mix(in srgb, var(--sev-critical) 18%, transparent); border: 1px solid var(--sev-critical); border-radius: 10px; padding: 8px 12px; margin-bottom: 12px; }
|
||||
.err-banner[hidden] { display: none; }
|
||||
.login { min-height: 100vh; display: grid; place-items: center; padding: 16px; }
|
||||
.login .panel { width: min(400px, 100%); padding: 26px 22px; text-align: center; }
|
||||
.login img { width: 84px; height: 84px; border-radius: 20px; }
|
||||
.login h1 { margin: 10px 0 2px; }
|
||||
.login p { color: var(--muted); margin: 0 0 16px; }
|
||||
.login form { display: grid; gap: 10px; }
|
||||
.login .msg { color: var(--sev-critical); min-height: 1.4em; }
|
||||
.login .controls { justify-content: center; margin-top: 14px; }
|
||||
@media (max-width: 960px) {
|
||||
.cols-main, .cols-3 { grid-template-columns: 1fr; }
|
||||
.cols-2 { grid-template-columns: 1fr; }
|
||||
}
|
||||
@media (max-width: 720px) {
|
||||
.wrap { padding: 12px; }
|
||||
.brand small { display: none; }
|
||||
.kpi .v { font-size: 24px; }
|
||||
table.stack thead { display: none; }
|
||||
table.stack, table.stack tbody, table.stack tr, table.stack td { display: block; width: 100%; }
|
||||
table.stack tr { border-top: 1px solid var(--line); padding: 8px 0; }
|
||||
table.stack td { border: 0; padding: 2px 0; display: flex; justify-content: space-between; gap: 12px; text-align: right; }
|
||||
table.stack td::before { content: attr(data-label); color: var(--muted); font-size: 11px; text-transform: uppercase; letter-spacing: .05em; text-align: left; flex: none; }
|
||||
table.stack td > * { min-width: 0; }
|
||||
.chart-wrap svg { height: 190px; }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) { * { transition: none !important; animation: none !important; } }
|
||||
#ips td:first-child, #ips td:nth-child(2), #sources td:nth-child(-n+2), #sources td:nth-child(n+4) { white-space: nowrap; overflow-wrap: normal; }
|
||||
@media (max-width: 720px) {
|
||||
#ips td, #sources td { white-space: normal !important; max-width: none !important; }
|
||||
#ips td:first-child { font-weight: 600; }
|
||||
}
|
||||
.tabs { display: flex; flex-wrap: wrap; gap: 6px; align-items: center; margin-bottom: 14px; }
|
||||
.tabs button[role="tab"] { background: var(--field); border: 1px solid var(--line); border-radius: 10px; padding: 8px 18px; cursor: pointer; font-weight: 600; }
|
||||
.tabs button[aria-selected="true"] { background: var(--accent); color: #04121c; border-color: transparent; }
|
||||
.tabs select { margin-left: auto; max-width: 100%; }
|
||||
.tabs select[hidden] { display: none; }
|
||||
.mapbox { display: grid; grid-template-columns: minmax(0, 3fr) minmax(0, 1fr); gap: 14px; align-items: start; }
|
||||
.map svg { width: 100%; height: auto; display: block; }
|
||||
.mapc { fill: var(--field); stroke: var(--line); stroke-width: .6; }
|
||||
.mapc.hit { fill: var(--sev-critical); stroke: var(--line); }
|
||||
.map.good .mapc.hit { fill: var(--accent); }
|
||||
.maplist .bar-row { padding: 4px 0; }
|
||||
.sw.t-req { background: color-mix(in srgb, var(--accent) 38%, transparent); }
|
||||
.sw.t-pages { background: var(--accent); }
|
||||
.b-treq { fill: color-mix(in srgb, var(--accent) 38%, transparent); }
|
||||
.b-tpages { fill: var(--accent); }
|
||||
.bar-row .sub { grid-column: 1 / -1; color: var(--muted); font-size: 11.5px; overflow-wrap: anywhere; }
|
||||
.origin { display: block; }
|
||||
.origin small, td small { display: block; color: var(--muted); font-size: 11.5px; overflow-wrap: anywhere; }
|
||||
footer #attrib { margin-top: 4px; opacity: .8; }
|
||||
@media (max-width: 960px) { .mapbox { grid-template-columns: 1fr; } }
|
||||
|
||||
/* compact IP table: one line per IP on desktop */
|
||||
#ips td { padding: 5px 8px; }
|
||||
#ips .origin { display: block; max-width: 170px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
#ips td:nth-child(4) { white-space: nowrap; }
|
||||
#ips td:nth-child(4) .chip { margin-bottom: 0; }
|
||||
@media (max-width: 720px) {
|
||||
#ips .origin { max-width: none; white-space: normal; }
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
/* Generated by scripts/gen-world.mjs from Natural Earth (public domain). */
|
||||
window.URUTAU_WORLD = {"w":2000,"h":789,"paths":{"FJ":"M1990 564l1 -1l2 2l-1 3l-3 0l-4 0l0 -3l2 -2l3 1zM0 556l1 0l-1 2l0 1M1996 560l-3 1l-1 -2l3 -1l2 0l3 -2M0 556z","TZ":"M1188 472l1 1l20 11l1 3l8 6l-3 7l1 3l3 2l0 1l-1 4l0 1l0 3l2 3l2 6l2 1l-4 3l-7 2l-3 0l-2 2l-4 0l-1 1l-7 -2l-4 1l-2 -8l-1 -2l-2 -2l-5 -1l-3 -2l-4 -1l-2 -1l-2 -1l-3 -7l-3 -3l-2 -3l1 -3l-1 -5l2 -1l2 -2l2 -2l2 -2l0 -1l-1 -2l-1 -2l2 -1l0 -3l-2 -3l2 -1l6 0l11 0z","EH":"M952 313l0 2l0 8l-18 0l0 14l-6 0l-1 3l1 8l-22 0l-1 2l0 -2l1 0l12 -1l1 -2l2 -2l2 -8l8 -6l2 -7l2 0l2 -5l4 0l2 0l3 0l2 -1l3 0l0 -3l1 0z","CA":"M318 194l-1 0l-11 -5l-4 -2l-10 -3l-3 -5l1 -3l-7 -2l-1 -5l-7 -4l0 -3l3 -2l0 -4l-10 -3l-5 -7l-4 -4l-5 -2l-4 -3l-3 -2l-5 1l-6 3l-5 -3l-3 -3l-6 -1l-5 0l0 -32l0 -21l10 2l9 2l6 1l5 -2l6 -2l9 1l8 -3l9 -1l4 2l4 -1l1 -3l4 1l9 5l8 -4l1 4l6 -1l2 -1l7 0l9 2l13 2l7 1l6 0l7 3l-8 2l10 2l15 -1l5 -1l6 3l6 -2l-6 -3l4 -2l7 0l4 -1l5 2l5 3l7 -1l9 3l9 -1l8 0l-1 -3l5 -1l9 2l0 5l4 -5l4 1l2 -6l-5 -3l-7 -3l0 -6l7 -4l7 1l6 2l8 7l-5 2l10 2l0 5l7 -4l7 3l-2 5l6 3l6 -4l4 -4l0 -7l8 1l8 1l7 2l1 3l-4 3l4 3l-1 3l-11 4l-8 1l-5 -2l-2 3l-6 4l-1 3l-7 4l-8 0l-4 2l0 4l-7 1l-7 4l-6 6l-2 5l0 6l8 1l3 5l2 5l8 -2l10 3l6 2l4 3l7 1l6 2l9 1l6 0l-1 5l2 6l4 6l8 5l4 -2l3 -5l-3 -9l-3 -3l8 -3l7 -4l3 -3l-1 -4l-3 -5l-7 -4l6 -6l-2 -5l-2 -9l4 -1l9 2l6 0l5 -1l5 2l7 3l1 2l10 0l0 5l2 7l5 1l4 3l8 -3l6 -6l3 -3l5 5l7 8l6 6l-2 4l7 3l5 3l9 1l3 2l3 5l4 1l2 2l1 6l-4 2l-4 2l-10 2l-7 5l-9 0l-12 -1l-8 0l-6 1l-5 4l-7 2l-8 7l-6 6l5 -1l9 -8l11 -4l9 -1l4 3l-5 4l2 6l2 4l7 3l9 -1l6 -6l0 4l4 2l-7 3l-12 4l-6 2l-6 4l-4 -1l-1 -4l10 -5l-9 0l-6 1l-4 -3l0 -8l-2 -1l-4 1l-2 -2l-4 4l-2 5l-2 2l-2 1l-2 0l0 2l-10 0l-9 0l-2 1l-6 4l-1 0l-2 2l-5 0l-5 0l-3 1l1 1l1 2l-1 1l-7 2l-6 1l-6 3l-1 0l-2 -1l-1 -1l1 -2l3 -3l2 -3l-1 -5l-2 -5l-5 -3l0 -1l-1 -1l-1 0l-1 0l0 -2l-2 1l-1 0l0 -1l-1 0l-1 -2l-4 -2l-4 -1l-6 -3l-5 -2l-5 2l-2 0l-7 -1l-4 0l-5 -1l-6 -1l-4 -1l-2 -1l-1 -3l-2 0l0 2l-11 0l-19 0l-19 0l-17 0l-16 0l-17 0l-17 0l-5 0l-17 0l-15 0zM533 120l5 -3l7 0l0 1l-6 3l-4 0l-2 -1zM557 62l-6 -3l0 -2l3 0l12 0l10 4l0 1l-6 0l-6 0l-6 1l-1 -1zM554 122l2 -2l2 0l2 1l-3 3l-2 0l-1 -2zM480 50l-3 2l-8 0l-7 -2l3 -2l8 -2l5 2l2 2zM479 36l-3 0l-10 0l-2 -2l11 0l4 1l0 1zM462 29l7 2l-1 2l-9 1l-4 -1l-3 -2l0 -3l7 1l3 0zM510 53l-9 0l-14 -2l-2 -3l-1 -3l-6 -2l-11 -1l-7 -2l3 -2l11 0l6 2l11 0l5 2l-1 2l6 1l4 2l7 0l8 0l9 -1l11 0l9 0l6 2l1 2l-3 2l-8 1l-7 -1l-16 1l-12 0zM382 32l8 1l-2 2l-11 2l-8 -2l5 -2l8 -1zM384 29l7 1l-7 1l-9 0l0 -1l6 -1l3 0zM691 182l-3 3l-4 5l4 -2l4 1l-2 2l5 2l2 -2l6 2l-2 4l4 -1l1 3l2 4l-3 4l-2 1l-4 -1l1 -5l-1 -1l-7 5l-3 0l4 -3l-6 -1l-5 0l-11 0l-1 -1l3 -2l-2 -2l5 -3l5 -9l4 -3l5 -2l2 0l-1 2zM534 105l6 2l6 2l1 2l4 0l4 2l-5 1l-9 -1l-3 -2l-5 3l-8 2l-2 -3l-8 1l5 -3l1 -4l2 -6l4 1l1 2l3 0l3 1zM562 65l6 -2l12 2l8 3l0 2l11 -1l5 4l14 2l5 2l5 5l-10 3l13 4l9 1l8 5l8 0l-1 4l-10 7l-7 -3l-9 -5l-7 1l-1 3l6 3l8 3l2 1l4 5l-2 4l-7 -1l-14 -4l8 4l6 4l0 2l-15 -3l-12 -3l-6 -3l2 -1l-9 -3l-8 -3l0 2l-16 1l-4 -2l3 -4l11 0l11 -1l-2 -2l2 -3l7 -5l-1 -3l-2 -1l-9 -3l-11 -2l4 -1l-6 -4l-5 0l-5 -2l-3 2l-10 0l-20 -1l-12 -2l-9 0l-4 -2l6 -3l-8 0l-2 -6l4 -5l6 -2l14 -1l-4 3l4 4l6 -5l14 -2l9 6l-1 3l11 -1zM475 55l12 0l10 1l-8 5l-7 1l-6 5l-6 -1l-4 -5l1 -2l2 -3l6 -1zM317 44l10 -4l11 -4l9 0l7 -1l0 5l-5 2l-5 0l-10 2l-9 1l-8 -1zM263 166l5 0l-2 6l5 5l-2 0l-3 -3l-2 -2l-3 -2l-1 -2l0 -2l3 0zM414 26l11 1l15 2l4 3l2 2l-9 -1l-9 -2l-12 0l5 -1l-7 -2l0 -2zM314 197l-3 1l-9 -3l-2 -2l-5 -1l-1 -2l-5 -1l-3 -3l1 -1l6 1l3 1l5 0l2 2l3 3l6 2l2 3zM325 53l8 1l14 1l5 1l6 2l-7 2l-13 4l-7 4l0 2l-15 3l-3 -3l-13 -3l3 -2l4 -4l4 -4l-5 -3l19 -1zM401 45l5 -1l6 1l1 2l-4 3l-18 1l-14 2l-9 0l-1 -1l12 -3l-25 1l-8 -1l8 -6l5 -1l16 2l9 3l10 0l-8 -5l5 -2l6 1l2 2l2 2zM408 61l6 2l4 5l2 4l9 3l10 3l-1 2l-9 1l4 2l-2 2l-10 -1l-10 -2l-6 1l-11 2l-14 0l-10 1l-3 -3l-7 -1l-5 0l-7 -4l4 -1l8 -1l8 1l7 -1l-10 -2l-12 1l-8 0l-3 -2l13 -2l-9 0l-9 -2l4 -4l4 -2l15 -4l6 1l-3 3l12 -2l8 3l6 -3l5 2l5 6l3 -3l-4 -5l5 -1l5 1zM442 63l-6 -4l6 -3l7 2l10 -1l1 2l-5 2l9 3l-1 5l-9 2l-6 -1l-4 -2l-13 -4l0 -2l11 1zM408 58l7 0l4 1l-4 3l-9 -3l2 -1zM453 40l4 3l0 3l-2 4l-9 1l-6 -1l0 -4l-9 1l-1 -4l6 0l9 -2l7 0l1 -1zM467 19l3 -2l6 0l-2 -1l13 -1l7 3l9 1l9 1l5 4l6 2l-7 2l-11 4l-9 0l-12 -1l-6 -2l0 -2l5 -1l-11 0l-6 -2l-3 -3l4 -2zM491 12l8 -1l7 -1l11 0l8 -3l7 1l6 1l4 -3l7 -1l10 0l17 0l3 0l16 -1l12 1l12 0l15 0l12 1l10 2l0 1l-13 3l-14 1l-5 1l12 0l-13 3l-9 2l-9 4l-12 1l-3 1l-17 1l7 1l-3 1l4 2l-5 2l-9 2l-2 2l-8 2l1 1l9 0l0 1l-15 3l-14 -1l-16 1l-9 -1l-10 0l-1 -3l10 -1l-2 -4l3 0l15 2l-8 -4l-9 -1l5 -2l10 -1l1 -2l-8 -2l-2 -3l15 0l5 1l8 -2l-12 -1l-20 0l-9 -2l-5 -2l-7 -1l-1 -2zM582 92l-3 2l-7 0l-1 -3l2 -3l5 -1l5 2l0 2l-1 1zM465 81l4 2l-4 2l-7 -2l-5 1l-7 -3l4 -2l4 -2l6 2l4 1l1 1zM642 190l1 -1l8 2l5 2l1 1l-3 0l-7 -2l-5 -2zM644 205l2 3l4 1l5 0l-2 2l-2 0l-7 -2l-2 -2l2 -2z","US":"M318 194l15 0l17 0l5 0l17 0l17 0l16 0l17 0l19 0l19 0l11 0l0 -2l2 0l1 3l2 1l4 1l6 1l5 1l4 0l7 1l2 0l5 -2l5 2l6 3l4 1l4 2l1 2l1 0l0 1l1 0l2 -1l0 2l1 0l1 0l1 1l0 1l5 3l2 5l1 5l-2 3l-3 3l-1 2l1 1l2 1l1 0l6 -3l6 -1l7 -2l1 -1l-1 -2l-1 -1l3 -1l5 0l5 0l2 -2l1 0l6 -4l2 -1l9 0l10 0l0 -2l2 0l2 -1l2 -2l2 -5l4 -4l2 2l4 -1l2 1l0 8l4 3l1 2l-6 2l-6
Line truncated
|
||||
Reference in new issue
Block a user