Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 30 additions & 4 deletions Install-pfSenseBackup.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -218,7 +218,7 @@ $LogsTaskName = "pfSense Logs - $Name"
$SshKeyFile = Join-Path $SecDir "$Name.ssh_ed25519"
$KnownHosts = Join-Path $SecDir "$Name.known_hosts"
$KeyLineFile = Join-Path $CfgDir "$Name-chave-ssh-pfsense.txt"
$ToolVersion = '2.1.2' # versao do pfSense-Backup
$ToolVersion = '2.1.3' # versao do pfSense-Backup
$SchemaVersion = 3 # versao do formato do config\<Nome>.json (1 = sem o campo; 3 = logs pelo SSH)
$DefaultLogSources = 'sistema,portal,openvpn,ipsec,dhcp,dns,gateways,firewall,pfblockerng,suricata,squid,squidguard,dhcp-concessoes'
$DefaultSshSources = 'sistema,autenticacao,portal,openvpn,ipsec,dhcp,dns,gateways,firewall,pfblockerng,suricata,squid,squidguard,dhcp-concessoes'
Expand Down Expand Up @@ -368,13 +368,25 @@ if (Test-Path $CfgFile) { $existing = Get-Content $CfgFile -Raw | ConvertFrom-Js
$oldSchema = 0
if ($existing) { $oldSchema = 1; if ($existing.SchemaVersion) { $oldSchema = [int]$existing.SchemaVersion } }
$upgrading = ($oldSchema -ge 1 -and $oldSchema -lt $SchemaVersion)
# Versao de correcao (mesmo formato de perfil, programa mais novo): atualiza sem perguntar nada.
$oldTool = ''; if ($existing -and $existing.ToolVersion) { $oldTool = [string]$existing.ToolVersion }
$patching = $false
if (-not $upgrading -and $oldSchema -eq $SchemaVersion -and $oldTool) {
try { $patching = ([version]$oldTool -lt [version]$ToolVersion) } catch { $patching = $false }
}
if ($upgrading) {
Step "Atualizacao: perfil '$Name' da versao $oldSchema encontrado -> versao $SchemaVersion ($ToolVersion)"
Ok 'mantidos sem perguntar: firewall, porta, usuario, chave, senha, certificado fixado, horario, retencao e tarefa do backup'
Ok 'sera feito: copiar os scripts novos, completar o config JSON e perguntar SO o que e novo (logs e relatorio)'
} elseif ($patching) {
Step "Atualizacao: pfSense-Backup $oldTool -> $ToolVersion (perfil '$Name', mesmo formato: versao $oldSchema)"
Ok 'mantidos sem perguntar: TODOS os valores do perfil (firewall, portas, horario, retencao, logs, SSH, chaves e senhas)'
Ok 'sera feito: copiar os scripts novos, recriar as tarefas e testar. Para mudar algum valor, rode de novo depois (ai ele pergunta)'
} elseif ($existing) {
Ok "perfil '$Name' ja esta na versao $oldSchema - reconfigurando (ENTER mantem cada valor)"
}
# Sem perguntas: atualizacao de formato (so pergunta o que e novo) ou de correcao.
$quiet = $upgrading -or $patching
if (-not $FwHost -and $existing) { $FwHost = $existing.Host }
if (-not $PSBoundParameters.ContainsKey('User') -and $existing -and $existing.User) { $User = $existing.User }
if (-not $PSBoundParameters.ContainsKey('Port') -and $existing -and $existing.Port) { $Port = [int]$existing.Port }
Expand All @@ -394,7 +406,7 @@ if ($User -in @('admin', 'root')) {
# porta nao veio na linha de comando (-Port), pergunta mostrando o padrao entre
# colchetes: 443 num cadastro novo, ou a porta ja salva no perfil. ENTER mantem.
# Com -Port ou -Yes nao pergunta nada (bom para automacao).
if (-not $PSBoundParameters.ContainsKey('Port') -and -not $Yes -and -not $upgrading) {
if (-not $PSBoundParameters.ContainsKey('Port') -and -not $Yes -and -not $quiet) {
Write-Host ''
Write-Host ' PORTA DA WebGUI DO pfSENSE' -ForegroundColor Yellow
Write-Host ' --------------------------'
Expand Down Expand Up @@ -425,7 +437,7 @@ function Read-Valor([string]$Rotulo, [string]$Atual, [scriptblock]$Valido, [stri
Warn $Ajuda
}
}
$perguntaAgenda = -not $Yes -and -not $upgrading -and -not ($PSBoundParameters.ContainsKey('Time') -and
$perguntaAgenda = -not $Yes -and -not $quiet -and -not ($PSBoundParameters.ContainsKey('Time') -and
$PSBoundParameters.ContainsKey('KeepDays') -and $PSBoundParameters.ContainsKey('MinKeep'))
if ($perguntaAgenda) {
Write-Host ''
Expand Down Expand Up @@ -568,7 +580,7 @@ if ($LightSquidUrl -and $logsOn) { Ok "LightSquid: $LightSquidUrl" }
if ($reportOn) { Ok 'relatorio de auditoria: ligado (auditoria\<Nome>\ a cada backup que muda a configuracao)' }

# ---------------------- 0. pre-requisito no pfSense -------------------
if (-not $Yes -and -not $upgrading -and (-not $existing -or $UpdatePassword -or $PSBoundParameters.ContainsKey('User'))) {
if (-not $Yes -and -not $quiet -and (-not $existing -or $UpdatePassword -or $PSBoundParameters.ContainsKey('User'))) {
Write-Host ''
Write-Host ' PRE-REQUISITO NO pfSense (obrigatorio)' -ForegroundColor Yellow
Write-Host ' ---------------------------------------'
Expand Down Expand Up @@ -868,6 +880,7 @@ if ($wc) {
}

# ------------- 5b. chave SSH e chave do pfSense (logs pelo SSH) -------------
$linhaAntiga = ''; $chaveIgual = $false
if ($logsOn -and $transport -eq 'ssh') {
Step 'Chave SSH deste servidor'
if (-not (Test-Path $SshKeyFile)) {
Expand Down Expand Up @@ -908,7 +921,20 @@ if ($logsOn -and $transport -eq 'ssh') {

$linha = (& powershell.exe -NoProfile -ExecutionPolicy Bypass -File $LogsEngine -Name $Name -BaseDir $BaseDir -PrintKeyFor "$SshKeyFile.pub" -KeyFrom $SshFrom) -join ''
if ($linha -notmatch '^restrict,from=') { throw "nao consegui montar a linha da chave: $linha" }
$linhaAntiga = ''
if (Test-Path $KeyLineFile) { $linhaAntiga = ([string](Get-Content $KeyLineFile -Raw)).Trim() }
Set-Content -Path $KeyLineFile -Value $linha -Encoding ASCII
$chaveIgual = ($linhaAntiga -and $linhaAntiga -eq $linha.Trim() -and $existing -and [string]$existing.LogTransport -eq 'ssh')
}
if ($logsOn -and $transport -eq 'ssh' -and $chaveIgual) {
Ok 'linha da chave no pfSense: nao mudou nesta versao, nada a fazer no pfSense'
} elseif ($logsOn -and $transport -eq 'ssh') {
if ($linhaAntiga) {
Write-Host ''
Write-Host ' ATENCAO: A LINHA DA CHAVE MUDOU NESTA VERSAO' -ForegroundColor Red
Write-Host ' Troque a linha antiga pela nova no pfSense (passo 1 abaixo). Ate trocar,'
Write-Host ' a verificacao dos logs falha - o backup continua normal.'
}
Write-Host ''
Write-Host ' PRE-REQUISITO DOS LOGS PELO SSH NO pfSense' -ForegroundColor Yellow
Write-Host ' -----------------------------------------'
Expand Down
16 changes: 14 additions & 2 deletions Logs-pfSense.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -934,6 +934,16 @@ function Sync-SshLog([string]$Source, [string]$Category, [string]$Path, $ByPath,
if ($KeepLines -and $kept.Count -gt 0) { Add-VisitorRecords ([string[]]$kept.ToArray()) }
}

function Get-XmlText($Node, [string]$Child) {
# Valor de um filho do config.xml como texto. Campo gravado como CDATA (comum no
# descr) volta como XmlElement no PowerShell: [string] daria "System.Xml.XmlElement".
if ($null -eq $Node -or $Node -is [string]) { return '' }
$v = $Node.$Child
if ($null -eq $v) { return '' }
if ($v -is [Xml.XmlElement]) { return $v.InnerText.Trim() }
return ([string]$v).Trim()
}

function Get-SuricataNames {
# suricata_<interface real><uuid> -> nome da interface (LAN, VISITANTES), pelo config.xml do ultimo backup.
$map = @{}
Expand All @@ -944,9 +954,11 @@ function Get-SuricataNames {
$x = New-Object Xml.XmlDocument; $x.Load($bk[0].FullName)
foreach ($r in @($x.pfsense.installedpackages.suricata.rule)) {
if ($null -eq $r -or $r -is [string]) { continue }
$ifk = [string]$r.interface; $i = $x.pfsense.interfaces.$ifk
$ifk = Get-XmlText $r 'interface'; if (-not $ifk) { continue }
$i = $x.pfsense.interfaces.$ifk
if ($null -eq $i -or $i -is [string]) { continue }
$map["suricata_$($i.if)$($r.uuid)"] = [string]$i.descr
$nome = Get-XmlText $i 'descr'; if (-not $nome) { $nome = $ifk.ToUpper() }
$map["suricata_$(Get-XmlText $i 'if')$(Get-XmlText $r 'uuid')"] = $nome
}
} catch {}
return $map
Expand Down
11 changes: 11 additions & 0 deletions docs/atualizacao.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,16 @@ Ele identifica a versão do perfil pelo campo `SchemaVersion` do `config\<Nome>.
| Tarefa do backup | recriada com os mesmos valores |
| Verificação do usuário e backup de teste | feitos, como numa instalação |

### Versão de correção (mesmo formato de perfil)

Quando muda só o programa e não o formato do perfil (por exemplo, da 2.1.2 para a 2.1.3), o instalador **não pergunta nada**: mantém todos os valores, copia os scripts, recria as tarefas e testa.

```
==> Atualizacao: pfSense-Backup 2.1.2 -> 2.1.3 (perfil 'FWCLIENTE', mesmo formato: versao 3)
```

No modo SSH ele compara a linha da chave com a da versão anterior. Se for igual, avisa que **não há nada a fazer no pfSense**. Se mudou, mostra em vermelho que a linha precisa ser trocada no User Manager.

Rodar de novo um perfil **já atualizado** funciona como antes: o instalador mostra cada valor atual entre colchetes, e ENTER mantém.

## Sem perguntas (vários servidores)
Expand All @@ -51,3 +61,4 @@ Rodar de novo um perfil **já atualizado** funciona como antes: o instalador mos
| 2.0.0 | `2` | [Relatório de auditoria](auditoria.md), [coleta de logs](logs.md) (com a planilha de visitantes e o LightSquid) e atualização sem refazer o processo |
| 2.1.0 | `3` | Logs **pelo SSH com chave travada**: completos (inclusive firewall e autenticação), sem lacuna e quase sem peso no pfSense. Suricata por interface. Na atualização da 2.0, o instalador pergunta só o modo (SSH ou WebGUI) |
| 2.1.2 | `3` | Correções no Windows Server 2016 (PowerShell 5.1) e no pfSense (shell `tcsh`). Quem já instalou a 2.1.x: rodar o instalador de novo e **trocar a chave** no User Manager pela linha nova de `config\<Nome>-chave-ssh-pfsense.txt` |
| 2.1.3 | `3` | Suricata: cada interface na sua pasta (`descr` em CDATA no `config.xml` virava `System.Xml.XmlElement`). Atualização de correção sem perguntas, e aviso se a linha da chave mudou |
7 changes: 4 additions & 3 deletions tests/Test-Logs.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ Cenario 'mais linhas que o pedido vira AVISO de lacuna' {
# ------------------------------------------------------------ modo SSH
Write-Host '13) Modo SSH (chave travada, comando forcado de verdade)'
$sw = Join-Path $WorkDir 'ssh'; $root = Join-Path $sw 'pfsense'
foreach ($d in @('var/log/arquivo', 'var/log/pfblockerng', 'var/log/suricata/suricata_igb033667', 'var/squidGuard/log', 'var/dhcpd/var/db', 'secrets', 'backups/SSHT')) {
foreach ($d in @('var/log/arquivo', 'var/log/pfblockerng', 'var/log/suricata/suricata_igb033667', 'var/log/suricata/suricata_igb0.2052418', 'var/squidGuard/log', 'var/dhcpd/var/db', 'secrets', 'backups/SSHT')) {
New-Item -ItemType Directory -Force (Join-Path $root $d), (Join-Path $sw $d) | Out-Null
}
function Hoje([int]$seg) { $d = (Get-Date).AddSeconds(-$seg); return ($d.ToString('MMM ', [Globalization.CultureInfo]::InvariantCulture) + $d.Day.ToString().PadLeft(2) + $d.ToString(' HH:mm:ss')) }
Expand All @@ -161,9 +161,10 @@ Escreve 'var/log/portalauth.log' @("$(Hoje 200) fw logportalauth[9]: Zone: visit
Escreve 'var/log/filter.log' @(1..6 | ForEach-Object { "$(Hoje (100 - $_)) fw filterlog[5]: 5,,,1000000103,igb0,match,block,in,4,0x0,,64,1,0,none,6,tcp,60,10.0.0.$_,8.8.8.8,5000,443,0,S,1,,64240,,mss" })
Escreve 'var/log/pfblockerng/ip_block.log' @('Nov 20 10:00:01,a', 'Nov 20 10:00:02,b', 'Nov 20 10:00:03,c')
Escreve 'var/log/suricata/suricata_igb033667/alerts.log' @("$((Get-Date).ToString('MM/dd/yyyy-HH:mm:ss')).1 [**] [1:1:1] ET teste [**] {TCP} 1.2.3.4:1 -> 172.16.10.5:80")
Escreve 'var/log/suricata/suricata_igb0.2052418/alerts.log' @("$((Get-Date).ToString('MM/dd/yyyy-HH:mm:ss')).2 [**] [1:2:1] ET visitante [**] {TCP} 10.10.30.9:1 -> 5.6.7.8:80", "$((Get-Date).ToString('MM/dd/yyyy-HH:mm:ss')).3 [**] [1:3:1] ET visitante 2 [**] {TCP} 10.10.30.9:2 -> 5.6.7.8:80")
Escreve 'var/squidGuard/log/block.log' @("$((Get-Date).ToString('yyyy-MM-dd HH:mm:ss')) [1] Request(default/adult/-) http://x.com/ 172.16.10.9/- - GET REDIRECT")
Escreve 'var/dhcpd/var/db/dhcpd.leases' @('lease 172.16.10.50 {', ' starts 4 2026/11/20 13:00:01;', ' ends 4 2026/11/20 15:00:01;', ' binding state active;', ' hardware ethernet aa:bb:cc:dd:ee:50;', ' client-hostname "PC-RH";', '}')
Escreve 'backups/SSHT/config-SSHT-2026-11-20_0300.xml' @('<?xml version="1.0"?><pfsense><interfaces><lan><if>igb0</if><descr>LAN</descr></lan></interfaces><installedpackages><suricata><rule><interface>lan</interface><uuid>33667</uuid></rule></suricata></installedpackages></pfsense>')
Escreve 'backups/SSHT/config-SSHT-2026-11-20_0300.xml' @('<?xml version="1.0"?><pfsense><interfaces><lan><if>igb0</if><descr><![CDATA[LAN]]></descr></lan><opt3><if>igb0.20</if><descr><![CDATA[VISITANTES]]></descr></opt3></interfaces><installedpackages><suricata><rule><interface>lan</interface><uuid>33667</uuid><descr><![CDATA[LAN]]></descr></rule><rule><interface>opt3</interface><uuid>52418</uuid><descr><![CDATA[VISITANTES - scan e ataques]]></descr></rule></suricata></installedpackages></pfsense>')
Copy-Item (Join-Path $root 'backups/SSHT/config-SSHT-2026-11-20_0300.xml') (Join-Path $sw 'backups/SSHT/')

. (Join-Path $repo 'Logs-pfSense.ps1') -Name 'SSHT' -BaseDir $sw
Expand Down Expand Up @@ -208,7 +209,7 @@ $CheckOnly = $false
Cenario 'primeira coleta: tudo, inclusive firewall e autenticacao' {
$script:Warnings.Clear(); $script:Counts.Clear()
Invoke-LogCollection | Out-Null
$esp = @{ 'sistema' = 4; 'autenticacao' = 1; 'portal-visitantes' = 1; 'firewall' = 6; 'pfblockerng/ip_block' = 3; 'suricata/LAN/alertas' = 1; 'squidguard-bloqueios' = 1 }
$esp = @{ 'sistema' = 4; 'autenticacao' = 1; 'portal-visitantes' = 1; 'firewall' = 6; 'pfblockerng/ip_block' = 3; 'suricata/LAN/alertas' = 1; 'suricata/VISITANTES/alertas' = 2; 'squidguard-bloqueios' = 1 }
foreach ($k in $esp.Keys) {
$n = Linhas (ArqSsh $k)
if ($n -ne $esp[$k]) {
Expand Down
Loading