Search

Helping developers and enterprises secure their code is what we do. Got a project, an RFP, or just some questions? Let us know!

info(at)matasano.com
1-888-677-0666 x0

Playbook is our product. It does firewall sync. To learn more about Playbook, check out the site, or get in touch with us via the web, e-mail, or phone.

playbook(at)matasano.com
1-888-677-0666 x7529 (PLAY)

« Indie Software Security: A ~12 Step Program | Main | Take Survey, Get Free Huge Poster, Courtesy Of Me »
Tuesday
Sep222009

Ruby for Pentesters: Stupid FFI Tricks

Lately, Ruby has left me wondering whether I should go back to C or (gasp) python for my day-to-day coding. But then I took a breath of fresh awesome that convinced me to stay put.

Here’s a fun trick I stumbled into while playing around with FFI and Metasm in ruby.

This probably falls under the “stupid ruby hacker tricks” category. I’m also pretty sure the FFI guys never had this in mind as an exposed feature in their library. But damn if it isn’t refreshing when sometimes things work exactly as you hope they will.

When I see something like this work, it also occurs to me that my reluctance to leave the fireside coziness of my IRB prompt is a sign of something. Probably something unhealthy.

Scenario:

You’re coding in assembly language (for good, evil, or neutral) and you’d like to quickly test your code as you work. You know what would be great? It would be great to have a way to dynamically assemble and shove your instructions into memory someplace, then call them on the fly.

Solution:

Write a little wrapper to load your bytecode into memory and jump to it. No fussing with ELF/PE/whatever headers, overwritten return addresses on the stack, heap bugs, etc. This isn’t necessarily exploit development, just shellcode development. The goal is just to make sure your bytecode works the way you expect it to when you land on it.

So… you could:

Abuse a function pointer in C:

Here’s how you could do this in C with minimum fuss. Use malloc(3) and memcpy(3) to load your code from a command-line argument and cast the resulting heap memory address to a function pointer. Then call the function pointer.

    #include <stdlib.h>
    #include <string.h>

    int main(int argc, char *argv[]) {
      size_t bloblen;
      char *blob;
      void (*funcptr)();

      if (argc > 1)  {
        bloblen = strlen(argv[1]); // hope you're nullsafe!
        blob = (char *) malloc(bloblen);
        if(blob != NULL) {
          memcpy(blob, argv[1], bloblen);
          funcptr = (void *) blob;
          funcptr();
          exit(0);
        }
      }
      exit(1);
    }

Or Abuse a FFI function pointer in ruby:

Here’s how you can (ab)use FFI from ruby to achieve the same effect. This reads the code from standard input instead of the command-line, by the way:

    begin ; require 'rubygems' ; rescue LoadError ; end
    require 'ffi'
 
    # Use FFI to stuff our bytecode somewhere on the heap.
    # here's the malloc(3)/memcpy(3) combo
    code = STDIN.read
    memp = FFI::MemoryPointer.from_string(code)
 
    # memp is now a pointer object FFI can use

    # Now we cast our function pointer.
    #
    # Yea so this is much nastier looking than:
    #
    #    void (*funcptr)();
    #    funcptr = (void *) blob;
    #
    # It'd be swell if FFI stopped changing this interface, but
    # hey, beggars can't be choosers. I'm not complaining...
    funcptr =
      ## use FFI::Function for ffi-0.5.0.
      if FFI.const.defined?("Function")
        FFI::Function.new(
          FFI.find_type(ret), args, memp, :convention => :default )

      ## use FFI::Invoker for ffi-0.4.0 - two flavors even!
      elsif FFI.const_defined?("Invoker")
        if RUBY_PLATFORM=='java' ## JRuby FFI
          FFI::Invoker.new(memp, args, FFI.find_type(ret), "")
        else ## and not Jruby...
          FFI::Invoker.new(memp, args, ret, FFI.find_type(ret), "", nil)
        end
      else
        raise "oh noes! this version of ffi is totally unfamiliar"
      end


    # Now we call our bytecode stub directly.
    # This is basically like saying "funcptr();" in the C version.
    funcptr.call()

FFI rocks in general. Ruby’s been lacking a good answer for python’s ctypes, and FFI is definitely the answer. But I’m stalking Wayne Meissner to make sure he keeps this feature around and maybe even gives it a standard interface.

