Rails Security Article - Brainstorm for Brute Force?

no comments

NOTE: This is a disproven thought experiment: unable to prove guessed password succeeded and pass the information along.

Prompt

I’ve just finished reading (yes, the whole thing) an article about securing Rails applications. While it talks about security with Rails specifically in mind, it isn’t limited to just Rails applications. It is a good read for anyone who creates, maintains, or audits web applications of any flavor. You can read the Ruby on Rails Security Guide now or later if you like. I’ll explain as much as necessary to get my point across for this article.

One section in particular concerns Cross-Site Request Forgery attacks. According to the article, such attacks are carried out by placing HTML (yes, HTML) pointing to a specific action in a Rails application. The article used the example of using an image to delete critical information from a target site. The article continues to explain that one can use javascript to create a form that a user mistakenly clicks to use POST attacks instead of simple GET requests. (I have figured out a way to modify this so clicking is not required below)

This method of attack got me thinking. I had never specifically thought of doing this to attack my own sites. It makes sense though and naturally follows from the application of the semantics of the HTTP protocol. It also got me thinking of how one might use it to further exploit a site.

Is it worth it?

I believe it is. If using no more evidence that it exists as chapter 3 in this article of 8 regarding security measures, the practical result is that, unmitigated, your application’s security is based upon the security of other, well-traveled applications. The article continues to explain a simple fix as provided by Rails. The ONLY fix is the protect from forgery secret. I haven’t evaluated in depth exactly how effective it is, but I’m currently cooking up a new attack based on the CSRF vector.

What’s your Vector Victor?

Security is no joke. I believe I’ve come up with an attack using the CSRF vector that could potentially be devastating. There’s really no one to report this to as it applies to every site that is vulnerable to this type of attack. I believe it should be called the CSRF-MPDBF: The Cross-Site Request Forgery Massively Parallel Distributed Brute Force attack.

How does it work?

It uses the POST exploit as discussed in the article using javascript to commandeer the computers of any visitor to try a random password or two and report success to another site using the same CSRF exploit.

The Set-up (Huh? No really, how would that work?)

Let’s presume there are 2 sites: A and B. Site A is some website for which the attacker wants login credentials. The attacker may, or may not know the login name of a user. Having it certainly helps the attacker, but it’s not strictly necessary for this exercise. Site B is a forum with lose security policies that allows javascript code to be inserted into pages by users. Examples aren’t limited to forums, but a multitude of other “public service” sites.

Presume that Site A has a simple log-in form, with or without SSL; encryption is moot. Also presume that this site doesn’t use request forgery protection. It’s just a simple login for such as:

<form action="/security/login" method="POST" />
<p><label for="username">Username:</label><input name="username" type="text" /></p>
<p><label for="password">Password:</label><input name="password" type="password" /></p>
<p><input type="submit" value="Login" />
</form>

Site A will look at the username and password in the POST body and do a look up of the username, then see if the password matches. I’m not talking about SQL injection here. Presume it’s a Rails application and it’s using the sanitize_sql functions correctly. If the login is successful, the URL will change (a redirection will occur), otherwise, presume the application displays the same message (same URL) without redirecting. Most applications redirect after login. But it is possible to confirm login another way. This is just one example. The key point is that an attacker is able to reliably confirm a successful login (and conversely, an unsuccessful one).

Are we there yet?

Sorry, let’s get to some steps of the attack:

The attack code

The first step is for the attacker to create special javascript code as in the above article with one key difference: target the login script and include a username and GUESSED password.

Say what? A GUESSED password?

Yes, guessed. I told you that this was a brute force attack. Javascript includes a random number generator:

Math.random()
So why not use it to generate a random password?

But that will never work!

Oh really? Why not? Every javascript engine is different. No browser and no visit to the page will likely use the same password. If you post some comment to a popular site and get a lot of people to trigger this, the target site A could be compromised in a matter of days, if not hours.

Dude, where’s my code?

