PowerShell: Ignite Your Digital Domain with Command-Line Brilliance !

Shreya T
InfoSec Write-ups
Published in
10 min readJun 9, 2023

--

Getting started with PowerShell profiles.

PowerShell profiles encompass scripts that are automatically executed upon initiating a PowerShell session. They furnish the ability to tailor the PowerShell environment to individual preferences, encompassing the establishment of predetermined variables, aliases, functions, as well as the execution of frequently utilized commands or scripts.

Diverse variants of PowerShell profiles exist, each serving a distinct purpose:

👉 Current User, Current Host: This profile exclusively pertains to the present user and the presently active PowerShell host, typically referring to the console window. It carries the utmost precedence in terms of execution priority.

👉 Current User, All Hosts: This profile extends its applicability to the current user across all PowerShell hosts, encompassing multiple environments.

👉 All Users, Current Host: This profile extends its reach to all users of the current PowerShell host, ensuring that the customizations established within it are accessible to all individuals utilizing said host.

👉 All Users, All Hosts: This profile possesses a broad scope of influence, being applicable to all users across all PowerShell hosts. Consequently, any modifications and configurations specified within this profile are universally accessible within the PowerShell ecosystem.

Creating a PowerShell profile

a. Check if you have one: Open PowerShell ISE

Test-Path $PROFILE

b. If the command returns False, it means that you don't have a profile file yet. Run the following command to create one:

New-Item -Path $PROFILE -Type File -Force

c. Now, open the profile file in a text editor by running:

notepad $PROFILE

d. Now, let’s create a script that automate a common task of backing up a specific folder to a designated location. Now, whenever you start a PowerShell session, this script will automatically run and perform the backup task.

To prevent encountering errors , use :

Set-ExecutionPolicy RemoteSigned — allows the execution of local scripts but requiring digitally signed scripts from remote sources.

Set-ExecutionPolicy Unrestricted — allows the execution of scripts without any restrictions or digital signatures.

Presented here is a demonstration showcasing the creation of a script designed to back up a folder within the current user profile. Following its implementation, the script’s functionality is observed by monitoring its execution in subsequent PowerShell sessions.

Now, imagine PowerShell as a digital Swiss Army knife, capable of executing commands and running scripts with precision on a Windows system. But what happens when a cunning adversary manages to bypass the execution policy, breaking through the protective barrier? It’s like handing them a set of master keys to your system’s fortress.

Generally, Execution Policy determines whether scripts can be run on a system. The execution policy can be set to different levels, such as “Restricted” (default), “AllSigned,” “RemoteSigned,” or “Unrestricted.” When the execution policy is set to a higher level of restriction, it prevents the execution of unsigned or remotely downloaded scripts. Bypassing the execution policy allows you to run scripts regardless of the current execution policy.

  1. Code Execution: PowerShell is a powerful scripting language that can execute commands and scripts on a Windows system. Bypassing the execution policy allows malicious scripts or commands to be executed, which can lead to unauthorized actions on the system. The threat actor may be able to run arbitrary code, install malware, modify system configurations, or perform other malicious activities.

For example, if Execution policy is restricted, we may not be able to run any external script on Powershell and encounter the following error:

Once, the execution policy is bypassed using the following command, external or remote malicious scripts can be run

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted

Script showing live processes running on a windows system

2. Persistence: By bypassing PowerShell execution policy, the threat actor can establish persistence on the compromised system. They can execute scripts or commands at will, even after system reboots, making it difficult to detect and remove their presence.

3. Evasion of Security Controls: Execution policies in PowerShell are designed to prevent the execution of potentially harmful scripts. Bypassing these policies enables the threat actor to evade security controls and run malicious code that would otherwise be blocked. This can make it easier for them to spread malware, steal data, or escalate privileges without detection.

4. Lateral Movement and Privilege Escalation: Once the execution policy is bypassed, the threat actor can use PowerShell to move laterally across a network and compromise other systems. They can leverage PowerShell’s capabilities to escalate privileges, gain access to sensitive information, or exploit vulnerabilities on other machines.

