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

Book Review: "Python for Secret Agents"

'Python for Secret Agents' by Steven F. Lott, published by Packt and sold through O'Reilly and Amazon, is easily worth $10 - $25 for any novice python programmer. The book is roughly 200 pages of python data manipulation tricks, from data generators and loops to parsing complex structures. The book has a wide collection of fundamental data manipulation techniques, but lacks more offensive techniques, such as those covered in 'Violent Python' and 'Black Hat Python'. It does however follow a consistently amusing theme, of accomplishing basic data manipulation tasks as a secret agent preparing data for HQ. Again, the tasks aren't actually security related, which makes the whole theme feel a little forced and cheesy, none the less it is an entertaining take on a programing book while still conveying fundamental python features structures. It's also important to note that the entire book deals strictly with python 3, which is not compatible with python2.7 (the python version I mainly refer to throughout this blog). All of that said, I give this book a solid 5/10 stars, as I think it's more of a beginner to intermediate general python book, and has little to do with security programing or things related to secret agents (other than its cute storyline). I also recommend this book to those looking to get better with programming and web programmers, but don't really recommend this book for penetration testers or security engineers in particular. The following is my typical table of contents overview format:

Chapter 1: Our Espionage Toolkit (Setup and iIntro)
 Getting the tools of the trade - Python 3.3
  Windows secrets (dependencies)
  Mac OS X secrets (dependencies)
 Confirming our tools
  How do we stop?
  Using the help() system
   Mac OS and GNU/Linux secrets (dependencies)
   Windows secrets (dependencies)
  Using the help mode
 Background briefing - math and numbers
  The usual culprits
  The ivory tower of numbers
   Integer numbers
   Rational numbers
   Floating-point numbers
   Decimal numbers
   Complex numbers
  Outside the numbers
  Assigning value to variables
  Writing scripts and seeing output
  Gather user input
   Handling exceptions
   Looping and trying again
 Handling text and strings
  Converting between numbers and strings
  Parsing strings
 Organizing our software
 Working with files and folders
  Creating a file
  Reading a file
  Defining more complex logical conditions

Chapter 2: Acquiring Intelligence Data
 Accessing data from the Internet
  Background briefing - the TCP/IP protocols
  Using http.client for HTTP GET
  Changing our client information
  Using FTP in Python
   Downloading a file via FTP
   Using FTP get() function
  Using urllib for HTTP, FTP, or file access
  Using urllib for FTP access
 Using a REST API in Python
  Getting simple REST data
  Using more complex RESTful queries
  Saving our data via JSON
 Organizing collections of data
  Using a python list
   Using list index operations
  Using a python tuple
   Using generator expressions with list of tuples
  Using a Python dictionary mapping
   Using the dictionary access methods
  Transforming sequences with generator functions
  Using the defaultdict and counter mappings
  Using a Python set
  Using the for statement with a collection
  Using Python operators on collections
 Solving problems - currency conversion rates

Chapter 4: Encoding Secret Messages with Stenanography
 Background briefing - handling file formats
  Working with the OS filesystem
  Processing simple text files
  Working with ZIP files
  Working with JSON files
  Working with CSV files
  JPEG and PNG graphics - pixels and metadata
 Using the Pillow library
  Adding the required supporting libraries
   GNU/Linux secrets
   Mac OS X secrets
   Windows secrets
  Installing and confirming Pillow
  Decoding and encoding image data
  Manipulating images - resizing and thumbnails
  Manipulating images - cropping
  Manipulating images - enhancing
  Manipulating images - filtering
  Manipulating images - ImageOps
 Some approaches to steganography
  Getting the red-channel data
  Extracting bytes from Unicode characters
  Manipulating bits and bytes
  Encoding the message
  Decoding a message
 Detecting and preventing tampering
  Using hash totals to validate a file
  Using a key with a digest
 Solving problems - encrypting a message
  Unpacking a message

