Files
voice_copy/voice-changer/installer/secure-dir.ps1
EJClaw c62bd9cf39 voice-changer: lock install folder ownership, migrate old mic backup, refresh comm modes on upgrade
- installer/secure-dir.ps1 (run elevated from tmp):
  CheckParent: refuse folders whose nearest existing parent is not a drive root or owned by
  Administrators/SYSTEM/TrustedInstaller.
  Prepare (before files are copied): owner Administrators + protected DACL (SY/BA full, Users RX),
  verify, abort setup on failure; refuse links pointing outside the folder; on upgrade delete the
  old executable parts (scripts/app/launcher/uninstall/root files) that 21b4278 left user-writable.
  Finish: Users modify only on data dirs; verify every admin-run file is admin-owned and not
  user-writable, otherwise skip APO registration and engine download.
- mic-apo.ps1: migrate config\mic-apo-backup.json to apo\ with value validation (CLSID/mode GUID/
  DWORD only, own CLSID stripped), never record our own APO as the original value, upgrade the
  DEFAULT-only mode list written by 21b4278 to DEFAULT/COMMUNICATIONS/SPEECH/MEDIA, remove the
  old config\mic-apo.json.

Windows 11 VM: user-precreated folder -> owner BA, basic-user WRITE_DAC/WRITE_OWNER/grant/icacls/
write/rename all ERROR_ACCESS_DENIED; user-owned parent refused (CheckParent exit 20);
21b4278 install -> upgrade: backup migrated, modes refreshed, Communications capture 440 Hz,
uninstall restores FxProperties to the pre-install state.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 19:01:36 +09:00

139 lines
8.5 KiB
PowerShell