5. Anti-Forensics: PowerShell execution policy plays a role in digital forensics by restricting the execution of potentially malicious scripts. When bypassed, it becomes more challenging to track and investigate the activities of the threat actor, as they can operate without leaving obvious traces or artifacts. If we have logging enabled, traces remains

PowerShell logging if correctly configured, like event IDs 4103 and 4104, can capture and reveal an attacker’s actions even if they bypass the execution policy. These logs provide valuable insights into the commands executed and malicious activities performed, aiding in incident analysis and response. Monitoring and analyzing PowerShell logs is crucial for detecting and mitigating PowerShell-based attacks.

Let us delve into the subject of PowerShell abuse with regard to privilege escalation.

UAC Bypass : In order to facilitate a more comprehensive comprehension, I have take a PowerShell script from the Hak5 forum, which exemplifies a UAC (User Account Control) bypass technique, and made certain modifications to enhance its functionality. Let’s dive in together 🏊

I have made a few alterations to the script, and the revised version appears as follows :

Before script execution:

No permission to access C:\Windows via local user

After script execution:

Curiosity piqued, ever wondered how threat actors effortlessly achieve remote login to a system? Let’s try this using PsExec, one of the most commonly employed tools in their arsenal, unraveling the intricacies of remote access and embracing the wonders it holds.

PsExec is a lightweight tool that enables you to :

  1. Remote System Access
  2. Command Execution
  3. Program Launching without manual installation
  4. Resource Manipulation
  5. Seamless Integration and Flexible Authentication and more

Now lets perform an exercise. Let’s get through it together :

I wanted to enable logging and monitoring for activities occurring on my system. To achieve this, I installed Splunk on my main Windows machine and also set up a Splunk forwarder on my Windows VM. The Splunk forwarder allows me to collect and forward logs from the VM to the main Splunk instance for centralized monitoring and analysis. If you need guidance on installing Splunk and configuring the forwarder, please refer to the following steps:

Install splunk forwarder

Install Splunk

Make sure to open the default ports:

9997 for forwarders to the Splunk indexer.
8000 for clients to the Splunk Search page
8089 for splunkd (also used by deployment server)

Enable forwarding of port in splunk, that u used in splunk forwarder. Its 9997 in my case.

Next, is to download PsExec in main machine and try remote login to vm.

Swich on the powershell in windows main machine, browse to the downloaded psexec directory and type:

psexec \\<vm ip> -u username -p password -s cmd.exe

If you encounter errors like:

Then you can troubleshoot by the following ways:

  1. Disable Defender both on vm and main machine
  2. Add port 445 and 139 as Port 445 is the default port for SMB (Server Message Block), which is the underlying protocol used by PsExec for remote administration tasks. Older versions of PsExec may also use TCP port 139 for NetBIOS over TCP/IP communication, which is used for file and printer sharing to Inbound rules in Windows defender firewall in both machines

If you still encounter error, you may create a new user in windows vm , followed by disabling firewall and adding the ports. You may use the following PS script , to create a new user and giving the nescessary permissions, then try again.

# Set the username and password for the new user
$Username = “Bony”
$Password = ConvertTo-SecureString “Bony” -AsPlainText -Force

# Create the new user account
New-LocalUser -Name $Username -Password $Password -FullName “Full Name of Bony” -Description “User: Bony”

# Add the new user to the local administrators group (optional)
$Group = “Administrators”
$User = Get-LocalUser -Name $Username
Add-LocalGroupMember -Group $Group -Member $User

If target user has a blank PW and you dont want to add one, run on target:

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa] “LimitBlankPasswordUse”=dword:00000000

Finally, disable UAC in Virtual machine, if still access is denied

reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f

Now, if you get error related to admin$ share as shown :

Then you can troubleshoot using the following powershell script:

$shareName = “admin$”
$sharePath = “C:\”