Chapter 4: Drops, Hideouts, Meetups, and Lairs
 Background briefing - latitude, longitude, and GPS
  Coping with GPS device limitations
  Handling politics - borders, precincts, jurisdictions, and neighborhoods
 Finding out where we are with geocoding services
  Geocoding an address
  Reverse geocoding a latitude-longitude point
 How close? What direction?
  Combining geocoding and haversine
 Compressing data to make grid codes
  Creating GeoRef codes
 Decoding a GeoRef code
  Creating Maidenhead grid codes
 Creating natural area codes
  Decoding natural area codes
 Solving problems - closest good restaurant
  Creating simple Python objects
  Working with HTML web services - tools
  Working with HTML web services - getting the page
  Working with HTML web services - parsing a table
  Making a simple Python object from columns of data
  Enriching Python objects with geocodes
  Enriching Python objects with heath scores
  Combining the pieces and parts
  Working with clean data portals
  Making a simple Python object from a JSON document
  Combining different pieces and parts
  Final steps
  Understanding the data - schema and metadata

Chapter 5: A Spymaster's More Sensitive Analyses
 Creating statistical summaries
  Parsing the raw data file
  Finding an average value
   Understanding generator expressions
  Finding the value in the middle
  Finding the most popular value
 Creating Python modules and applications
  Creating and using a module
  Creating an application module
  Creating a hybrid module
 Creating our own classes of objects
  Using a class definition
 Comparisons and correlations
  Computing the standard deviation
  Computing a standardized score
   Comparing a sequence and an iterable
  Computing a coefficient of correlation
 Writing high-quality software
  Building a self-testing module and a test module
  Creating more sophisticated tests
  Adding doctest cases to a class definition
 Solving problems - analyzing some interesting datasets
  Getting some more data
  Further research

There you have it. You can easily tell that the sub-chapters and topics are all basic python data manipulation based, as opposed to security examples. This, coupled with the fact that the code is generally not compatible with python 2.7 code, makes this book for the narrower audience of those wanting to lean general programming vs those looking to learn new security related techniques. That said, the book keeps the reader entertained with its 'secret agent' them. Don't take my word for it, check out the preview offered by O'Reilly, and dig into some python 3 web queries and data parsing.

Thursday, February 12, 2015

AWS API Security Auditing Cheat Sheet

AWS provides a number of cloud based services for building out an entire information technology infrastructure. The API allows for a scriptable and command line interface for manipulating these various services in all kinds of ways. If you happen to come across AWS API keys in your penetration tests they can be extremely valuable for pivoting into this cloud infrastructure further penetrating your client organization. So let's jump right into the various services offered by AWS and some of their general vulnerabilities, before diving into the cheat sheet.

Some general AWS API vulnerabilities include:
Using the API and expressly not checking the SSL certificate.
Using the root account instead of limited IAM accounts.

Create config file w/ their keys:
echo "[default]" >> ~/.aws/config
echo "aws_access_key_id=[YOUR ACCESS KEY]" >> ~/.aws/config
echo "aws_secret_access_key=[YOUR SECRET KEY]" >> ~/.aws/config

It's also easy to spot the difference a user and a root key based on the naming convention:
root keys start with: AKIAIUM....
user keys starts with: AKIAIKA....

IAM or Identity and Access Management is a service that you can use to manage users and user permissions under your AWS account.

General AWS IAM vulnerabilities include:
Lack of key rotation
Lack of (inactive) key rotation
Lack of Multi-Factor Authentication (on root accounts)
Password and Access Key authorized for a given account
Existence of user policy
root account has active keys
root account used recently

EC2 allows users to launch instances, set network firewall rules to instance, move volume storage, and create snapshots of volumes.

General AWS EC2 vulnerabilities include:
Sensitive ports open to the Internet (e.g. SSH, RDP, SQL, ...)
Plaintext-protocol ports open (e.g. FTP, Telnet, ...)
Lack of network firewall rules (Inbound)
Lack of network firewall rules (Outbound)
Permissions to stand up fraudulent servers
Lack of monitoring for fraudulent servers
Unencrypted volumes

S3 allows users to store volumes, snapshots, and anything else in cloud hosted storage.

General AWS S3 vulnerabilities include:
Bucket world-writable
Bucket world-readable

CloudTrial allows organizations to create logging and audit trails of AWS API interactions.