As evidence that I’m mentally unhinged, here’s a version of that script with all kinds of superfluous and ridiculous additional features.

   Usage: asm_lab.rb [opts] < someassmebly.s
          -s, --sled=SIZE         Add a nop-sled
          -g, --debug             Add debug trap and spawn gdb in xterm.
          -f, --file=FILE         Read input from file instead of stdin
          -r, --raw               Input as raw bytecode
          -d, --drop_id=RID       Drop real privs to RID
          -D, --drop_eid=EID      Drop effective privs to EID
          -h, --help              Show this message.

Um, a not so superfluous feature there: metasm!

Metasm rocks! ‘Nufsaid.

References (37)

References allow you to track sources for this article, as well as articles that were written in response to this article.

Reader Comments (49)

I prefer tihs tool:

http://www.secdev.org/projects/eggrun/

dumps your asm to a C char array, lets you jit debug with gdb (attaches on a crash), or debug from start, etc. basically everything you need for easy shellcode development.

September 24, 2009 | Unregistered Commenterbob

@Eric nice (ab)use of ruby. On the fly assembly is a big win. It would be nice to see jit debugging.

@bob eggrun seems pretty linux centric. Having this in a portable scripting language seems beneficial. Also, is it me, or does making every payload on you box an executable seem a little, well, crazy?

September 25, 2009 | Unregistered CommenterJtran

@bob I ran across eggrun a while back and yea, it's pretty damn handy.

@jtran Thanks. I'm pretty sure you can use eggrun elsewhere besides linux. You just can't do the /proc filesystem trick everywhere. And if by crazy you mean totally awesome then I'm with you.

September 25, 2009 | Registered CommenterEric Monti

buen post

November 2, 2009 | Unregistered Commenterffi

Juicy clothes
Buy full line Juicy couture products from our site at a low price to make yourself a fashionista! Dress juicy couture clothing, holding juicy couture
Shop prom dresses, formal dresses, prom shoes, 2010 designer prom gowns at dres4sale.
for cocktail dresses, dresses for prom, homecoming dresses, and evening dresses. Cheap prom dresses or couture designer evening gowns for your next formal.
evening dresses
Evening Dresses. Women's Formal & Special Occasion Dresses ... Welcome to Cheap Evening Dresses for Sale! ... Buy Cheap Evening Dresses Sales & Accessories
prom dresses

March 20, 2010 | Unregistered Commenterasdasd

I think this is definitely the future. We definitely need to push security more and more. I think this is a must.
whistle blower policy

April 22, 2010 | Unregistered Commenterjames lee

P90x .It really is not expensive if you factor in the cost

of a gym membership,P90x workout . The cost for P90X is

about three months of a paid gym membership but you get to

keep the program foreverP90x . You can try many of the

online sites, but it will be the same as buying from the

company or a Beachbody Coach. Make sure you are getting

original DVD's. People are selling copies all over. The

problem is how long will they last, P90x workout ,and you

truly need the exercise and nutrition guide to even follow

the program. You can go to any site

http://www.p90xmall.com/ or you can go to and click on

products. P90x dvd You can order directly from the

site,P90x dvd.

May 8, 2010 | Unregistered Commenterp90x

P90x .It really is not expensive if you factor in the cost

of a gym membership,P90x workout . The cost for P90X is

about three months of a paid gym membership but you get to

keep the program foreverP90x . You can try many of the

online sites, but it will be the same as buying from the

company or a Beachbody Coach. Make sure you are getting

original DVD's. People are selling copies all over. The

problem is how long will they last, P90x workout ,and you

truly need the exercise and nutrition guide to even follow

the program. You can go to any site

http://www.p90xmall.com/ or you can go to and click on

products. P90x dvd You can order directly from the

site,P90x dvd.

May 8, 2010 | Unregistered Commenterp90x

Provide high quality silver Tiffany jewellery including necklaces,rings and other style jewelry at wholesale prices.Pick your dreaming
Tiffany jewellery
Tiffany co
Tiffany
Tiffany Stores is the best online United Kingdom jewelry stores where you can buy the cheapest Tiffany & Co silver jewelry.
Our huge selection of Tiffany
Tiffany & Co Rings
Tiffany & Co Earrings
Tiffany & Co Bracelets
Buy cartier ring, cartier love on abcartier.com. We also provide cartier bracelet, cartier jewelry and so on. Now come on and get what you want.
Cartier Jewelry
Cartier jewellery

