undergroundwires / privacy.sexy

Open-source tool to enforce privacy & security best-practices on Windows, macOS and Linux, because privacy is sexy
https://privacy.sexy
GNU Affero General Public License v3.0
4.02k stars 170 forks source link

[BUG]: Cannot delete Microsoft Defender detection history #246

Closed DimkaTsv closed 11 months ago

DimkaTsv commented 1 year ago

Description

Technically not a bug, but script that is unable to do it's job.

Using "Clean Windows Defender scan history" doesn't work... Not by command nature, though as used command below is fine. del "%ProgramData%\Microsoft\Windows Defender\Scans\History\" /s /f /q

There are 2 different issues that heavily restrict ability to delete scan history.

  1. Defender is ALWAYS accessing part of files in %ProgramData%\Microsoft\Windows Defender\Scans (and not only \Scans folder). Meaning when you attempt to delete anything from such folder, you will get either "file is used by another process" or "Access Denied" error.
  2. By default Defender now creates this folder under SYSTEM authority and sometimes even restricts access to folder itself (meaning user cannot even open this folder). And you cannot even tamper with permissions/owner even with admin rights (options are greyed out). Only way to circumvent this is to change owner and edit permissions through safe mode, but even then you cannot delete history because of reason 1.

OS

Windows 11 Pro, 22H2, build 22621.2215

Reproduction steps

Cannot state explicit STEPS to reproduce this bug, except just selecting script and using it. For me it just won't do anything unless i disable Defender.

Scripts

@echo off
:: https://privacy.sexy — v0.12.2 — Tue, 29 Aug 2023 01:22:27 GMT
:: Ensure admin privileges
fltmc >nul 2>&1 || (
    echo Administrator privileges are required.
    PowerShell Start -Verb RunAs '%0' 2> nul || (
        echo Right-click on the script and select "Run as administrator".
        pause & exit 1
    )
    exit 0
)

:: ----------------------------------------------------------
:: -----------Clean Windows Defender scan history------------
:: ----------------------------------------------------------
echo --- Clean Windows Defender scan history
del "%ProgramData%\Microsoft\Windows Defender\Scans\History\" /s /f /q
:: ----------------------------------------------------------

pause
exit /b 0

Screenshots

image

Additional information

Every file will be either taken by process or straight up access denied because of cursed ownership system within Windows. Meaning even when you set your user as owner, but it actually isn't an owner despite exact same tag. Moreover you need to ask permission from yourself which you cannot grant to do anything. And you cannot even use takeover command or forced removal.

Potential solution? ... And i found a way to do this... I used NirSoft "Advanced Run" to elevate same exact command Privacy.Sexy uses toTrustedInstaller level. It cannot touch currently used files, but it definitely deleted history. Fun fact. Even SYSTEM level access actually didn't work.

undergroundwires commented 1 year ago

Hi @DimkaTsv , thanks for your contribution with a lot of useful information and context. Deleting currently accessed files can be mitigated by user first disabling Defender. However, if there's lack of permissions then I consider this also a bug.

I could reproduce this:

  1. Do some activites on W11 machine, like download privacy.sexy, generate a script, save it, open it to trigger some logs.

  2. Run simple del command: del "%ProgramData%\Microsoft\Windows Defender\Scans\History\" /s /f /q

    C:\Users\undergroundwires>del "%ProgramData%\Microsoft\Windows Defender\Scans\History\" /s /f /q
    C:\ProgramData\Microsoft\Windows Defender\Scans\History\CacheManager\4F99214A-D8EF-4BCA-B99B-  CA03B1202BEB-1.bin
    The process cannot access the file because it is being used by another process.
  3. Verify that No Scans\History objects are deleted.

  4. Run same command as TrustedInstaller:

    C:\Users\undergroundwires>PowerShell -ExecutionPolicy Unrestricted -Command "$command = 'del "^""%ProgramData%\Microsoft\Windows Defender\Scans\History"^"" /s /f /q'; $trustedInstallerSid = [System.Security.Principal.SecurityIdentifier]::new('S-1-5-80-956008885-3418522649-1831038044-1853292631-2271478464'); $trustedInstallerName = $trustedInstallerSid.Translate([System.Security.Principal.NTAccount]); $streamOutFile = New-TemporaryFile; $batchFile = New-TemporaryFile; try {; $batchFile = Rename-Item $batchFile "^""$($batchFile.BaseName).bat"^"" -PassThru; "^""@echo off`r`n$command`r`nexit 0"^"" | Out-File $batchFile -Encoding ASCII; $taskName = 'privacy.sexy invoke'; schtasks.exe /delete /tn "^""$taskName"^"" /f 2>&1 | Out-Null <# Clean if something went wrong before, suppress any output #>; $taskAction = New-ScheduledTaskAction -Execute 'cmd.exe' -Argument "^""cmd /c `"^""$batchFile`"^"" > $streamOutFile 2>&1"^""; $settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries; Register-ScheduledTask -TaskName $taskName -Action $taskAction -Settings $settings -Force -ErrorAction Stop | Out-Null; try {; ($scheduleService = New-Object -ComObject Schedule.Service).Connect(); $scheduleService.GetFolder('\').GetTask($taskName).RunEx($null, 0, 0, $trustedInstallerName) | Out-Null; $timeOutLimit = (Get-Date).AddMinutes(5); Write-Host "^""Running as $trustedInstallerName"^""; while((Get-ScheduledTaskInfo $taskName).LastTaskResult -eq 267009) {; Start-Sleep -Milliseconds 200; if((Get-Date) -gt $timeOutLimit) {; Write-Warning "^""Skipping results, it took so long to execute script."^""; break;; }; }; if (($result = (Get-ScheduledTaskInfo $taskName).LastTaskResult) -ne 0) {; Write-Error "^""Failed to execute with exit code: $result."^""; }; } finally {; schtasks.exe /delete /tn "^""$taskName"^"" /f | Out-Null <# Outputs only errors #>; }; Get-Content $streamOutFile; } finally {; Remove-Item $streamOutFile, $batchFile; }"
    Running as NT SERVICE\TrustedInstaller
    C:\ProgramData\Microsoft\Windows Defender\Scans\History\CacheManager\4F99214A-D8EF-4BCA-B99B-CA03B1202BEB-1.bin
    The process cannot access the file because it is being used by another process.
    Deleted file - C:\ProgramData\Microsoft\Windows Defender\Scans\History\Results\Resource\{9F039494-DF57-465C-A79F-6F963D4C8D32}
    Deleted file - C:\ProgramData\Microsoft\Windows Defender\Scans\History\Store\DA42D924D349AA438A2C4551C6466119
  5. Verify that it was able to delete some files at \Scans\History folder

I will patch this in following versions by running the command as TrustedInstaller.

Thank you again for the report, the context you gave me was great which enabled me to quickly understand the problem and tried to reproduce and solve it with your suggestion solution. Your contribution is appreciated, please feel free to report more if you see any other issues.

SnowzNZ commented 1 year ago

Have you looked at something like AtlasOS's RunAsTI.bat? This could be added to the script so that everything is ran as TI to ensure all commands execute correctly. In the past I have had to run the script with NSudo so that the commands would execute without (permissive) errors.

undergroundwires commented 1 year ago

@SnowzNZ the code there is so bad, both as in dirty/obfuscated and does unnecessary/outdated stuff. If you look at our implementation RunInlineCodeAsTrustedInstaller, it's much easier to read and the logic does not do more than necessary. You can use this to run commands in elevated session. However due to a bug in privacy.sexy's internal compiler I cannot call this function without revertCode which is blocking this issue, so I will fix that first.

If you search for RunInlineCodeAsTrustedInstaller in YAML file you'll see that some scripts use it. I think it's cleaner and more secure to elevate the privileges only when needed. If you identify other scripts that won't work properly without these permissions, we can fix/change them.

undergroundwires commented 11 months ago

The fix is released in 0.12.4 🚀.

plntd commented 1 month ago

Hi! It seems that I have a similar problem with the "Clear Defender scan (protection) history" script:

Impossible de supprimer = Impossible to delete L'accès au chemin d'accès est refusé = Access to the access path is denied

image

I tried to run the command you mentionned with TrustedInstaller, first Windows Defender blocked the script but after authorising it, I also got an "Access denied" :(

Windows 10 Pro 22H2 Privacy Sexy v0.13.5 (Desktop version)

DimkaTsv commented 1 month ago

I tried to run the command you mentionned with TrustedInstaller, first Windows Defender blocked the script but after authorising it, I also got an "Access denied" :(

Well, things slightly changed. After making it so command would execute from TrustedInstaller, Microsoft few months later made it so Defender locks all it's files and registry keys when running. To avoid that run script when booted into Safe Mode, as Defender won't lock history logs as files this way.

Current iteration of script does work from safe mode (even though like 4 files will still be locked by usage). At this point I kinda wonder if lowering privilege level to SYSTEM would still work (As Defender files and Registry are owned by SYSTEM), but don't see point in trying with only reason being "just to know"