The big news right now is the remote code exploit in Samba that could allow an attacker to run arbitrary code on a linux machine as root. This is a big ugly and I wouldn't be surprised to see exploit code coming soon that does more than the current proof of concepts do.
Linux has a way of being in a lot of places even when you don't expect it to be. Embedded devices are an example of machines that might be running linux and might not get patched as frequently as they should. So we need a way to identify the machines that are running Samba versions that are vulnerable to this exploit. Here is my first attempt.
Since I have a large IP space to scan, I decided to approach the problem in multiple passes. In the first pass I used nmap to get fast results even though the results will not be detailed enough to answer my question. Here is the command that I used:
nmap -PN -T5 -p445 -sV -oG /tmp/nmap-output.txt 10.0.0.0/16
That will create a list of machines that are running anything on port 445. Now let's trim that down to just a list of the ip addresses of machines that are running some version of samba.
grep Samba /tmp/nmap-output.txt | cut -d" " -f2 > /tmp/samba-list.txt
For the second pass around the network I decided to use the smb_version module in metasploit. It's not well known, but you can pass a file instead of an ip address into the rhosts option. Here are the options that I set:
When I run that, I get the specific version number that is running on each machine. Now when a machine is updated to Samba 3.6 I'll know that I don't have to worry about it anymore. It is a lot faster to do this in multiple passes because nmap will run through a large network quite a bit faster than the metasploit module (possibly because it is gathering less information).
So there's my quick and dirty trick to find the work that still needs to be done.
Wednesday, April 11, 2012
Tuesday, March 27, 2012
Bayesian Network to Combat Twitter Spam
Ever since I learned about Bayesian networks I see them everywhere. I'm constantly constructing them in my head and sometimes I even put them into samiam so I can see what it looks like and play around with some of the values. Recently I started thinking about applying this to Twitter spam. I've seen an uptick in the amount of spam I'm getting on Twitter so this is constantly coming up for me.
Now whenever you're talking about spam it's a good idea to read the classic Slashdot post that often appears when talking about spam. If you read Slashdot, you've seen this: http://tech.slashdot.org/comments.pl?sid=954433&cid=24892585. The reason I suspect that Twitter is in a different place is that it is the only source of Tweeting, so if you have a solution that requires everyone to change at once Twitter is actually able to make that happen. Anonymous senders from other countries are less of a problem because it isn't like there are any open Twitter relays out there (are there?).
So this is what my Bayesian network looks like. The network tries to decide if it should allow a message, throttle a message, or completely block the sending account and make them go through some hoop to restore access. The decision to allow/throttle/block is made based on the reputation of the tweeter, suspiciousness of the message, and any indicators that the account has been compromised.
The indicators of compromise is a set of information that Twitter would likely be able to gather that an MTA would never be able to reliably evaluate. The network would evaluate whether the user's account had a recent password change and if the message was being sent from a geographic region or time of day that is unusual for the user. The network would also look for significant upticks in the number of tweets being sent by the user.
Of course any spam system needs to evaluate the content of the message so mine would look for keywords or phrases and the presence of links. In particular, a message that includes only a link and a handle would be viewed suspiciously. Also of note is the relationship between the sender and recipient. If there has been two-way communication the message will be less suspicious but if there is only one-way communication or zero previous communication the message again becomes suspicious in the presence of the other indicators.
The most complicated part of the network is evaluating the reputation of the sender. The reputation is made up of how much the sender has participated in Twitter and how the user has been accepted by the Twitter community. Users that have many followers and retweets are viewed more favorably than new users with few followers. Recent spam complaints affect both the acceptance of the user and are also an indicator of compromise. The network would also try to evaluate how long the sender has been a member of twitter, how often the user tweets and how many people the sender is following.
Combatting Spam
The techniques for combating spam are fairly well known, things like reputation of the sender and the content of the message. There are, of course, problems for dealing with spam in email. For example, my MTA usually doesn't know much about the sender of the email message that it is evaluating. But Twitter is in a unique position in that it knows every tweet that has been sent. When I send a tweet the Twitter application knows how long I have been a member, how many followers I have, when I last reset my password, what IP addresses or phone numbers I use and what time I typically tweet. I imagine if my MTA knew that kind of detail about the sender of every email message that it evaluates spam would have been a solved problem by now.Now whenever you're talking about spam it's a good idea to read the classic Slashdot post that often appears when talking about spam. If you read Slashdot, you've seen this: http://tech.slashdot.org/comments.pl?sid=954433&cid=24892585. The reason I suspect that Twitter is in a different place is that it is the only source of Tweeting, so if you have a solution that requires everyone to change at once Twitter is actually able to make that happen. Anonymous senders from other countries are less of a problem because it isn't like there are any open Twitter relays out there (are there?).
Bayesian Network
The indicators of compromise is a set of information that Twitter would likely be able to gather that an MTA would never be able to reliably evaluate. The network would evaluate whether the user's account had a recent password change and if the message was being sent from a geographic region or time of day that is unusual for the user. The network would also look for significant upticks in the number of tweets being sent by the user.
Of course any spam system needs to evaluate the content of the message so mine would look for keywords or phrases and the presence of links. In particular, a message that includes only a link and a handle would be viewed suspiciously. Also of note is the relationship between the sender and recipient. If there has been two-way communication the message will be less suspicious but if there is only one-way communication or zero previous communication the message again becomes suspicious in the presence of the other indicators.
The most complicated part of the network is evaluating the reputation of the sender. The reputation is made up of how much the sender has participated in Twitter and how the user has been accepted by the Twitter community. Users that have many followers and retweets are viewed more favorably than new users with few followers. Recent spam complaints affect both the acceptance of the user and are also an indicator of compromise. The network would also try to evaluate how long the sender has been a member of twitter, how often the user tweets and how many people the sender is following.
Getting Scientific
One beautiful thing about Twitter being the sole source of tweets is that they likely have excellent data about the whole population of tweets and twitters. For example, of new accounts being created how many are shut down within one week for spamming. How many spam complaints come in for a given reporting period. This is data that we can use to populate the probabilities in our network and measure success down the road.
One technique I would try is to build this network and then have it select 1000 random tweets that it would have blocked and have those tweets reviewed by a human. That should give us an idea of our false positive rate. After the system is implemented we can look for a reduction in the volume of spam complaints. There are obviously more metrics to look at; the point is that we want to find some evidence to support whether a system like this actually reduces the volume of spam. If we can validate the system that way, then we have real evidence to back up our best practices and suggest these measures to the next social media site that is going to blow up. I'm talking to you, Pinterest.
Skepticism
I recently finished reading The Drunkards Walk and How We Decide and picked up a few tips for making better judgements. One trick that I really liked was to try to list three reasons why you're wrong. Look for evidence that your hypothesis is wrong rather than evidence that it is correct. Hypothesis1 is that a Bayesian network like this will measurably reduce Twitter spam. Hypothesis2 is that the system is practical. I'm going to cheat a bit and just come up with three objections rather than six.
- This is too hard for a computer to do for the high volume of tweets that Twitter deals with. (Hypothesis2)
- The false positive rate will be too high for users to accept. (Hypothesis2)
- Spammers will be able to easily adjust to avoid the system as they always have (Hypothesis1)
I think the first two of these objections can actually be proven or disproven so I'm not too worried about them. With the last one it is difficult to prove or disprove and there is a lot of evidence that spammers are able to work around spam filters, so that might derail the whole approach. I would say more thought is required on that one.
Simple Fix
Sometimes its better to implement something simple that isn't as effective because you can implement that quickly for little cost. I wonder what kind of dent it would put in Twitter spam if Twitter simply throttled messages that are going from a sender to a recipient that have never interacted before and which only contain a link and a couple words. Then while the tweets are throttled, block the account after a few spam complaints.
Stats for Risk Modelling: Poisson and Lognormal distributions
This is a blog entry that I wrote for the Society for Information Risk Analysts blog on March 5, 2012. https://www.societyinforisk.org/content/stats-risk-modelling-poisson-and-lognormal-distributions
It's been a while since I wrote up a blog post explaining some distributions, and I thought this time I might try something a little different. I'm going to combine them into a scenario and build a model around that using the distributions that I want to explain. So let's give it a shot and see how well it works.
I work at a University, and Universities are widely seen as a hotbed of piracy by large content holders. So as you can imagine, every semester I receive a fairly decent pile of DMCA takedown requests that I need to handle. And of course I also receive a fair number of calls from vendors selling me a product to help manage or eliminate my copyright complaints. Let's define some variables.
Every semester I receive at least 80 copyright complaints and I have never received more than 113 in a semester. The only exception is summertime when I usually get 3 to 5. On average I spend about 5 to 10 minutes dealing with a single copyright complaint, however there are extreme cases where I have spent over an hour with a complaint that involved a repeat offender and a referral to the Student Conduct office. And since I am a low-paid state worker, I make $100/hour (at least in this scenario).
The question is: should I be willing to spend $30,000 plus another $5000 in labor to purchase a product that promises to cut my copyright complaints down to a quarter of what I'm getting right now? The product will also require approximately $10,000/year in licensing costs.
So the first thing we should try to model is the number of copyright complaints that I'm going to receive in a semester, and in this case I'd like to use the Poisson distribution. Poisson is your friend when you're trying to model the frequency of something within a space of time. For example, the number of defects a machine produces in an hour or how many people will call into your call center between 9:00am and 10:00am. Poisson is really easy to understand because all we need is the average number to create a distribution. The major thing to watch out for is that Poisson is intended for modeling independent variables, meaning that each event has equal probability and one event does not trigger the next event. I have come to believe that there are very few truly independent variables out there, but there are a lot of variables that are independent enough. These two graphics show the Summer and Spring distribution. For Spring, I selected an average of 96.5, which is right between my minimum and my maximum. The result is a distribution that is heavily weighted around 100, but is willing to accept that sometimes I'm going to get 65 or 130 in a semester. In the Summer, there is about a 5% chance that I wont get any at all, but I could see a rough year that puts me up to 8.

