Tuesday, October 2, 2012

Seven Languages in Seven Weeks - Scala Day 2 Self Study

Hey there! I'm currently reading Seven Languages in Seven Weeks by Bruce A. Tate. As the title implies, this book explores seven different programming languages. Each chapter ends with a self study section. Here are the exercises of day 2 with the Scala programming language:

Use foldLeft to compute the total size of a list of strings:
Here are two variants, the first calls the foldLeft method (note the multiple parameter list, this is used for currying, i.e. partial function application) while the second is using the /: infix operator, which is in fact an overload of foldLeft:
  val list = List("foo", "bar", "hello", "world")
  list.foldLeft(0)((len, elem) => elem.size + len)//> res0: Int = 16
  (0 /: list) {(len, elem) => elem.size + len}    //> res1: Int = 16

Write a Censor trait with a method that will replace the curse words Shoot and Darn with Pucky and Beans alternatives. Use a map to store the curse words and their alternatives. Then, load the curse words and alternatives from a file:
The trait expects the curse words dictionary in the file words.txt:
Shoot:Pucky
Darn:Beans
The words are loaded line by line, each line is splitted at the : character and the values are stored in the substitions map. The replace method takes a text as input parameter, converts it as a list of words and applies the substitutions by looking up the map.
  trait Censor {
   val substitutions = new HashMap[String, String]
   
   Source.fromFile("/words.txt", "US-ASCII").getLines.foreach { line =>
    val elem = line.split(":", 2)
    substitutions += (elem(0) -> elem(1))
   }
   
   def replace(text: String): String = {
    text.split("\\s").map({word =>
     substitutions.getOrElse(word, word)
    }).reduceLeft((concat, word) => concat + " " + word)
   }
  }
Here's a simple example showing how the trait works:
  val censor = new Censor {}
  censor.replace("hello Darn world") //> res2: String = hello Beans world
Stay tuned, I'll soon be posting the 3rd study section about Scala.

Wednesday, September 26, 2012

vortex7

About a year ago I stumbled upon the Over The Wire hacker challenges and started solving the first set of levels (called vortex). Since then, I have been publishing my solutions in my blog. Here is vortex level 7:

The code

int main(int argc, char **argv)
{
        char buf[58];
        u_int32_t hi;
        if((hi = crc32(0, argv[1], strlen(argv[1]))) == 0xe1ca95ee) {
                strcpy(buf, argv[1]);
        } else {
                printf("0x%08x\n", hi);
        }
}

The vulnerability exposed in this code is a basic buffer overflow with two subtleties:

  1. The CRC of the buffer must equate to a given value (0xe1ca95ee)
  2. The buffer is rather small (58 bytes)

Manipulating the checksum

The cyclic redundancy check (CRC) computes a check value (or checksum), which is used to detect accidental changes in data, e.g. when transmitting over unreliable communication channels. With this error detecting code, the slightest change (i.e. bit-flip) in the input data results in a very different output pattern. As opposed to cryptographic hash functions like SHA1 or MD5, preimage resistance is not a property of CRC, it is not designed to withstand preimage attacks: given a checksum C, it is not hard to find an input m such that CRC(m) = C. As such, one shouldn't rely on it for integrity checks over insecure channels since it is very easy to manipulate it as is shown in the solution.

To solve this level, I chose to apply the CRC-reversing algorithm described in Reversing CRC – Theory and Practice, which by the way also contains a very nice introduction to CRC. The method consists in appending a 32-bit pattern to the buffer in order to adjust the CRC-remainder to the desired checksum. The same principle is proposed in the suggested lecture, CRC and how to Reverse it. But as opposed to the first approach which uses the inverse of the divisor polynomial, the bit pattern is derived using a system of equations.

Overflowing the buffer

This level contains a classic vulnerability which can easily be exploited to execute arbitrary code: a buffer overflow. The use of the strcpy standard library function to copy a buffer of data to another completely disregards the destination's capacity. If the source buffer is larger than the destination, all bytes will be copied, even though the destination's bound has been exceeded, and in doing so, subsequent structures in memory will be destroyed.

Intercepting the instruction pointer

Depending where the destination buffer is located in the process memory, it may be possible for an attacker to take influence on the program execution flow. In this case, the destination buffer is on the stack. By overflowing the buffer, copying bytes past its bound, the stored eip value will be overwritten. This is a pointer to the next instruction to return to after leaving the current stack frame, i.e. when returning from the current function call. With a meaningful value, it is possible to redirect the execution of the program to any executable location in memory.

Creating a shellcode

The payload we want to execute consists in a small fragment of x86 machine instructions, which perform 2-3 syscalls that allow us to run a shell:

  • geteuid()/setreuid() are used to set the effective user-id. The exploited binary runs with the suid-bit, which means the process is executed in the name of the file owner (the user that has read-privileges for the next level's password file).
  • execve() is called to run /bin/bash.

The original x86/asm code can be found here. Check out the Makefile to see how it is compiled and the raw instruction data is extracted. It is then necessary to encode the data to avoid specific patterns such as \0 bytes. I used metasploit's msfencode tool for this.

Executing arbitrary code

Since the buffer is rather small (58 bytes), it is difficult to dissimulate the malicious payload. An alternative way to include arbitrary data into the process memory is to define an evironment variable containing the data. It will be accessible from the beginning of the stack. The buffer must then overflow the saved eip value to point at the corresponding region in memory. Unfortunately, this address cannot be precisely deduced. Therefore, a common strategy consists in prepending a large number of nop instructions before the shellcode. This extends the landing platform of the target address thus increasing the probability of hitting the shellcode.

The exploit

The finalized exploit is available here. It is a C wrapper which prepares a shellcode and the buffer contents and calls the binary to exploit. I employed following methods from SAR-PR-2006-05 to implement the table driven CRC32 algorithm:

  • make_crc_table()
  • crc32_tabledriven()
  • fix_crc_end()

Since at first the resulting checksum values did not match the ones generated by vortex7 I additionally extracted the CRC32 table from the binary and stored them in crc_table_static. I realized that the vortex7 implementation actually uses 0x00000000 instead of 0xFFFFFFFF for INITXOR and FINALXOR.

The fix_crc_end() function adjusts the buffer such that its checksum eventually results in the desired value 0xe1ca95ee.

make_buffer() creates the data used to overflow the buffer. It contains a repetitive sequence of the target address. It allows to shift the sequence bytewise in order to adjust its alignment. make_payload() generates the buffer which contains the nop sled and the shellcode.

Finally, the wrapper executes vortex7, passing the address buffer as a command line argument and the payload in the environment variables.

The program expects two arguments:

  1. An offset for the target address, relative to the environment pointer taken from the current process (the wrapper).
  2. An alignment index (0-4) used to align the target address in the buffer.

Following arguments worked for me:

$ ./v7_wrapper 0 2
Using address: 0xFFFFD91F
$ whoami
vortex8

The password for the next level is then retrieved from the password file for the next level:

$ cat /etc/vortex_pass/vortex8 
X70A_gcgl

That's it! If you want to learn more about buffer overflows, I suggest you read Smashing the Stack for Fun and Profit by aleph1, originally posted in Phrack Magazine. Also have a look at my blog where I regularily publish vortex level solutions: blog.ant0i.net

Sunday, August 19, 2012

Seven Languages in Seven Weeks - Scala Day 1 Self Study

It's time for the next programming language in Seven Languages in Seven Weeks: Scala!
The self-study assignment consists in writing a program that will take a tic-tac-toe board and determine which player won (if any):
import scala.io.Source;

object TicTacToe extends App {

  val wins = List(
    List(0, 1, 2), List(3, 4, 5), List(6, 7, 8),
    List(0, 3, 6), List(1, 4, 7), List(2, 5, 8),
    List(0, 4, 8), List(2, 4, 6)
  )
  val input = Source.fromFile("tictactoe.txt").mkString
  val board = (for (chars <- "X|O".r findAllIn input) yield chars).toList

  if (isWin("X")) {
    if (isWin("O")) {
      println("Tie")
    } else {
      println("Player X wins")
    }
  } else {
 if (isWin("O")) {
      println("Player O wins")
 } else {
   println("No winner")
 }
  }

  def isWin (char: String): Boolean = {
    for (win <- wins) {
      var result = true
      for (x <- win) {
        result &= board(x) == char
      }
      if (result)
        return true
    }
 return false
  }
}

Monday, August 13, 2012

vortex6

The goal of vortex level 6 is to reverse engineer a binary executable to exploit it. I used objdump to decompile the code section. Check out the solution on github: https://github.com/antoinet/vortex/tree/master/vortex06

Sunday, July 29, 2012

Flattr on Dailymotion

Do you know Dailymotion? It's one of the leading video streaming platforms on the net. And ever head of flattr? It's a social micro-payment system, that allows making small donations to support people for the content they share on the web (e.g. check out the excellent metaebene.me blogs). I like to think of the flattr-button as facebook's like-button with a small contribution for every click. An interesting fact: flattr was initated amongst others by Peter Sunde, a co-founder of thepiratebay.org.

End of April 2012, Dailymotion integrated flattr into their platform, enabling video creators to insert a flattr button on their pages. Here's how the idea was born. My brother works for Dailymotion. He once skyped me up to tell me the company was going to hold a hackathon to promote innovative projects. He asked me if I had any suggestions. I called out to my colleague David who almost instantly mentioned flattr. I replied and some time later the idea was accepted by management. My brother's team didn't win the contest, but as he told me, it's the only project that turned productive.

This has some echo on the web: wired.com, techcrunch.com, venturebeat.com, they all covered the story. David and I were pretty astonished by the impact his idea had had. So if you'd like to give him some credit, go ahead and >>flattr him<<, I think he deserves it :-)

For your entertainment (if you speak french), here's the log transcript of our skype conversation:
23.11.11 15:31
un hackaton aura lieu de mardi a mercredi prochain ici
23.11.11 15:32
avec une tablette pour l'equipe gagnante
23.11.11 15:33
t'as pas des idees?
23.11.11 15:33
un truc qui revolutionne la facon dont tu regardes les videos et qui prends 10 ligne de code
23.11.11 15:33
lol
Antoine 23.11.11 15:35 
oh wow.
23.11.11 15:35
je veux le tablet
yann 23.11.11 15:35 
hihi
23.11.11 15:35
yeah moi aussi
Antoine 23.11.11 15:36 
des videos pr0n$
yann 23.11.11 15:36 
haha
23.11.11 15:36
oui
Antoine 23.11.11 15:36 
en 3d
yann 23.11.11 15:36 
yeah
23.11.11 15:36
ya deja un mec qui dev la 3d ici
Antoine 23.11.11 15:37 
cool
yann 23.11.11 15:37 
il a des lunettes lol
Antoine 23.11.11 17:05 
une idée d'un de mes collègues:
23.11.11 17:05
incorporer http://flattr.com/ pour le content dailymotion.
yann 23.11.11 17:06 
yeah this is nice bro
Antoine 23.11.11 17:07 
tu connais?
yann 23.11.11 17:07 
un petit peu
23.11.11 17:07
juste le principe
23.11.11 17:07
c'est de la remuneration sur le contenu
23.11.11 17:07
si ca te plait tu peux remunerer l'auteur
yann 23.11.11 17:11 
yeah
23.11.11 17:11
jvais lire flattr
23.11.11 17:12
faut voir mec
Antoine 23.11.11 17:13 
ouais. ce serait cool mec.
yann 23.11.11 17:13 
carrement
23.11.11 17:18
c'est une bonne idee
23.11.11 17:19
LET'S GET THIS TABLET!!

Wednesday, July 18, 2012

vortex5

Vortex level 5 consists in cracking a password hashed with MD5, which is called a preimage attack. No salt was used when applying the hash function, this makes it very easy by today's means to find the originating value.

The fastest way I found to achieve this is searching for the hash value with Google. Of course this will return lots of references to this level's solution, but you'll also get results for some websites that publish datasets of precomputed hashes, like for example md5crack or md5this.

Alternatively, you could crack the MD5 hash using some tool such as John The Ripper to perform a brute force attack. In the worst case this could result in computing all 62^5 combinations of the password (it was specified to be 5 characters long and consisting of a-zA-Z0-9). To restrict the number of tries, you can provide a wordlist of plausible passwords. Obviously, this will only generate a result if the password already existed in the list. This method works best when using real password data (e.g. from a leaked password database), since people tend to use similar patterns and also reuse their passwords.

Other tools such as RainbowCrack perform the attack using a rainbow table: a data structure used for the efficient storage of precomputed hash values. As for the websites mentioned above, you can easily get ahold of various tables, ranging from 50 to 500GB depending on the space of hashed values.

Saturday, July 14, 2012