FIIINE! This javascript is inserted on site B to attack site A (modified from the article: “On Rails Security”

<a href="http://www.b.com/" onmouseover="
  var f = document.createElement('form');
  function passwordGuess() { /* ... details here ... */ }
  f.style.display = 'none';
  this.parentNode.appendChild(f);
  f.method = 'POST';
  f.action = 'http://www.a.com/account/destroy';
  var x = document.createElement('input'));
  f.appendChild(x);
  x.setAttribute('name','username');
  x.setAttribute('value','TARGETUSER');
  x = document.createElement('input'));
  f.appendChild(x);
  x.setAttribute('name','password');
  x.setAttribute('value',passwordGuess());
  f.submit();
  return false;">To the harmless survey</a>

Here’s how it works. I added a stub function for the password guessing routine as that is not what is at issue here. This code is to be injected into a forum post or SQL injection or whatever vector such that it appears to public users of site B. When the javascript is called, on click, it creates a form in HTML. This is a bit strange. Javascript modifies the DOM to add a form. The form is then submitted as though the user had submitted a form from site B. But server A doesn’t know the form exists on site B and processes the username and password as though the request came from site A. This, my friends, is effectively a login attempt. The user is completely unaware that anything occurred. It’s executed when the hover over the link and when they click, the link works as desired. This is different from the original article as it worked on click. The unwitting user at site B cannot detect that this attack has occurred unless he or she inspects the traffic. What normal user does that?

2010/02/01 – Editor’s Note: I’m trying to get this to work, I cannot seem to get the status of a password guess using Javascript. This might be a hair-brained idea after all.

OK, but the attacker can’t get that random password!

Not true. Use the same attack vector. Presume site B or some other site C is vulnerable to the same type of attack. To deliver the credentials back to the attacker simply modify the javascript to detect if the page was redirected. Once the credentials are verified, post the brute forced credentials to a public location. An attacker could even use the same type of attack to post those results. The attacker simply checks the destination site for updates and snarfs the credentials. Then the real fun begins and I don’t have to explain what can happen at this point.

Impact?

Well, think of it in simple terms. Every browser visiting site B’s compromised page becomes a weapon. Each person that goes to this page on site B with the code contributes to the attack. Assuming site B is very popular, but lax on code insertion filtering, site A will be attacked x times, where x is the number of users that trigger the attack on site B. If the attack runs m times (multiple attempts), then site A will be attacked x*m times. If B is a popular site, then x can easily approach millions of triggers in a period of a few weeks. Assuming a small dictionary can be loaded, a clever attacker could author the script to try word combinations, or insert symbols between, before, and after words, try numbers, etc. If the username is known in advance, it’s only a matter of time before that account on site A is compromised by visitors on site B. If multiple sites with B’s lax security exist, then the attack is: m*(x1 + x2 + …xn) where x is set sites like B to which the malicious code is posted.

It’s sort of like creating a bot network that only exists when users go to a specific page or pages.

But it’s a random password, won’t the same password be tried again and again?

Yes. There will, undoubtedly, be collisions in the the attack space. The key is that, depending on the javascript random engine, there will be significantly greater quantities of untried attacks. Even pseudo-random number generators try to be difficult to predict. In this case, this randomness works in favor of the attack by created more unique generations. A super-sophistocated attack could post failed results to a forum. These results could then be compiled to a random number black list that will skip over previously failed trials. That would significantly reduce the collisions (not eliminate) but is more sophisticated and again, if the PRNG has a decent algorithm, won’t be necessary.

Proof of concept?

Ha, no way. I would not write one in the wild.

Has anyone else thought of this?

I suppose I should have looked this up before I started writing. However, writing down an idea helps solidify the thought. I didn’t find anything with a quick Google Search but that isn’t thorough research. Most of the hits involve the tokens getting brute forced. My example assumes there are no tokens. But you can see how even brute forcing the tokens leads to slowing the progress of an attack.

Why is this so bad?

Because there’s no one IP source to block. It’s distributed and not easily detectable. Couple this with a password dictionary somewhere and you have a serious attack. Couple it further without the need to click something to trigger the attack (below) and it’s even more wide-spread.

