Skip to content

Instantly share code, notes, and snippets.

@hickskl
Last active June 30, 2024 20:06
Show Gist options
  • Save hickskl/7f5a5e67ed73441f01f96a674f948ab5 to your computer and use it in GitHub Desktop.
Save hickskl/7f5a5e67ed73441f01f96a674f948ab5 to your computer and use it in GitHub Desktop.
UTW Powershell Notes
Windows Server: https://learn.microsoft.com/en-us/powershell/module/dnsserver/get-dnsserver?view=windowsserver2022-ps
General: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-service?view=powershell-7.4
get-command -verb get -noun DNS*
get-help
get-alias
Get-WmiObject -Class Win32_Service -Filter "name='WinRM'"
(Get-WmiObject -Class Win32_Service -Filter "name='WinRM'").pathname
cd $env:systemroot #%?% --> env variable
$env:<var> = "<new value>" #append +=
...| select-object -first 20
...| where-object { $_.<property> -like "<string>" }
...| sort-object -property creationtime -descending
...| where { -not $_.linkedgrouppolicyobjects }
...| where {$_.property -ne $null}
...| format-list -property <property>
...| out-string -Stream | select-string -pattern "command" -context 2,2 #returns object as string (now greppable!), -Stream needed for piped expressions, plus 2 lines before, 2 lines after
...| Group-Object -Property <a>, <b> -NoElement #group objects by property a, then b
Get-childitem . | get-member #get the object type and its properties
Solutions: cmdlet, get-wmiobject (or more modern get-ciminstance), .NET
CIM vs WMI cmdlets
- Common Information Model, Windows Management instrumentation
- WMI uses DCOM to access remote machines, distributed component object model
- DCOM is not firewall friendly, can be blocked by network equipment, poor error reporting
get-item
get-itemproperty
get-itempropertyvalue
-PassThru
==========================
Century1: Century1
Century2: 10.0.14393.6343
$PSVersionTable
Century3: get-childitem443
wget = invoke-webrequest
ls = get-childitem
cat = get-content
Century4: 123
get-help <cmdlet-name> -Detailed
cmdlet reference: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/add-content?view=powershell-7.4
[enum]::GetNames("system.io.fileattributes")
hidden, system, directory, archive, device, normal, temporary, sparsefile
reparsepoint, compressed, offline, notcontentindexed, encrypted
https://learn.microsoft.com/en-us/dotnet/api/system.io.fileattributes?view=net-8.0&redirectedfrom=MSDN
get-childitem
-Name list all item names
-Path location, e.g. C:\"Program files"
-Recurse -Force recurse through directory tree, force hidden files (mode h) to be listed
-Exclude S* exclude items that start with s from results, requires \* on Path
-Depth 2 Search up to 2 subdirectory layers
-Attributes ! NOT / + AND / , OR
-filter limit searches
-directory return only directories; add -Recurse to recurse
-File return files only
-path C:\..\ -Attributes !Directory+Hidden,!Directory+Hidden #find hidden directories
-Path C:\..\*.txt -Recurse -Force #find all .txt files in directory tree
-Path ..\* -Include *.log #find objects that have .log extension
-Path ..\ -Include *.log -Recurse #(same output as above)
(some people use -filter instead of -include, not sure that it does anything -filter can''t)
-path C:\"Test Folder"\* -filter *.docx #filter results for .docx only
get-childitem -Path HKLM:\SOFTWARE get items from HKEY_LOCAL_MACHINE
get-childitem -path HKLM:\SOFTWARE -exclude R*,C*
get-childitem -path Registry::HKEY_LOCAL_MACHINE #define physical state of computer, i.e. data about bus type, sys memory, installed HW/SW, etc.
::HKEY_CLASSES_ROOT #entries define types/classes of documents and properties assocated with those types
::HKEY_CURRENT_CONFIG #info about the current hardware profile of the local system, diff b/w current and standard config
#alias for HKEY_LOCAL_MACHINE\System\CurrentControlSet\HardwareProfiles\Current
::HKEY_CURRENT_USER #define preferences for current user, e.g. env vars, colours, network connections, etc.
#maps to current user's branch in HKEY_USERS
::HKEY_USERS #defines default user configuration for new users and current user
::HKEY_PERFORMANCE_DATA #access performance data
get-childItem -file -filter "*.txt" | foreach-object { write-host $_.FullName }
get-childitem | select-object PSChildName #returns child name
get-childitem -file | where-object extension -eq '.txt' | ...
get-childitem -path Cert:\* -Recurse -CodeSigningCert #retrieve certificates
PS C:\users\century3\desktop> get-psdrive
Name Used (GB) Free (GB) Provider Root CurrentLocation
---- --------- --------- -------- ---- ---------------
Alias Alias
C 28.79 20.87 FileSystem C:\ users\century3\desktop
Cert Certificate \
Env Environment
Function Function
HKCU Registry HKEY_CURRENT_USER
HKLM Registry HKEY_LOCAL_MACHINE
Variable Variable
WSMan WSMan
PS set-location HKLM:
PS HKLM:\>
get-itemproperty . #returns properties, values of keys in HKLM
get-itempropertyvalue -path <path to HKLM> -Name ProgramFilesDir #returns C:\Program Files
Set-ItemProperty -Path .\IsReadOnlyTextFile.txt -Name IsReadOnly -Value $True #set read only property to true
get-psprovider #returns powershell providers for this session
PS C:\Users\century3\Desktop> get-psprovider
Name Capabilities Drives
---- ------------ ------
Registry ShouldProcess, Transactions {HKLM, HKCU}
Alias ShouldProcess {Alias}
Environment ShouldProcess {Env}
FileSystem Filter, ShouldProcess, Credentials {C}
Function ShouldProcess {Function}
Variable ShouldProcess {Variable}
Certificate ShouldProcess {Cert}
WSMan Credentials {WSMan}
Providers:
- .NET programs that provide access to specialized data stores for easier viewing and management
- data appears in a drive that is accesses in a path (get-psdrive)
- each provider may have dynamic parameters to add to comdlets, available when you use the cmdlet with the provider
- Built-in:
- Alias: objects like system.management.automation.aliasinfo
- Certificate: objects like microsoft.powershell.commands.X509StoreLocation
- Environment: objects like system.collections.dictionaryentry
- Filesystem: objects like system.io.fileinfo, system.io.directoryinfo
- Function: objects like system.management.automation.functioninfo
- Variable: objects like system.management.automation.psvariable
- Registry: objects like microsoft.win32.registrykey
- WSMan provider
- Add/remove: remove-module, remove-psdrive
get-process #gets processes running on computer
get-process <name>
-fileversioninfo #version information for .exe
-module #returns modules loaded for this process
get-location #returns CWD
get-date
get-content #get object contents, cat in LINUX
add-content #add content to object
-PassThru #prints added content to console
add-content -path .\*.txt -Exclude help* -Value 'End of file' # add "End of file" to the end of txt files
add-content -path .\DateTimeFile1.log, .\DateTimeFile2.log -value (Get-date) -PassThru #add date at end of files
$from = get-content -path .\copyfromfile.txt
Add-content -path .\copytofile.txt -value $from #add contents of one file to another
get-content -path .\copyfromfile.txt | add-content -path .\copytofile.txt #same as above
add-content -path .\newfile.txt -value (get-content -path .\copyfromfile.txt) #same as above, but copy to new file
===Useful pipeline commands===
where-object #selects objects that have particular property values
Get-Service | Where-Object { $_.Status -eq "Stopped" }
Get-Service | Where-Object Status -EQ "Stopped"
Get-Module -ListAvailable | Where-Object {
($_.Name -notlike "Microsoft*" -and $_.Name -notlike "PS*") -and $_.HelpInfoUri
sort-object
foreach-object
1..100 | foreach-object { add-content -path .\test.txt -value "Test # $_" } #prints 100 lines of "Test # "
select-object #selects specifies properties of an object
-property PSChildName #
Get-Process | Select-Object -Property ProcessName, Id, WS
Get-Process Explorer | Select-Object -Property ProcessName -ExpandProperty Modules | Format-List
Get-Process | Sort-Object -Property WS | Select-Object -Last 5 #select top 5 processes for memory usage
format-table
format-table -view priority #formats get-process output into table sorted by priority
can add custom labels and columns to format-table output!
measure-Object #count objects, count words/lines/characters,
get-childitem | measure-Object #count files and folders in directory
(Get-ChildItem -File ..\Desktop | Measure-Object).Count #return count property of output object of measure-object
.. | select-String -notmatch -pattern <pattern>
REGISTRY:
- system-defined, hierarchical database
- apps and system components store and retrieve config data
- applications use the registry API to retrieve, mody and delete registry data
- each node in the tree is a key (which contain subkeys and data called values)
- some apps just need the key, others open the key and uses the values associated with the key
- registry values can be binary, 32- or 64-bit number, expandable reference (%PATH%), symlinks, multiple strings
- DWORD = 32 bits (Double Word, based on older word size of 16bits), QWORD = 64 bits, quad-word
- HKEY_LOCAL_MACHINE > HARWARE > DEVICEMAP > VIDEO > \Device\Video0 {\REGISTRY\Machine\system...}
- all keys and sub-keys down to value Video0 and its data (\REGISTRY\system\..)
- E.g. under CURRENT_USER, can set value KeyboardSpeed with integer data 31
- registry tree can be 512 levels deep; can create up to 32 levels per registry API call
- data more than 1-2Kb should be stored as a file and referred to by using a key in the registry, rather than as a value
- value entry uses less registry space than key, so store related data in a structure as a value, not separate keys
- system has predefined keys that are always open, allowing new subkeys to be added
- handles to these keys are entry points into the registry
- HKEY_CLASSES_ROOT (HKCR): contains file name extension associations and COM class registration info
- ProgIDs: programmatic identifier, can be associated with CLSID, not globally unique
- CLSIDs: identifies COM class object
- IIDs: Interface ID, identifies interfaces
- Open keys to add values and data; close keys to write them to memory
- HIVE: logical group of keys, subkeys and values in the registry that has a set of supporting files loaded in memory
- e.g. user profile hive when user logs in
- most supporting files for hives are in %SystemRoot%\System32\Config
Powershell:
- lets you use software components with .NET framework and COM interfaces to perform system tasks
- File processing performance in high-volumen environments: get-childitem can be slow when getting filenames
- file processing with .NET can boost performance, e.g. System.IO.FileStream class from .NET
- Instead of invoke-webrequest, choose System.net.http.httpclient for large and complex scripts
- powershell is more readable
- PS COM-compatible ArrayList vs. .NET List<String>
- "Idiomatic" Powershell = out-file, set-content, get-childitem
- .NET is harder to use in powershell than in C#, e.g.
- List<T> in .NET: https://blog.dcrich.net/post/2022/powershell-journeyman-generic-collections/#list
COM: Component Object model
- platform-independent, distributed, object-oriented system for creating binary software components that can interaction
- foundational technology for Microsoft OLE (compound documents) and ActiveX (internet-enabled components), and others
- standard, not OO Language; specifies object model and programming requirements that enable COM objects in interact
- languages must be able to create structures of pointers and call functions through pointers
- YES: C++, smalltalk
- NO: C, Java, VBScript
- COM Object: access to an object data is achieved exclusively through one or more interfaces (function sets) and methods
Machine Word: 32-bit or 64-bit machine (in Windows x64, an app can run as 32- or 64-bit machine word)
Word Type: typically the native data size of the CPU (16-bit or 32-bit), width of CPU registers
- x86, WORD 16, DWORD 32 (when CPUs became 32-bit), QWORD 64 (64-bit extensions bolted on to 32-bit CPU)
- most computers now have a word size of 64-bits
CPU Architecture: ARM vs x86
- ARM: Reduced Instruction Set Computing (RISC)
- execute one instruction set per clock style
- streamlined/uniform memory access
- core emphasis on energy efficiency
- great for battery-powered devices like smartphones, portable devices
- Integrated circuit: ARM processors do not have separate CPU; it is on same physical substrate as all of the hardware controllers
- processors operate with focus on register-based processing, limiting direct memory access
- programming needs mroe detailed commands --> a bit tougher to build
- android, iOS, linux, Windows on ARM, Chrome OS, freeBSD, Ubuntu Touch, Tizen, specialized/embedded systems
- PROS: lower power consumption, cost efficient, heat efficient, market on mobile devices
- CONS: lower performance at same clock speed (not ideal for high-end gaming or computationally intensive tasks),
software compatibility, less variety in desktops, more memory usage (more instructions for complex task)
- x86: Complex Instruction Set Computing (CISC)
- execute multiple instruction sets per clock style
- complex/hierarchical memory access
- core emphasis on perormance and speed
- can do more tasks at once, but processor is more complicated and expensive to create
- allows more direct interaction with memory
- extra layer helps manage mroe complicated instructions, can result in larger executable files
- more common in powerful computers
- sound + graphics cards, memory, storage, CPU all independent in x86 system
- linux, Windows (95-11), macOS, freeBSD, openbsd, netbsd, solaris, MS-DOS, virtualization environments
- PROS: high performance, intensive computing (gaming, data analysis, complex simulations),
extensive software ecosystem, advanced features (hyper-threading, virtualization, complex instruction sets)
- CONS: higher power consumption, heat production, cost
Instruction Set Architecture: RISC, CISC, EDGE, MISC, NISC, ZISC, quantum, etc.
RISC Architectures: MIPS, SPARC, RISC-V, PowerPC, ARM
CISC Architectures: x86, VAC, AMD
Types of Processing Units:
- CPU: primary processors on most computers, hand general tasks
- Von Neumann Architecture: Control Unit (CU), ALU, processor registers
- usually connected through motherboard to main memory, hard drive and peripherals
- GPU: designed to efficiently perform computer graphics operations, including linear algebra
- highly parallel, usually perform worse than CPUs on serial tasks
- graphics, machine learning, blockchain, bitcoin mining
- AI accelerators/neural processing units (NPUs), Vision Processing Units (VSUs), Tensor (TPU)
- Sound chips/cards: process audio
- Digital Signal Processors (DSPs) for digital signals
- Image Signal processors (ISPs) are DSPs for images
- Deep Learning Processors
- Physics Processing Units (PPUs): physical related calculations, esp. in video games
- Field-programmable gate arrays (FPGAs): specialized circuits that can be reconfigured for particular domains
- Quantum processors: use quantum physics to enable algorithms that are impossible on classical computers
- Photonic rocessors: use light to make computations instead of semiconducting electronics --> LASERS
- Cryptoprocessors
Hardware Security Module (HSM): physical computing device, secure cryptoprocessor
- functions
safeguards and manages secrets (e.g. digital keys)
key generation and storage
secure deletion of cryptographic or sensitive data
performs encryption and decryption functions for digital signatures, strong authentication and other functions
may also be hardware cryptographic accelerators (e.g. for AES)
- PKI environment, SSL connections (SSL Acceleration HSM moves RSA operations from CPU to HSM)
- plug-in card or external device for computer or network server
- contains one or more secure cryptoprocessor chips
- Common Criteria standards (up to EAL7) or FIPS-140 (highest level of certification is Security Level 4)
- most HSMs have Level 3 certification or EAL4+
DLP: Endpoint Data Loss Prevention
- monitors and blocks activities the engine identifies as potential evidence for data leakage
- deep content analysis
- 3 Policy Elements
Conditions: using Sensitive Information Type (SIT) to tell DLP what kind of info the policy should look for
e.g. credit card numbers, passport numbers, custom types
Actions: what to do when a DLP policy violation occurs
e.g. restrict access, encrypt content, audit, restrict, remove files
Notifications: informs users
SID: Security identifier
- each account or group, or process that runs in a security context of an account, is issued a SID
- Windows domain controller issues SID, stored in security database
- Each time a user signs in, system generates access token
- token containers SID, user rights, SIDs for any groups the user belongs to
- token provides the security context for whatever actions the user performs
- fundamental building block of the Windows security model
- OS itself refers to accounts and processes by their SIDs
- SID for local account or group generated by Local Security Authority (LSA)
- SID for domain account or group generated by the domain security authority
- stored as an attribute of the User or Group object in AD Domain Services
century5: 34182
cd ".\Can you open me" or cd .\"Can you open me"
century6: underthewire3347
lsof -i tcp:80 #LINUX: is port 80 in use? lsof to find process using it
lsof -p <PID> #LINUX: check the process ID of httpd to find the server's binary
du #disk usage
df #disk free
Dig
nslookup #resolve issues with name lookup
firewall-cmdlet #front end of nftables (replaced iptables)
review history commands
curl --list-only "URL" #list remote directories
curl --head "URL" #fetch http headers
Environment variables: $env:...
- $env:COMPUTERNAME
- $env:USERNAME
- $env:USERDOMAIN
- $env:USERDNSDOMAIN
get-wmiobject win32_computersystem
get-wmiobject
Get-WmiObject -Class Win32_Service -ComputerName 10.1.4.62 #get services on remote computer
(Get-WmiObject -Class Win32_Service -Filter "name='WinRM'" -ComputerName Server01).StopService() #stop service on remote computer
get-wmiobject -class win32_bios | format-list -property * #get BIOS info on local computer
Get-WmiObject Win32_Service -Credential FABRIKAM\administrator -ComputerName Fabrikam #get services on remote computer
WMI: windows management instrumentation
- Providers: AD, bitlocker, BizTalk, Boot Configuration Data, CIMWin32(.dll), distributed file System,
DNS, disk quota, event log, internet information service (IIS), TPM, IP route provider, job object, local network load
ping, policy, remote desktop services, reporting, power management, security, endpoint protection, registry, etc.
- Classes: https://learn.microsoft.com/en-us/windows/client-management/wmi-providers-supported-in-windows
century7: 197
(get-childitem -directory | measure-object).count
century8: 7points
get-content (get-childitem .\* -recurse -filter *readme*)
century9: 696
(get-content .\unique.txt | get-unique | measure-object).count
century10: pierid
((get-content .\Word_File.txt).split(" "))[160] #array index starts at 0
century11: windowsupdates110
get-service "windows update"
-displayname long name of service
-name instance name service
-name "win*" -exclude "winrm"
get-service win32_service
get-service -name "Windows Update" | Select-Object * #returns all properties of service
#get-wmiobjec can return more information about the service than get-service
get-wmiobject win32_service | ?{$_.name -like 'wuauserv'} | select Description
get-wmiobject -class win32_service -filter "Name='wuauserv'" | select-object * #from get-service... above, we know "name"
(get-wmiobject -class win32_service -filter "name='i_heart_robots'").pathname
century12: secret_sauce
get-childitem -path desktop,documents,downloads,favorites,music,videos -file -attribute !D+H
-erroraction silentlycontinue #doesn't print error to console
century13: i_authenticate_things
https://learn.microsoft.com/en-us/powershell/module/activedirectory/get-addomaincontroller?view=windowsserver2022-ps
get-help "domain controller"
get-addomaincontroller #SSL port, OS, LDAP port, IP, hostname, etc.
#Domain controller: identified by GUID, IPv4, global IPv6, DNS hostname
get-addomain #netbios, etc.
#more detailed description of DC
get-adcomputer -filter {name -eq "utw"} -properties description #not shown by default
-identity #distinguished name, GUID, SID, SAM account name
Get-ADComputer -Identity "User01-SRV1" -Properties *
Get-ADComputer -Filter 'Name -like "User01*"' -Properties IPv4Address | Format-Table Name, DNSHostName, IPv4Address -AutoSize
get-adcomputer -filter *
whoami /user #username and SID
get-wmiobject win32_useraccount | select name,sid | where-object name -eq guest #returns guest name and sid
get-wmiobject win32_useraccount | select * | where-object name -eq century12 #returns useraccount Data
century14: 755
get-content .\countmywords | measure-object -Word
century15: 153
((get-content .\countpolos).split(' ') | select-string -pattern "^polo").length or .count
=================================
cyborg1: cyborg1
Get-Command #gets commands available to powershell
Get-Member #get members, properties and methods of objects
cyborg2: kansas
get-module #lists PS modules that have been or can be imported
-ListAvailable #modules available for import from $PSModulePath
get-command -module activedirectory
get-aduser -filter 'surname -like "rogers"' -properties * #gets all user info
cyborg3: 172.31.45.167_ipv4
Resolve-DnsName <hostname> #returns IP, hostname.DNS
get-dnsserverzone #returns DNS zones, portion of namespace hosted on DNS server (granular control of namespace)
Get-DnsServerResourceRecord -RRType "A" -zonename "underthewire.tech" #returns A-RRs in specific zone
Resource Records:
- info that a zone maintains about resources, e.g. hosts, that the zone contains
- Name/host of RR, how long record is in cache, record type, type-specific data
- A: maps hostname to IP
- CNAME: alias, forwards alias domain name to another primary name
- MX: mail exchanger, specifis name of computer that exchanges or forwards mail, locates mail server
- PTR: pointer; reverse DNS lookups; maps IP --> domain
- SRV: service location; specifies host, port, protocol for a service; used when clients use DNS to locate location services (e.g. AD DCs)
- NS: name server, specifies authoritative name servers for a Domain
- TXT: publication of text in DNS records
- DNAME: alias for domain, but includes all subdomains
- SOA: start of authority; authoritative information about DNS zones like primary nameserver, contact info, etc.
cyborg4: 88_objects
X.500 Directory Specification:
- CN: common name
- OU: organizational unit
- DC: domain component
- L: locality
- ST: state or province
- O: organization name
- C: country
- UID: user ID
- Distinguished Name: CNs + OUs + DCs
- Tree structure, right to left, root as DC, nodes as CNs
get-adgroup #returns all AD group objects
-name #name of Group
-groupcategory #category of group, e.g. security
get-adgroup -filter { name -like "cyborg" } -property * #full details of cyborg adgroup
get-aduser -filter { surname -eq "Rosky" } -property * #full details of user Rosky
#no AD Group info
get-adgroupmember "Cyborg" -recursive
-identity administrators #get all members with admin identity
.length or | measure-Object #total objects returned
cyborg5: bacon_eggs
get-module -ListAvailable #returns module type, version, name, methods
cyborg6: rowray_timer
get-aduser -filter 'logonhours -like "*"' -Property logonhours
-filter '<attribute> -like "*"' #non-empty attribute
cyborg7: cybergeddon
Base64: ends in "==" or "="
get-content <file.txt> | %{[Text.Encoding]::UTF8.GetString([Convert]::FromBase65String($_))}
$m = get-content(cypher.txt)
[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($m))
[System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String($m))
$b = [System.Text.Encoding]::UTF8.GetBytes("blahblah")
$b = [System.Text.Encoding]::Unicode.GetBytes("blahblah")
[System.Convert]::ToBase64String($b)
cyborg8: skynet
get-wmiobject -class win32_startupcommand #autostart apps
cyborg9: 4
NTFS: New Technology File System
- Journalling file system that stores metadata using partition boot sector, master file table and system files
- streams contain data that is written to a file, gives more info than attributes and properties
- Replaced FAT (file allocation table), FAT32; better performance, enhanced data supported-in-windows
- features: journalling file system, ACL, Bitlocker drive encryption, support for large server volume,
logging, capacity allocation, rapid file retrieval (complex binary trees), transparent compression
ADS: alternate data streams, NTFS feature
- can write data to a hidden fork of a file
- can store anything in the ADS without affecting the reported file size
- store version info, network details, author name, version data, timestamps, tags
- https://jdhitsolutions.com/blog/scripting/8888/friday-fun-with-powershell-and-alternate-data-streams/
get-item <image> -Stream * #returns ADS's on a file
#each entry indicates a different file Stream
#$DATA (raw photo data) and Zone.Identifier ADSs on a single photo
get-content <image> -Stream $Data #raw dump of photo DATA
get-content <image> -Stream Zone.identifier #additional data: [ZoneTransfer] ZoneId=4
... | set-content -Stream <name> -value <value> #create ADS for file
cyborg10: onita99
get-aduser -filter 'telephonenumber -eq "876-5309"' -property telephonenumber
cyborg11: terminated!99
Applocker:
- helps prevent users from running unapproved apps via policies
- Features: app inventory, licensing conformance, software standardization
- https://learn.microsoft.com/en-us/windows/security/application-security/application-control/windows-defender-application-control/applocker/use-the-applocker-windows-powershell-cmdlets
- GPO: group policy object
- effective = local applocker policies + any applied applocker domain policies on local computer
get-applockerpolicy #gets policy from local or specified GPO; local, effective or domain policies
get-applockerpolicy -effective -xml #returns effective policies in xml
cyborg12: spaceballs
IIS: Internet Information services
- web server by Microsoft, shipped part of Windows Server Services
- used for troubleshooting web applications
- %systemdrive%\inetpub\logs\LogFiles (typically C:\)
- IIS log: server-side logging enabled on URL group, fixed ASCII text, no customization
- Finding IIS logs: start > inetmgr or Admin Tools > IIS Manager
- Each website has a Site ID, logfiles > Site ID
- can use Windows Server Event Viewer to view logs
- Source IP, web pages accessed, URI queries, HTTP methods, HTTP status codes
.. | select-String -notmatch -pattern <pattern>
get-content .\u_ex160413.log | select-string -NotMatch -Pattern "Mozilla|Opera"
cyborg13: ywa6_heart
get-service -name "i_heart_robots" | select-object * #details about service, not enough
get-wmiobject -class win32_service -filter "name='i_heart_robots'" | select-object PathName #returns pathname plus overhead (no good)
(get-wmiobject -class win32_service -filter "name='i_heart_robots'").pathname #returns pathname only
$b = [System.Text.Encoding]::Unicode.GetBytes("text")
[System.Convert]::ToBase64String($b)
cyborg14: 22_days
ipconfig /all
get-command -verb get -noun DNS*
CommandType Name Version Source
----------- ---- ------- ------
Alias Get-DnsServerRRL 2.0.0.0 DnsServer
Function Get-DnsClient 1.0.0.0 DnsClient
Function Get-DnsClientCache 1.0.0.0 DnsClient
Function Get-DnsClientGlobalSetting 1.0.0.0 DnsClient
Function Get-DnsClientNrptGlobal 1.0.0.0 DnsClient
Function Get-DnsClientNrptPolicy 1.0.0.0 DnsClient
Function Get-DnsClientNrptRule 1.0.0.0 DnsClient
Function Get-DnsClientServerAddress 1.0.0.0 DnsClient
Function Get-DnsServer 2.0.0.0 DnsServer
Function Get-DnsServerCache 2.0.0.0 DnsServer
Function Get-DnsServerClientSubnet 2.0.0.0 DnsServer
Function Get-DnsServerDiagnostics 2.0.0.0 DnsServer
Function Get-DnsServerDirectoryPartition 2.0.0.0 DnsServer
Function Get-DnsServerDnsSecZoneSetting 2.0.0.0 DnsServer
Function Get-DnsServerDsSetting 2.0.0.0 DnsServer
Function Get-DnsServerEDns 2.0.0.0 DnsServer
...
get-dnsserverzoneaging -zonename "underthewire.tech"
cyborg15: propshts_objects
get-wmiobject -class win32_DCOMApplicationSetting #more Data
get-CimInstance -classname Win32_DCOMApplicationSetting -property * #data included above
(get-CimInstance -classname Win32_DCOMApplicationSetting -property * -filter "AppID='{59B8AFA0-229E-46D9-B980-DDA2C817EC7E}'").caption
=========================================
groot1: groot1
get-childitem -Path C:\ -recurse -erroraction silentlycontinue -include "hosts"
$env:windir\System32\drivers\etc\hosts
Get-FileHash -algorithm md5 .\hosts
groot2: 464C3
Subexpression: "Today is $(get-date)"
Array: $list = @(get-process | select-object -First 10)
$list.gettype(); $list.count
Hash table: @{}
Call operator: $c = "get-childitem" ; & $c #executes command $c
Redirection: >, >>, 2>, 2>>, 2>&1
Containment operators: -in, -notin, -contains, -notcontains
Type comparison: -is, -isnot, -as
Logical operators: -and, -or, -xor, -not, !
Comparison operators:
-eq, -ne, -gt, -lt, -le, -ge
-match, -notmatch, -replaced + REGEX
-like, -notlike + *
Split, join: -split, -join
Range operator: ..
- foreach ($_ in 1..100) {...}
(get-content .\elements.txt)[1481110..1481117] -join "" #hiding
groot3: hiding
((get-content .\words.txt).split(' ') | select-string -pattern "^beetle").length or .count
((get-content .\words.txt).split(' ') | select-string -pattern "^beetle" -Allmatches).length
groot4: 5
set-location HKCU:\
get-childitem ./* -recurse -include "*drax*"
groot5: destroyer
(get-aduser baby.groot -properties userworkstations).userworkstations
groot6: wk11_enterprise
get-wmiobject -class win32_startupcommand
get-wmiobject -class win32_startupcommand | select * #full description of each command
get-wmiobject -class win32_startupcommand | select-object Name, command, location, user | format-list
groot7: star-lord_rules
Services & DLLs
- .exe service loads dll
- SVCHOST.exe can host a dll, but it is not recommended. Reserved for OS
- write the service as a kernel-mode driver and add a servicedll value in the service registry key pointing to the dll
- How does Windows know which DLL to load for a hosted service?
- registry configuration: subkey + value --> ServiceDLL that points to the DLL to be loaded
get-childitem Registry::\ #searches all hives
groot8: srpapi_home
https://learn.microsoft.com/en-us/windows-hardware/drivers/install/hklm-system-currentcontrolset-services-registry-tree
HKLM:\SYSTEM\CurrentControlSet\Services #registry tree with info for each service; each driver has key at
HKLM:\SYSTEM\CurrentControlSet\Services\<DriverName> #each kernel-mode driver has key here
#output of tree gives individual items for each Service
PS HKLM:\SYSTEM\CurrentControlSet\Services> get-item -path .\applockerfltr #dll info + other
PS HKLM:\SYSTEM\CurrentControlSet\Services> get-item -path .\applockerfltr | select-object * #other registry info
PS HKLM:\SYSTEM\CurrentControlSet\Services> get-itemproperty applockerfltr #combo info of above
groot9: call_me_starlord
get-netfirewall* #firewall cmdlets
#filters are used to identify firewall rules faster
get-netfirewallrule #rules
Get-NetFirewallPortFilter | Where-Object { $_.LocalPort -eq 5353 } | Get-NetFirewallRule
...| select-object -first 20
get-netfirewallapplicationfilter | where-object { $_.program -like "*mysql*" } #get firewall filter for app
(get-netfirewallapplicationfilter | where-object { $_.program -like "*mysql*" } | Get-NetFirewallRule).description
get-netfirewallrule -action block #returns rules that block traffic
groot10: t-25_tester
get-adorganizationalunit #returns all OUs
Get-ADOrganizationalUnit -filter * -properties ProtectedFromAccidentalDeletion
Get-ADOrganizationalUnit -filter * -properties * | where-object { $_.ProtectedFromAccidentalDeletion -like "False" }
groot11: taserface
compare-object (get-content <file1>) (get-content <file2>)
groot12: spaceships
get-item .\* -Stream * #get stream data for all items in .
get-content TPS_Reports04.pdf -Stream secret
groot13: airwolf
get-acl '.\Nine Realms' | format-list #returns access control, owner, group
(Get-acl '.\Nine Realms').owner
groot14: utw_team_ned
PS HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion> get-itemproperty . #shows properties of current item/path (currentversion)
PS get-itemproperty -path HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion #same as above
groot15: scheduled_things_8
get-smbshare
Name ScopeName Path Description
---- --------- ---- -----------
ADMIN$ * Remote Admin
C$ * Default share
IPC$ * Remote IPC
NETLOGON * Logon server share
shoretroopers$ * Nothing to see here
SYSVOL * Logon server share
Tasker * scheduled_things
( get-smbshare | where-object { $_.name -like "*task*" } ).description
get-smbshare -name "*tasks*"
=========================
oracle1: oracle1
get-psdrive #drives in current session
get-psprovider #returns providers, include FILESYSTEM (C:\)
get-psdrive -psprovider filesystem #returns all drives in filesystem (A, C, D, ...)
[system.io.driveinfo]::getdrives() | format-table #.NET option
Name DriveType DriveFormat IsReady AvailableFreeSpace TotalFreeSpace TotalSize RootDirectory VolumeLabel
---- --------- ----------- ------- ------------------ -------------- --------- ------------- -----------
C:\ Fixed NTFS True 22327873536 22327873536 53317988352 C:\ Windows
get-ciminstance -class win32_logicaldisk #CIM option
DeviceID DriveType ProviderName VolumeName Size FreeSpace
-------- --------- ------------ ---------- ---- ---------
C: 3 Windows 53317988352 22327676928
get-ciminstance -class win32_networkconnection #returns networked drives
get-wmiobject -class win32_mappedlogicaldisk
net use
get-smbmapping
get-timezone
$pwdlastset = (get-aduser -filter 'name -like "*raccoon*"' properties pwdlastset
[datetime]::fromfiletime($pwdlastset)
oracle2: utc
get-filehash -algorithm md5 (get-childitem .) | sort-object -property hash
oracle3: 2f5c4
Get-WinEvent -Path ".\log.evtx" -Oldest | Where-Object {$_.Id -eq 1102}
get-winevent -listprovider *
oracle4: 05/09/2017
get-gpo -all
get-gpo -all | sort-object -property creationtime -descending
oracle5: alpha83
get-gpo -all | where-object { $_.description -like "*I_AM_GROOT*" }
oracle6: charlie1337
get-adorganizationalunit -filter * -property * | where { -not $_.linkedgrouppolicyobjects }
oracle7: t-50_97
get-adtrust #returns trusted domain objects
Trusted Domain:
- a domain that the local system trusts to authenticate users
- a user/application trusted by the TD is accepted by all domains that trust the TD
- local security authority (LSA) has a trusteddomain as an object Type
- used to store information about trust relationships:
- name and SID of trusted domain
- which account to use for authentication requests
- name and SID translation requests
- names of domain controllers
oracle8: multiverse111
get-content .\logs.txt | select-string -pattern "guardian"
oracle9: star-lord
Get-DnsServerResourceRecord -RRType "MX" -zonename "underthewire.tech"
oracle10: utw_exch9229
PS HKCU:\Software\Microsoft\internet explorer> get-itemproperty -path . #IE stores typed URLs in REGISTRY
oracle11: yondu
psdrive
net use
oracle12: m
PS HKCU:\Software\Microsoft\Terminal Server Client> ls
Hive: HKEY_CURRENT_USER\Software\Microsoft\Terminal Server Client
Name Property
---- --------
192.168.2.3 UsernameHint : MyServer\raccoon
oracle13: 192.168.2.3
Get-WinEvent -Path ".\log.evtx" -Oldest | Where-Object {$_.Id -eq 1102}
oracle14: gamora88
# local sg (4731/635), global (631/4727), universal (658/4727)
Get-WinEvent -path .\security.evtx | where-object {$_.id -eq 632 -OR $_.id -eq 4728} | where-object {$_.message -like "*bereet*"} | format-list -property message
https://evotec.xyz/powershell-everything-you-wanted-to-know-about-event-logs/
oracle15: nebula2112
==========================
trebek1: trebek1
get-winevent -Path .\security.evtx | where {$_.id -eq "4699"} | format-list -property message | out-string -Stream | select-string -pattern "command"
#when <command> includes powershell.exe, look for <argument> to see script executed
trebek2: mess_cleaner
get-service | where {$_.displayname -like "*c-3po*"}
get-wmiobject win32_service | ?{$_.Name -like '*c-3po*'} | select name, displayname, state, pathname
get-wmiobject win32_service | ?{$_.Name -like '*c-3po*'} | select *
trebek3: droid823
get-winevent -path .\security.evtx | where {$_.id -eq "4624"} | format-list -property message | out-string -Stream | select-string "yoda" -context 2,20 | out-string -Stream | select-string "network address"
trebek4: 10.30.1.18address
Program Execution Data:
- Registry: ShimCache, MUICache, UserAssist
- Prefetch files
- logs
get-ciminstance win32_service | select Name, DisplayName, PathName | sort pathname | where {$_.name -eq "c-3po" }
PS C:\windows\prefetch> Get-ChildItem . | out-string -Stream | select-string "access"
trebek5: 01/05/2017_red
Software Protection Service (SPPSVC.EXE)
- required to run on startup
- enables the download, installation, enforcement of digital licenses for Windows and Windows apps
- if disabled, OS and licensed applications may run in notification mode
- recommended to not disable
WinEvent properties:
- EventLogRecord: get-winevent -path .\application.evtx | get-member
- timecreated, message, id, description, logname, providername, properties, etc.
- https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.diagnostics/get-winevent?view=powershell-7.4
- Event types: information, warning, error, success audit, failure audit
- Severity level: information, verbose, warning, error, critical
get-winevent -listlog * #get all logs from a local computer
get-winevent -listlog <category> | format-list -property * #get the <category> logs, e.g. Setup, Security, application, system
get-winevent -listlog 'Server01'
get-winevent -listprovider *policy* #get providers that have "policy" in name
(get-winevent -listlog application).providernames #get all event log providers that write to the application log
(get-winevent -listprovider <provider>).events | format-list Id, Description #get event Ids that event provider generates
get-winevent -logname 'Windows Powershell'
Get-WinEvent -LogName *PowerShell*, Microsoft-Windows-Kernel-WHEA* | #get events with Powershell or Microsoft... in name
Group-Object -Property LevelDisplayName, LogName -NoElement | #group by level (error, info, warning, etc.), then logname
Format-Table -AutoSize
get-event -path <path/to/event.evtx> -maxevents 100 #return newest 100 events; -oldest for oldest 100
get-winevent -path .\application.evtx | where {$_.timecreated -eq '3/23/2017 8:08:53 PM' } | format-list
get-childitem -path . -recurse | group-object -property extension -noelement | sort-object -property count -descending
get-winevent -logname system -maxevents 1000 | group-object -property LevelDisplayName #group event logs by entry Type
get-process | group-object -property priorityclass -noelement #noelement leaves group members out
get-process | group-object -property name -noelement | where-object {$_.count -gt 1}
trebek6: wlms
Get-ChildItem C:\'program files'\adobe\ -recurse | group-object -property extension -noelement | out-string -Stream | select-string dll
(Get-ChildItem C:\'program files'\adobe\ -Recurse | Out-String -Stream | findstr dll).count
trebek7: 40_reader
Image File Execution Options (IFEO)
- HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options
- used for debugging, often used by malware
- settings stored in the registry, gives developers the option to debug software
- can attach any program to any executable using IFEO keys: "Debugger"="/path/to/debugger.ext"
- Malware development:
- starting point for code: attach exe to popular Windows exe (preferably one that starts by default)
- attached exe will get run as well.
- e.g. userinit.exe or iexplore.exe
- can interfere with protective software by attaching a debugger to the main exe
- malware can check if there are non-default entries under IFEO keys to determine if it is on an analyst machine
Windows NT (New Technology) Architecture:
- layered design of user and kernel mode; preemptive, reentrant multitasking OS
- https://en.wikipedia.org/wiki/Architecture_of_Windows_NT#/media/File:Windows_2000_architecture.svg
- User mode = system-defined processes + DLLs
- Environment Subsystem interfaces between user-mode apps and OS kernel mode; 4 options:
- Win32 subsystem:
- can run 32-bit Windows apps, console, supports virtual DOS machines
- window management, handles input events
- csrss.exe: Win32 environment subsystem process
- OS/2 subsystem: supports 16 bit character-based OS/2 apps and emulates OS/2 1.x apps
- POSIX subsystem: supports apps strictly written to POSIX 1 standard; POSIX > Interix/Windows Services for UNIX > Windows Subsystem for Linux (WSL)
- Security Subsystem: security tokens, access control, login + authentication, AD
- Kernel mode: the executive (task-specific modules like IO, security, IPC, etc.), kernel, hardware abstraction layer, kernel drivers
- hardware <> hardware abstraction layer <> kernel <> executive: OM <...> executive: services <> user mode
- Executive: services that make up low-level kernel mode portion of OS
- contained in NTOSKRNL.EXE
- IO, object management, security, process management; divided into subsystems
- Object manager: all other executive subsystems must pass through to access Windows NT resources
- each resource is an object
sticky keys exe = sethc.exe
PS HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options> ls | where {$_.name -like "*sethc*"}
Hive: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options
Name Property
---- --------
sethc.exe Debugger : han_solo.exe
Applications triggered to run "on startup" run before windows logon.
PS > cd 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Image File Execution Options\sethc.exe'
PS > Get-ItemProperty -Path .
trebek8: han_solo99
(get-content -path .\Clone_Trooper_data.pdf -encoding byte)[0..7] -join " " #get 8 bytes of pdf
Encodings:
- ascii, ansi, bigendianunicode, bigendianutf32, oem, byte
- unicode, utf7, utf8, utf8BOM, utf8NoBOM, utf32
- Convert encodings: iconv -f FROM-ENCODING -t TO-ENCODING file.txt
trebek9: 779014403000
get-smbshare
SMB Share: Server message block share (Windows), via network path to share
- share files, printers, storage devices, VM storage over network
- allows apps to read and write to files and request services from servers in a network
- more flexibility than NFS: clients can share files with each other
- can use SMB to establish connections with other devices like printers or file servers
- users can access devices like they are local to the client
- file system is not mounted on the local SMB
- network share accessed via network path
NFS: Network File System (Linux), via mounting share
- share files and directories over network
- user or client device can connect to a network server and access files
- Client requests file or directory using RPC
--> server then checks that dir is available and client has required access permissions
--> network share mounts the file or dir remotely on the client and shares access via virtual connections
- client uses the remote server file like accessing a local File
trebek10: shoretroopers$_hiding
Event ID: 4722, user account was enabled
Get-WinEvent -path .\security.evtx | where {$_.id -eq 4722 -and $_.message -like "*obi-wan*"} | format-list -property *
Get-WinEvent -Path ..\Desktop\Logs\Security.evtx | where {$_.Id -Eq 4722} | Format-List -Property Message | Out-String -Stream | Select-String "kenobi" -Context 8,1
Get-ADUser -Filter 'Name -like "*ackbar*"'
trebek11: ackbar2121
Time Created: M/D/YYYY H:M:S AM/PM
Event ID: 4720, user account creation
https://learn.microsoft.com/en-us/windows-server/identity/ad-ds/plan/appendix-l--events-to-monitor
get-winevent -path .\security.evtx | where {$_.timecreated -like "*:26:*" -and $_.id -eq "4720" } | format-list message
trebek12: general.hux100
get-winevent -path .\security.evtx | where {$_.id -eq 4720 -and $_.message -like "*tekka*"} | format-list -property message
trebek13: poe.dameron53
get-aduser -property city | where {$_.city -ne $null}
trebek14: prindel3003
(used CyberChef)
trebek15: join_the_rebels_today
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment