From d83cb6340189e05e6a052c7f645b5cb9d8cf29cd Mon Sep 17 00:00:00 2001 From: Paulo Victor T Silva Date: Tue, 17 Nov 2026 17:59:28 -0300 Subject: [PATCH] =?UTF-8?q?fix(usb):=20gatilho=20com=20repeti=C3=A7=C3=A3o?= =?UTF-8?q?=20al=C3=A9m=20do=20RestartCount,=20icacls=20por=20caminho=20ab?= =?UTF-8?q?soluto,=20ACL=20dos=20filhos=20conferida=20por=20SDDL=20e=20avi?= =?UTF-8?q?so=20de=20Windows\Temp=20(seguimento=20do=20Crivo=20no=20#91)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/usb.md | 6 +- internal/usb/apply.go | 4 +- internal/usb/seguimento_crivo_test.go | 114 ++++++++++++++++++++++++++ internal/usb/windows.go | 75 +++++++++++++++-- 4 files changed, 189 insertions(+), 10 deletions(-) create mode 100644 internal/usb/seguimento_crivo_test.go diff --git a/docs/usb.md b/docs/usb.md index ecb0a46..113d7b8 100644 --- a/docs/usb.md +++ b/docs/usb.md @@ -102,7 +102,7 @@ plano diz que ele ficou fora da lista mas que a política **não o bloquearia**. 4. **backup**: `usb-backup.json` (atômico) com SHA-256 do conteúdo, de cada alvo da lista fechada (inclusive "não existia"), e `usb-restrictions-backup.reg` (com hash) quando a chave já existia; relido e comparado com o gravado; 5. cópia do binário na pasta protegida (hash da cópia = hash do original); -6. **tarefa de reversão** criada (SYSTEM, execução única, `StartWhenAvailable`, **até 3 novas tentativas, 1 por minuto**, se o programa sair com erro; comando fixo) e **conferida**: existe, habilitada, programa e argumento **exatos**, +6. **tarefa de reversão** criada (SYSTEM, execução única, `StartWhenAvailable`, **até 3 novas tentativas, 1 por minuto**, se o programa sair com erro, E o gatilho repete a cada minuto por 30 min (não depende de o Agendador tratar a saída com erro como falha; o desfazer apaga a tarefa ao concluir e a repetição para sozinha; o `reverter` é idempotente); comando fixo) e **conferida**: existe, habilitada, programa e argumento **exatos**, SYSTEM, próximo disparo no futuro e dentro do prazo (com folga de 2 min); 7. **só então** as chaves, na ordem segura: `AllowDenyLayered` primeiro (sem ela a negação venceria a liberação), a lista de IDs, e a negação **por último**; 8. releitura: cada entrada tem de estar como gravada. @@ -126,10 +126,10 @@ O Apply seguinte apaga o rastro velho. Se a reversão falhar, o backup e a taref "confirmado" se a política ainda está aplicada. **Preparação.** A árvore do registro é lida de novo logo antes da primeira escrita; se mudou na janela (GPO/MDM), o aplicar aborta sem escrever. Se o toolkit -foi iniciado de uma pasta que usuário comum grava (fora de Program Files e Windows), o plano avisa: a tarefa executa uma CÓPIA dele. +foi iniciado de uma pasta que usuário comum grava (fora de Program Files e Windows\System32; Windows\Temp e Windows\Tasks contam como graváveis), o plano avisa: a tarefa executa uma CÓPIA dele. **Pasta protegida já existente.** `C:\ProgramData\toolkit` pode ter sido criada por um usuário comum antes. Além do dono e da ACL da pasta, o toolkit refaz a ACL -e o dono de cada FILHO (`icacls /reset` e `/setowner`, nunca na pasta raiz), recusa link (ponto de reparse) dentro dela e apaga um `.reg` velho antes do export. +e o dono de cada FILHO (`icacls /reset` e `/setowner`, por caminho ABSOLUTO `C:\Windows\System32\icacls.exe`, nunca pelo PATH e nunca na pasta raiz) e RELÊ a ACL de cada filho por SDDL (dono Administradores; só SYSTEM e Administradores com FullControl herdado): qualquer outra coisa recusa o aplicar antes de escrever (a conferência cobre o primeiro nível da pasta), recusa link (ponto de reparse) dentro dela e apaga um `.reg` velho antes do export. Antes de importar o `.reg` no roteiro manual, confira o SHA-256 dele com o que está no `usb-backup.json` (`Get-FileHash`). ## Desfazer garantido diff --git a/internal/usb/apply.go b/internal/usb/apply.go index 7a4e4fd..a3da146 100644 --- a/internal/usb/apply.go +++ b/internal/usb/apply.go @@ -30,10 +30,10 @@ type ApplyResult struct { } // ExeFolderWarning avisa quando o toolkit em execução está numa pasta que usuário comum pode gravar: é a cópia DELE que -// a tarefa de reversão (SYSTEM) executa daqui a minutos. Vazio = pasta de administrador (Program Files, Windows). +// a tarefa de reversão (SYSTEM) executa daqui a minutos. Vazio = pasta de administrador (Program Files, Windows\System32; Windows\Temp e Windows\Tasks são graváveis por usuário comum). func ExeFolderWarning(exePath string) string { p := strings.ToLower(strings.ReplaceAll(exePath, "/", `\`)) - for _, ok := range []string{`c:\program files\`, `c:\program files (x86)\`, `c:\windows\`} { + for _, ok := range []string{`c:\program files\`, `c:\program files (x86)\`, `c:\windows\system32\`} { if strings.HasPrefix(p, ok) { return "" } diff --git a/internal/usb/seguimento_crivo_test.go b/internal/usb/seguimento_crivo_test.go new file mode 100644 index 0000000..2d3d12e --- /dev/null +++ b/internal/usb/seguimento_crivo_test.go @@ -0,0 +1,114 @@ +package usb + +import ( + "context" + "strings" + "testing" +) + +// Seguimento da revisão do Crivo no #91 (delta de68760). + +// 1) A reversão não pode depender só do RestartCount (o Agendador pode não tratar saída != 0 como falha): o gatilho +// também repete a cada minuto por 30 min; o Undo apaga a tarefa ao concluir, então a repetição para sozinha. +func TestArmTaskGatilhoRepeteALemDoRestart(t *testing.T) { + s := armTaskScript(10) + var trig string + for _, l := range strings.Split(s, "\n") { + if strings.HasPrefix(l, "$t=New-ScheduledTaskTrigger") { + trig = l + } + } + for _, want := range []string{"-Once", "-RepetitionInterval (New-TimeSpan -Minutes 1)", "-RepetitionDuration (New-TimeSpan -Minutes 30)"} { + if !strings.Contains(trig, want) { + t.Errorf("o gatilho não tem %q: %q", want, trig) + } + } + if !strings.Contains(s, "-RestartCount 3") { + t.Error("o RestartCount continua (as duas proteções somam)") + } + if err := asciiOnly(s); err != nil { + t.Error(err) + } +} + +// 2) Executável do Windows SEMPRE por caminho absoluto (nunca pelo PATH): o icacls roda com privilégio. +func TestIcaclsPorCaminhoAbsoluto(t *testing.T) { + s := protectDirScript + if strings.Contains(s, "& icacls") { + t.Error("icacls resolvido pelo PATH") + } + if !strings.Contains(s, `C:\Windows\System32\icacls.exe`) { + t.Error("o caminho absoluto do icacls não aparece") + } + if strings.Count(s, `System32\icacls.exe`) < 2 { + t.Error("tanto o /reset quanto o /setowner usam o caminho absoluto") + } +} + +// 3) A ACL dos FILHOS é conferida por SDDL: dono Administradores e só SYSTEM e Administradores com FullControl HERDADO. +func TestCheckChildSDDL(t *testing.T) { + good := []string{ + `O:BAG:SYD:AI(A;ID;FA;;;SY)(A;ID;FA;;;BA)`, + `O:S-1-5-32-544G:SYD:AI(A;OICIID;FA;;;BA)(A;OICIID;FA;;;SY)`, + } + for _, s := range good { + if err := checkChildSDDL("x", s); err != nil { + t.Errorf("%s recusado: %v", s, err) + } + } + bad := map[string]string{ + "dono usuário": `O:S-1-5-21-1-2-3-1001G:SYD:AI(A;ID;FA;;;SY)(A;ID;FA;;;BA)`, + "ACE de Users": `O:BAG:SYD:AI(A;ID;FA;;;SY)(A;ID;FA;;;BA)(A;ID;0x1200a9;;;BU)`, + "ACE própria do dono": `O:BAG:SYD:AI(A;;FA;;;SY)(A;ID;FA;;;BA)`, + "DACL protegida": `O:BAG:SYD:PAI(A;;FA;;;SY)(A;;FA;;;BA)`, + "só uma ACE": `O:BAG:SYD:AI(A;ID;FA;;;SY)`, + "sem DACL": `O:BAG:SY`, + "ACE de usuário FA": `O:BAG:SYD:AI(A;ID;FA;;;SY)(A;ID;FA;;;S-1-5-21-1-2-3-1001)`, + } + for name, s := range bad { + if err := checkChildSDDL("x.reg", s); err == nil { + t.Errorf("%s aceito: %s", name, s) + } + } +} + +func TestProtectDirConfereOsFilhos(t *testing.T) { + run := func(children string) error { + rn := &psOut{out: `{"reparse":false,"sddl":"` + goodSDDL + `","children":` + children + `}`} + w := NewWindowsSystem(rn, nil).(*windowsSystem) + return w.ProtectDir(context.Background(), ProtectedDir) + } + good := `[{"name":"usb-backup.json","reparse":false,"sddl":"O:BAG:SYD:AI(A;ID;FA;;;SY)(A;ID;FA;;;BA)"}]` + if err := run(good); err != nil { + t.Fatalf("filhos corretos recusados: %v", err) + } + if err := run(`[]`); err != nil { + t.Fatalf("sem filhos: %v", err) + } + planted := `[{"name":"usb-restrictions-backup.reg","reparse":false,"sddl":"O:S-1-5-21-1-2-3-1001G:SYD:(A;;FA;;;S-1-5-21-1-2-3-1001)"}]` + if err := run(planted); err == nil || !strings.Contains(err.Error(), "usb-restrictions-backup.reg") { + t.Fatalf("arquivo plantado com ACL do usuário aceito: %v", err) + } + link := `[{"name":"x","reparse":true,"sddl":"O:BAG:SYD:AI(A;ID;FA;;;SY)(A;ID;FA;;;BA)"}]` + if err := run(link); err == nil || !strings.Contains(err.Error(), "reparse") { + t.Fatalf("filho que é link aceito: %v", err) + } + // a leitura traz os filhos (o script lista com -Force e lê o SDDL de cada um) + if !strings.Contains(readDirScript, "Get-ChildItem -LiteralPath $d -Force") || !strings.Contains(readDirScript, "children=") { + t.Error("o readDirScript não lê os filhos") + } +} + +// 4) c:\windows\temp e c:\windows\tasks são graváveis por usuário comum: só System32 vale como pasta de administrador. +func TestExeFolderWarningSoSystem32DoWindows(t *testing.T) { + for _, ok := range []string{`C:\Windows\System32\t.exe`, `c:\windows\system32\drivers\t.exe`, `C:\Program Files\t\t.exe`} { + if w := ExeFolderWarning(ok); w != "" { + t.Errorf("%s não deveria avisar", ok) + } + } + for _, bad := range []string{`C:\Windows\Temp\t.exe`, `c:\windows\tasks\t.exe`, `C:\Windows\t.exe`} { + if w := ExeFolderWarning(bad); w == "" { + t.Errorf("%s deveria avisar", bad) + } + } +} diff --git a/internal/usb/windows.go b/internal/usb/windows.go index db2f065..cc7626e 100644 --- a/internal/usb/windows.go +++ b/internal/usb/windows.go @@ -408,6 +408,9 @@ func (w *windowsSystem) ExportReg(ctx context.Context, file string) error { // --- pasta protegida --- // Scripts FIXOS (ASCII, sem aspas duplas). A pasta é sempre a constante ProtectedDir. +// icaclsExe é por caminho ABSOLUTO (nunca pelo PATH: o icacls roda com privilégio). +const icaclsExe = `C:\Windows\System32\icacls.exe` + const protectDirScript = `$ErrorActionPreference='Stop' $d='` + ProtectedDir + `' if(Test-Path -LiteralPath $d){ $i=Get-Item -LiteralPath $d -Force; if(($i.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0){ throw 'reparse point' }; foreach($c in @(Get-ChildItem -LiteralPath $d -Force)){ if(($c.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0){ throw 'reparse point dentro da pasta' } } } else { New-Item -ItemType Directory -Path $d | Out-Null } @@ -418,21 +421,71 @@ $acl.SetOwner($adm) $acl.SetAccessRuleProtection($true,$false) foreach($s in @($sys,$adm)){ $acl.AddAccessRule((New-Object System.Security.AccessControl.FileSystemAccessRule($s,'FullControl','ContainerInherit,ObjectInherit','None','Allow'))) } Set-Acl -LiteralPath $d -AclObject $acl -foreach($c in @(Get-ChildItem -LiteralPath $d -Force)){ & icacls.exe $c.FullName /reset /t /c /l | Out-Null; if($LASTEXITCODE -ne 0){ throw 'icacls reset' }; & icacls.exe $c.FullName /setowner '*S-1-5-32-544' /t /c /l | Out-Null; if($LASTEXITCODE -ne 0){ throw 'icacls setowner' } } +foreach($c in @(Get-ChildItem -LiteralPath $d -Force)){ & '` + icaclsExe + `' $c.FullName /reset /t /c /l | Out-Null; if($LASTEXITCODE -ne 0){ throw 'icacls reset' }; & '` + icaclsExe + `' $c.FullName /setowner '*S-1-5-32-544' /t /c /l | Out-Null; if($LASTEXITCODE -ne 0){ throw 'icacls setowner' } } [IO.File]::Delete((Join-Path $d '` + RegFile + `')) ` const readDirScript = `$ErrorActionPreference='Stop' $d='` + ProtectedDir + `' $i=Get-Item -LiteralPath $d -Force -[pscustomobject]@{reparse=(($i.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0);sddl=(Get-Acl -LiteralPath $d).GetSecurityDescriptorSddlForm('All')} | ConvertTo-Json -Compress +$ch=@() +foreach($c in @(Get-ChildItem -LiteralPath $d -Force)){ $ch+=[pscustomobject]@{name=[string]$c.Name;reparse=(($c.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0);sddl=(Get-Acl -LiteralPath $c.FullName).GetSecurityDescriptorSddlForm('All')} } +[pscustomobject]@{reparse=(($i.Attributes -band [IO.FileAttributes]::ReparsePoint) -ne 0);sddl=(Get-Acl -LiteralPath $d).GetSecurityDescriptorSddlForm('All');children=$ch} | ConvertTo-Json -Compress -Depth 3 ` -type dirInfo struct { +type childInfo struct { + Name string `json:"name"` Reparse bool `json:"reparse"` SDDL string `json:"sddl"` } +type dirInfo struct { + Reparse bool `json:"reparse"` + SDDL string `json:"sddl"` + Children []childInfo `json:"children"` +} + +// checkChildSDDL confere a ACL de um FILHO da pasta protegida depois do icacls /reset e /setowner: dono Administradores, +// DACL que HERDA (sem P) e só duas ACEs de permissão FullControl herdadas (flag ID) para SYSTEM e Administradores. Um +// arquivo plantado por usuário comum, com ACL própria dele, é recusado. (O /t do icacls reseta a subárvore; a conferência +// por SDDL cobre o primeiro nível, que é onde ficam o backup, o .reg e a cópia do binário.) +func checkChildSDDL(name, sddl string) error { + bad := func(why string) error { + return fmt.Errorf("a ACL de %q na pasta protegida não é a esperada: %s", textsafe.Line(name), why) + } + o := reSDDLOwner.FindStringSubmatch(sddl) + if o == nil || (o[1] != "BA" && o[1] != "S-1-5-32-544") { + return bad("o dono não é Administradores") + } + d := reSDDLDACL.FindStringSubmatch(sddl) + if d == nil { + return bad("sem DACL") + } + if strings.Contains(d[1], "P") { + return bad("a DACL não herda da pasta") + } + aces := regexp.MustCompile(`\(([^)]*)\)`).FindAllStringSubmatch(d[2], -1) + got := map[string]bool{} + for _, a := range aces { + f := strings.Split(a[1], ";") + if len(f) != 6 || f[0] != "A" || f[2] != "FA" || !strings.Contains(f[1], "ID") { + return bad("há uma ACE que não é de FullControl herdado") + } + switch f[5] { + case "SY", "S-1-5-18": + got["SY"] = true + case "BA", "S-1-5-32-544": + got["BA"] = true + default: + return bad("há uma ACE para " + f[5]) + } + } + if len(aces) != 2 || !got["SY"] || !got["BA"] { + return bad("deveria haver só SYSTEM e Administradores") + } + return nil +} + var ( reSDDLOwner = regexp.MustCompile(`O:([A-Z]{2}|S-[0-9-]+)`) reSDDLDACL = regexp.MustCompile(`D:([A-Z]*)((?:\([^)]*\))*)`) @@ -495,7 +548,19 @@ func (w *windowsSystem) ProtectDir(ctx context.Context, dir string) error { if info.Reparse { return fmt.Errorf("a pasta protegida é um ponto de reparse (link): recusada") } - return checkDirSDDL(info.SDDL) + if err := checkDirSDDL(info.SDDL); err != nil { + return err + } + // o icacls /c segue depois de um erro e o código de saída final não é garantido: relê cada filho e confere + for _, c := range info.Children { + if c.Reparse { + return fmt.Errorf("%q na pasta protegida é um ponto de reparse (link): recusado", textsafe.Line(c.Name)) + } + if err := checkChildSDDL(c.Name, c.SDDL); err != nil { + return err + } + } + return nil } // stageSelf copia o toolkit em execução para dir e confere o SHA-256 da cópia. @@ -558,7 +623,7 @@ func (w *windowsSystem) StageBinary(_ context.Context, dir string) (StagedBinary func armTaskScript(minutes int) string { return `$ErrorActionPreference='Stop' $a=New-ScheduledTaskAction -Execute '` + taskExe() + `' -Argument '` + RevertArgs + `' -$t=New-ScheduledTaskTrigger -Once -At ((Get-Date).AddMinutes(` + strconv.Itoa(minutes) + `)) +$t=New-ScheduledTaskTrigger -Once -At ((Get-Date).AddMinutes(` + strconv.Itoa(minutes) + `)) -RepetitionInterval (New-TimeSpan -Minutes 1) -RepetitionDuration (New-TimeSpan -Minutes 30) $p=New-ScheduledTaskPrincipal -UserId 'S-1-5-18' -LogonType ServiceAccount -RunLevel Highest $s=New-ScheduledTaskSettingsSet -StartWhenAvailable -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -ExecutionTimeLimit (New-TimeSpan -Minutes 5) -RestartCount 3 -RestartInterval (New-TimeSpan -Minutes 1) Register-ScheduledTask -TaskName '` + TaskName + `' -TaskPath '` + TaskPath + `' -Action $a -Trigger $t -Principal $p -Settings $s | Out-Null