General AWS CloudTrail vulnerabilities include:
Access CloudTrail logs
Disable CloudTrail logging

RDS or Relational Database Service makes it easy to set up, operate, and scale a relational databases in the cloud. These include MySQL, PostgreSQL, Oracle, Microsoft SQL Server, and Amazon's Aurora DB engine.

General AWS RDS Vulnerabilities include:
Database is exposed to internet

CloudFormation is a template service that describes all the AWS resources that you want to deploy (like EC2 instances or RDS DB instances), and AWS CloudFormation takes care of provisioning and configuring those resources for you.

General AWS CloudFormation vulnerabilities include:
Templates with database passwords

Elastic Beanstalk is a service for deploying and scaling web applications and services developed with Java, .NET, PHP, Node.js, Python, Ruby, and Docker on familiar servers such as Apache, Nginx, Passenger, and IIS.

General AWS Elastic Bean Stalk vulnerabilities include:
Permissions to stand up fraudulent stacks
Lack of monitoring for fraudulent stacks

Get your current user:
aws iam get-user

List all users of IAM (Identity / Access Management):
aws iam list-users

List user's access key for IAM:
aws iam list-access-keys --user-name [username]

List the groups a user belongs to:
aws iam list-groups-for-user --user [username]

List policy names applied to a group:
aws iam list-group-policies --group-name [groupname]

Get the contents of a policy:
aws iam get-group-policy --group-name [groupname] --policy-name [policyname]

List Cloudtrail logs:
aws --region us-east-1 cloudtrail describe-trails

Get Cloudtrail log status:
aws --region us-east-1 cloudtrail get-trail-status --name [default]

Stop Cloudtrail logging:
aws --region us-east-1 cloudtrail stop-logging --name [default]

List s3 storage buckets:
aws s3 ls

Download files from s3:
aws s3 cp s3://[bucket]/[sub-folder]/[file.txt] ./localfile.txt

List CloudFormation stacks:
aws cloudformation list-stacks

Describe CloudFormation stacks:
aws cloudformation describe-stacks

List user's access keys for ec2:
aws --region us-east-1 ec2 describe-key-pairs

List information about virtual machines / instances, such as volume IDs:
aws --region us-east-1 ec2 describe-instances

Get currently running output from a specific virtual machine:
aws --region us-east-1 ec2 get-console-output --instance-id [id]

Get group IDs and group names:
aws --region us-east-1 ec2 describe-security-groups

List user's access keys for ec2:
aws --region us-east-1 ec2 describe-key-pairs

To view volumes:
aws --region us-east-1 ec2 describe-volumes

To view snapshots, and find snapshot IDs:
aws --region us-east-1 ec2 describe-snapshots  #FilterOptions: --filter "status=pending" --filter "tag-value=*db_*"

View a snapshots attributes:
aws --region us-east-1 ec2 describe-snapshot-attribute --snapshot-id [id]

Start a new volume from a snapshot with encryption off:
aws --region us-east-1 ec2 ec2-create-volume --encryption off --snapshot [id]

Less useful password-data, not actual passwords :
aws --region us-east-1 ec2 get-password-data --instance-id [id]

If you are looking at a massive AWS environment, I suggest using iSECPartner's Scout2 to automate the assessment, it even takes multi-factor authentication. This tool is great for its output! It lists all of the categories based on the services which makes grouping, details, seeing specific vulnerabilities and the scope they effect easy to digest. Further, this tool automates the process across all regions to make sure you didn't miss any services in any regions. You can also add custom rule sets to the default findings, allowing the addition of vulnerabilities your organization has determined independently or within the scope of your assessment. To use it simply install it and follow the instructions below:

Export your keys as environment variables:

Or create CSV file w/ API keys:
echo "[YOUR USERNAME],[YOUR ACCESS KEY],[YOUR SECRET KEY]" > ~/.aws/creds.csv
And run scout pointing to your CSV:
python --credentials ~/.aws/creds.csv  

Another good tool out there for both auditing and monitoring your AWS instance is Netflix's Security Monkey. Netflix produces a lot of AWS tools, but security monkey is perfectly inline with our goals of finding AWS misconfigurations as well as alerting if these misconfigurations pop back up in the future. There's a lot of documentation on Security Monkey, so I'm not going to go into this tool too much now.