May 31, 2010 | Unregistered Commenterharry123

The article written by your very good, I like it very much. I will keep your new article.
rosetta stone spanish,
rosetta stone,
rosetta stone language.

June 6, 2010 | Unregistered Commenterrosetta

People usually say :"Seeing is believing." GHD Each attempt has a corresponding gain, in part or obvious, or vague. At least we have the kind of satisfaction After I bought this watch ,in a sense,it means a great deal to me. net a porter thank you!it is very useful tools to protect our time.If you never pay attention to yourself ,please grasp this chance.a few days ago,I bought a Rolex watches.IT's very good to use.So i want to write an article about watches to share with everyone on So as to more and more people to konw it. UGG brand is relatively common, in addition to the Rolex ping g15even see watch on the movement and you don't know.
Rolex watches

June 25, 2010 | Unregistered Commenterrolex watches

Certified Professional (MCP) resources CompTIA Security+ Certification and benefits, including opportunities to connect with a vast, global network of MCPs. Database administrators install or configure Microsoft SQL CompTIA Nerwork+ Certification Server and manage or maintain databases 70-680 Exam or multidimensional databases, user accounts, database availability, recovery, and reporting. MCITP

July 8, 2010 | Unregistered Commenterliuhan

The 70-290 is appropriate for you if you are working or want to work in a typically complex computing environment of medium-to-large organizations. This 70-293 consists of Multiple Choice, Hot Area, Drag and Drop, Build list and reorder, and Build a Tree questions. The 70-291 can be adaptive and simulation questions might be asked. There are no Case study type questions. 70-680

July 8, 2010 | Unregistered Commenterliuhan

Wir bieten alle wow key Dienstleistungen.

July 12, 2010 | Unregistered Commenterabvcd

Stock lace wigs and full lace wigs. We supply Indian remy hair stock, celebrity, and custom full lace front wigs & cheap lace front wigs worldwide.Besides that,cheap hair extensions service is also included.

Wearing front lace wigs is becoming more and more popular among women. Suddenly it seems there are more and more celebrity stars wearing lace front wigs. lace front wigs for black women are plentiful, allowing you to choose a color and style lace wig with hair extensions that fits your needs perfectly.

July 14, 2010 | Unregistered CommenterMonica

You write good articles, I will always be concerned about

nfl jerseys

July 16, 2010 | Unregistered Commenternfl jerseys

Discount EasyTone shoes here. Reebok EasyTone wholesale. Reebok Easy Tone on sale.

July 23, 2010 | Unregistered CommenterReebok EasyTone

<font color=#999999>Fitness shoes of MBT and Vibram Five Fingers are collected at our website. MBT Shoes on sale. MBT Shoes Clearance. You will find high-quality brand shoes at low prices.</font>

July 23, 2010 | Unregistered CommenterMBT Shoes

PopularUGG is coming!UGG Classic Cardy is the hottest fashion trend in winter.Ugg Boots Sale at best price.

July 23, 2010 | Unregistered CommenterMBT Shoes

Juicy Couture womens fashions at Juicy Couture. Shop popular stores to find Juicy Couture womens fashions on sale - all in one place.
juicy couture,juicy couture tracksuits
juicy couture handbags
Juicy Couture was founded in 1997, by Gela Nash-Taylor and Pamela Skaist-Levy, as premium designer, marketer
Juicy Couture is a contemporary line of both casual and dressy apparel based in Arleta
juicy couture jewelry
Find a great range of Ed Hardy products. Ed Hardy Women's Ellerise Lowrise Sneaker · Ed Hardy Women's
thanks for your post.perhaps you will like
Ed hardy bags
Ed hardy T Shirts
ed hardy belts and Accessories On Sale,Official Ed Hardy Store for all Clothing and Gear,Ed hardy bags.,Mendelly beddings,crystal jewelry

July 28, 2010 | Unregistered Commenterjuicy couture

You write good articles, I will always be concerned about

nfl jerseys

July 29, 2010 | Unregistered Commenternfl jerseys

The modern replica submariner watches
comes housed in a black plastic case with stainless steel lugs at each side. The black

wristband is nicely crafted from leather, and in case you plan on banging your new watch

around a bit, the display is protected by a durable, scratch-resistant mineral crystal

face.

August 3, 2010 | Unregistered Commentervanjian
Editor Permission Required
You must have editing permission for this entry in order to post comments.