Introduction to Windows Command Line
CMD
Command Prompt Basics
Local Access
-
Using the Windows key +
r
to bring up the run prompt, and then typing in cmd. OR -
Accessing the executable from the drive path
C:\Windows\System32\cmd.exe
.
Remote Access
We can do this through the use of telnet
(insecure and not recommended), Secure Shell (SSH
), PsExec
, WinRM
, RDP
, or other protocols as needed. For a sysadmin, remote management and access are a boon to our workflow.
Basic Usage
dir
Case Study: Windows Recovery
boot to Repair Mode
Getting Help
help
help time
help ipconfig
ss64 Is a handy quick reference for anything command-line related, including cmd, PowerShell, Bash, and more.
ipconfig /all
systeminfo
# clear the screen
cls
# command history
doskey /history
Key/Command | Description |
---|---|
doskey /history | doskey /history will print the session's command history to the terminal or output it to a file when specified. |
page up | Places the first command in our session history to the prompt. |
page down | Places the last command in history to the prompt. |
⇧ | Allows us to scroll up through our command history to view previously run commands. |
⇩ | Allows us to scroll down to our most recent commands run. |
⇨ | Types the previous command to prompt one character at a time. |
⇦ | N/A |
F3 | Will retype the entire previous entry to our prompt. |
F5 | Pressing F5 multiple times will allow you to cycle through previous commands. |
F7 | Opens an interactive list of previous commands. |
F9 | Enters a command to our prompt based on the number specified. The number corresponds to the commands place in our history. |
System Navigation
Listing the Contents of the File System:
tree
tree /F
Interesting Directories
Name: | Location: | Description: |
---|---|---|
%SYSTEMROOT%\Temp | C:\Windows\Temp | Global directory containing temporary system files accessible to all users on the system. All users, regardless of authority, are provided full read, write, and execute permissions in this directory. Useful for dropping files as a low-privilege user on the system. |
%TEMP% | C:\Users\ |
Local directory containing a user's temporary files accessible only to the user account that it is attached to. Provides full ownership to the user that owns this folder. Useful when the attacker gains control of a local/domain joined user account. |
%PUBLIC% | C:\Users\Public | Publicly accessible directory allowing any interactive logon account full access to read, write, modify, execute, etc., files and subfolders within the directory. Alternative to the global Windows Temp Directory as it's less likely to be monitored for suspicious activity. |
%ProgramFiles% | C:\Program Files | folder containing all 64-bit applications installed on the system. Useful for seeing what kind of applications are installed on the target system. |
%ProgramFiles(x86)% | C:\Program Files (x86) | Folder containing all 32-bit applications installed on the system. Useful for seeing what kind of applications are installed on the target system. |
Working with Directories and Files
# create a new directory
md new-directory
mkdir yet-another-dir
# delete a directory
rd Git-Pulls
rd /S Git-Pulls
# move a directory
tree example /F
move example C:\Users\htb\Documents\example
# copy a directory
# /E told Xcopy to copy any files and subdirectories to include empty directories.
xcopy C:\Users\htb\Documents\example C:\Users\htb\Desktop\ /E
robocopy C:\Users\htb\Desktop C:\Users\htb\Documents\
robocopy /E /B /L C:\Users\htb\Desktop\example C:\Users\htb\Documents\Backup\
robocopy /E /MIR /A-:SH C:\Users\htb\Desktop\notes\ C:\Users\htb\Documents\Backup\Files-to-exfil\
# list files and view their contents
more secrets.txt
more /S secrets.txt
ipconfig /all | more
type bio.txt
type passwords.txt >> secrets.txt
# Echo to Create and Append Files
echo Check out this text > demo.txt
echo More text for our demo file >> demo.txt
# Fsutil to Create a file
fsutil file createNew for-sure.txt 222
echo " my super cool text file from fsutil "> for-sure.txt
# Ren(ame) A file
ren demo.txt superdemo.txt
# Output To A File
ipconfig /all > details.txt
# Append to a File
echo f g h i j k see how this works now? >> test.txt
# Pass in a Text File to a Command
# the result is showing us the line where it found see
find /i "see" < test.txt
# Run A Then B
# It does not care if the command succeeded or failed. It just issues them.
ping 8.8.8.8 & type test.txt
# State Dependent &&
# && to run command A, and if it succeeds, run command B
cd C:\Users\student\Documents\Backup && echo 'did this work' > yes.txt
# Dynamic Del And Erase
del file-1
# Using Del And Erase to remove a list of files
erase file-3 file-5
# View Files With the Read-only Attribute
dir /A:R
# Delete a Read-only File
del /A:R *
# Viewing Hidden Files
dir /A:H
# Removing Hidden Files
del /A:H *
# Copying and Moving Files
copy secrets.txt C:\Users\student\Downloads\not-secrets.txt
# Copy Validation
copy calc.exe C:\Users\student\Downloads\copied-calc.exe /V
move C:\Users\student\Desktop\bio.txt C:\Users\student\Downloads
Gathering System Information
# Systeminfo Output
systeminfo
# Hostname Output
hostname
# Ver Output
ver
# Ipconfig Without Parameters
ipconfig
# Utilizing ARP to Find Additional Hosts
arp /a
# Understanding Our Current User
whoami
whoami /all
# Checking Out Our Privileges
whoami /priv
# Investigating Groups
whoami /groups
# Investigating Other Users/Groups
net user
net group
# Exploring Resources on the Network
net share
net view
Finding Files and Directories
where calc.exe
where /R C:\Users\student\ bio.txt
where /R C:\Users\student\ *.csv
Get-ChildItem -Path C:\ -Filter *.txt -Recurse
gci C:\ -Filter *.txt -Recurse
find "password" "C:\Users\student\not-passwords.txt"
# /N switch to display line numbers for us and the /I display to ignore case sensitivity
# use /V with the search string password against a file, it will show us any line that does not have the specified string
find /N /I /V "IP Address" example.txt
# The findstr command is similar to find in that it searches through files but for patterns instead. It will look for anything matching a pattern, regex value, wildcards, and more. Think of it as find2.0. For those familiar with Linux, findstr is closer to grep.
findstr
# Compare
# Comp will check each byte within two files looking for differences and then displays where they start.
comp .\file-1.md .\file-2.md
# Compares two files or sets of files and displays the differences between them
fc.exe /?
# print the line numbers and the ASCII comparison using the /N modifier
fc passwords.txt modded.txt /N
# feeding the contents of the file file to sort
sort.exe .\file-1.md /O .\sort-1.md
sort.exe .\sort-1.md /unique
Get-ChildItem -Path C:\ -Filter waldo.txt -Recurse
Environment Variables
%SUPER_IMPORTANT_VARIABLE%
# Showcasing Global Variables
echo %WINDIR%
# Showcasing Local Variables
set SECRET=HTB{5UP3r_53Cr37_V4r14813}
echo %SECRET%
# Display with Set
>set %SYSTEMROOT%
Environment variable C:\Windows not defined
# Display with Echo
echo %PATH%
Both set
and setx
are command line utilities that allow us to display, set, and remove environment variables. The difference lies in how they achieve those goals. The set
utility only manipulates environment variables in the current command line session. This means that once we close our current session, any additions, removals, or changes will not be reflected the next time we open a command prompt. Suppose we need to make permanent changes to environment variables. In that case, we can use setx
to make the appropriate changes to the registry, which will exist upon restart of our current command prompt session.
set DCIP=172.16.5.2
echo %DCIP%
setx DCIP 172.16.5.2
setx DCIP ""
C:\htb> set DCIP
Environment variable DCIP not defined
C:\htb> echo %DCIP%
%DCIP%
Important Environment Variables
Variable Name | Description |
---|---|
%PATH% | Specifies a set of directories(locations) where executable programs are located. |
%OS% | The current operating system on the user's workstation. |
%SYSTEMROOT% | Expands to C:\Windows. A system-defined read-only variable containing the Windows system folder. Anything Windows considers important to its core functionality is found here, including important data, core system binaries, and configuration files. |
%LOGONSERVER% | Provides us with the login server for the currently active user followed by the machine's hostname. We can use this information to know if a machine is joined to a domain or workgroup. |
%USERPROFILE% | Provides us with the location of the currently active user's home directory. Expands to C:\Users\{username}. |
%ProgramFiles% | Equivalent of C:\Program Files. This location is where all the programs are installed on an x64 based system. |
%ProgramFiles(x86)% | Equivalent of C:\Program Files (x86). This location is where all 32-bit programs running under WOW64 are installed. Note that this variable is only accessible on a 64-bit host. It can be used to indicate what kind of host we are interacting with. (x86 vs. x64 architecture) |
Managing Services
sc
sc query type= service
# Querying for Windows Defender
sc query windefend
# Stopping an Elevated Service
sc stop windefend
# Finding the Print Spooler Service
sc query Spooler
sc stop Spooler
# Starting Services
sc start Spooler
# Modifying Services
# Checking the State of the Required Services
sc query wuauserv
sc query bits
sc stop bits
sc config wuauserv start= disabled
sc config bits start= disabled
sc start wuauserv
# Other Routes to Query Services
tasklist /svc
# using net start without specifying a service will list all of the active services on the system.
net start
wmic service list brief
Working With Scheduled Tasks
Action | Parameter | Description |
---|---|---|
Query | Performs a local or remote host search to determine what scheduled tasks exist. Due to permissions, not all tasks may be seen by a normal user. | |
/fo | Sets formatting options. We can specify to show results in the Table, List, or CSV output. | |
/v | Sets verbosity to on, displaying the advanced properties set in displayed tasks when used with the List or CSV output parameter. | |
/nh | Simplifies the output using the Table or CSV output format. This switch removes the column headers. | |
/s | Sets the DNS name or IP address of the host we want to connect to. Localhost is the default specified. If /s is utilized, we are connecting to a remote host and must format it as "\host". | |
/u | This switch will tell schtasks to run the following command with the permission set of the user specified. | |
/p | Sets the password in use for command execution when we specify a user to run the task. Users must be members of the Administrator's group on the host (or in the domain). The u and p values are only valid when used with the s parameter. |
schtasks /?
SCHTASKS /Query /V /FO list
Action | Parameter | Description |
---|---|---|
Create | Schedules a task to run. | |
/sc | Sets the schedule type. It can be by the minute, hourly, weekly, and much more. Be sure to check the options parameters. | |
/tn | Sets the name for the task we are building. Each task must have a unique name. | |
/tr | Sets the trigger and task that should be run. This can be an executable, script, or batch file. | |
/s | Specify the host to run on, much like in Query. | |
/u | Specifies the local user or domain user to utilize | |
/p | Sets the Password of the user-specified. | |
/mo | Allows us to set a modifier to run within our set schedule. For example, every 5 hours every other day. | |
/rl | Allows us to limit the privileges of the task. Options here are limited access and Highest. Limited is the default value. | |
/z | Will set the task to be deleted after completion of its actions. |
# New Task Creation
schtasks /create /sc ONSTART /tn "My Secret Task" /tr "C:\Users\Victim\AppData\Local\ncat.exe 172.16.1.100 8100"
Change the Properties of a Scheduled Task
Action | Parameter | Description |
---|---|---|
Change | Allows for modifying existing scheduled tasks. | |
/tn | Designates the task to change | |
/tr | Modifies the program or action that the task runs. | |
/ENABLE | Change the state of the task to Enabled. | |
/DISABLE | Change the state of the task to Disabled. |
schtasks /change /tn "My Secret Task" /ru administrator /rp "P@ssw0rd"
schtasks /query /tn "My Secret Task" /V /fo list
Delete the Scheduled Task(s)
Action | Parameter | Description |
---|---|---|
Delete | Remove a task from the schedule | |
/tn | Identifies the task to delete. | |
/s | Specifies the name or IP address to delete the task from. | |
/u | Specifies the user to run the task as. | |
/p | Specifies the password to run the task as. | |
/f | Stops the confirmation warning. |
schtasks /delete /tn "My Secret Task"
PowerShell
CMD Vs. PowerShell
Get-Help Test-Wsman
Get-Help Test-Wsman -online
# ensure we have the most up-to-date information for each cmdlet
Update-Help
Get-Location
# display the contents of our current directory or the one we specify
Get-ChildItem
# Changing our location
Set-Location .\Documents\
# Display Contents of a File
Get-Content Readme.md
# find a pesky command that might be slipping from our memory right when we need to use it
Get-Command
Get-Command -verb get
Get-Command -noun windows*
# By default, PowerShell keeps the last 4096 commands entered, but this setting can be modified by changing the $MaximumHistoryCount variable.
# By default, Get-History will only show the commands that have been run during this active session
Get-History
# Viewing PSReadLine History
get-content C:\Users\DLarusso\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
# Clear Screen
Clear-Host
clear
cls
Hotkeys
HotKey | Description |
---|---|
CTRL+R | It makes for a searchable history. We can start typing after, and it will show us results that match previous commands. |
CTRL+L | Quick screen clear. |
CTRL+ALT+Shift+? | This will print the entire list of keyboard shortcuts PowerShell will recognize. |
Escape | When typing into the CLI, if you wish to clear the entire line, instead of holding backspace, you can just hit escape, which will erase the line. |
↑ | Scroll up through our previous history. |
↓ | Scroll down through our previous history. |
F7 | Brings up a TUI with a scrollable interactive history from our session. |
Get-Alias
# the Get-Alias cmdlet has a default alias of gal
gal
Set-Alias -Name gh -Value Get-Help
Helpful Aliases
Alias | Description |
---|---|
pwd | gl can also be used. This alias can be used in place of Get-Location. |
ls | dir and gci can also be used in place of ls. This is an alias for Get-ChildItem. |
cd | sl and chdir can be used in place of cd. This is an alias for Set-Location. |
cat | type and gc can also be used. This is an alias for Get-Content. |
clear | Can be used in place of Clear-Host. |
curl | Curl is an alias for Invoke-WebRequest, which can be used to download files. wget can also be used. |
fl and ft | These aliases can be used to format output into list and table outputs. |
man | Can be used in place of help. |
All About Cmdlets and Modules
A cmdlet as defined by Microsoft is:
"a single-feature command that manipulates objects in PowerShell."
A PowerShell module is structured PowerShell code that is made easy to use & share. As mentioned in the official Microsoft docs, a module can be made up of the following:
- Cmdlets
- Script files
- Functions
- Assemblies
- Related resources (manifests and help files)
Using PowerShell Modules
Get-Module
# The -ListAvailable modifier will show us all modules we have installed but not loaded into our session.
Get-Module -ListAvailable
Get-Help Import-Module
Import-Module .\PowerSploit.psd1
Get-NetLocalgroup
# Viewing PSModulePath
$env:PSModulePath
# Checking Execution Policy State
Get-ExecutionPolicy
Set-ExecutionPolicy undefined
Set-ExecutionPolicy -scope Process
Get-ExecutionPolicy -list
# Calling Cmdlets and Functions From Within a Module
Get-Command -Module PowerSploit
The PowerShell Gallery is a repository that contains PowerShell scripts, modules, and more created by Microsoft and other users. They can range from anything as simple as dealing with user attributes to solving complex cloud storage issues.
PowerShellGet
is a module built into PowerShell meant to help us interact with the PowerShell Gallery.
Get-Command -Module PowerShellGet
Find-Module -Name AdminToolbox | Install-Module
Tools To Be Aware Of
-
AdminToolbox: AdminToolbox is a collection of helpful modules that allow system administrators to perform any number of actions dealing with things like Active Directory, Exchange, Network management, file and storage issues, and more.
-
ActiveDirectory: This module is a collection of local and remote administration tools for all things Active Directory. We can manage users, groups, permissions, and much more with it.
-
Empire / Situational Awareness: Is a collection of PowerShell modules and scripts that can provide us with situational awareness on a host and the domain they are apart of. This project is being maintained by BC Security as a part of their Empire Framework.
-
Inveigh: Inveigh is a tool built to perform network spoofing and Man-in-the-middle attacks.
-
BloodHound / SharpHound: Bloodhound/Sharphound allows us to visually map out an Active Directory Environment using graphical analysis tools and data collectors written in C# and PowerShell.
User and Group Management
Built-In Accounts
Account | Description |
---|---|
Administrator | This account is used to accomplish administrative tasks on the local host. |
Default Account | The default account is used by the system for running multi-user auth apps like the Xbox utility. |
Guest Account | This account is a limited rights account that allows users without a normal user account to access the host. It is disabled by default and should stay that way. |
WDAGUtility Account | This account is in place for the Defender Application Guard, which can sandbox application sessions. |
Domain users differ from local users in that they are granted rights from the domain to access resources such as file servers, printers, intranet hosts, and other objects based on user and group membership. Domain user accounts can log in to any host in the domain, while the local user only has permission to access the specific host they were created on.
get-localgroup
Get-LocalUser
New-LocalUser -Name "JLawrence" -NoPassword
$Password = Read-Host -AsSecureString
Set-LocalUser -Name "JLawrence" -Password $Password -Description "CEO EagleFang"
Get-LocalGroup
Get-LocalGroupMember -Name "Users"
Add-LocalGroupMember -Group "Remote Desktop Users" -Member "JLawrence"
Get-LocalGroupMember -Name "Remote Desktop Users"
# install RSAT (Remote System Administration Tools) to get the official ActiveDirectory PowerShell module
Get-WindowsCapability -Name RSAT* -Online | Add-WindowsCapability -Online
# Locating The AD Module
Get-Module -Name ActiveDirectory -ListAvailable
Get-ADUser -Filter *
Get-ADUser -Identity TSilver
Get-ADUser -Filter {EmailAddress -like '*greenhorn.corp'}
# add new AD user
New-ADUser -Name "MTanaka" -Surname "Tanaka" -GivenName "Mori" -Office "Security" -OtherAttributes @{'title'="Sensei";'mail'="MTanaka@greenhorn.corp"} -Accountpassword (Read-Host -AsSecureString "AccountPassword") -Enabled $true
Get-ADUser -Identity MTanaka -Properties * | Format-Table Name,Enabled,GivenName,Surname,Title,Office,Mail
# Changing a Users Attributes
Set-ADUser -Identity MTanaka -Description " Sensei to Security Analyst's Rocky, Colt, and Tum-Tum"
Get-ADUser -Identity MTanaka -Property Description
Get-ADUser -Filter {GivenName -like '*Robert*'}
Working with Files and Directories
Common Commands Used for File & Folder Management
Command | Alias | Description |
---|---|---|
Get-Item | gi | Retrieve an object (could be a file, folder, registry object, etc.) |
Get-ChildItem | ls / dir / gci | Lists out the content of a folder or registry hive. |
New-Item | md / mkdir / ni | Create new objects. ( can be files, folders, symlinks, registry entries, and more) |
Set-Item | si | Modify the property values of an object. |
Copy-Item | copy / cp / ci | Make a duplicate of the item. |
Rename-Item | ren / rni | Changes the object name. |
Remove-Item | rm / del / rmdir | Deletes the object. |
Get-Content | cat / type | Displays the content within a file or object. |
Add-Content | ac | Append content to a file. |
Set-Content | sc | overwrite any content in a file with new data. |
Clear-Content | clc | Clear the content of the files without deleting the file itself. |
Compare-Object | diff / compare | Compare two or more objects against each other. This includes the object itself and the content within. |
Get-Location
new-item -name "SOPs" -type directory
cd SOPs
mkdir "Physical Sec"
mkdir "Cyber Sec"
mkdir "Training"
Get-ChildItem
new-Item "Readme.md" -ItemType File
cd '.\Physical Sec\'
new-Item "Physical-Sec-draft.md" -ItemType File
cd ..
cd '.\Cyber Sec\'
new-Item "Cyber-Sec-draft.md" -ItemType File
cd ..
cd .\Training\
new-Item "Employee-Training-draft.md" -ItemType File
cd ..
tree /F
Add-Content .\Readme.md "Title: Insert Document Title Here
>> Date: x/x/202x
>> Author: MTanaka
>> Version: 0.1 (Draft)"
Rename-Item .\Cyber-Sec-draft.md -NewName Infosec-SOP-draft.md
get-childitem -Path *.txt | rename-item -NewName {$_.name -replace ".txt",".md"}
Finding & Filtering Content
Get-LocalUser administrator | get-member
Get-LocalUser administrator | Select-Object -Property *
Get-LocalUser * | Select-Object -Property Name,PasswordLastSet
Get-LocalUser * | Sort-Object -Property Name | Group-Object -property Enabled
Get-Service | Select-Object -Property *
# fl: format output into list
get-service | Select-Object -Property DisplayName,Name,Status | Sort-Object DisplayName | fl
Get-Service | where DisplayName -like '*Defender*'
Comparison Operators
Expression | Description |
---|---|
Like | Like utilizes wildcard expressions to perform matching. For example, 'Defender' would match anything with the word Defender somewhere in the value. |
Contains | Contains will get the object if any item in the property value matches exactly as specified. |
Equal to | Specifies an exact match (case sensitive) to the property value supplied. |
Match | Is a regular expression match to the value supplied. |
Not | specifies a match if the property is blank or does not exist. It will also match $False . |
Get-Service | where DisplayName -like '*Defender*' | Select-Object -Property *
# Using the Pipeline to Count Unique Instances
get-process | sort | unique | measure-object
Get-ChildItem -Path C:\Users\MTanaka\ -File -Recurse
Get-Childitem –Path C:\Users\MTanaka\ -File -Recurse -ErrorAction SilentlyContinue | where {($_.Name -like "*.txt")}
Get-Childitem –Path C:\Users\MTanaka\ -File -Recurse -ErrorAction SilentlyContinue | where {($_.Name -like "*.txt" -or $_.Name -like "*.py" -or $_.Name -like "*.ps1" -or $_.Name -like "*.md" -or $_.Name -like "*.csv")}
# sls: Select-string is not case sensitive by default
Get-ChildItem -Path C:\Users\MTanaka\ -Filter "*.txt" -Recurse -File | sls "Password","credential","key"
Get-Childitem –Path C:\Users\MTanaka\ -File -Recurse -ErrorAction SilentlyContinue | where {($_. Name -like "*.txt" -or $_. Name -like "*.py" -or $_. Name -like "*.ps1" -or $_. Name -like "*.md" -or $_. Name -like "*.csv")} | sls "Password","credential","key","UserName"
Working with Services
Get-Help *-Service
Get-Service | ft DisplayName,Status
Get-Service | where DisplayName -like '*Defender*' | ft DisplayName,ServiceName,Status
Start-Service WinDefend
get-service WinDefend
get-service
Stop-Service Spooler
Get-Service Spooler
get-service spooler | Select-Object -Property Name, StartType, Status, DisplayName
Set-Service -Name Spooler -StartType Disabled
Get-Service -Name Spooler | Select-Object -Property StartType
get-service -ComputerName ACADEMY-ICL-DC
Get-Service -ComputerName ACADEMY-ICL-DC | Where-Object {$_.Status -eq "Running"}
# We are telling PowerShell that we want to run a command on a local or remote computer
invoke-command -ComputerName ACADEMY-ICL-DC,LOCALHOST -ScriptBlock {Get-Service -Name 'windefend'}
Working with the Registry
# Root Registry Keys
Get-ChildItem C:\Windows\System32\config\
Hive Breakdown |Name |Abbreviation |Description | |-------|---------------|------------| |HKEY_LOCAL_MACHINE |HKLM |This subtree contains information about the computer's physical state, such as hardware and operating system data, bus types, memory, device drivers, and more. | |HKEY_CURRENT_CONFIG |HKCC |This section contains records for the host's current hardware profile. (shows the variance between current and default setups) Think of this as a redirection of the HKLM CurrentControlSet profile key.| |HKEY_CLASSES_ROOT |HKCR |Filetype information, UI extensions, and backward compatibility settings are defined here. | |HKEY_CURRENT_USER |HKCU |Value entries here define the specific OS and software settings for each specific user. Roaming profile settings, including user preferences, are stored under HKCU. | |HKEY_USERS |HKU |The default User profile and current user configuration settings for the local computer are defined under HKU. |
# Querying Registry Entries
Get-Item -Path Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run | Select-Object -ExpandProperty Property
Get-ChildItem -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion -Recurse
Get-ItemProperty -Path Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Run
reg query HKEY_LOCAL_MACHINE\SOFTWARE\7-Zip
# Searching With Reg Query
REG QUERY HKCU /F "Password" /t REG_SZ /S /K
-
/f "password": /f sets the pattern we are searching for. In this instance, we are looking for "Password".
-
/t REG_SZ: /t is setting the value type to search. If we do not specify, reg query will search through every type.
-
/s: /s says to search through all subkeys and values recursively.
-
/k: /k narrows it down to only searching through Key names.
# New Registry Key
New-Item -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce\ -Name TestKey
# Set New Registry Item Property
New-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce\TestKey -Name "access" -PropertyType String -Value "C:\Users\htb-student\Downloads\payload.exe"
# add the same key/value pair using Reg.exe
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce\TestKey" /v access /t REG_SZ /d "C:\Users\htb-student\Downloads\payload.exe"
# Delete Reg properties
Remove-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce\TestKey -Name "access"
Get-ItemProperty -Path HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce\TestKey
Working with the Windows Event Log
Event Log Categories and Types
Log Category | Log Description |
---|---|
System Log | The system log contains events related to the Windows system and its components. A system-level event could be a service failing at startup. |
Security Log | Self-explanatory; these include security-related events such as failed and successful logins, and file creation/deletion. These can be used to detect various types of attacks that we will cover in later modules. |
Application Log | This stores events related to any software/application installed on the system. For example, if Slack has trouble starting it will be recorded in this log. |
Setup Log | This log holds any events that are generated when the Windows operating system is installed. In a domain environment, events related to Active Directory will be recorded in this log on domain controller hosts. |
Forwarded Events | Logs that are forwarded from other hosts within the same network. |
Event Types
Type of Event | Event Description |
---|---|
Error | Indicates a major problem, such as a service failing to load during startup, has occurred. |
Warning | A less significant log but one that may indicate a possible problem in the future. One example is low disk space. A Warning event will be logged to note that a problem may occur down the road. A Warning event is typically when an application can recover from the event without losing functionality or data. |
Information | Recorded upon the successful operation of an application, driver, or service, such as when a network driver loads successfully. Typically not every desktop application will log an event each time they start, as this could lead to a considerable amount of extra "noise" in the logs. |
Success Audit | Recorded when an audited security access attempt is successful, such as when a user logs on to a system. |
Failure Audit | Recorded when an audited security access attempt fails, such as when a user attempts to log in but types their password in wrong. Many audit failure events could indicate an attack, such as Password Spraying. |
Event Severity Levels
Severity Level | Level # | Description |
---|---|---|
Verbose | 5 | Progress or success messages. |
Information | 4 | An event that occurred on the system but did not cause any issues. |
Warning | 3 | A potential problem that a sysadmin should dig into. |
Error | 2 | An issue related to the system or service that does not require immediate attention. |
Critical | 1 | This indicates a significant issue related to an application or a system that requires urgent attention by a sysadmin that, if not addressed, could lead to system or application instability. |
ls C:\Windows\System32\winevt\logs
wevtutil /?
# Enumerating Log Sources
wevtutil el
# Gathering Log Information
wevtutil gl "Windows PowerShell"
wevtutil gli "Windows PowerShell"
# Querying Events
wevtutil qe Security /c:5 /rd:true /f:text
# Exporting Events
wevtutil epl System C:\system_export.evtx
# PowerShell - Listing All Logs
Get-WinEvent -ListLog *
# Security Log Details
Get-WinEvent -ListLog Security
# Querying Last Five Events
Get-WinEvent -LogName 'Security' -MaxEvents 5 | Select-Object -ExpandProperty Message
# Filtering for Logon Failures
Get-WinEvent -FilterHashTable @{LogName='Security';ID='4625 '}
Get-WinEvent -FilterHashTable @{LogName='System';Level='1'} | select-object -ExpandProperty Message
Networking Management from The CLI
Protocol | Description |
---|---|
SMB | SMB provides Windows hosts with the capability to share resources, files, and a standard way of authenticating between hosts to determine if access to resources is allowed. For other distros, SAMBA is the open-source option. |
Netbios | NetBios itself isn't directly a service or protocol but a connection and conversation mechanism widely used in networks. It was the original transport mechanism for SMB, but that has since changed. Now it serves as an alternate identification mechanism when DNS fails. Can also be known as NBT-NS (NetBIOS name service). |
LDAP | LDAP is an open-source cross-platform protocol used for authentication and authorization with various directory services. This is how many different devices in modern networks can communicate with large directory structure services such as Active Directory. |
LLMNR | LLMNR provides a name resolution service based on DNS and works if DNS is not available or functioning. This protocol is a multicast protocol and, as such, works only on local links ( within a normal broadcast domain, not across layer three links). |
DNS | DNS is a common naming standard used across the Internet and in most modern network types. DNS allows us to reference hosts by a unique name instead of their IP address. This is how we can reference a website by "WWW.google.com" instead of "8.8.8.8". Internally this is how we request resources and access from a network. |
HTTP/HTTPS | HTTP/S HTTP and HTTPS are the insecure and secure way we request and utilize resources over the Internet. These protocols are used to access and utilize resources such as web servers, send and receive data from remote sources, and much more. |
Kerberos | Kerberos is a network level authentication protocol. In modern times, we are most likely to see it when dealing with Active Directory authentication when clients request tickets for authorization to use domain resources. |
WinRM | WinRM Is an implementation of the WS-Management protocol. It can be used to manage the hardware and software functionalities of hosts. It is mainly used in IT administration but can also be used for host enumeration and as a scripting engine. |
RDP | RDP is a Windows implementation of a network UI services protocol that provides users with a Graphical interface to access hosts over a network connection. This allows for full UI use to include the passing of keyboard and mouse input to the remote host. |
SSH | SSH is a secure protocol that can be used for secure host access, transfer of files, and general communication between network hosts. It provides a way to securely access hosts and services over insecure networks. |
Querying Networking Settings
ipconfig
ipconfig /all
# ARP is a protocol utilized to translate IP addresses to Physical addresses.
arp -a
nslookup ACADEMY-ICL-DC
netstat -an
PowerShell Net Cmdlets
Cmdlet | Description |
---|---|
Get-NetIPInterface | Retrieve all visible network adapter properties. |
Get-NetIPAddress | Retrieves the IP configurations of each adapter. Similar to IPConfig. |
Get-NetNeighbor | Retrieves the neighbor entries from the cache. Similar to arp -a. |
Get-Netroute | Will print the current route table. Similar to IPRoute. |
Set-NetAdapter | Set basic adapter properties at the Layer-2 level such as VLAN id, description, and MAC-Address. |
Set-NetIPInterface | Modifies the settings of an interface to include DHCP status, MTU, and other metrics. |
New-NetIPAddress | Creates and configures an IP address. |
Set-NetIPAddress | Modifies the configuration of a network adapter. |
Disable-NetAdapter | Used to disable network adapter interfaces. |
Enable-NetAdapter | Used to turn network adapters back on and allow network connections. |
Restart-NetAdapter | Used to restart an adapter. It can be useful to help push changes made to adapter settings. |
test-NetConnection | Allows for diagnostic checks to be ran on a connection. It supports ping, tcp, route tracing, and more. |
Get-NetIPAddress -ifIndex 25
Set-NetIPInterface -InterfaceIndex 25 -Dhcp Disabled
Set-NetIPAddress -InterfaceIndex 25 -IPAddress 10.10.100.54 -PrefixLength 24
Get-NetIPAddress -ifindex 20 | ft InterfaceIndex,InterfaceAlias,IPAddress,PrefixLength
Get-NetIPinterface -ifindex 20 | ft ifIndex,InterfaceAlias,Dhcp
Restart-NetAdapter -Name 'Ethernet 3'
Test-NetConnection
Setting up SSH on a Windows Target
Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH*'
Add-WindowsCapability -Online -Name OpenSSH.Client~~~~0.0.1.0
Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH*'
Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0
Get-WindowsCapability -Online | Where-Object Name -like 'OpenSSH*'
Start-Service sshd
Set-Service -Name sshd -StartupType 'Automatic'
Enabling WinRM
winrm quickconfig
# Testing Unauthenticated Access
Test-WSMan -ComputerName "10.129.224.248"
# Testing Authenticated Access
Test-WSMan -ComputerName "10.129.224.248" -Authentication Negotiate
PowerShell Remote Sessions
# Establishing a PowerShell Session
Enter-PSSession -ComputerName 10.129.224.248 -Credential htb-student -Authentication Negotiate
$PSVersionTable
# Using Enter-PSSession from Linux
$ [PS]> Enter-PSSession -ComputerName 10.129.224.248 -Credential htb-student -Authentication Negotiate
$PSVersionTable
Interacting With The Web
Get-Help Invoke-Webrequest
Invoke-WebRequest -Uri "https://web.ics.purdue.edu/~gchopra/class/public/pages/webdesign/05_simple.html" -Method GET | Get-Member
# Filtering Incoming Content
Invoke-WebRequest -Uri "https://web.ics.purdue.edu/~gchopra/class/public/pages/webdesign/05_simple.html" -Method GET | fl Images
# Raw Content
Invoke-WebRequest -Uri "https://web.ics.purdue.edu/~gchopra/class/public/pages/webdesign/05_simple.html" -Method GET | fl RawContent
# Download To Our Host
Invoke-WebRequest -Uri "https://raw.githubusercontent.com/PowerShellMafia/PowerSploit/master/Recon/PowerView.ps1" -OutFile "C:\PowerView.ps1"
# If We Can't Use Invoke-WebRequest
(New-Object Net.WebClient).DownloadFile("https://github.com/BloodHoundAD/BloodHound/releases/download/4.2.0/BloodHound-win32-x64.zip", "Bloodhound.zip")
PowerShell Scripting and Automation
PowerShell Extensions
Extension | Description |
---|---|
ps1 | The *.ps1 file extension represents executable PowerShell scripts. |
psm1 | The *.psm1 file extension represents a PowerShell module file. It defines what the module is and what is contained within it. |
psd1 | The *.psd1 is a PowerShell data file detailing the contents of a PowerShell module in a table of key/value pairs. |
PS C:\htb> New-ModuleManifest -Path C:\Users\MTanaka\Documents\WindowsPowerShell\Modules\quick-recon\quick-recon.psd1 -PassThru
# Module manifest for module 'quick-recon'
#
# Generated by: MTanaka
#
# Generated on: 10/31/2022
#
@{
# Script module or binary module file associated with this manifest.
# RootModule = ''
# Version number of this module.
ModuleVersion = '1.0'
<SNIP>
Sample Manifest
# Module manifest for module 'quick-recon'
#
# Generated by: MTanaka
#
# Generated on: 10/31/2022
#
@{
# Script module or binary module file associated with this manifest.
# RootModule = 'C:\Users\MTanaka\WindowsPowerShell\Modules\quick-recon\quick-recon.psm1'
# Version number of this module.
ModuleVersion = '1.0'
# ID used to uniquely identify this module
GUID = '0a062bb1-8a1b-4bdb-86ed-5adbe1071d2f'
# Author of this module
Author = 'MTanaka'
# Company or vendor of this module
CompanyName = 'Greenhorn.Corp.'
# Copyright statement for this module
Copyright = '(c) 2022 Greenhorn.Corp. All rights reserved.'
# Description of the functionality provided by this module
Description = 'This module will perform several quick checks against the host for Reconnaissance of key information.'
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = @()
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = @()
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = @()
# List of all modules packaged with this module
# ModuleList = @()
# List of all files packaged with this module
# FileList = @()
}
Create Our Script File
ni quick-recon.psm1 -ItemType File
New-Item quick-recon.psm1 -ItemType File
Import Into Our Module
Import-Module ActiveDirectory
function Get-Recon {
# Collect the hostname of our PC.
$Hostname = $env:ComputerName
# Collect the IP configuration.
$IP = ipconfig
# Collect basic domain information.
$Domain = Get-ADDomain
# Output the users who have logged in and built out a basic directory structure in "C:\Users\".
$Users = Get-ChildItem C:\Users\
# Create a new file to place our recon results in.
new-Item ~\Desktop\recon.txt -ItemType File
# A variable to hold the results of our other variables.
$Vars = "***---Hostname info---***", $Hostname, "***---Domain Info---***", $Domain, "***---IP INFO---***", $IP, "***---USERS---***", $Users
# It does the thing
Add-Content ~\Desktop\recon.txt $Vars
}
Export-ModuleMember -Function Get-Recon -Variable Hostname
# Exclude From Export
Export-ModuleMember
# Export Specific Functions and Variables
Export-ModuleMember -Function Get-Recon -Variable Hostname
Importing the Module For Use
Import-Module 'C:\Users\MTanaka\Documents\WindowsPowerShell\Modules\quick-recon.psm1'
get-module
# Help Validation
get-help get-recon
Skill Assessment
Get-ChildItem -Path C:\Users\user4\Documents -Filter flag.txt -Recurse | Get-Content
# find the Registered Owner of the host
reg query "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion" /v RegisteredOwner
Get-ADUser -Filter {Surname -like '*Flag*'}
# Use the tasklist command to print running processes and then sort them in reverse order by name.
tasklist | sort /R
This script queries the Security Event Log for Event ID 4625, groups the results by the target user account, and sorts them in descending order by the number of failed logon attempts.
# Query Event ID 4625 (Logon Failure) from the Security Log
$events = Get-WinEvent -FilterHashtable @{
LogName = 'Security'
ID = 4625
}
# Group events by target user account and count the number of failures
$failedLogons = $events | Group-Object { $_.Properties[5].Value } | Select-Object Name, Count | Sort-Object Count -Descending
# Display the results
$failedLogons | Format-Table -AutoSize