# Check if the admin$ share already exists
$existingShare = Get-WmiObject -Class Win32_Share -Filter “Name=’$shareName’”
if ($existingShare -eq $null) {
# Create the admin$ share as a directory
$null = New-Item -ItemType Directory -Path $sharePath -Name $shareName
$share = Get-WmiObject -Class Win32_Share
$null = $share.Create($sharePath, $shareName, 0)

if ($share.ReturnValue -eq 0) {
Write-Host “The $shareName share has been enabled on the local machine.”
} else {
Write-Host “Failed to enable the $shareName share.”
}
} else {
Write-Host “The $shareName share is already enabled on the local machine.”
}

The script is using New-Item with the admin$ name under the specified path (C:\). Then, it uses the Win32_Share class to create the share using the Create method.

After gaining access, you will be presented with a screen that looks like the following :

Play around with the stuffs you have access to.

The splunk log :

  • Security ID: S-1–5–18
  • Account Name: DESKTOP-7LBCFHB$
  • Account Domain: WORKGROUP
  • Logon ID: 0x3E7

This section provides information about the account on the local system that requested the logon. In this case, the logon was initiated by the computer itself (DESKTOP-7LBCFHB$) in the WORKGROUP domain.

Logon Information:

  • Logon Type: 5
  • Restricted Admin Mode: -
  • Remote Credential Guard: -
  • Virtual Account: No
  • Elevated Token: Yes
  • Impersonation Level: Impersonation

This section provides details about the logon process:

  • Logon Type 5 indicates a service logon.
  • Restricted Admin Mode and Remote Credential Guard fields are not applicable in this case.
  • Virtual Account is not used.
  • Elevated Token indicates that the logon has administrative privileges.
  • Impersonation Level indicates the extent to which a process in the logon session can impersonate.

New Logon:

  • Security ID: S-1–5–18
  • Account Name: SYSTEM
  • Account Domain: NT AUTHORITY
  • Logon ID: 0x3E7
  • Linked Logon ID: 0x0
  • Network Account Name: -
  • Network Account Domain: -
  • Logon GUID: {00000000–0000–0000–0000–000000000000}

This section provides information about the account that was logged on, which in this case is the SYSTEM account (NT AUTHORITY) with a logon ID of 0x3E7. The Linked Logon ID and Network Account fields are not applicable in this case.

Process Information:

  • Process ID: 0x220
  • Process Name: C:\Windows\System32\services.exe

This section provides information about the process that initiated the logon. In this case, the logon was initiated by the services.exe process with a process ID of 0x220.

Network Information:

  • Workstation Name: -
  • Source Network Address: -
  • Source Port: -

This section provides information about the network from which the logon request originated. In this case, the fields are blank, indicating that the logon was initiated locally.

Detailed Authentication Information:

  • Logon Process: Advapi (When a user logs on to a Windows system, the Advapi32.dll file is involved in verifying the user’s credentials, such as username and password, against the security database. It also handles tasks like loading user profiles, managing security tokens, and enforcing security policies during the logon process)
  • Authentication Package: Negotiate
  • Transited Services: -
  • Package Name (NTLM only): -
  • Key Length: 0

This section provides detailed information about the authentication process:

  • Logon Process: The process used for logon, in this case, Advapi.
  • Authentication Package: The authentication package used, in this case, Negotiate.
  • Transited Services: Indicates which intermediate services participated in the logon request.
  • Package Name (NTLM only): Indicates the specific NTLM sub-protocol used.
  • Key Length: The length of the generated session key, which is 0 in this case.

Overall, this log entry provides information about a successful logon event initiated by the local system (DESKTOP-7LBCFHB$) using the SYSTEM account. It indicates that the logon was performed with elevated privileges and originated from the local machine itself

The log didnt detect psexec as in this case psexec is behaving like a service and not a process. There are other ways to detect psexec connections and logons using namedpipe, netconn, smb file transfer etc. I will be elaborating on this in some other blog…

Till then, keep learning keep growing 🤓

Feel free to share your thoughts and insights !

Reach out to me at :

🖋️ LinkedIn : https://www.linkedin.com/in/shreya4n6

🖋️ Twitter Id : @shreya4n6

🖋️ Email : shreya4n6@gmail.com

--

--

Security researcher | Cyber Forensics | Malware Analysis | Threat hunting | Speaker | Blogger | Learner