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
6 changes: 3 additions & 3 deletions docs/usb.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
Expand Down
4 changes: 2 additions & 2 deletions internal/usb/apply.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 ""
}
Expand Down
114 changes: 114 additions & 0 deletions internal/usb/seguimento_crivo_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
}
75 changes: 70 additions & 5 deletions internal/usb/windows.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand All @@ -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]*)((?:\([^)]*\))*)`)
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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
Expand Down
Loading