# 설치 폴더 보안 (설치 프로그램이 관리자 권한으로 {tmp} 에서 실행). 종료 코드로 결과를 알린다. # (상위 폴더는 일반 사용자 소유여도 된다. 관리자 권한으로 실행되는 APO · mic-apo.ps1 · 제거 프로그램은 설치 폴더가 아니라 # Program Files\VoiceChanger 에 있어서, 사용자가 설치 폴더를 통째로 바꿔쳐도 관리자 권한을 얻지 못한다) # -Mode Prepare -App <폴더> [-Upgrade] 파일을 풀기 전: 폴더를 만들고 소유자를 Administrators 로, 권한을 관리자 · SYSTEM 전체 + # Users 읽기로 잠근다. 업데이트(-Upgrade 또는 v1.0.1 까지의 uninstall\ 이 있음)면 이전 버전이 사용자 쓰기 폴더에 두었던 실행 부분을 지운다. # 10 = 다른 파일이 있는 폴더, 11 = 링크(정션 · 심볼릭 링크)가 있음, 12 = 잠그지 못함 # -Mode Finish -App <폴더> 파일을 푼 뒤: 데이터 폴더에만 Users 수정 권한을 주고, 관리자 권한으로 실행되는 파일이 # 관리자 소유이고 일반 사용자가 쓸 수 없는지 확인한다. 13 = 확인 실패 param([Parameter(Mandatory)][string]$Mode, [Parameter(Mandatory)][string]$App, [switch]$Upgrade) $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 } if ($Mode -eq 'Prepare') { $upgrade = $Upgrade -or (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)은 설치 폴더 전체를 사용자 쓰기로 두었다. 이전 배포에 들어 있던 실행 부분은 믿지 않고 # 이름을 하나씩 지정해서만 지운다 (새 파일은 곧 다시 풂). 목록에 없는 파일(사용자가 넣어 둔 녹음 등)은 지우지 않고, # 아래에서 소유자 · 권한만 관리자 쪽으로 정리한다. 제거 기록(unins*.dat)은 제거할 때 관리자 권한으로 쓰이므로 꼭 지운다. $known = [ordered]@{ '.' = @('VoiceChanger.exe', 'install.bat', 'train.bat', 'examples.bat', 'README.md') 'scripts' = @('install.ps1', 'mic-apo.ps1') 'app' = @('common.py', 'examples.py', 'mic_bridge.py', 'models.py', 'record_servers.py', 'setup_engine.py', 'train.py', 'voice_changer.py') 'launcher' = @('launcher.c') 'apo' = @('VoiceChangerAPO.dll', 'vcapo.cpp', 'vccore.h', 'vcapo.def', 'mic-apo.json', 'mic-apo.log') 'uninstall' = @('unins*.exe', 'unins*.dat', 'unins*.msg') 'app\__pycache__' = @('*.pyc') } $n = 0 foreach ($d in $known.Keys) { $dir = if ($d -eq '.') { $App } else { Join-Path $App $d } if (-not (Test-Path -LiteralPath $dir -PathType Container)) { continue } foreach ($pat in $known[$d]) { Get-ChildItem -LiteralPath $dir -Force -File -Filter $pat | ForEach-Object { Remove-Item -LiteralPath $_.FullName -Force; $n++ } } } foreach ($d in 'app\__pycache__', 'app', 'scripts', 'launcher', 'uninstall') { # 비었을 때만 $dir = Join-Path $App $d if ((Test-Path -LiteralPath $dir) -and -not [IO.Directory]::EnumerateFileSystemEntries($dir).GetEnumerator().MoveNext()) { Remove-Item -LiteralPath $dir -Force } } Say "업데이트: 이전 배포 파일 $n 개 정리 (그 밖의 파일은 남김)" } 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"