No Clicking Required

The article gives the example of javascript code that creates a form, then replaces a link a user would normally click with the form such that it performs the CSRF attack. It is possible to create an exploit using the same vector but not require a click to activate it. Simply create a form as indicated in the article with my modifications, then write a script to periodically execute it asynchronously and without redirecting the user to the login page. This hides the attack and permits multiple guesses; as many as can be squeezed into the time the user is on the B site.

How bad is it?

I would imagine most of the big sites already mitigate this attack using forgery tokens. While no security expert, I believe that Facebook is using them based on their login form. I’ve removed some of the worthless table formatting, added line breaks, and only used the HTML form fields. For some reason, the field is listed as having the id=“lsd”. I have no idea why.

<form method="POST" action="https://login.facebook.com/login.php?login_attempt=1" id="login_form">
<input type="hidden" name="charset_test" value="&euro;,&acute;,€,´,水,Д,Є" />
<input type="hidden" id="locale" name="locale" value="en_US" autocomplete="off" />
<input type="hidden" id="non_com_login" name="non_com_login" autocomplete="off" />
[...]
<input type="checkbox" class="inputcheckbox " id="persistent" name="persistent" value="1" />
[...]
<input type="text" class="inputtext" title="Email" placeholder="Email" id="email" name="email" value="" />
<input type="password" class="inputpassword" id="pass" name="pass" value="" />
<input type="text" class="inputtext hidden_elem DOMControl_placeholder" id="pass_placeholder" name="pass_placeholder" value="" />
<input value="Login" type="submit" class="UIButton_Text" />
<input type="hidden" name="charset_test" value="&euro;,&acute;,€,´,水,Д,Є" />
<input type="hidden" id="lsd" name="lsd" value="KboH0" autocomplete="off" />
</form>

The 5 characters seem to change from browser to browser. It appears to be generated, then persisted using cookies (cookie name: lsd).

The real problem will be with smaller sites that are written with custom code that do not use the forgery prevention tokens. I cannot even begin to guess how many sites are affected.

“And what was the real lesson? Don’t leave things in the fridge.”

Spike may have been onto something there (quote is from Cowboy Bebop, “Toys in the Attic”). Don’t get soft on your security. As you can see, we’re all in this together. Your weakness is someone else’s exploit vector. You won’t just become a statistic, you’ll be actively, albeit unwittingly, contributing to an attack on other sites at the discretion of less scrupled persons.

Read the article! Don’t leave your applications in security cold-storage. It’s important.

Disclaimer

Again, this is an informational article to help site programmers build more secure sites. I am not responsible for people that misuse these ideas or examples.

Theoretical Sets

no comments

Recently, I have been thinking about a particular data structure that I’ve never seen before. For those who do not know, I am an avid C/C++ programmer and have recently discovered Ruby and Rails. Thus, I am familiar with the STL that is so closely related to C++. One of my favorite containers is the set. Sets operate just like you’d expect of a mathematical set (thus the name). It contains a set of values.

For example (an assume I have a magical print function to inspect the sets on the terminal):

set my_set;
my_set.insert( 7 );
my_set.insert( 5 );
magic_set_printer( my_set );
Figure 1: A C++ STL set with two values.
Will produce:
{5,7}
The very neat part about sets is the fact that one can operate using set functions over two or more sets. My favorite is set_difference, but set_union and set_intersection are also highly useful.

As you can see, they’re good for keeping small sets of things.

So What is a Theoretical Set?

The problem with sets as they appear in C++: they require storage space for every item stored in them. This isn’t a big problem if you have only a few elements in a set, but what’s the fun in that? Suppose you have the same set above in Figure 1 but decide to add the value 6. Under a normal set, your set will contain the values 5, 6, and 7. Extending the argument, if your set contains a contiguous, uinterrupted set from, say, 5 to 1,000, your set will contain, yes, you guessed it: 995 elements. Clearly, there’s room for some improvement if you expect contiguous values.