The next variable I want to model is how much time I spent on each copyright complaint. In this case, we have an average of 10 to 15 minutes per complaint, but there are rare but extreme examples of the time stretching into hours. The distribution I've chosen to use is Lognormal. Lognormal is a continuous distribution, so we're able to get values that fall between the units; for example a complaint could take 12.28 minutes to resolve. Lognormal is particularly well suited to distributions that have long tails with low probability on the far side. I have selected an average of 15 minutes, and a standard deviation of 25 minutes. Just like with a normal distribution, the standard deviation tells us the dispersion of the variable. A larger number means that there is more variability and the spread is wider. Here is a graph of what a single copyright complaint might require for time. You can see that 58.9% of the simulated copyright complaints will take ten minutes or less. You can't see it in this picture, but 71.8% will take 15 minutes or less. 3.8% of the simulations will require more than an hour of my time.
Now the challenging part: in each semester I am going to generate a random number of events, and then I need to add that many instances of my impact variable. If that sounds like a bit of mental gymnastics, consider this: what if my frequency variable returns a value of 130 copyright complaints and my impact variable returns a value of 60 minutes. If I multiply the first variable by the second I will get a result that is so astronomically unlikely that it isn't worth considering at all. My model will be returning junk. Someone from Vose Software, maybe David Vose himself, put a fantastic video of how to handle this situation the right way and wrong way on YouTube: http://www.youtube.com/watch?v=0EZLiDyfF30. I was really disappointed to learn that there isn't a clean and easy way to do this in @Risk, and the free version of ModelRisk that I downloaded doesn't have the aggregate feature either. I'm not going to buy another software product to do something that @Risk should do, so I had to get a little more creative.
The way I solved this problem was to put a distribution of impact into a cell and copy that formula down 300 rows. I know that I am rarely going to have my simulation return more than 264 copyright complaints for a single year so that seemed safe. I highlighted the whole column and named the column 'Simulations' in Excel. The Simulations table starts in row C9 in my spreadsheet, and the output of my Poisson distribution is in cell C2. So in another cell I put in this formula: SUM(OFFSET(C9,0,0,C2,1)). The offset formula is a lot of fun, it returns a range of cells starting from a reference cell. My reference cell is C9. I tell offset to start at C9, move over zero columns and zero rows, then return a range that is 1 column wide and has a height of whatever is in C2. So even though my spreadsheet is going to generate 300 instances of my impact variable, I'm only going to add up whatever number my frequency distribution outputs. It's a lot of wasted computing effort, I know. Here is the output of the total number of minutes:
The max number was 5064 minutes spent on copyright complaints per year. Notice that the shape of the distribution looks nothing like the Lognormal distribution that we defined for impact. That's the Central Limit Theorum at work again. When you add a number of random variables the result becomes more and more Normal. That's another reason why we can't just multiply one instance of our impact varaible by the frequency variable. What we would get is a really really big Lognormal distribution which does not reflect what happens when you add up random variables. When I mutliply this by my per-minute rate of $1.67 I get a cost distribution that looks like this:
The maximum on this was $8,440 which doesn't even cover the yearly maintenance let alone the upfront cost of the application. So I feel confident that it is more efficient for me to continue processing copyright complaints manually rather than purchasing software. Also, I don't really make anywhere close to $100/hour so the odds of recommending that we purchase this software is very low. This is the exact technique I use to convince my boss not to purchase another product that I have to maintain. If that isn't a Risk Management success story then I don't know what is.
So here is the takeaway from this blog post:
- If you're modeling the frequency of an event and the probability of each event is constant then try out the Poisson distribution. But if one event raises the probability of another then Poisson probably isn't the right choice.
- For impacts that have long tails with low probability the Lognormal distribution is probably the best choice to model the variable.
- Be careful when you multiply two variables. Multiplying one instance of a variable by 80 is not the same as adding up 80 instances of a random variable.
Monday, February 20, 2012
Analytic Hierarchy Process for IT Project Selection
A couple weeks ago I had the opportunity to meet with the IT leadership at another university outside of the state where I work. I really value opportunities like that because it gives me a chance to learn what approaches are being used without sitting in the echo chamber that sometimes forms among the usual set of schools that I talk to. Much of the time we talked about IT Project Management and one question that came up in particular was how to prioritize which projects will be green lighted for the next development cycle when there are several candidates with equal or nearly equal priority. That lead to an interesting discussion about the importance of having a steering committee made up of a variety of stakeholders and an open process for weighing projects.
Since then I've had more time to think about that open process for weighing projects, and I'd like to explore the use of Analytic Hierarchy Processing (AHP) to prioritize projects. I'm not going to explain the entire AHP process here, but I'll give you the four sentence explanation. AHP is similar to using a weighted matrix to prioritize items. Just like with a weighted matrix, you're still going to decompose the decision into various items of concern and try to gauge the importance of each one. And you're going to then try to decide on how well each alternative scores in each of those categories just like you would with a weighted matrix. The magic of AHP is that each one of these decisions is arrived at mathematically by making a series of comparisons between two items. That is much easier to do than looking at a long list of criteria and trying to assign weights all at once. So you might consider both time and budget when prioritizing projects. At some point you will be asked which of these two is more important and how much more important using an ordinal scale. The AHP will develop the weights and the scores of each alternative and produce information about the logical consistency of the result. Wikipedia has a great walk-through of the process: http://en.wikipedia.org/wiki/Analytic_hierarchy_process
This post is mainly about the criteria that should be used when comparing the projects. I was just writing some stuff down the other day and I came up with this list. I'm sure we could add more to it, but I think that if you even used these items verbatim you would have a process that is consistent, valid, repeatable, and defensible for selecting IT projects. Especially if the process of rating the projects and the selection of criteria is driven by the steering committee that I talked about earlier.
- Estimated time to complete the project - A%
- Estimated cost of the project - B%
- Alignment with the organization's strategic priorities - C%
- Priority 1 (some fraction of C%)
- Priority 2 (some fraction of C%)
- Priority 3 (some fraction of C%)
- Alignment with ITS priorities - D%
- Urgency of need - E%
- Number of stakeholders benefiting from the project - F%
- Perceived absence of risk - G%
- How long has this project been in the queue - H%
After going through the AHP on each of the proposed projects you should have them ranked in such a way that you can tell which ones are the most important and how much more important they are. Rather than a typical ordinal scale, the output of AHP is a ratio so a project that scores .2 is twice as "good" as a project that scores .1. Now you can select which of the big projects that will take up most of the development cycle will get green lit. It's also easy to see which of the smaller projects you should use to round out the development cycle.
If you want to play with this some more, check out the demo of Make it Rational's product for performing AHP. The demo runs in a browser and seems to be fully featured except for the ability to save your work. http://makeitrational.com/demo
Tuesday, December 27, 2011
Rails authentication using Devise and devise_ldap_authenticatable
About a week ago I posted about my attempts to integrate Rails applications with Active Directory. I have successfully rolled my own authentication using net/ldap, but I want to use a gem so that there will be more than just me using it and fixing it up.
Last week I was successful getting Devise and Omniauth-ldap to work together to integrate with Active Directory, but I decided that the solution was not enterprise-ready because there is currently no way to override the login page and make it look like the rest of my application.
Now I think I have the solution, and it was a little bit easier too. Devise + devise_ldap_authenticatable. Here is the walkthrough for what worked for me.
Adding your Gems
For this project I am going to add the following lines to my gemfile:
The annotate gem and the nifty-generators gem aren't necessary, but I like to use them. Nifty-generators will make the flash notices that you'll need later on in the project so you might consider using it if you're just following along. Now run bundle to get everything set up.
Setting up nifty-generators
Configuring devise for user management
Now we need to create a model for our users, and we'll call that model User. We will use devise because then we'll have all of the helpers created for things like checking if the current user is authenticated. This part is amazingly simple.
Setting up devise_ldap_authenticatable
First we need to generate the devise_ldap_authenticatable installation.
Now we need to set the LDAP parameters used to connect to Active Directory. This is kept config/ldap.yml.
The most important thing here is that you set the attribute to sAMAccountName and that you have the full DN and password of your binding user. There are options here to force certain group membership or make sure that certain attributes are set, but I haven't played with that yet. Right now, anybody that is a member of the domain is able to log into my app.
The last thing we need to do is make some edits to config/initializers/devise.rb which has some new options that were added by the devise_ldap_authenticatable installer. This is why my configuration looks like:
Look a little further in the document to find these lines and change them to match mine:
Changes to the user model
We want to keep track of some Active Directory attributes, so we need to make a few changes to our user model. Let's add a firstname, lastname, username, and displayname field.
This is when I like to use annotate so that I can keep track of what I've done to my models. Anyway, lets take a look at the app/models/user.rb file. We need to update our attributes accessible, and add some methods to pull in Active Directory attributes and save them with our user.
Changes to the views
The final change is to make sure that our view is going to reflect whether or not a user is logged in and provide some basic information about the logged in user. I added this right under the title in app/views/changes/index.html.erb
We also need to make a critical change to the login form. Right now it is still asking for an email address and it wont let you get away with typing a username into the email field. So we need to have devise show us our view so that we can edit it.
rails generate devise:views
Now edit app/views/devise/sessions/new.html.erb. Change the email label to say username and change the email_field to text_field.
Also, if you want to have the user redirect to your root path, then you need to add something like this to config/routes.rb
Last week I was successful getting Devise and Omniauth-ldap to work together to integrate with Active Directory, but I decided that the solution was not enterprise-ready because there is currently no way to override the login page and make it look like the rest of my application.
Now I think I have the solution, and it was a little bit easier too. Devise + devise_ldap_authenticatable. Here is the walkthrough for what worked for me.
Adding your Gems
For this project I am going to add the following lines to my gemfile:
gem "nifty-generators", :git => 'https://github.com/ryanb/nifty-generators.git' gem 'devise' gem 'devise_ldap_authenticatable', :git => 'git://github.com/cschiewek/devise_ldap_authenticatable.git' gem 'annotate', :git => 'git://github.com/ctran/annotate_models.git'
The annotate gem and the nifty-generators gem aren't necessary, but I like to use them. Nifty-generators will make the flash notices that you'll need later on in the project so you might consider using it if you're just following along. Now run bundle to get everything set up.
Setting up nifty-generators
There are a couple steps that I'm going to go through to set up nifty-generators which are optional if you decide that you don't mind having your rails project look ugly.
Also, make sure you edit config/routes.rb and add a path to root:rails generate nifty:config
rails generate nifty:layout
rails generate nifty:scaffold Change title:string description:string
cp public/stylesheets/application.css app/assets/stylesheets/nifty.css
rm public/index.html
cat app/views/layouts/application.html.erb | sed \
's/javascript_include_tag :defaults/javascript_include_tag "application"/' \
> /tmp/what.txt
cp /tmp/what.txt app/views/layouts/application.html.erb
rake db:migrate
root :to => 'changes#index'At this point you should have a working application that will allow you to create, edit, and delete changes. It should look nice and neat. Make sure that you have the ability to delete objects, and if you do not check the line in app/views/layouts/application.html.erb to make sure that javascript_include_tag is including "application" not :defaults. A tell-tale sign that javascript is the source of your delete problem is that when you try to delete a change you're not even given the "are you sure" prompt.
Configuring devise for user management
Now we need to create a model for our users, and we'll call that model User. We will use devise because then we'll have all of the helpers created for things like checking if the current user is authenticated. This part is amazingly simple.
Bam! That's it. Now you have a user model with all kinds of neat options. If you didn't want to perform Active Directory authentication you would be almost done now with just some work to customize the views.rails generate devise:installrails generate devise Userrake db:migrate
Setting up devise_ldap_authenticatable
First we need to generate the devise_ldap_authenticatable installation.
rails generate devise_ldap_authenticatable:installThere are options that you can set, but I don't need them. The gem assumes that your user model is called User which mine is.
Now we need to set the LDAP parameters used to connect to Active Directory. This is kept config/ldap.yml.
development: host: domaincontroller.domain.com port: 389 attribute: sAMAccountName base: dc=domain,dc=com admin_user: cn=admin,dc=test,dc=com admin_password: admin_password ssl: false # <<: *AUTHORIZATIONS
The most important thing here is that you set the attribute to sAMAccountName and that you have the full DN and password of your binding user. There are options here to force certain group membership or make sure that certain attributes are set, but I haven't played with that yet. Right now, anybody that is a member of the domain is able to log into my app.
The last thing we need to do is make some edits to config/initializers/devise.rb which has some new options that were added by the devise_ldap_authenticatable installer. This is why my configuration looks like:
# ==> LDAP Configuration
config.ldap_logger = true
config.ldap_create_user = true
# config.ldap_update_password = true
config.ldap_config = "#{Rails.root}/config/ldap.yml"
config.ldap_check_group_membership = false
config.ldap_check_attributes = false
config.ldap_use_admin_to_bind = true
# config.ldap_ad_group_check = false
Look a little further in the document to find these lines and change them to match mine:
config.authentication_keys = [ :username ] config.case_insensitive_keys = [ :email, :username ]
Changes to the user model
We want to keep track of some Active Directory attributes, so we need to make a few changes to our user model. Let's add a firstname, lastname, username, and displayname field.
rails generate migration add_fields_to_users firstname:string lastname:string username:string displayname:string
rake db:migrate
This is when I like to use annotate so that I can keep track of what I've done to my models. Anyway, lets take a look at the app/models/user.rb file. We need to update our attributes accessible, and add some methods to pull in Active Directory attributes and save them with our user.
attr_accessible :username, :email, :password, :password_confirmation, :remember_me, :firstname, :lastname, :displayname
before_save :get_ldap_lastname, :get_ldap_firstname, :get_ldap_displayname, :get_ldap_email
def get_ldap_lastname
Rails::logger.info("### Getting the users last name")
tempname = Devise::LdapAdapter.get_ldap_param(self.username,"sn")
puts "\tLDAP returned lastname of " + tempname
self.lastname = tempname
end
def get_ldap_firstname
Rails::logger.info("### Getting the users first name")
tempname = Devise::LdapAdapter.get_ldap_param(self.username,"givenname")
puts "\tLDAP returned firstname of " + tempname
self.firstname = tempname
end
def get_ldap_displayname
Rails::logger.info("### Getting the users display name")
tempname = Devise::LdapAdapter.get_ldap_param(self.username,"displayname")
self.displayname = tempname
end
def get_ldap_email
Rails::logger.info("### Getting the users email address")
tempmail = Devise::LdapAdapter.get_ldap_param(self.username,"mail")
self.email = tempmail
end
Changes to the views
The final change is to make sure that our view is going to reflect whether or not a user is logged in and provide some basic information about the logged in user. I added this right under the title in app/views/changes/index.html.erb
<% if user_signed_in? %>
Welcome <%= current_user.firstname %>, you last logged on <%= current_user.last_sign_in_at %> from <%= current_user.last_sign_in_ip %>
<% else %>
<%= link_to "login", new_user_session_path %>
<% end %>
We also need to make a critical change to the login form. Right now it is still asking for an email address and it wont let you get away with typing a username into the email field. So we need to have devise show us our view so that we can edit it.
rails generate devise:views
Now edit app/views/devise/sessions/new.html.erb. Change the email label to say username and change the email_field to text_field.
Also, if you want to have the user redirect to your root path, then you need to add something like this to config/routes.rb
match '/changes' => 'changes#index', :as => 'user_root'
Tuesday, December 20, 2011
Rails authentication using devise and omniauth-ldap
Recently I've been doing some development in Ruby on Rails and I wanted to be able to have users log into the application using Active Directory credentials and I wanted some user information to persist in a database so that I could make objects belong_to a User. In this case the application is for IT Change Management so I have two models, User and Change. User has_many changes and Change belongs_to user. I started to code something up myself, but then I thought I would take some time to figure out how to do it using some of the gems out there that make life simple. So I wanted to combine devise with omniauth-ldap. It took me a while to get it all working, and so I want to document my process for everyone (especially me) to come back and reference. So here is my walkthrough of creating a very simple application using devise and omniauth-ldap for user management.
Adding your gems
For this project I am going to add the following lines to my gemfile:
Also, make sure you edit config/routes.rb and add a path to root:
You have probably also seen some devise warnings popping up when you run some of these commands. Don't worry, we're going to take care of that in the next section.
Configuring devise for user management
Now we need to create a model for our users, and we'll call that model User. We will use devise because then we'll have all of the helpers created for things like checking if the current user is authenticated. This part is amazingly simple.
Integrating omniauth-ldap into devise
There are two things that really caused me a lot of headache and once I learned them this whole process went a lot faster. The first thing you should know is that omniauth-ldap does not use the credentials that the user enters to bind to LDAP. So unless your Active Directory is configured to allow anonymous LDAP then you're going to need to provide credentials for binding. I wasn't doing that and I couldn't figure out why I kept getting LDAP errors. The second thing that is useful to know is that the configuration for omniauth-ldap is done in the devise initialization file: config/initializers/devise.rb. If you go to the github site for omniauth-ldap, Ping (the author) has some instructions and a sample application (look in the wiki for the sample application). In that sample application, the omniauth-ldap configuration is in a file called config/initializers/omniauth.rb. In our application, we're going to ignore that and instead put that into config/initializers/devise.rb. Look for the string config.omniauth and include this in the configuration right after the comments:
Setting up your views
In my view, I want to do something really simple. If a user is logged in, I want to welcome them and provide a logout link. If a user is not logged in, I want to present a login link. So I'm going to go into app/views/changes/index.html.erb and add this right under the title:
We also need to make a change to our user model that was generated by devise. If you look in app/model/users.rb you'll see a line with some devise configuration that makes this user model :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, and :validatable. To this list we need to add :omniauthable. If you're seeing an error about user_omniauth_authorize_path not being defined it is because you didn't add :omniauthable to the user model.
At this point your application should run and you should be able to click those links. You'll be taken to an ugly looking log in screen. Log in isn't going to work yet because we haven't wired up the callback. Here are a couple tests you can run to make sure that everything is right so far. 1. Try to log in with valid credentials. You'll be directed to a sign in page and see an error message that you couldn't log in because of an LDAP error. 2. Try to log in with invalid credentials. This time you'll be redirected to the same page, but you'll have an error message about invalid credentials.
More changes to the User model
In my case I want to retain some information about the user that is returned from LDAP so that I can have associations between changes and users. So we need to generate a migration to add a few database fields to our User table. Run this command:
When you successfully authenticate to LDAP you'll get back a big bundle of information about the user. We're going to use that information to either log in an existing user or create a new user and log that user in. The code for this is going to be located in the omniauth_callbacks file which does not exist right now. We need to create the file and add a method called ldap to handle the way LDAP results are returned. This ldap method is going to check if there is an existing user and log that person in, otherwise create a new user. Here is the code for that file:
This information could use a bit of explaining. The results from LDAP are put into an environment variable called omniauth.auth, which is in a format called omniauth.auth format. If we were using something like Facebook or Twitter for our authenticator omniauth could probably figure out things like the username and this code wouldn't be as ugly. But the data we need is in an a hash called raw_info, which itself is a hash within a hash within a hash. Each of the return values that we need are in an array, so my firstname is in an array which is why I have to put the [0] after ldap_return.givenname. Don't worry too much about the email line, in your organization you probably will be able to use ldap_return.email. In my case, the email address that I want an application to use is different than what is stored in that value, so I am grabbing an address from a different part of the response and stripping off the SMTP: that appears at the begining.
What's next?
We have a working application that can authenticate users via Active Directory. There are a few loose ends that I would like to clean up, but this is as far as I was able to get. For example, if a user's authentication fails he is redirected to a sign up page that I don't want them to see. However, I wasn't able to figure out how to change the application routing to make them redirect to the sign in page instead. Also, the login page is not customizable at all. That really doesn't work for an enterprise environment which is where you're most likely to see Active Directory integration. It looks unprofessional when your user gets redirected to a login page that looks nothing like the rest of your site.
So while this will work for back end stuff or personal stuff that you aren't going to expose to the end users it isn't going to meet your needs right now for enterprise applications. If you want Active Directory integration that looks professional you're stuck with rolling your own for now.
I hope someone proves me wrong in the comments. I really wanted this to work.
Adding your gems
For this project I am going to add the following lines to my gemfile:
gem "nifty-generators", :git => 'https://github.com/ryanb/nifty-generators.git' gem 'devise', :git => 'https://github.com/plataformatec/devise.git' gem 'omniauth-ldap', :git => 'https://github.com/intridea/omniauth-ldap.git' gem 'annotate', :git => 'git://github.com/ctran/annotate_models.git'The annotate gem and the nifty-generators gem aren't necessary, but I like to use them. Nifty-generators will make the flash notices that you'll need later on in the project so you might consider using it if you're just following along. Now run bundle to get everything set up.
Setting up nifty-generators
There are a couple steps that I'm going to go through to set up nifty-generators which are optional if you decide that you don't mind having your rails project look ugly.
rails generate nifty:config
rails generate nifty:layout
rails generate nifty:scaffold Change title:string description:string
cp public/stylesheets/application.css app/assets/stylesheets/nifty.css
rm public/index.html
cat app/views/layouts/application.html.erb | sed \
's/javascript_include_tag :defaults/javascript_include_tag "application"/' \
> /tmp/what.txt
cp /tmp/what.txt app/views/layouts/application.html.erb
root :to => 'changes#index'At this point you should have a working application that will allow you to create, edit, and delete changes. It should look nice and neat. Make sure that you have the ability to delete objects, and if you do not check the line in app/views/layouts/application.html.erb to make sure that javascript_include_tag is including "application" not :defaults. A tell-tale sign that javascript is the source of your delete problem is that when you try to delete a change you're not even given the "are you sure" prompt.
You have probably also seen some devise warnings popping up when you run some of these commands. Don't worry, we're going to take care of that in the next section.
Configuring devise for user management
Now we need to create a model for our users, and we'll call that model User. We will use devise because then we'll have all of the helpers created for things like checking if the current user is authenticated. This part is amazingly simple.
Bam! That's it. Now you have a user model with all kinds of neat options. If you didn't want to perform Active Directory authentication you would be almost done now with just some work to customize the views. Now we're going to start on the stuff that took me the longest.rails generate devise:installrails generate devise Userrake db:migrate
Integrating omniauth-ldap into devise
There are two things that really caused me a lot of headache and once I learned them this whole process went a lot faster. The first thing you should know is that omniauth-ldap does not use the credentials that the user enters to bind to LDAP. So unless your Active Directory is configured to allow anonymous LDAP then you're going to need to provide credentials for binding. I wasn't doing that and I couldn't figure out why I kept getting LDAP errors. The second thing that is useful to know is that the configuration for omniauth-ldap is done in the devise initialization file: config/initializers/devise.rb. If you go to the github site for omniauth-ldap, Ping (the author) has some instructions and a sample application (look in the wiki for the sample application). In that sample application, the omniauth-ldap configuration is in a file called config/initializers/omniauth.rb. In our application, we're going to ignore that and instead put that into config/initializers/devise.rb. Look for the string config.omniauth and include this in the configuration right after the comments:
config.omniauth :ldap, :host => 'YOUR_LDAP_SERVER, :base => 'THE_BASE_WHERE_YOU_SEARCH_FOR_USERS', :uid => 'sAMAccountName', :port => 389, :method => :plain, :bind_dn => THE_FULL_DN_OF_THE_USER_YOU_WILL_BIND_WITH', :password => 'THE_PASSWORD_OF_THE_BIND_USER'
You'll probably need to get most of this information from an Active Directory administrator. I don't advise using your own DN and password because then every time you change your password the application will break. I would suggest running rails server right now just to make sure that you didn't enter anything that will cause the application to fail.
Setting up your views
In my view, I want to do something really simple. If a user is logged in, I want to welcome them and provide a logout link. If a user is not logged in, I want to present a login link. So I'm going to go into app/views/changes/index.html.erb and add this right under the title:
<% if user_signed_in? %> Welcome <%= current_user.email %> (<%= link_to "logout", destroy_user_session_path, :method => :delete %>) <% else %> Nobody logged in. <%= link_to "log in here", user_omniauth_authorize_path(:ldap) %> <% end %>Those routes to destroy_user_session_path and user_omniauth_authorize_path are all generated by devise and didn't take any additional work on my part.
We also need to make a change to our user model that was generated by devise. If you look in app/model/users.rb you'll see a line with some devise configuration that makes this user model :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, and :validatable. To this list we need to add :omniauthable. If you're seeing an error about user_omniauth_authorize_path not being defined it is because you didn't add :omniauthable to the user model.
At this point your application should run and you should be able to click those links. You'll be taken to an ugly looking log in screen. Log in isn't going to work yet because we haven't wired up the callback. Here are a couple tests you can run to make sure that everything is right so far. 1. Try to log in with valid credentials. You'll be directed to a sign in page and see an error message that you couldn't log in because of an LDAP error. 2. Try to log in with invalid credentials. This time you'll be redirected to the same page, but you'll have an error message about invalid credentials.
More changes to the User model
In my case I want to retain some information about the user that is returned from LDAP so that I can have associations between changes and users. So we need to generate a migration to add a few database fields to our User table. Run this command:
rails generate migration AddColumnsToUsers firstname:string lastname:string displayname:string username:stringThat should generate a migration for you that looks like this:
If you want to make sure that your username is also unique, you should add add_index :users, :username, :unique => true to the migration. I also want to make sure that the username is not blank. Now run rake db:migrate to add those fields to your table. Then we need to edit the file app/models/user.rb to make those fields useful. First, we need to add our new columns to the attributes_accessible line in the model.
attr_accessible :firstname, :lastname, :displayname, :username, :email, :password, :password_confirmation, :remember_meIn my application, we are not going to set the users password, we're going to depend on Active Directory to do the authentication. But I don't like the idea of removing the validation from devise and I don't want to have user accounts with no password in the database. So I'm going to create a method that I can use to set a random password for each user. I'm using the self.method notation to make this a class method rather than an instance method.
def self.generate_random_password
Digest::SHA1.hexdigest(Time.now.to_s)
end
Wiring up the callback
The next thing we need to do is tell devise what controller to use for the omniauth callback. We're going to do this in our routes file, so edit config/routes.rb and find the line that reads devise_for :users and change it to read:
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" }That tells devise that when we get an answer back from ldap, we should look in app/controllers/users/omniauth_callbacks. If we were using omniauth without devise, the user would log in by visiting /auth/ldap. What we've done here is make use of the integration between devise and omniauth. So users will visit /users/auth/ldap. We also need to specify what controller is going to handle the callback. Without devise we do the same thing by adding a line like this to config/routes:
match "/auth/:provider/callback" => "users/omniauth_callbacks#create"
When you successfully authenticate to LDAP you'll get back a big bundle of information about the user. We're going to use that information to either log in an existing user or create a new user and log that user in. The code for this is going to be located in the omniauth_callbacks file which does not exist right now. We need to create the file and add a method called ldap to handle the way LDAP results are returned. This ldap method is going to check if there is an existing user and log that person in, otherwise create a new user. Here is the code for that file:
class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController def ldap # We only find ourselves here if the authentication to LDAP was successful. ldap_return = request.env["omniauth.auth"]["extra"]["raw_info"] firstname = ldap_return.givenname[0].to_s lastname = ldap_return.sn[0].to_s displayname = ldap_return.displayname[0].to_s username = ldap_return.sAMAccountName[0].to_s email = ldap_return.proxyaddresses[0][5..-1].to_s if @user = User.find_by_username(username) sign_in_and_redirect @user else @user = User.create(:firstname => firstname, :lastname => lastname, :displayname => displayname, :username => username, :email => email, :password => User.generate_random_password) sign_in_and_redirect @user end end end
What's next?
We have a working application that can authenticate users via Active Directory. There are a few loose ends that I would like to clean up, but this is as far as I was able to get. For example, if a user's authentication fails he is redirected to a sign up page that I don't want them to see. However, I wasn't able to figure out how to change the application routing to make them redirect to the sign in page instead. Also, the login page is not customizable at all. That really doesn't work for an enterprise environment which is where you're most likely to see Active Directory integration. It looks unprofessional when your user gets redirected to a login page that looks nothing like the rest of your site.
So while this will work for back end stuff or personal stuff that you aren't going to expose to the end users it isn't going to meet your needs right now for enterprise applications. If you want Active Directory integration that looks professional you're stuck with rolling your own for now.
I hope someone proves me wrong in the comments. I really wanted this to work.
Thursday, November 10, 2011
Stats for risk modeling: The Uniform Distribution
This blog entry originally appeared on the Society of Information Risk Analysts web page on November 3, 2011: http://societyinforisk.org/content/stats-risk-modeling-uniform-distribution
Next up in my series on distributions, I'd like to talk about the Uniform distribution. Uniform is quickly becoming my favorite distribution because it is really easy to understand and it helps us to avoid a common mistake in risk modeling; namely that we tend to underestimate the likelihood of the extremes. If you remember back to my previous post on the Normal distribution you will recall that once you get three standard deviations away from the mean you are getting into frequencies that are pretty low. In fact, in a perfect normal distribution it would take 10,000 loss events to find 15 losses that were greater than 3 times the standard deviation.
Uniform distribution makes a great "safety" distribution. Maybe you're pretty confident that some random variable can be represented by a normal distribution, and if that is the case then use it. That's what it's there for. But what if your random variable is bimodal, meaning that has ups and downs and no single most likely value? What if you think that values at the far end of the distribution likely occur more often than what the Normal distribution allows? Uniform distribution never lets me underestimate my tails (unless my random variable is a strange U shaped phenomenon) and it never makes me ignore one mode in favor of another.
SOME BACKGROUND: Distributions can be discreet or
continuous. Discrete distributions have clear values with nothing in
between. In the two pictures above, the distribution on top is
continuous, and the bottom is discrete. A fair six-sided die
is a good example of a discrete uniform distribution. It has 6 and only
6 possible outcomes. If I used a continuous uniform distribution to
represent that variable I might get values like 4.5. One of the "rules"
of modeling risk in Monte Carlo simulations is that each value in each
iteration has to be possible. No gibberish in the model. So having a
variable that tells you (with great frequency) that you rolled 3.291 is
bad. Built into Excel you have the RANDBETWEEN function which will give
you a discrete uniform distribution of random numbers. If you're using
the FAIR Lite tool, you can get a nearly uniform distribution by
setting the confidence of an estimate to very low and putting the most
likely value right between the minimum and the maximum. It's not
exactly uniform, but probably close enough.
WHEN TO USE IT: Use the uniform distribution when you have a good idea about the upper and lower bound of your variable, but you are uncertain about the shape.
WHAT MAKES IT COOL: It's easy to understand. You can explain this distribution to even the most statistically challenged of executives. And thanks to the Central Limit Theorem when you combine several uniform distributions you'll get a normal distribution which will satisfy the people that want nice graphs and tighter estimates of the most likely value.
WHEN TO AVOID IT: You should absolutely avoid this distribution if you have any evidence that the variable you're representing is U-shaped, in other words the values at the extreme are more likely than values in the middle. Other than that, this is a great distribution if you want to be open to possibilities and are willing to admit that you don't know a whole lot.
EXTRA CREDIT: U-shaped distributions are most often seen where there is cyclic data. For example, if you were molding the the snowfall in a given month and your X axis starts with January and ends with December then you would likely see more snowfall on the two ends and less in the middle. Can you think of any variables in information security that might follow a U-shaped distribution?
Next up in my series on distributions, I'd like to talk about the Uniform distribution. Uniform is quickly becoming my favorite distribution because it is really easy to understand and it helps us to avoid a common mistake in risk modeling; namely that we tend to underestimate the likelihood of the extremes. If you remember back to my previous post on the Normal distribution you will recall that once you get three standard deviations away from the mean you are getting into frequencies that are pretty low. In fact, in a perfect normal distribution it would take 10,000 loss events to find 15 losses that were greater than 3 times the standard deviation.
Uniform distribution makes a great "safety" distribution. Maybe you're pretty confident that some random variable can be represented by a normal distribution, and if that is the case then use it. That's what it's there for. But what if your random variable is bimodal, meaning that has ups and downs and no single most likely value? What if you think that values at the far end of the distribution likely occur more often than what the Normal distribution allows? Uniform distribution never lets me underestimate my tails (unless my random variable is a strange U shaped phenomenon) and it never makes me ignore one mode in favor of another.
WHEN TO USE IT: Use the uniform distribution when you have a good idea about the upper and lower bound of your variable, but you are uncertain about the shape.
WHAT MAKES IT COOL: It's easy to understand. You can explain this distribution to even the most statistically challenged of executives. And thanks to the Central Limit Theorem when you combine several uniform distributions you'll get a normal distribution which will satisfy the people that want nice graphs and tighter estimates of the most likely value.
WHEN TO AVOID IT: You should absolutely avoid this distribution if you have any evidence that the variable you're representing is U-shaped, in other words the values at the extreme are more likely than values in the middle. Other than that, this is a great distribution if you want to be open to possibilities and are willing to admit that you don't know a whole lot.
EXTRA CREDIT: U-shaped distributions are most often seen where there is cyclic data. For example, if you were molding the the snowfall in a given month and your X axis starts with January and ends with December then you would likely see more snowfall on the two ends and less in the middle. Can you think of any variables in information security that might follow a U-shaped distribution?
Subscribe to:
Posts (Atom)