Lastly, I want to leave you with a general overview of AWS security, and why this is such a cool platform to mess with:

Wednesday, February 4, 2015

Python XMPP Command and Control

Lately, I've been having a lot of fun writing reverse shells for penetration testing that use interesting covert channels for their command and control (c2). Some of the best examples of covert channels being used for command and control are actually from real world malware; IRC has a long history of being used for c2. An even more modern take on this is using social media, and malware has taken to this, such as Flashback using Twitter or Whitewell using Facebook.

When I saw these examples, I immediately wanted to write a reverse shell that used social media, as these sites are inherently trusted on most networks. I soon found that DigiNinja beat me to it, having released KreiosC2, which can use both Twitter and LinkedIn as it's command and control channels. Kreios also has a number of interesting features that lend themselves to additional stealth and makes a great addition to a pentester's toolk kit, as a another well trusted and encrypted covert channel on the network we can leverage. Checkout the following bit which goes over using Kreios:

At the end of that excerpt, Robin calls out for more interesting c2 channels that are often on corp networks, and today we answer that call. This solution, a python based XMPP chat bot / shell, will connect to chat rooms much like the IRC bots would, but with the encryption and reputation of social media based XMPP servers (for example or I like this approach because it's a modern take on the 'IRC chat bot net' which is a really fun concept to play with because of how creative you can be with chat bots. The original poc which uses google talk,, requires a google account pre-established for the chat bot, with low security apps turned on. This is a great method for a reverse shell because the c2 server is actually, using XMPP over TLS. Once your account is set up you can easily set the bot to call back to you, as a unique chat bot take on the reverse shell concept. There is still a lot of functionality we will be adding to this special reverse shell over time, so make sure to check back as this is a fun project.

Tuesday, February 3, 2015

Python Steganographic Payload Dropper

Hey All! Recently on a penetration test, I needed to get a well known payload into a highly secure network, but could only go through a Blue Coat proxy which used Kaspersky's anti-virus for deep content inspection. To get around this, I decided to send a 'clear-text' image through the content inspection proxy, with my well known payload hidden inside using steganography, then extract it on the other side with my dropper. Note, all other ports have been blocked and the traffic has to travel through the proxy if it wants to connect to The Internet. Further, Kaspersky's proxy AV will block encrypted archives and files it doesn't recognize. Thus, all of this nonsense resulted in The Stego Dropper.

The dropper is a full python implementation of LSB-Steganography that reaches out to a hard coded website, downloads an image from that site, steganographically extracts an embedded executable out of the image, and then runs the extracted executable. The package also comes with a helper script to stego executables into images that will be placed on the attackers web server. Overall, this is a nice dropper for getting past deep packet inspection and good for testing defense in-depth during your penetration tests. This is also a great dropper for generally fooling SOCs as they will never see the tools being transferred over the wire.

This dropper works similar to the way Operation Shady Rat would download images and extract its configuration information out of them. To get a better understanding on how to use a dropper or tools like this in a security assessment, check out the presentation below:

Tuesday, January 27, 2015

Python Reverse DNS Shell

Recently a friend needed a reverse shell during a pentest, but could only connect out using DNS. To solve this, T1 and I whipped together a killer DNS based reverse shell. The shell uses legitimate DNS requests and responses to encode commands and exfiltrated data, making the traffic look like just a bunch of funky DNS requests on the wire. (I recently discovered dnscat, after writing my tool.)

The victim shell queries a specific IP address (the reverse shell server) for a DNS TXT record with a specific sentinel value. The reverse shell server will then respond with a DNS TXT record of base64 encoded commands. The victim shell will run these commands, and send the output back to the reverse shell server (this time as DNS A record requests, for multiple domains which together make up the output of the commands run on the server). This process will repeat until the reverse shell server issues the "quit" command to the victim. Like our other python reverse shells, this is pretty easy to build down to a native executable.

The backdoor more or less works as described in the below video, but there are still some major short comings in our backdoor, which we will be updating over time: