Files
urutau/internal/ua/ua.go
T
Lucas RayanandClaude Opus 5.5 b4a2c2c9ec
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
feat: Urutau 1.0.0, lightweight threat intelligence and web analytics
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>
2026-11-14 16:13:34 -03:00

505 lines
14 KiB
Go

// Package ua interpreta User-Agents sem dependências: navegador, SO, tipo de
// dispositivo, bots conhecidos (buscadores/IA) e ferramentas de varredura.
package ua
import (
"strings"
"sync"
)
// Info é o resultado de Parse.
type Info struct {
Browser string `json:"browser,omitempty"`
BrowserMajor string `json:"browser_major,omitempty"`
OS string `json:"os,omitempty"`
Device string `json:"device"` // desktop | mobile | tablet | bot | tool | unknown
Bot bool `json:"bot"`
BotName string `json:"bot_name,omitempty"`
Tool string `json:"tool,omitempty"`
}
const (
Desktop = "desktop"
Mobile = "mobile"
Tablet = "tablet"
BotDev = "bot"
ToolDev = "tool"
Unknown = "unknown"
)
const cacheMax = 4096
var (
cacheMu sync.RWMutex
cache = make(map[string]Info, 256)
)
// Parse é pura (sem estado observável) e segura para uso concorrente; usa um
// cache pequeno e limitado.
func Parse(ua string) Info {
cacheMu.RLock()
in, ok := cache[ua]
cacheMu.RUnlock()
if ok {
return in
}
in = parse(ua)
if len(ua) <= 512 {
cacheMu.Lock()
if len(cache) >= cacheMax {
clear(cache)
}
cache[ua] = in
cacheMu.Unlock()
}
return in
}
type needle struct {
s string // minúsculo
name string
// prefix: só vale no início do UA
prefix bool
}
// Ferramentas de varredura, ataque, automação e monitoramento. Ordem importa
// apenas entre entradas que se sobrepõem.
var tools = []needle{
{"zgrab", "zgrab", false},
{"masscan", "masscan", false},
{"nuclei", "Nuclei", false},
{"sqlmap", "sqlmap", false},
{"nmap", "Nmap", false},
{"nikto", "Nikto", false},
{"dirbuster", "DirBuster", false},
{"gobuster", "gobuster", false},
{"ffuf", "ffuf", false},
{"wfuzz", "wfuzz", false},
{"feroxbuster", "feroxbuster", false},
{"wpscan", "WPScan", false},
{"acunetix", "Acunetix", false},
{"nessus", "Nessus", false},
{"openvas", "OpenVAS", false},
{"qualys", "Qualys", false},
{"netsparker", "Netsparker", false},
{"burpcollaborator", "Burp", false},
{"zmeu", "ZmEu", false},
{"l9explore", "l9explore", false},
{"l9tcpid", "l9tcpid", false},
{"libredtail", "libredtail-http", false},
{"censysinspect", "CensysInspect", false},
{"expanse", "Expanse", false},
{"internet-measurement", "InternetMeasurement", false},
{"netsystemsresearch", "NetSystemsResearch", false},
{"hello, world", "Hello World", true},
{"hello world", "Hello World", true},
{"headlesschrome", "HeadlessChrome", false},
{"phantomjs", "PhantomJS", false},
{"selenium", "Selenium", false},
{"puppeteer", "Puppeteer", false},
{"playwright", "Playwright", false},
{"chrome-lighthouse", "Lighthouse", false},
{"curl/", "curl", false},
{"wget", "Wget", false},
{"httpie", "HTTPie", false},
{"python-requests", "python-requests", false},
{"python-urllib", "python-urllib", false},
{"python-httpx", "python-httpx", false},
{"aiohttp", "aiohttp", false},
{"python/", "Python", true},
{"go-http-client", "Go-http-client", false},
{"fasthttp", "fasthttp", false},
{"okhttp", "okhttp", false},
{"java/", "Java", true},
{"apache-httpclient", "Apache-HttpClient", false},
{"jakarta commons", "Jakarta-HttpClient", false},
{"libwww-perl", "libwww-perl", false},
{"lwp::simple", "libwww-perl", false},
{"ruby", "Ruby", true},
{"faraday", "Faraday", false},
{"guzzlehttp", "GuzzleHttp", false},
{"php/", "PHP", true},
{"node-fetch", "node-fetch", false},
{"axios/", "axios", false},
{"undici", "undici", false},
{"deno/", "Deno", true},
{"dart/", "Dart", true},
{"reqwest", "reqwest", false},
{"scrapy", "Scrapy", false},
{"postmanruntime", "Postman", false},
{"insomnia", "Insomnia", false},
{"winhttp", "WinHTTP", false},
{"wappalyzer", "Wappalyzer", false},
{"apache/", "Apache", true},
{"uptime-kuma", "Uptime-Kuma", false},
{"uptimerobot", "UptimeRobot", false},
{"pingdom", "Pingdom", false},
{"statuscake", "StatusCake", false},
{"site24x7", "Site24x7", false},
{"zabbix", "Zabbix", false},
{"prometheus", "Prometheus", false},
{"kube-probe", "kube-probe", false},
{"elb-healthchecker", "ELB-HealthChecker", false},
{"amazon-route53-health-check", "Route53-HealthCheck", false},
{"googlehc", "GoogleHC", false},
{"check_http", "check_http", false},
{"nagios", "Nagios", false},
{"monitoring", "Monitoring", true},
}
// Bots de buscadores, IA, redes sociais e SEO.
var bots = []needle{
{"googlebot", "Googlebot", false},
{"adsbot-google", "AdsBot-Google", false},
{"mediapartners-google", "Mediapartners-Google", false},
{"google-inspectiontool", "Google-InspectionTool", false},
{"google-extended", "Google-Extended", false},
{"googleother", "GoogleOther", false},
{"google-cloudvertexbot", "Google-CloudVertexBot", false},
{"storebot-google", "Storebot-Google", false},
{"apis-google", "APIs-Google", false},
{"feedfetcher-google", "FeedFetcher-Google", false},
{"google-read-aloud", "Google-Read-Aloud", false},
{"google-site-verification", "Google-Site-Verification", false},
{"google page speed", "Google-PageSpeed", false},
{"bingbot", "Bingbot", false},
{"bingpreview", "BingPreview", false},
{"adidxbot", "adidxbot", false},
{"msnbot", "MSNBot", false},
{"yahoo! slurp", "Yahoo Slurp", false},
{"slurp", "Yahoo Slurp", false},
{"duckassistbot", "DuckAssistBot", false},
{"duckduckbot", "DuckDuckBot", false},
{"baiduspider", "Baiduspider", false},
{"yandex", "YandexBot", false},
{"sogou", "Sogou", false},
{"exabot", "Exabot", false},
{"seznambot", "SeznamBot", false},
{"qwantify", "Qwantify", false},
{"applebot", "Applebot", false},
{"petalbot", "PetalBot", false},
{"gptbot", "GPTBot", false},
{"chatgpt-user", "ChatGPT-User", false},
{"oai-searchbot", "OAI-SearchBot", false},
{"claudebot", "ClaudeBot", false},
{"claude-web", "Claude-Web", false},
{"claude-user", "Claude-User", false},
{"claude-searchbot", "Claude-SearchBot", false},
{"anthropic-ai", "anthropic-ai", false},
{"perplexitybot", "PerplexityBot", false},
{"perplexity-user", "Perplexity-User", false},
{"mistralai-user", "MistralAI-User", false},
{"cohere-ai", "cohere-ai", false},
{"bytespider", "Bytespider", false},
{"ccbot", "CCBot", false},
{"amazonbot", "Amazonbot", false},
{"diffbot", "Diffbot", false},
{"youbot", "YouBot", false},
{"imagesiftbot", "ImagesiftBot", false},
{"timpibot", "Timpibot", false},
{"omgili", "omgili", false},
{"meta-externalagent", "meta-externalagent", false},
{"meta-externalfetcher", "meta-externalfetcher", false},
{"facebookexternalhit", "facebookexternalhit", false},
{"facebot", "Facebot", false},
{"twitterbot", "Twitterbot", false},
{"linkedinbot", "LinkedInBot", false},
{"slackbot", "Slackbot", false},
{"slack-imgproxy", "Slack-ImgProxy", false},
{"discordbot", "Discordbot", false},
{"telegrambot", "TelegramBot", false},
{"whatsapp/", "WhatsApp", false},
{"pinterestbot", "Pinterestbot", false},
{"redditbot", "redditbot", false},
{"skypeuripreview", "SkypeUriPreview", false},
{"embedly", "Embedly", false},
{"quora link preview", "Quora Link Preview", false},
{"semrushbot", "SemrushBot", false},
{"ahrefsbot", "AhrefsBot", false},
{"ahrefssiteaudit", "AhrefsSiteAudit", false},
{"mj12bot", "MJ12bot", false},
{"dotbot", "DotBot", false},
{"rogerbot", "rogerbot", false},
{"blexbot", "BLEXBot", false},
{"dataforseobot", "DataForSeoBot", false},
{"barkrowler", "Barkrowler", false},
{"megaindex", "MegaIndex", false},
{"serpstatbot", "serpstatbot", false},
{"screaming frog", "Screaming Frog", false},
{"ia_archiver", "ia_archiver", false},
{"archive.org_bot", "archive.org_bot", false},
{"better uptime bot", "Better Uptime Bot", false},
{"wp rocket", "WP Rocket", false},
}
func lower(s string) string {
for i := 0; i < len(s); i++ {
if c := s[i]; c >= 'A' && c <= 'Z' {
return strings.ToLower(s)
}
}
return s
}
func matchNeedle(list []needle, l string) string {
for i := range list {
n := &list[i]
if n.prefix {
if strings.HasPrefix(l, n.s) {
return n.name
}
} else if strings.Contains(l, n.s) {
return n.name
}
}
return ""
}
func parse(raw string) Info {
s := strings.TrimSpace(raw)
if s == "" || s == "-" {
return Info{Device: Unknown}
}
l := lower(s)
if t := matchNeedle(tools, l); t != "" {
in := Info{Device: ToolDev, Tool: t}
if strings.HasPrefix(l, "mozilla/") {
in.Browser, in.BrowserMajor = browser(s)
in.OS = osName(s)
}
return in
}
if b := matchNeedle(bots, l); b != "" {
return Info{Device: BotDev, Bot: true, BotName: b}
}
if b := genericBot(s); b != "" {
return Info{Device: BotDev, Bot: true, BotName: b}
}
in := Info{}
in.Browser, in.BrowserMajor = browser(s)
in.OS = osName(s)
in.Device = device(s, l, &in)
return in
}
// genericBot reconhece bots não listados: tokens terminados em "bot",
// "crawler"/"spider", ou "(compatible; Nome/1.0; +http://...)".
func genericBot(s string) string {
isSep := func(r byte) bool {
return r == ' ' || r == ';' || r == '(' || r == ')' || r == '/' || r == ','
}
var firstCompat string
for i := 0; i < len(s); {
for i < len(s) && isSep(s[i]) {
i++
}
j := i
for j < len(s) && !isSep(s[j]) {
j++
}
tok := s[i:j]
i = j
if len(tok) < 3 {
continue
}
lt := lower(tok)
if strings.EqualFold(tok, "compatible") {
firstCompat = "?"
continue
}
if firstCompat == "?" {
firstCompat = tok
}
if lt == "cubot" {
continue
}
if strings.HasSuffix(lt, "bot") || strings.Contains(lt, "crawler") || strings.Contains(lt, "spider") {
return tok
}
}
// "(compatible; Foo/1.0; +http...)" sem navegador conhecido
if firstCompat != "" && firstCompat != "?" && strings.Contains(s, "+http") &&
!strings.HasPrefix(firstCompat, "MSIE") && !strings.HasPrefix(firstCompat, "Opera") {
return firstCompat
}
return ""
}
// major devolve os dígitos após tok em s ("Chrome/" -> "89").
func major(s, tok string) (string, bool) {
i := strings.Index(s, tok)
if i < 0 {
return "", false
}
i += len(tok)
j := i
for j < len(s) && s[j] >= '0' && s[j] <= '9' {
j++
}
if j == i {
return "", false
}
return s[i:j], true
}
func browser(s string) (name, ver string) {
type rule struct {
tok, name string
}
// ordem: derivados de Chromium/WebKit antes de Chrome e Safari
for _, r := range [...]rule{
{"Edg/", "Edge"}, {"EdgA/", "Edge"}, {"EdgiOS/", "Edge"}, {"Edge/", "Edge"},
{"OPR/", "Opera"}, {"OPT/", "Opera"}, {"OPiOS/", "Opera"},
{"SamsungBrowser/", "Samsung Internet"},
{"Vivaldi/", "Vivaldi"},
{"YaBrowser/", "Yandex Browser"},
{"UCBrowser/", "UC Browser"},
{"DuckDuckGo/", "DuckDuckGo"},
{"MiuiBrowser/", "MIUI Browser"},
{"HuaweiBrowser/", "Huawei Browser"},
{"Whale/", "Whale"},
{"QQBrowser/", "QQ Browser"},
{"Silk/", "Silk"},
{"Electron/", "Electron"},
{"MicroMessenger/", "WeChat"},
{"FBAV/", "Facebook"},
{"Instagram ", "Instagram"},
{"Firefox/", "Firefox"},
{"FxiOS/", "Firefox"},
{"Chromium/", "Chromium"},
{"CriOS/", "Chrome"},
} {
if v, ok := major(s, r.tok); ok {
return r.name, v
}
}
if strings.Contains(s, "Opera Mini/") {
v, _ := major(s, "Opera Mini/")
return "Opera Mini", v
}
if strings.Contains(s, "Opera") {
if v, ok := major(s, "Version/"); ok {
return "Opera", v
}
if v, ok := major(s, "Opera/"); ok {
return "Opera", v
}
v, _ := major(s, "Opera ")
return "Opera", v
}
if v, ok := major(s, "MSIE "); ok {
return "Internet Explorer", v
}
if strings.Contains(s, "Trident/") {
v, _ := major(s, "rv:")
return "Internet Explorer", v
}
if v, ok := major(s, "Chrome/"); ok {
if strings.Contains(s, "; wv)") {
return "Android WebView", v
}
return "Chrome", v
}
if strings.Contains(s, "Safari/") || strings.Contains(s, "AppleWebKit/") {
if v, ok := major(s, "Version/"); ok {
return "Safari", v
}
if strings.Contains(s, "Safari/") {
return "Safari", ""
}
return "WebKit", ""
}
if strings.HasPrefix(s, "Lynx/") {
v, _ := major(s, "Lynx/")
return "Lynx", v
}
if strings.HasPrefix(s, "w3m/") {
return "w3m", ""
}
return "", ""
}
func osName(s string) string {
switch {
case strings.Contains(s, "Windows Phone"):
return "Windows Phone"
case strings.Contains(s, "Windows"):
return "Windows"
case strings.Contains(s, "Android"):
return "Android"
case strings.Contains(s, "iPhone"), strings.Contains(s, "iPod"), strings.Contains(s, "iPad"):
return "iOS"
case strings.Contains(s, "CrOS"):
return "ChromeOS"
case strings.Contains(s, "Macintosh"):
// iPadOS 13+ se apresenta como Mac, mas traz "Mobile/<build>"
if strings.Contains(s, " Mobile/") {
return "iOS"
}
return "macOS"
case strings.Contains(s, "Mac OS X"):
return "macOS"
case strings.Contains(s, "KaiOS"):
return "KaiOS"
case strings.Contains(s, "Tizen"):
return "Tizen"
case strings.Contains(s, "Web0S"), strings.Contains(s, "WebOS"), strings.Contains(s, "webOS"):
return "webOS"
case strings.Contains(s, "FreeBSD"):
return "FreeBSD"
case strings.Contains(s, "OpenBSD"):
return "OpenBSD"
case strings.Contains(s, "NetBSD"):
return "NetBSD"
case strings.Contains(s, "BlackBerry"), strings.Contains(s, "BB10"):
return "BlackBerry"
case strings.Contains(s, "Linux"), strings.Contains(s, "X11"), strings.Contains(s, "Ubuntu"),
strings.Contains(s, "Fedora"), strings.Contains(s, "Debian"):
return "Linux"
case strings.Contains(s, "Dalvik/"):
return "Android"
}
return ""
}
func device(s, l string, in *Info) string {
if strings.Contains(s, "iPad") ||
(in.OS == "iOS" && strings.Contains(s, "Macintosh")) {
return Tablet
}
if strings.Contains(l, "tablet") || strings.Contains(s, "Kindle") || strings.Contains(s, "PlayBook") ||
(in.OS == "Android" && strings.Contains(s, "Silk/")) {
return Tablet
}
switch in.OS {
case "Android":
if strings.Contains(s, "Mobile") || strings.Contains(s, "Dalvik/") || in.Browser == "Opera Mini" {
return Mobile
}
if strings.Contains(s, "Android TV") || strings.Contains(s, "SMART-TV") {
return Unknown
}
return Tablet
case "iOS", "Windows Phone", "KaiOS", "BlackBerry":
return Mobile
case "Tizen", "webOS":
return Unknown
}
if strings.Contains(s, "Mobile") || strings.Contains(s, "IEMobile") || in.Browser == "Opera Mini" {
return Mobile
}
if strings.Contains(s, "SMART-TV") || strings.Contains(s, "HbbTV") || strings.Contains(s, "CrKey") || strings.Contains(s, "AppleTV") {
return Unknown
}
switch in.OS {
case "Windows", "macOS", "Linux", "ChromeOS", "FreeBSD", "OpenBSD", "NetBSD":
return Desktop
}
if in.Browser != "" {
return Desktop
}
return Unknown
}