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.

Wednesday, December 5, 2012

On Sophistication

Having played both the attacker and defender role for many years something I have often seen and even done myself is make statements and assumptions about the "sophistication" of my adversary.

Often when some big hack occurs, blogs, media stories and quotes from experts will espouse opinions that "the attacker was not very sophisticated" or "it was an extremely sophisticated attack". I believe that often times, and I myself have been guilty of this, these assertions are the result of a wrong headed analysis and misunderstanding of what sophistication means in the context of computer attacks.

An example will help illustrate the point. I have heard stuxnet labeled both sophisticated and unsophisticated. One might be tempted to point to the inclusion of 4 0days as proving that highly skilled attackers launched this attack. Well 0days can be bought. Others might say; well the way it was caught and the fact that it could infect more than it's presumed target means the attackers weren't very good. Even the most well developed attacks get caught eventually. (See the device the Russians implanted in the Great Seal 60 years ago)

A truly sophisticated attacker will use only what is necessary and cost effective to achieve their goals and no more. An even better attacker will attempt to convince you they are not very good and waste as much of your time as possible while still achieving the goal.

I would put forth the idea that the determination of sophistication be based on the following:

Did the attacker achieve their goals?

Let us assume further that these goals consist of:

1.) Gaining unauthorized access to one or more of your systems

If they achieve #1 then they have already proven to be more sophisticated than your first line of defensive / prevention system as well as your user awareness and training program.To speak of the attacker as unsophisticated because they used an automated SQL injection tool or basic phishing email is silly because you have no idea how good they are based soley on the penetration mechanism and they are already more sophisticated than your ability to stop them.

2.) Evasion of detection, at least for the period of time required to complete some goals

If they have a shell on one of your systems, and nothing detects, alerts or responds, then the attacker is more sophisticated than your SIM implementation, IDS and first line analysts at least from the detection during initial attack standpoint. The fact that they used XOR vs full SSL to protect network communications from detection is irrelevant and gives you no clue as to how good they are.

3.) Access to and/or exfiltration of sensitive data

If the attacker has been able to take the data they are targeting then they have overcome your internal controls, ACLs and data protection. It matters not if they used a zip file or steganography to package the data.

4.) Persistence

If the attacker can persist with unauthorized access on your system for any period of time then they have outsmarted your defensive team, your secure configuration management and basically all your defenses. It doesn't matter if their method of persistence is a simple userland executable launched from the Run key in the registry or a highly stealthy kernel driver, they won that round.

5.) Effect

If they can cause a real world effect such as blowing up your centrifuges, gaining a competitive advantage, or spending your money then that is the final nail in your coffin. They are more sophisticated than you are, regardless of what type of exploit they used, if it was a 10 year old PERL CGI bug or one that uses memory tai chi to elegantly overcome windows 7 buffer overflow protection. 

Lets think about this for a minute. Think of all the money, time, resources and personel you have expended on perimeter defense, detection and alerting, and analytical teams. Think of the work involved at the vendors who have developed all of the products and appliances you have purchased. The PHDs at AV vendors designing heuristics, the smart guys and girls developing exploits and signatures at your favorite IDS company. The awesome hax0rs at the pen test company you just hired. The often millions of dollars spent on defense.

All of this and the attacker has subverted it, maybe with a month of work, maybe less, and considerably less funding in most cases. So who is the sophisticated one?

The only place you might have won is in the forensics post-event department, usually the least funded and most resource starved component of your program. This is usually where the determination is made that the attacker was not very sophisticated because it was possible to reverse engineer the attack and understand the tools and techniques used. That's great but just because you an understand that an assasin used a rock to kill a VIP doesn't mean the assasin sucks if they got away from the highly skilled protection detail, the target is dead, and their identity remains unknown.

So pause for a moment before you label an attacker unsophisticated or a skript kiddie. Ask yourself, did they achieve the above mentioned goas? If so then they outsmarted you.

V.