# 설치 폴더 보안 (설치 프로그램이 관리자 권한으로 {tmp} 에서 실행). 종료 코드로 결과를 알린다.
# -Mode CheckParent -App <폴더> 가장 가까운 상위 폴더가 드라이브 루트이거나 관리자 · SYSTEM · TrustedInstaller 소유인지
# 0 = 괜찮음, 20 = 일반 사용자 소유 (그 사용자가 설치 폴더를 통째로 바꿔치기할 수 있음)
# -Mode Prepare -App <폴더> 파일을 풀기 전: 폴더를 만들고 소유자를 Administrators 로, 권한을 관리자 · SYSTEM 전체 +
# Users 읽기로 잠근다. 업데이트면 이전 버전이 사용자 쓰기 폴더에 두었던 실행 부분을 지운다.
# 10 = 다른 파일이 있는 폴더, 11 = 링크(정션 · 심볼릭 링크)가 있음, 12 = 잠그지 못함
# -Mode Finish -App <폴더> 파일을 푼 뒤: 데이터 폴더에만 Users 수정 권한을 주고, 관리자 권한으로 실행되는 파일이
# 관리자 소유이고 일반 사용자가 쓸 수 없는지 확인한다. 13 = 확인 실패
param([Parameter(Mandatory)][string]$Mode, [Parameter(Mandatory)][string]$App)
$ErrorActionPreference = 'Stop'
$SY = 'S-1-5-18'; $BA = 'S-1-5-32-544'; $BU = 'S-1-5-32-545'
$TI = 'S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464'
$UserDirs = 'models', 'training', 'datasets', 'config', 'cache', 'env', 'engine', 'tools'
# 쓰기 계열 권한 비트: WriteData · AppendData · WriteEA · DeleteChild · WriteAttributes · Delete · WriteDAC · WriteOwner + GENERIC_ALL/WRITE
$WriteBits = 0x2 -bor 0x4 -bor 0x10 -bor 0x40 -bor 0x100 -bor 0x10000 -bor 0x40000 -bor 0x80000 -bor 0x10000000 -bor 0x40000000
$Sid = [System.Security.Principal.SecurityIdentifier]
$App = [IO.Path]::GetFullPath($App).TrimEnd('\')
function Say($m) { Write-Host "[secure-dir] $m" }
function Is-Link([string]$p) { ([IO.File]::GetAttributes($p) -band [IO.FileAttributes]::ReparsePoint) -ne 0 }
# 링크를 따라 들어가지 않고 폴더 안을 모두 훑어, 설치 폴더 밖을 가리키는 첫 링크를 찾는다.
# 안을 가리키는 링크는 괜찮다 (uv 가 tools\python 안에 "cpython-3.12-..." → "cpython-3.12.x-..." 정션을 만듦).
function Link-Target([string]$p) {
$t = @((Get-Item -LiteralPath $p -Force).Target) | Select-Object -First 1
if (-not $t) { return $null }
$t = [string]$t
if ($t.StartsWith('\\?\')) { $t = $t.Substring(4) }
if (-not [IO.Path]::IsPathRooted($t)) { $t = Join-Path (Split-Path -Parent $p) $t }
return [IO.Path]::GetFullPath($t)
}
function Find-Link([string]$dir) {
$stack = New-Object System.Collections.Stack
$stack.Push($dir)
while ($stack.Count) {
foreach ($e in [IO.Directory]::EnumerateFileSystemEntries($stack.Pop())) {
$a = [IO.File]::GetAttributes($e)
if ($a -band [IO.FileAttributes]::ReparsePoint) {
$t = Link-Target $e
if (-not $t -or -not ($t.StartsWith($App + '\', [StringComparison]::OrdinalIgnoreCase))) { return "$e -> $t" }
continue # 안쪽 링크: 따라 들어가지 않음 (가리키는 곳은 따로 훑음)
}
if ($a -band [IO.FileAttributes]::Directory) { $stack.Push($e) }
}
}
return $null
}
function Owner-Sid([string]$p) { (Get-Acl -LiteralPath $p).GetOwner($Sid).Value }
if ($Mode -eq 'CheckParent') {
$p = Split-Path -Parent $App
while ($p -and -not (Test-Path -LiteralPath $p)) { $p = Split-Path -Parent $p }
if (-not $p -or $p -eq [IO.Path]::GetPathRoot($p)) { Say "상위: 드라이브 루트"; exit 0 }
$o = Owner-Sid $p
Say "상위: $p 소유자 $o"
if ($o -in @($BA, $SY, $TI)) { exit 0 }
exit 20
}
if ($Mode -eq 'Prepare') {
$upgrade = Test-Path -LiteralPath (Join-Path $App 'uninstall\unins000.exe')
if (Test-Path -LiteralPath $App) {
if (Is-Link $App) { Say "설치 폴더가 링크: $App"; exit 11 }
if (-not $upgrade -and [IO.Directory]::EnumerateFileSystemEntries($App).GetEnumerator().MoveNext()) { exit 10 }
$link = Find-Link $App
if ($link) { Say "링크 발견: $link"; exit 11 }
}
if ($upgrade) {
# 이전 버전(21b4278)은 설치 폴더 전체를 사용자 쓰기로 두었다. 관리자 권한으로 실행되는 부분(스크립트 · 앱 코드 ·
# 제거 프로그램과 그 기록 · 실행기)은 믿지 않고 지운 뒤 새로 푼다. apo\ 는 원래 마이크 설정 백업만 남긴다(mic-apo.ps1 이 검증).
foreach ($d in 'scripts', 'app', 'launcher', 'uninstall') {
$p = Join-Path $App $d
if (Test-Path -LiteralPath $p) { Remove-Item -LiteralPath $p -Recurse -Force }
}
Get-ChildItem -LiteralPath $App -Force -File | Remove-Item -Force
$apo = Join-Path $App 'apo'
if (Test-Path -LiteralPath $apo) { Get-ChildItem -LiteralPath $apo -Force | ? { $_.Name -ne 'mic-apo-backup.json' } | Remove-Item -Recurse -Force }
Say "업데이트: 이전 실행 파일 정리"
}
New-Item -ItemType Directory -Force -Path $App | Out-Null
$sd = New-Object System.Security.AccessControl.DirectorySecurity
# 소유자 · 그룹 · DACL 만 쓴다 (SACL 까지 쓰면 감사 특권이 필요함)
$sd.SetSecurityDescriptorSddlForm("O:BAG:SYD:PAI(A;OICI;FA;;;SY)(A;OICI;FA;;;BA)(A;OICI;0x1200a9;;;BU)",
[System.Security.AccessControl.AccessControlSections]'Owner, Group, Access')
[IO.Directory]::SetAccessControl($App, $sd)
foreach ($c in Get-ChildItem -LiteralPath $App -Force) {
& icacls $c.FullName /setowner "*$BA" /C /Q | Out-Null
if ($LASTEXITCODE -ne 0) { Say "소유자 변경 실패: $($c.FullName)"; exit 12 }
if ($c.Name -notin $UserDirs) {
# 관리자 쪽 하위 항목(apo\ 백업 등): 전부 관리자 소유, 명시 권한 없이 상속만
& icacls $c.FullName /setowner "*$BA" /T /C /Q | Out-Null
& icacls $c.FullName /reset /T /C /Q | Out-Null
if ($LASTEXITCODE -ne 0) { Say "권한 초기화 실패: $($c.FullName)"; exit 12 }
}
}
$acl = Get-Acl -LiteralPath $App
$rules = @($acl.GetAccessRules($true, $true, $Sid))
$bad = @($rules | ? { $_.IsInherited -or $_.IdentityReference.Value -notin @($SY, $BA, $BU) -or
($_.IdentityReference.Value -eq $BU -and ([int]$_.FileSystemRights -band $WriteBits)) })
if ($acl.GetOwner($Sid).Value -ne $BA -or -not $acl.AreAccessRulesProtected -or $bad.Count -gt 0) {
Say "잠금 확인 실패: owner=$($acl.GetOwner($Sid).Value) protected=$($acl.AreAccessRulesProtected) bad=$($bad.Count)"
exit 12
}
Say "잠금 완료"
exit 0
}
if ($Mode -eq 'Finish') {
foreach ($d in $UserDirs) {
$p = Join-Path $App $d
if (-not (Test-Path -LiteralPath $p)) { New-Item -ItemType Directory -Path $p | Out-Null }
if (Is-Link $p) { Say "데이터 폴더가 링크: $p"; exit 13 }
$has = @((Get-Acl -LiteralPath $p).GetAccessRules($true, $false, $Sid) | ? {
$_.IdentityReference.Value -eq $BU -and ([int]$_.FileSystemRights -band 0x2) -and $_.InheritanceFlags -eq 'ContainerInherit, ObjectInherit' })
if (-not $has) {
& icacls $p /grant "*${BU}:(OI)(CI)M" /C /Q | Out-Null
if ($LASTEXITCODE -ne 0) { Say "데이터 폴더 권한 실패: $p"; exit 13 }
}
}
# 관리자 권한으로 실행되거나 읽히는 것: 루트 파일, scripts\ app\ apo\ launcher\ uninstall\ 아래 전부
$items = @(Get-Item -LiteralPath $App -Force) + @(Get-ChildItem -LiteralPath $App -Force -File)
foreach ($d in 'scripts', 'app', 'apo', 'launcher', 'uninstall') {
$p = Join-Path $App $d
if (Test-Path -LiteralPath $p) { $items += Get-Item -LiteralPath $p -Force; $items += @(Get-ChildItem -LiteralPath $p -Recurse -Force) }
}
foreach ($it in $items) {
if (Is-Link $it.FullName) { Say "링크: $($it.FullName)"; exit 13 }
$acl = Get-Acl -LiteralPath $it.FullName
$o = $acl.GetOwner($Sid).Value
$w = @($acl.GetAccessRules($true, $true, $Sid) | ? { $_.AccessControlType -eq 'Allow' -and
$_.IdentityReference.Value -notin @($SY, $BA, $TI) -and ([int]$_.FileSystemRights -band $WriteBits) })
if ($o -notin @($BA, $SY) -or $w.Count -gt 0) { Say "확인 실패: $($it.FullName) owner=$o 쓰기권한=$($w.Count)"; exit 13 }
}
Say "확인 완료: $($items.Count)개"
exit 0
}
throw "알 수 없는 Mode: $Mode"