/* Urutau - DEFENSE page: is fail2ban acting? Bans over time per jail, time to ban, blocklist coverage, leak and the SSH users tried. Data: /api/v1/defense. Log data is hostile: dynamic text goes through textContent only. */ (function () { 'use strict'; var MAX_BUCKETS = 400; function boot() { var U = window.Urutau; if (!U || !U.registerPage) return false; U.registerI18n({ en: { 'df.title': 'Defense', 'df.lead.some': 'fail2ban applied {n} bans {range}', 'df.lead.sub.ok': '{a} bans are active. Few attackers kept arriving after being banned.', 'df.lead.sub.leak': '{a} bans are active, but {l} attackers kept arriving after a ban or listing.', 'df.lead.none': 'fail2ban did not ban anyone {range}', 'df.lead.none.sub': 'No ban events in this window. If attacks were seen, check that the fail2ban log is being read.', 'df.kpi.active': 'Active bans', 'df.kpi.active.sub': '{n} bans in the window', 'df.kpi.ttb': 'Time to ban', 'df.kpi.ttb.sub': 'median per attack episode; 90% within {p}', 'df.kpi.ttb.none': 'no data', 'df.kpi.cov': 'Blocklist coverage', 'df.kpi.cov.sub': '{n} addresses listed', 'df.kpi.leak': 'Leak', 'df.kpi.leak.sub': '{n} events after the ban', 'df.bans': 'Bans per jail over time', 'df.jails': 'Bans by jail', 'df.jails.center': 'bans', 'df.users': 'SSH users tried', 'df.users.hint': 'Names attackers tried to log in with. Red: a real account of yours.', 'df.users.none': 'No SSH failures in this window.', 'df.ssh.sum': '{f} failures from {s} sources; {o} successful logins after failures.', 'df.cov': 'Blocklist coverage', 'df.cov.hint': 'Share of the attackers of the window that are in the blocklist.', 'df.cov.label': 'of attackers listed', 'df.bl.size': '{n} addresses ({v4} IPv4, {v6} IPv6 /64)', 'df.bl.updated': 'last change {t}', 'df.bl.download': 'Download blocklist', 'df.error': 'Could not load the defense data.', 'df.disabled': 'The event registry is off', 'df.disabled.sub': 'Defense is computed from the event registry; enable it to see this page.', 'df.partial': 'Partial result: the study hit its time or size limit.', 'df.admin': 'your account', 'df.en.title': 'Second firewall', 'df.en.hint': 'Urutau can also block attackers by itself, as a safety net next to fail2ban.', 'df.en.mode': 'Mode', 'df.en.mode.off': 'Off', 'df.en.mode.observe': 'Observing only', 'df.en.mode.on': 'Active', 'df.en.mode.off.sub': 'Urutau does not block anyone. Nothing is written; the coverage below shows what you would gain by turning it on.', 'df.en.mode.observe.sub': 'Urutau decides who it would block and records it, but blocks nobody. Use it to check the decisions before trusting them.', 'df.en.mode.on.sub': 'Urutau blocks the attackers it recognises, on its own, for a limited time.', 'df.en.mode.where': 'The mode is chosen at deploy time with the variable URUTAU_ENFORCE (off, observe or on). It cannot be changed from this page.', 'df.en.how.title': 'How to turn it on', 'df.en.how.body': 'Set URUTAU_ENFORCE=observe on the server and restart Urutau. Watch the decisions for a few days; when they look right, change it to on.', 'df.en.share': 'Sharing between hosts', 'df.en.share.on': 'on: bans are shared with other servers', 'df.en.share.off': 'off: bans stay on this server', 'df.en.threshold': 'Blocks from score {n}', 'df.en.nolog.title': 'Blocks are not being saved', 'df.en.nolog.body': 'The mode is active but the block file cannot be written, so nobody is really blocked. Check the permissions of the folder where Urutau writes the blocklist.', 'df.en.lead': '{b} of {a} attacking addresses were blocked {range}', 'df.en.lead.sub': '{fw} by the server firewall, {ur} by Urutau, {wb} would be blocked in observation mode and {un} got through.', 'df.en.lead.none': 'No attacking addresses {range}', 'df.en.lead.none.sub': 'Nothing to block in this window.', 'df.en.cov': 'Who was blocked', 'df.en.cov.hint': 'Each attacking address counted once, by the first line of defense that stopped it.', 'df.en.cov.center': 'addresses', 'df.en.cov.fw': 'Blocked by the server firewall', 'df.en.cov.ur': 'Blocked by Urutau', 'df.en.cov.wb': 'Would be blocked (observation mode)', 'df.en.cov.un': 'Got through without a block', 'df.en.counts': 'What Urutau decided', 'df.en.counts.hint': 'Counts in this window. "Skipped" are attackers it deliberately left alone.', 'df.en.c.decided': 'Decisions', 'df.en.c.written': 'Blocks written', 'df.en.c.dropped': 'Dropped by rate limit', 'df.en.c.already': 'Already blocked', 'df.en.recent': 'Recent decisions', 'df.en.recent.hint': 'The latest decisions, newest first.', 'df.en.recent.none': 'No decisions in this window.', 'df.en.col.time': 'Time', 'df.en.col.ip': 'Address', 'df.en.col.cc': 'Country', 'df.en.col.reason': 'Reason', 'df.en.col.score': 'Score', 'df.en.col.ttl': 'Duration', 'df.en.col.action': 'Action', 'df.en.col.src': 'Origin', 'df.en.act.ban': 'Blocked', 'df.en.act.would_ban': 'Would block', 'df.en.act.skip': 'Not blocked', 'df.en.act.unban': 'Unbanned', 'df.en.skip.operator_allow': 'Released by you', 'df.en.allows': 'Operator releases', 'df.en.allows.hint': 'Addresses you unbanned and asked not to block again for a while. The system will not block them until the time ends.', 'df.en.allows.none': 'No active releases.', 'df.en.allows.until': 'Until', 'df.en.allows.end': 'End release', 'df.en.allows.ended': 'Release ended', 'df.en.allows.err': 'Could not end the release.', 'df.en.allows.unwritable': 'The unban file is not writable, so unbanning will fail.', 'df.en.src.local': 'this server', 'df.en.src.peer': 'from {n}', 'df.en.skip.trusted': 'Trusted address (your own list)', 'df.en.skip.private': 'Private network (not on the internet)', 'df.en.skip.crawler': 'Verified search engine', 'df.en.skip.legit_visitor': 'Looks like a legitimate visitor', 'df.en.skip.peer': 'Another of your servers', 'df.en.reason.scanner-flood': 'Many vulnerability probes in a short time', 'df.en.reason.exploit-flood': 'Repeated exploit attempts', 'df.en.reason.web-bruteforce': 'Password guessing on a website', 'df.en.reason.wp-bruteforce': 'Password guessing on WordPress', 'df.en.reason.ssh-bruteforce': 'Password guessing on SSH', 'df.en.reason.rce': 'Attempt to run commands on the server', 'df.en.reason.path-traversal': 'Attempt to read files outside the site', 'df.en.reason.env-probe': 'Hunting for secret configuration files (.env)', 'df.en.reason.vcs-probe': 'Hunting for source code history (.git)', 'df.en.reason.webshell': 'Looking for or uploading a backdoor (webshell)', 'df.en.reason.sqli': 'Attempt to tamper with the database (SQL injection)', 'df.en.reason.log4shell': 'Log4Shell exploit attempt', 'df.en.reason.port-scan': 'Scanning many network ports on the server', 'df.en.reason.known-attacker': 'Known attacker returning (hostile verdict)', 'df.en.reason.neighbor-campaign': 'Part of a campaign: several neighbours in the same network range were already banned', 'df.en.error': 'Could not load the second firewall data.', 'df.fw.title': 'Firewall: inbound attempts', 'df.fw.hint': 'New connection attempts that reached this host from the internet, counted by the firewall before any ban drops them. What a provider firewall (for example a cloud security list) blocks earlier never gets here.', 'df.fw.lead': '{n} inbound attempts {range}', 'df.fw.lead.sub': 'The totals are exact (counters of the host kit). Ports and origins come from a sample of {r} of them.', 'df.fw.kpi.total': 'Attempts', 'df.fw.kpi.total.sub': '{n} per hour on average', 'df.fw.kpi.closed': 'To closed ports', 'df.fw.kpi.closed.sub': '{n} to ports nothing serves', 'df.fw.kpi.banned': 'From banned sources', 'df.fw.kpi.banned.sub': 'about {n} attempts; estimated from the sample', 'df.fw.kpi.ratio': 'Sampled', 'df.fw.kpi.ratio.sub': '{n} logged attempts of the total', 'df.fw.hourly': 'Attempts per hour', 'df.fw.hourly.closed': 'Closed ports', 'df.fw.hourly.open': 'Served ports', 'df.fw.ports': 'Top destination ports', 'df.fw.ports.hint': 'Sampled. A red bar is a port this host does not serve.', 'df.fw.asns': 'Top origin networks', 'df.fw.asns.hint': 'Sampled, by the ASN of the source address.', 'df.fw.ccs': 'Top origin countries', 'df.fw.ccs.hint': 'Sampled, by the country of the source address.', 'df.fw.sampled': 'Sampled: these details cover about {r} of the attempts; the totals above are exact.', 'df.fw.banned.note': 'Banned means the source was in a jail (fail2ban or Urutau) when its attempt was logged. Those attempts are dropped by the firewall and never count as new evidence against the address.', 'df.fw.none': 'No inbound telemetry yet', 'df.fw.none.sub': 'Install the host kit with "sudo sh deploy/host/install.sh --ingress" and let the probe send ingress.log and ingress.counters.', 'df.fw.nodata': 'No attempts counted in this window', 'df.fw.error': 'Could not load the firewall data.' }, 'pt-BR': { 'df.title': 'Defesa', 'df.lead.some': 'O fail2ban aplicou {n} bans {range}', 'df.lead.sub.ok': '{a} bans estão ativos. Poucos atacantes continuaram chegando depois do ban.', 'df.lead.sub.leak': '{a} bans estão ativos, mas {l} atacantes continuaram chegando depois de um ban ou da listagem.', 'df.lead.none': 'O fail2ban não baniu ninguém {range}', 'df.lead.none.sub': 'Nenhum evento de ban nesta janela. Se houve ataques, confira se o log do fail2ban está sendo lido.', 'df.kpi.active': 'Bans ativos', 'df.kpi.active.sub': '{n} bans na janela', 'df.kpi.ttb': 'Tempo até o ban', 'df.kpi.ttb.sub': 'mediana por episódio de ataque; 90% em até {p}', 'df.kpi.ttb.none': 'sem dados', 'df.kpi.cov': 'Cobertura da blocklist', 'df.kpi.cov.sub': '{n} endereços listados', 'df.kpi.leak': 'Vazamento', 'df.kpi.leak.sub': '{n} eventos depois do ban', 'df.bans': 'Bans por jail ao longo do tempo', 'df.jails': 'Bans por jail', 'df.jails.center': 'bans', 'df.users': 'Usuários SSH tentados', 'df.users.hint': 'Nomes com que os atacantes tentaram entrar. Vermelho: uma conta real sua.', 'df.users.none': 'Nenhuma falha de SSH nesta janela.', 'df.ssh.sum': '{f} falhas de {s} origens; {o} logins bem-sucedidos depois de falhas.', 'df.cov': 'Cobertura da blocklist', 'df.cov.hint': 'Parcela dos atacantes da janela que está na blocklist.', 'df.cov.label': 'dos atacantes listados', 'df.bl.size': '{n} endereços ({v4} IPv4, {v6} IPv6 /64)', 'df.bl.updated': 'última alteração {t}', 'df.bl.download': 'Baixar a blocklist', 'df.error': 'Não foi possível carregar os dados de defesa.', 'df.disabled': 'O registro de eventos está desligado', 'df.disabled.sub': 'A defesa é calculada a partir do registro de eventos; ative-o para ver esta página.', 'df.partial': 'Resultado parcial: o estudo atingiu o limite de tempo ou de tamanho.', 'df.admin': 'sua conta', 'df.en.title': 'Segundo firewall', 'df.en.hint': 'O Urutau também pode bloquear atacantes por conta própria, como uma rede de segurança ao lado do fail2ban.', 'df.en.mode': 'Modo', 'df.en.mode.off': 'Desligado', 'df.en.mode.observe': 'Só observando', 'df.en.mode.on': 'Ativo', 'df.en.mode.off.sub': 'O Urutau não bloqueia ninguém e não grava nada. A cobertura abaixo mostra o quanto você ganharia ao ligá-lo.', 'df.en.mode.observe.sub': 'O Urutau decide quem bloquearia e registra, mas não bloqueia ninguém. Use para conferir as decisões antes de confiar nelas.', 'df.en.mode.on.sub': 'O Urutau bloqueia sozinho os atacantes que reconhece, por tempo limitado.', 'df.en.mode.where': 'O modo é escolhido no deploy, pela variável URUTAU_ENFORCE (off, observe ou on). Não dá para mudá-lo por esta página.', 'df.en.how.title': 'Como ligar', 'df.en.how.body': 'Defina URUTAU_ENFORCE=observe no servidor e reinicie o Urutau. Acompanhe as decisões por alguns dias; quando estiverem certas, troque para on.', 'df.en.share': 'Compartilhamento entre hosts', 'df.en.share.on': 'ligado: os bloqueios são compartilhados com outros servidores', 'df.en.share.off': 'desligado: os bloqueios ficam só neste servidor', 'df.en.threshold': 'Bloqueia a partir da pontuação {n}', 'df.en.nolog.title': 'Os bloqueios não estão sendo salvos', 'df.en.nolog.body': 'O modo está ativo, mas o arquivo de bloqueios não pode ser gravado; na prática ninguém está sendo bloqueado. Confira as permissões da pasta onde o Urutau grava a blocklist.', 'df.en.lead': '{b} de {a} endereços atacantes foram bloqueados {range}', 'df.en.lead.sub': '{fw} pelo firewall do servidor, {ur} pelo Urutau, {wb} seriam bloqueados no modo observação e {un} passaram.', 'df.en.lead.none': 'Nenhum endereço atacante {range}', 'df.en.lead.none.sub': 'Nada a bloquear nesta janela.', 'df.en.cov': 'Quem foi bloqueado', 'df.en.cov.hint': 'Cada endereço atacante conta uma vez, pela primeira linha de defesa que o barrou.', 'df.en.cov.center': 'endereços', 'df.en.cov.fw': 'Bloqueado pelo firewall do servidor', 'df.en.cov.ur': 'Bloqueado pelo Urutau', 'df.en.cov.wb': 'Seria bloqueado (modo observação)', 'df.en.cov.un': 'Passou sem bloqueio', 'df.en.counts': 'O que o Urutau decidiu', 'df.en.counts.hint': 'Contagens desta janela. "Ignorados" são atacantes que ele deixou passar de propósito.', 'df.en.c.decided': 'Decisões', 'df.en.c.written': 'Bloqueios gravados', 'df.en.c.dropped': 'Descartados pelo limite de ritmo', 'df.en.c.already': 'Já estavam bloqueados', 'df.en.recent': 'Decisões recentes', 'df.en.recent.hint': 'As últimas decisões, da mais nova para a mais antiga.', 'df.en.recent.none': 'Nenhuma decisão nesta janela.', 'df.en.col.time': 'Hora', 'df.en.col.ip': 'Endereço', 'df.en.col.cc': 'País', 'df.en.col.reason': 'Motivo', 'df.en.col.score': 'Pontuação', 'df.en.col.ttl': 'Duração', 'df.en.col.action': 'Ação', 'df.en.col.src': 'Origem', 'df.en.act.ban': 'Bloqueado', 'df.en.act.would_ban': 'Bloquearia', 'df.en.act.skip': 'Não bloqueado', 'df.en.act.unban': 'Desbanido', 'df.en.skip.operator_allow': 'Liberado por você', 'df.en.allows': 'Liberações do operador', 'df.en.allows.hint': 'Endereços que você desbaniu e pediu para não bloquear de novo por um tempo. O sistema não os bloqueia até o prazo acabar.', 'df.en.allows.none': 'Nenhuma liberação ativa.', 'df.en.allows.until': 'Até', 'df.en.allows.end': 'Encerrar', 'df.en.allows.ended': 'Liberação encerrada', 'df.en.allows.err': 'Não foi possível encerrar a liberação.', 'df.en.allows.unwritable': 'O arquivo de desban não é gravável, então desbanir vai falhar.', 'df.en.src.local': 'este servidor', 'df.en.src.peer': 'vindo de {n}', 'df.en.skip.trusted': 'Endereço confiável (sua própria lista)', 'df.en.skip.private': 'Rede privada (fora da internet)', 'df.en.skip.crawler': 'Buscador verificado', 'df.en.skip.legit_visitor': 'Parece um visitante legítimo', 'df.en.skip.peer': 'Outro servidor seu', 'df.en.reason.scanner-flood': 'Muitas sondagens de vulnerabilidade em pouco tempo', 'df.en.reason.exploit-flood': 'Tentativas repetidas de exploração', 'df.en.reason.web-bruteforce': 'Tentativa de adivinhar senha num site', 'df.en.reason.wp-bruteforce': 'Tentativa de adivinhar senha no WordPress', 'df.en.reason.ssh-bruteforce': 'Tentativa de adivinhar senha no SSH', 'df.en.reason.rce': 'Tentativa de executar comandos no servidor', 'df.en.reason.path-traversal': 'Tentativa de ler arquivos fora do site', 'df.en.reason.env-probe': 'Caça a arquivos de configuração secretos (.env)', 'df.en.reason.vcs-probe': 'Caça ao histórico do código-fonte (.git)', 'df.en.reason.webshell': 'Procura ou envio de porta dos fundos (webshell)', 'df.en.reason.sqli': 'Tentativa de adulterar o banco de dados (injeção de SQL)', 'df.en.reason.log4shell': 'Tentativa de explorar o Log4Shell', 'df.en.reason.port-scan': 'Varredura de muitas portas de rede do servidor', 'df.en.reason.known-attacker': 'Atacante conhecido voltando (veredito hostil)', 'df.en.reason.neighbor-campaign': 'Parte de uma campanha: vários vizinhos da mesma faixa de rede já foram banidos', 'df.en.error': 'Não foi possível carregar os dados do segundo firewall.', 'df.fw.title': 'Firewall: tentativas de entrada', 'df.fw.hint': 'Tentativas novas de conexão que chegaram a este host pela internet, contadas pelo firewall antes de qualquer banimento descartá-las. O que um firewall do provedor (por exemplo uma lista de segurança na nuvem) barra antes nunca chega aqui.', 'df.fw.lead': '{n} tentativas de entrada {range}', 'df.fw.lead.sub': 'Os totais são exatos (contadores do kit do host). Portas e origens vêm de uma amostra de {r} delas.', 'df.fw.kpi.total': 'Tentativas', 'df.fw.kpi.total.sub': '{n} por hora em média', 'df.fw.kpi.closed': 'Para portas fechadas', 'df.fw.kpi.closed.sub': '{n} para portas em que nada escuta', 'df.fw.kpi.banned': 'De origens banidas', 'df.fw.kpi.banned.sub': 'cerca de {n} tentativas; estimado pela amostra', 'df.fw.kpi.ratio': 'Amostrado', 'df.fw.kpi.ratio.sub': '{n} tentativas registradas do total', 'df.fw.hourly': 'Tentativas por hora', 'df.fw.hourly.closed': 'Portas fechadas', 'df.fw.hourly.open': 'Portas com serviço', 'df.fw.ports': 'Portas de destino mais visadas', 'df.fw.ports.hint': 'Amostrado. Barra vermelha é uma porta que este host não serve.', 'df.fw.asns': 'Redes de origem mais frequentes', 'df.fw.asns.hint': 'Amostrado, pelo ASN do endereço de origem.', 'df.fw.ccs': 'Países de origem mais frequentes', 'df.fw.ccs.hint': 'Amostrado, pelo país do endereço de origem.', 'df.fw.sampled': 'Amostrado: estes detalhes cobrem cerca de {r} das tentativas; os totais acima são exatos.', 'df.fw.banned.note': 'Banida quer dizer que a origem estava numa jaula (fail2ban ou Urutau) quando a tentativa foi registrada. Essas tentativas são descartadas pelo firewall e nunca contam como nova evidência contra o endereço.', 'df.fw.none': 'Ainda sem telemetria de entrada', 'df.fw.none.sub': 'Instale o kit do host com "sudo sh deploy/host/install.sh --ingress" e deixe a sonda enviar ingress.log e ingress.counters.', 'df.fw.nodata': 'Nenhuma tentativa contada nesta janela', 'df.fw.error': 'Não foi possível carregar os dados do firewall.' } }); var el = U.el, t = U.t, nf = U.fmt.num; var root = null, seq = 0, alive = false, ctx = null, data = null; function clear(n) { while (n.firstChild) n.removeChild(n.firstChild); } function dur(s) { s = Math.round(s); if (s < 60) return s + ' s'; if (s < 3600) return Math.round(s / 60) + ' min'; if (s < 86400) return (s / 3600).toFixed(s < 36000 ? 1 : 0).replace(/\.0$/, '') + ' h'; return (s / 86400).toFixed(1).replace(/\.0$/, '') + ' d'; } function pctTxt(v) { return (v > 0 && v < 10 ? v.toFixed(1) : Math.round(v)) + '%'; } function series(d) { var step = d.step || 3600, from = d.from || 0; var end = Math.max(ctx && ctx.to ? ctx.to : Math.floor(Date.now() / 1000), 0); (d.bans || []).forEach(function (b) { if (b.t > end) end = b.t; }); var n = Math.min(MAX_BUCKETS, Math.floor((end - from) / step) + 1); if (n < 2) n = 2; var start = from; if (Math.floor((end - from) / step) + 1 > MAX_BUCKETS) start = Math.floor(end / step) * step - (MAX_BUCKETS - 1) * step; var jails = {}, order = []; (d.by_jail || []).forEach(function (j) { jails[j.jail] = new Array(n).fill(0); order.push(j.jail); }); (d.bans || []).forEach(function (b) { var i = Math.round((b.t - start) / step); if (i < 0 || i >= n) return; if (!jails[b.jail]) { jails[b.jail] = new Array(n).fill(0); order.push(b.jail); } jails[b.jail][i] += b.n; }); return { step: step, start: start, list: order.map(function (j) { return { key: j, label: j, values: jails[j] }; }) }; } function paint() { if (!root) return; clear(root); if (!data) { root.appendChild(el('div', { class: 'skeleton', style: { height: '8rem' } })); return; } if (!data.enabled) { root.appendChild(U.ui.empty(t('df.disabled'), t('df.disabled.sub'))); return; } var d = data, range = U.rangeLabel({ inline: true }), leak = d.leak || { ips: 0, events: 0 }; var bl = d.blocklist || {}, ssh = d.ssh || { users: [] }, ttb = d.ttb || {}; if (d.bans_total > 0) { var bad = leak.ips > 0 && leak.ips * 4 > d.bans_total; root.appendChild(U.ui.lead(t('df.lead.some', { n: nf(d.bans_total), range: range }), leak.ips > 0 ? t('df.lead.sub.leak', { a: nf(d.bans_active), l: nf(leak.ips) }) : t('df.lead.sub.ok', { a: nf(d.bans_active) }), bad ? 'danger' : 'ok')); } else { root.appendChild(U.ui.lead(t('df.lead.none', { range: range }), t('df.lead.none.sub'), 'danger')); } if (d.truncated) root.appendChild(el('p', { class: 'hint' }, t('df.partial'))); var kp = el('div', { class: 'grid-12 df-kpis' }); function k(node) { node.classList.add('span-3'); kp.appendChild(node); } k(U.ui.metric(t('df.kpi.active'), nf(d.bans_active), { sub: t('df.kpi.active.sub', { n: nf(d.bans_total) }) })); k(U.ui.metric(t('df.kpi.ttb'), ttb.n ? dur(ttb.median_s) : t('df.kpi.ttb.none'), ttb.n ? { sub: t('df.kpi.ttb.sub', { p: dur(ttb.p90_s) }) } : {})); var cov = bl.coverage_pct || 0; k(U.ui.metric(t('df.kpi.cov'), pctTxt(cov), { sub: t('df.kpi.cov.sub', { n: nf(bl.size || 0) }), tone: cov >= 70 ? 'ok' : cov >= 40 ? 'warn' : 'danger' })); k(U.ui.metric(t('df.kpi.leak'), nf(leak.ips), { sub: t('df.kpi.leak.sub', { n: nf(leak.events) }), tone: leak.ips ? 'warn' : 'ok' })); root.appendChild(kp); var grid = el('div', { class: 'grid-12' }); var sr = series(d); var ap = U.ui.panel({ title: t('df.bans'), cls: 'span-8' }); if (U.charts && U.charts.stackedArea && sr.list.length) ap.body.appendChild(U.charts.stackedArea(sr.list, sr.step, { start: sr.start, title: t('df.bans') })); else ap.body.appendChild(U.ui.empty(t('df.lead.none', { range: range }))); grid.appendChild(ap); var jp = U.ui.panel({ title: t('df.jails'), cls: 'span-4' }); var jd = (d.by_jail || []).filter(function (j) { return j.total > 0; }).map(function (j) { return { key: j.jail, label: j.jail, value: j.total }; }); if (U.charts && U.charts.donut) jp.body.appendChild(U.charts.donut(jd, { title: t('df.jails'), centerLabel: t('df.jails.center'), format: nf })); grid.appendChild(jp); var up = U.ui.panel({ title: t('df.users'), hint: t('df.users.hint'), cls: 'span-8' }); var users = ssh.users || []; if (!users.length) up.body.appendChild(U.ui.empty(t('df.users.none'))); else { up.body.appendChild(el('p', { class: 'hint df-sum' }, t('df.ssh.sum', { f: nf(ssh.fails), s: nf(ssh.sources), o: nf(ssh.ok_after_fail) }))); var rows = users.slice(0, 15).map(function (u) { var lit = u.user === 'admin' || u.user === 'root'; return { key: u.user, label: u.admin ? u.user + ' (' + t('df.admin') + ')' : u.user, value: u.n, color: u.admin ? '--danger' : lit ? '--warn' : '--viz-1' }; }); if (U.charts && U.charts.bars) up.body.appendChild(U.charts.bars(rows, { title: t('df.users'), format: nf })); } grid.appendChild(up); var gp = U.ui.panel({ title: t('df.cov'), hint: t('df.cov.hint'), cls: 'span-4' }); if (U.charts && U.charts.gauge) gp.body.appendChild(U.charts.gauge(Math.round(cov), 100, [{ at: 0, tone: 'danger' }, { at: 40, tone: 'warn' }, { at: 70, tone: 'ok' }], { label: t('df.cov.label'), format: function (v) { return v + '%'; } })); gp.body.appendChild(el('p', { class: 'df-bl' }, t('df.bl.size', { n: nf(bl.size || 0), v4: nf(bl.v4 || 0), v6: nf(bl.v6 || 0) }) + (bl.updated ? ' · ' + t('df.bl.updated', { t: U.fmt.ago(bl.updated) }) : ''))); gp.body.appendChild(el('a', { class: 'btn', href: '/api/v1/blocklist.txt?download=1&range=7d', download: 'urutau-blocklist.txt' }, t('df.bl.download'))); grid.appendChild(gp); root.appendChild(grid); } var enData = null, enSeq = 0, enBox = null; function ttlTxt(s) { return s > 0 ? dur(s) : '-'; } function reasonTxt(r) { if (!r) return '-'; var k = 'df.en.reason.' + r; if (t(k) !== k) return t(k); var parts = String(r).split(/[-_:]/); for (var i = 0; i < parts.length; i++) { var c = 'df.en.reason.' + parts[i]; if (t(c) !== c) return t(c) + ' (' + r + ')'; } return r; } function tbl(cols, rows) { var tb = el('tbody'); rows.forEach(function (r) { tb.appendChild(el('tr', null, r.map(function (c, i) { return el('td', { class: cols[i].cls || '' }, c); }))); }); return el('div', { class: 'df-scroll' }, el('table', { class: 'df-table' }, el('thead', null, el('tr', null, cols.map(function (c) { return el('th', { class: c.cls || '' }, c.label); }))), tb)); } function paintEnforce() { if (!enBox) return; clear(enBox); if (!enData) return; var e = enData, cv = e.coverage || {}, cn = e.counts || {}, sk = cn.skipped || {}, range = U.rangeLabel({ inline: true }); var mode = /^(off|observe|on)$/.test(e.mode) ? e.mode : 'off'; var head = el('div', { class: 'df-en-head' }); var mt = el('h2', { class: 'df-en-title' }, t('df.en.title')); if (U.help) U.help(mt, 'term.second_firewall'); head.appendChild(mt); head.appendChild(el('p', { class: 'hint' }, t('df.en.hint'))); enBox.appendChild(head); var grid = el('div', { class: 'grid-12' }); var mp = U.ui.panel({ title: t('df.en.mode'), cls: 'span-4', help: mode === 'observe' ? 'term.observe_mode' : null }); var tone = mode === 'on' ? 'ok' : mode === 'observe' ? 'info' : 'warn'; mp.body.appendChild(el('p', { class: 'df-mode' }, U.ui.badge(t('df.en.mode.' + mode), tone))); mp.body.appendChild(el('p', { class: 'df-en-p' }, t('df.en.mode.' + mode + '.sub'))); mp.body.appendChild(el('p', { class: 'hint' }, t('df.en.mode.where'))); var meta = el('p', { class: 'hint df-en-meta' }, t('df.en.threshold', { n: nf(e.threshold || 0) }) + ' · ' + t('df.en.share') + ': ' + (e.share === 'on' ? t('df.en.share.on') : t('df.en.share.off'))); if (U.help) U.help(meta, 'term.ban_ttl'); mp.body.appendChild(meta); if (mode === 'on' && e.log_writable === false) mp.body.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('df.en.nolog.title')), el('span', null, t('df.en.nolog.body')))); if (mode === 'off') { mp.body.appendChild(el('p', { class: 'df-en-how' }, el('strong', null, t('df.en.how.title') + ': '), t('df.en.how.body'))); } grid.appendChild(mp); var total = (cv.blocked_by_firewall || 0) + (cv.blocked_by_urutau || 0) + (cv.would_block || 0) + (cv.unblocked || 0); var cp = U.ui.panel({ title: t('df.en.cov'), hint: t('df.en.cov.hint'), cls: 'span-8' }); var rows = [ { key: 'fw', label: t('df.en.cov.fw'), value: cv.blocked_by_firewall || 0, color: '--ok' }, { key: 'ur', label: t('df.en.cov.ur'), value: cv.blocked_by_urutau || 0, color: '--info' }, { key: 'wb', label: t('df.en.cov.wb'), value: cv.would_block || 0, color: '--warn' }, { key: 'un', label: t('df.en.cov.un'), value: cv.unblocked || 0, color: '--danger' } ]; var blocked = (cv.blocked_by_firewall || 0) + (cv.blocked_by_urutau || 0); cp.body.appendChild(el('p', { class: 'df-en-sum' }, total ? t('df.en.lead', { b: nf(blocked), a: nf(cv.attack_ips || total), range: range }) : t('df.en.lead.none', { range: range }))); if (total) { cp.body.appendChild(el('p', { class: 'hint' }, t('df.en.lead.sub', { fw: nf(rows[0].value), ur: nf(rows[1].value), wb: nf(rows[2].value), un: nf(rows[3].value) }))); if (U.charts && U.charts.donut) { cp.body.appendChild(U.charts.donut(rows, { title: t('df.en.cov'), centerLabel: t('df.en.cov.center'), format: nf, colors: rows.map(function (r) { return r.color; }) })); if (U.help) { var lis = cp.body.querySelectorAll('.vz-legend li'); if (lis[2]) U.help(lis[2], 'term.observe_mode'); } } } else cp.body.appendChild(U.ui.empty(t('df.en.lead.none', { range: range }), t('df.en.lead.none.sub'))); grid.appendChild(cp); var np = U.ui.panel({ title: t('df.en.counts'), hint: t('df.en.counts.hint'), cls: 'span-12' }); var kp = el('div', { class: 'grid-12 df-kpis' }); function k(node) { node.classList.add('span-3'); kp.appendChild(node); } k(U.ui.metric(t('df.en.c.decided'), nf(cn.decided || 0))); k(U.ui.metric(t('df.en.c.written'), nf(cn.written || 0), { tone: 'ok' })); k(U.ui.metric(t('df.en.c.dropped'), nf(cn.dropped_rate || 0), { tone: cn.dropped_rate ? 'warn' : 'neutral' })); k(U.ui.metric(t('df.en.c.already'), nf(cn.already_blocked || 0))); np.body.appendChild(kp); var skl = el('ul', { class: 'df-skips' }); ['trusted', 'private', 'crawler', 'legit_visitor', 'peer', 'operator_allow'].forEach(function (key) { if (!sk[key]) return; skl.appendChild(el('li', null, el('span', { class: 'num' }, nf(sk[key])), ' ' + t('df.en.skip.' + key))); }); if (skl.firstChild) np.body.appendChild(skl); grid.appendChild(np); var rp = U.ui.panel({ title: t('df.en.recent'), hint: t('df.en.recent.hint'), cls: 'span-12', variant: 'list' }); var rec = e.recent || []; if (!rec.length) rp.body.appendChild(U.ui.empty(t('df.en.recent.none'))); else { var cols = [{ label: t('df.en.col.time') }, { label: t('df.en.col.ip'), cls: 'mono' }, { label: t('df.en.col.cc') }, { label: t('df.en.col.reason') }, { label: t('df.en.col.score'), cls: 'num' }, { label: t('df.en.col.ttl'), cls: 'num' }, { label: t('df.en.col.action') }, { label: t('df.en.col.src') }]; rp.body.appendChild(tbl(cols, rec.map(function (r) { var act = /^(ban|would_ban|skip|unban)$/.test(r.action) ? r.action : 'skip'; var actNode = el('span', { class: 'df-act' }, U.ui.badge(t('df.en.act.' + act), act === 'ban' ? 'ok' : act === 'would_ban' ? 'warn' : 'neutral')); if (act === 'ban') actNode.appendChild(el('button', { type: 'button', class: 'btn btn-sm df-unban', onclick: function () { U.unbanDialog(r.ip, loadEnforce); } }, t('unban.btn'))); if (act === 'skip' && r.skip_reason) { var sk2 = 'df.en.skip.' + r.skip_reason; actNode.appendChild(el('small', { class: 'df-skipwhy' }, t(sk2) !== sk2 ? t(sk2) : r.skip_reason)); } var peer = String(r.src || 'local'); var src = peer.indexOf('peer:') === 0 ? t('df.en.src.peer', { n: peer.slice(5) }) : t('df.en.src.local'); return [el('span', { class: 'df-nowrap' }, U.fmt.clock(r.t)), el('a', { href: U.href('ip', [r.ip]) }, r.ip), (r.cc ? U.fmt.flag(r.cc) + ' ' : '') + (r.cc || '-'), reasonTxt(r.reason), nf(r.score || 0), ttlTxt(r.ttl || 0), actNode, src]; }))); } grid.appendChild(rp); var ap = U.ui.panel({ title: t('df.en.allows'), hint: t('df.en.allows.hint'), cls: 'span-12', variant: 'list' }); var als = e.allows || []; if (e.unban_log_writable === false) ap.body.appendChild(el('p', { class: 'state-warn' }, t('df.en.allows.unwritable'))); if (!als.length) ap.body.appendChild(U.ui.empty(t('df.en.allows.none'))); else { ap.body.appendChild(tbl([{ label: t('df.en.col.ip'), cls: 'mono' }, { label: t('df.en.allows.until') }, { label: '' }], als.map(function (a) { return [el('a', { href: U.href('ip', [a.ip]) }, a.ip), U.fmt.date ? U.fmt.date(a.until) : String(a.until), el('button', { type: 'button', class: 'btn btn-sm', onclick: function () { U.apiSend('DELETE', '/api/v1/enforce/allow?ip=' + encodeURIComponent(a.ip)).then(function () { U.toast(t('df.en.allows.ended')); loadEnforce(); }, function () { U.toast(t('df.en.allows.err')); }); } }, t('df.en.allows.end'))]; }))); } grid.appendChild(ap); enBox.appendChild(grid); } function loadEnforce() { var my = ++enSeq; U.api('/api/v1/enforce', Object.assign(U.rangeParams(), ctx && ctx.host && ctx.host !== 'all' ? { host: ctx.host } : {})).then(function (d) { if (!alive || my !== enSeq) return; enData = d; paintEnforce(); }).catch(function () { if (!alive || my !== enSeq || enData || !enBox) return; clear(enBox); enBox.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('df.en.error')))); }); } var fwData = null, fwSeq = 0, fwBox = null; function ratioTxt(r) { var v = (r || 0) * 100; return (v > 0 && v < 10 ? v.toFixed(1) : Math.round(v)) + '%'; } function paintFirewall() { if (!fwBox) return; clear(fwBox); if (!fwData) return; var d = fwData, tt = d.totals || {}, sm = d.sample || {}, range = U.rangeLabel({ inline: true }); var head = el('div', { class: 'df-en-head' }); head.appendChild(el('h2', { class: 'df-en-title' }, t('df.fw.title'))); head.appendChild(el('p', { class: 'hint' }, t('df.fw.hint'))); fwBox.appendChild(head); if (!d.enabled) { fwBox.appendChild(U.ui.empty(t('df.fw.none'), t('df.fw.none.sub'))); return; } if (!tt.attempts) { fwBox.appendChild(U.ui.empty(t('df.fw.nodata'))); return; } fwBox.appendChild(U.ui.lead(t('df.fw.lead', { n: nf(tt.attempts), range: range }), t('df.fw.lead.sub', { r: ratioTxt(sm.ratio) }), 'info')); var kp = el('div', { class: 'grid-12 df-kpis' }); function k(node) { node.classList.add('span-3'); kp.appendChild(node); } k(U.ui.metric(t('df.fw.kpi.total'), nf(tt.attempts), { sub: t('df.fw.kpi.total.sub', { n: nf(Math.round(tt.per_hour || 0)) }) })); k(U.ui.metric(t('df.fw.kpi.closed'), pctTxt(tt.closed_pct || 0), { sub: t('df.fw.kpi.closed.sub', { n: nf(tt.closed || 0) }) })); k(U.ui.metric(t('df.fw.kpi.banned'), pctTxt(sm.banned_pct || 0), { sub: t('df.fw.kpi.banned.sub', { n: nf(sm.banned_est || 0) }), tone: (sm.banned_pct || 0) >= 50 ? 'warn' : 'neutral' })); k(U.ui.metric(t('df.fw.kpi.ratio'), ratioTxt(sm.ratio), { sub: t('df.fw.kpi.ratio.sub', { n: nf(sm.logged || 0) }) })); fwBox.appendChild(kp); var grid = el('div', { class: 'grid-12' }); var hours = d.hourly || []; var hp = U.ui.panel({ title: t('df.fw.hourly'), cls: 'span-12' }); if (U.charts && U.charts.stackedArea && hours.length) { var step = 3600, start = hours[0].t, last = hours[hours.length - 1].t; var n = Math.min(MAX_BUCKETS, Math.floor((last - start) / step) + 1); if (n < 2) { n = 2; } var cl = new Array(n).fill(0), op = new Array(n).fill(0); hours.forEach(function (h) { var i = Math.round((h.t - start) / step); if (i >= 0 && i < n) { cl[i] += h.closed; op[i] += h.open; } }); hp.body.appendChild(U.charts.stackedArea([{ key: 'closed', label: t('df.fw.hourly.closed'), values: cl }, { key: 'open', label: t('df.fw.hourly.open'), values: op }], step, { start: start, title: t('df.fw.hourly') })); } else hp.body.appendChild(U.ui.empty(t('df.fw.nodata'))); grid.appendChild(hp); function barsPanel(title, hint, rows, cls) { var p = U.ui.panel({ title: title, hint: hint, cls: cls }); if (!rows.length) p.body.appendChild(U.ui.empty(t('df.fw.nodata'))); else if (U.charts && U.charts.bars) p.body.appendChild(U.charts.bars(rows, { title: title, format: nf })); grid.appendChild(p); } barsPanel(t('df.fw.ports'), t('df.fw.ports.hint'), (d.ports || []).slice(0, 10).map(function (p) { return { key: p.proto + '/' + p.port, label: p.proto + '/' + p.port, value: p.n, color: p.served ? '--viz-1' : '--danger' }; }), 'span-4'); barsPanel(t('df.fw.asns'), t('df.fw.asns.hint'), (d.asns || []).slice(0, 10).map(function (a) { return { key: a.asn, label: a.asn + (a.org ? ' ' + a.org : ''), value: a.n }; }), 'span-4'); barsPanel(t('df.fw.ccs'), t('df.fw.ccs.hint'), (d.countries || []).slice(0, 10).map(function (c) { return { key: c.cc, label: (U.fmt.flag ? U.fmt.flag(c.cc) + ' ' : '') + c.cc, value: c.n }; }), 'span-4'); fwBox.appendChild(grid); fwBox.appendChild(el('p', { class: 'hint' }, t('df.fw.sampled', { r: ratioTxt(sm.ratio) }))); fwBox.appendChild(el('p', { class: 'hint' }, t('df.fw.banned.note'))); } function loadFirewall() { var my = ++fwSeq; U.api('/api/v1/ingress', Object.assign(U.rangeParams(), ctx && ctx.host && ctx.host !== 'all' ? { host: ctx.host } : {})).then(function (d) { if (!alive || my !== fwSeq) return; fwData = d; paintFirewall(); }).catch(function () { if (!alive || my !== fwSeq || fwData || !fwBox) return; clear(fwBox); fwBox.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('df.fw.error')))); }); } function load() { loadEnforce(); loadFirewall(); var my = ++seq; U.api('/api/v1/defense', Object.assign(U.rangeParams(), ctx && ctx.host && ctx.host !== 'all' ? { host: ctx.host } : {})).then(function (d) { if (!alive || my !== seq) return; data = d; paint(); }).catch(function () { if (!alive || my !== seq || data) return; clear(root); root.appendChild(el('div', { class: 'state-error' }, el('strong', null, t('df.error')))); }); } U.registerPage({ id: 'defense', group: 'operate', titleKey: 'df.title', icon: '', mount: function (node, cx) { root = el('div', { class: 'df-page' }); node.appendChild(root); enBox = el('div', { class: 'df-page df-en' }); node.appendChild(enBox); fwBox = el('div', { class: 'df-page df-en' }); node.appendChild(fwBox); ctx = cx; alive = true; data = null; enData = null; fwData = null; paint(); load(); }, update: function (cx) { ctx = cx; load(); }, refresh: function () { load(); }, unmount: function () { alive = false; seq++; enSeq++; fwSeq++; if (root && root.parentNode) root.parentNode.removeChild(root); if (enBox && enBox.parentNode) enBox.parentNode.removeChild(enBox); if (fwBox && fwBox.parentNode) fwBox.parentNode.removeChild(fwBox); root = null; enBox = null; fwBox = null; data = null; enData = null; fwData = null; } }); return true; } if (!boot()) { var tries = 0, iv = setInterval(function () { if (boot() || ++tries > 50) clearInterval(iv); }, 100); } })();