Enter the theoretical set.

It is just like a normal STL set, however, it will take shortcuts on memory by combining values into ranges. For example, the set: {5,6,7} becomes: {5..7}. The original set will use 3 values, the theoretical set will use 2. As you can see, if you have a large set from 5..1000, it is better to use the theoretical set as search times and memory will be saved. While I’m not sure, exactly, at what point it becomes more economical to use theoretical sets (and again, it depends on use), if you expect to have contiguous ranges in your sets, I suspect much improved performance.

Unfortunately, operating on ranges is harder than operating on single values. Thus, there is a relatively significant performance penalty when calculating intersections, differences, etc. Though, in the long-run, the penalty is not noticeable.

A Ruby Theoretical Set

I had originally envisioned such a construct to be written for the benefit of C++ coders. However, due to the number constraints, I was dissuaded. Ideally, one should be able to use a theoretical set on any type of number. While templates offer some solution, I also wanted more: complex types.

Should one not be able to arrange a set of contiguous dates? Maybe not contiguous to the second, but perhaps weekends? A set over a range of objects. Makes you tingle a bit, doesn’t it?

The nice thing about loosely typed languages, is that you can pass just about anything into them without worrying much about some of the details. So that solves the typing problems with C++ and makes for a good set!

I have not actually implemented a straight-up Ruby Theoretical Set. I have created on that uses ActiveRecord, but that’s a post for another time.

Covert Channel Paper

no comments

I wrote a paper for my Operating Systems class this recent semester about covert channels.

Abstract

A thirty year-old problem, covert channels continue to plague the security of modern operating systems. These channels are explained and discussion of the subject is motivated. A short evolution of the problem is given as well as several classifications of covert channels. Several methods such as type enumeration, flow analysis, virtualization, and adding noise are discussed and analyzed. Finally, one system is evaluated in context of those methods and future directions into covert channel research are suggested.

Read more

Algorithms: Pretty Printing

no comments

I’ve been up and down the Internet looking for a good solution to the “Pretty Printing” problem. I was dismayed by the lack of readily indexed solutions. So! If you’re looking to solve this one, I’m here to point you in the right direction.

Problem Description

Given a set of W words, form a list of lines such that the sum of the slack of the characters in a line L (column s- character count = Slack) squared (some implementations cube this, the algorithm is the same), is minimized.

Most problems include that there must be 1 space between every word (except those which do not share the same line) and those spaces must be included in that slack value calculation. Regardless:

The Problem Type

This problem a subset of Dynamic Programming problems known as “Mutli-way Choices.” A similar, but less sophisticated version of this problem is the “Segmented Least Squares” problem.

I’m not going to attempt to solve the problem for fear I will make myself the fool. Maybe I’ll do it later and post it here again when I’m confident in my answer. The important part is you now know how to look for answers. Admittedly, even armed with this information, you’ll still get some pretty shady results. But I found some decent material with this google query . You should be able to construct a cogent answer with a Least Squares example.

Good luck! Happy algorithms!

Impracticality of Instantaneous Faster than Light Travel

1 comment

Prompt

I enjoy various science fiction television series: Firefly (2002), StarTrek (1987), and Battlestar Galactica (2004). While watching an episode of the latter-most title, the crew demonstrated the ability to perform a “hyperlight jump.” Such a jump is the physical translocation of an object, such as the spaceship, from one point in 3D space, to another point in space without crossing any of the points in between in space or time (it was instantaneous). This circumvents Einstein’s upper bound on the velocity of matter. However, I had one lingering feeling that something is amiss.

Alright, you caught me. Yes, I was trying to figure out if such a means of travel could be implemented. Nothing in our universe has been observed that demonstrates a similar ability. Not to say it does not exist here or in another universe (assuming you believe in the multiverse theory) but merely to state a lack of templates. However, simply because something has not yet been observed does not make it impossible. However, energy requirements of such a maneuver (or lack thereof) are insurmountable.

Givens

Armed only with those two (the third works against me) concepts, I can deduce: if such FTL travel is physically possible, the energy requirements to perform it nullifies its practicality. Newton’s law will suffice, imperfect and non-universal as it is. It still provides a quick and dirty estimation of gravity at sufficient mass and distance.

Why the first law of thermodynamics?

Because it means that you cannot create energy for free. I propose that such a faster than light jump is a method for creating a perpetual motion/energy device unless the energy requirement is bounded by the law of gravitation.

An object in relativistic free-fall with a larger mass trades potential energy for kinetic energy until reaching a final potential energy state. You can determine the amount of potential energy gained (or lost) using the potential energy equation: U~m~ = mgh where U~m~ is the potential energy of a mass, m is the mass of the object, g is the gravitational acceleration (varies with distance) and h is the distance between the two masses. Lets face it, if you’re trying to get passed gravity, you have at least two masses you’re trying to separate.

See Waterfall by M.C.Escher. Source: M.C.Escher Gallery

If you could theoretically teleport an object from the surface of the earth to a point in sub-orbit with less energy than it generates as kinetic energy when it falls back to earth, you have created a machine with greater than 100% efficiency: a perpetual energy device. Any one could use this technology to capture the kinetic energy and generate power (think never-ending waterfall). This violates the First Law of Thermodynamics and is widely considered to be impossible, though some venture fruitlessly and sometimes embarrassingly to develop the exception to the rule.

Convert gravitational Acceleration into a function of radial distance To compensate for the acceleration changing based on distance, turn the gravitational acceleration into a function of radial distance, then convert the potential energy formula into a function of radial distance for both height and gravitational acceleration. Then, integrate over the height.

Applying the change in acceleration over the potential energy of a system

Therefore: the total energy required of such a faster than light jump must be greater than, or equal two that equation. And that statement explains absolutely nothing until you understand one more concept. I’m assuming that the potential energy equation is universal just as the law of thermodynamics is understood to be universal.

Worst case universal potential energy scenario
Worst case potential energy configuration of the universe: Mass is represented by the black line, your spaceship is in blue as are some labels, the distances are in green. Source: Christopher Wojno’s GIMP Scientific Doodle Collection: 2007

So, the energy required must account for the worst case scenario: You have two bodies in all of the universe, the object and energy attempting a faster than light jump, and the rest of the universe aligned in a single file column at the atomic level. Why? The universe is not self aware. It does not keep track of its own configuration (though, that is an interesting twist on a god or gods threory). So, there is no set maximum of contiguous mass below the mass that already exists and energy capable of being converted into mass. Since one could theoretically jump from any point in space to another, with any configuration of universal masses, the worst case energy scenario must be assumed as the least amount of energy which can be expended. Unless, of course, the universe is cognizant and can plot the path of least energy through the potential energy fields that would have been traversed should the instantaneous travel been foregone and only require that amount of energy. This is highly unlikely, but if it that is the case, from a computer science stand-point, it would be interesting to see how the universe does optimization algorithms. But I digress… considerably.

This is the MINIMUM amount of energy required for a single jump. Remember, you can’t get something for nothing and there has to be an resolution of apparently dissimilar and discontinuous potential energies. It’s impossible to calculate the worst case scenario without knowing the precise mass of the universe and the desired distance to jump. But know that the greater the distance, the greater the energy that will be required. I may have jumped the gun calculating the potential energy as a function of distance because it’s clear to see that the amount of energy required to overcome the concerted gravitational pull of the entire universe, minus your insignificant (by comparison) ship and fuel, makes such a technology practically impossible.

Even if you jump inwardly toward the universe, it is also assumed the universe knows no direction of instantaneous travel. You will always be competing against the absolute lower bound of universal potential energy.

Disclaimer

This is just my theory. It’s not even well supported. I offer no other support for it at this time. If I’m wrong, please make the appropriate corrections and e-mail or comment. I really hope this isn’t the case or that there is some quantum loop-hole or unobserved phenomena that contradicts the assumptions.

Sorry if I killed your dreams of owning a spaceship with FTL capability. I know I am.