04 November 2007

double free()

So, while writing an exploit for a publicly known bug at work I stumbled across another one, a double free(). Then I started looking into how exactly one exploit's a double free, and it looked grim. The program has to survive a double free, meaning that it cannot crash. The default action for glibc is to print an error message such as:

glibc detected *** double free or corruption (fasttop): 0x12345678 ***

and then call abort(), which terminates the program. So it looked like it was not exploitable, and just a DoS, so I looked at BSD libc and the libc from Solaris, neither of them appeared to be affected by double free's either. So I went back and looked in glibc's source code to determine what exactly it checks to detect a double free (There are a couple different checks depending on type, I'm only covering one here because it is what pertains to my situation and the others are essentially the same with a few other easily bypassed checks).

So, glibc has the concept of fast bin's, or arrays where it stores free chunks of memory under certain conditions, most importantly chunks that are less than 512 bytes in length. So I looked at the glibc code in malloc/malloc.c and find the following relevant section:

fb = &(av->fastbins[fastbin_index(size)]);
/* Another simple check: make sure the top of the bin is not the
record we are going to add (i.e., double free). */
if (__builtin_expect (*fb == p, 0))
errstr = "double free or corruption (fasttop)";
goto errout;

Here we have something interesting, let me explain the code first though. In the first line we take the variable 'fb' and make it point to the address of the element in the fast bin array for the size of the chunk in question. In other words, the fast bin array is sorted by size of chunks, and we are assigning the fb variable to the address of the index for the given size of our current chunk. Then we check to see if what that address points to (*fb) is the address of the current chunk being free'd (p), if so we've found the chunk being free'd in the list of free chunks and we have a double free situation (or linked list corruption).

But what if? What if another chunk of the same size and thus in the same fast bin has been deallocated since the current chunk was free'd, for instance, what if we have:

ptr0 = malloc(siz);
ptr1 = malloc(siz);

// presume both calls succeed


Then the top entry in the list won't be ptr0, it will be ptr1, and (assuming no other chunks in that list have been deallocated) ptr0 will be the second end on the linked list and the check will succeed and we will be able to free the pointer again, not have abort() called and potentially exploit the situation for our advantage.

#include <stdio.h>
#include <stdlib.h>

main(int argc, char **argv)
void *ptr0;

ptr0 = malloc((size_t)64);

if (NULL == ptr0) {

if (1 < argc) {

void *ptr1;

ptr1 = malloc((size_t)64);

if (NULL == ptr1) {


} else {




I've got a bit more on the glibc heap implementation, some of which I thought myself clever for finding only to realize it's been documented in a recent paper, others which just are redundant to mention at this point.


Miroslav Beranič ml. said...

Hmmm, interesting. Nice to know.

But how would one prevent/detect double freeing? Is it possible to check if memory was freed in the past?

Anonymous said...

China Wholesale has been described as the world’s factory. This phenomenom is typified by the rise ofbusiness. Incredible range of products available with China Wholesalers “Low Price and High Quality” not only reaches directly to their target clients worldwide but also ensures that wholesale from china from China means margins you cannot find elsewhere and buy products wholesaleChina Wholesale will skyroket your profits.wedding dressescheap naruto cosplayanime cosplaycheap Gemstone Jewelry

Anonymous said...

Women’s nike tn Shox Rivalry est le modèle féminin le plus tendance de baskets pour le sport. tn chaussuresConcernant la semelle :spyder jacketsCheap Brand Jeans Shop - True Religion Jeans cheap nike shox & Puma Shoes Online- tn nike,Diesel Jeans le caoutchouc extérieur, l’EVA intermédiaire Levis Jeanset le textile intérieur s’associent pour attribuer à la.ed hardy shirts pretty fitCharlestoncheap columbia jackets. turned a pair of double plays to do the trick.Lacoste Polo Shirts, puma basket, Burberry Polo Shirts.wholesale Lacoste polo shirts and cheap polo shirtswith great price.Thank you so much!!cheap polo shirts men'ssweate,gillette mach3 razor bladesfor men.As for Cheap Evisu JeansCheap Armani Jeanspolo shirtsPuma shoes

Anonymous said...

gucci replica handbags
men gucci shoes
Gucci men sneakers
Gucci men moccasins
gucci women sneakers
gucci women boots
Gucci men boots
Gucci shop
Gucci bags
Gucci shoes
wholesale gucci shoes
cheap Gucci handbags
Gucci ON sale
Gucci Belts
Gucci small accessories
Gucci hats & scarves
Gucci wallets
Gucci Handbags
Women Gucci shoes
Men Gucci shoes
discount gucci shoes
cheap Gucci shoes

jf said...

@Miroslav -- its a difficult subject the minute threads get involved. You need to have some concept of 'thread ownership' of the block in order to be able to stop it; i noted from another blog that there have been recent changes to some of the code and it may prevent some of what i talked of here. Bottom line is however, if thread a allocates, then free's, then thread b allocates and get the same chunk, then thread a double free's, theres no clean way to detect it.

GUCCI BOSS said...

coach coupons
coach backpack
New Coach Bag
bags cheap
Coach Classic
coach discount
Coach Handbags
coach purses cheap
Coach Purses

coach poppy
Coach Tote
coach outlet store
coach store
Coach Wallets

Coach Luggage
Coach leather bag
Coach Sandals
Coach Jewelry
Coach Accessories
Coach Sunglasses
Coach glasses

Coach Bags
Coach Handbags
Coach Purses
Coach Outlet
Coach Purses Outlet
Coach Bags Outlet
Coach Wholesale

hxl said...

baby bedding
bed in a bag
sexual health
health plan
beauty cosmetics
skin care
health fitness sports
mens health
fashion shoes reviews
best air shoes
best women shoes
fashion dress
comfortable man shoes
fashion shoes
sneakers reviews
top ten boots
boots of world
rosetta stone
boots classic
wholesale lots
china wholesaler
china wholesale
wedding dress
lightinthebox reviews
fashion shoes

polo shirts said...

History of polo ralph lauren. Polo fashions had its humble beginnings in 1968 when tie salesman Ralph Lauren gave it a kick start. By 1969 he had a boutique polo ralph lauren factory stores within the Manhattan department store Bloomingdale's. ... Brands and luxury standard. Since Ralph Lauren's first brand, Polo Ralph Lauren, was launched, the company has expanded to include a variety of luxury brands such as Polo Golf, Polo Denim, Polo Sport. You can buy cheap Ralph Lauren Clothing at Ralph Lauren outlet.Also We provide polo shirts
Ralph Lauren polo shirt, 50% OFF! polo ralph lauren outlet online is your best choice!In 2006, polo ralph lauren outlet became the first designer in Wimbledon's 133-year history to create official uniforms for the tournament. As part of this year's event, which starts next week, polo ralph lauren sale will introduces the first ... determination to maintain and enhance the values for which our two brands are famous throughout the world. The rugby ralph lauren brand brings to Wimbledon the look of timeless elegance, drawing on our rich history and traditions

Anonymous said...

Max Azria Herve Leger of Herve Leger from France, was founded in 1985, Paris is the famous fashion herve leger design house. Herve Leger dress to shaping the modern women, women have shown that line feels soft and the silhouette. Herve Leger clothing each place of body, to cut out the Christian Louboutin Pumps perfect bodily form female carved image and get the name "the bandage dress". Whether on the red carpet in Christian Louboutin attendance or Leger Herve party town of clothing for you to create unforgettable image.
In 1999, Paris dress GHD Styler design house by the Los Angeles fashion giant Herve Leger BCBG Azria Group owns, Max. This is the first time in history of French fashion brand by American herve leger bandage dress designer at the helm. Herve Leger in design and production of high-grade luxury and ready-to-wear uniforms. She and the perfect combination of Azria Max undoubtedly makes the Christian Louboutin Boots brand development in a new step. Max Azria Group determined BCBG Herve expand Leger of retail sales in New York, soon will appear on Madison avenue Herve four Hermes Leger boutiques. Soon, Beverly villa, the legendary Rue Paris Cambon, Las Vegas also have a shop.
In the summer of 2007, in order to meet the market demand growth, Leger released by Max Herve Azria cocktail dress design. Soon, the world and the garment Moncler wholesalers, will cooperate with Herve Leger garment around the world.
Since its establishment, from Herve Leger marked and sexy design style attracted numerous international customers worldwide, which is the most beautiful and the most ghd hair straighteners fashionable women. Hollywood star like Lindsay Lohan, article required, new Charlize Theron Zeta - a flop, and Beyonce, Christina Aguilera, Eva Mendes, Jackson, cernet operated language examiner "- Nicole Richie, Jessica Simpson, herve leger dresses Eva Longoria and Jessica Biel, Leger Herve became the most loyal fans. Herve Leger name forever and Hollywood's glittering and charm.

boshi said...

Third, Far away on the mysterious Isle of Zoobles reside hundreds of adorable, little creatures with a magnificent ability, they can magically transform into tiny balls hiding from the unknown, rolling to colorful destinations, sleeping after a long day But beware, you never know when these mischievous Zoobles are going to pop open and surprise you.

Fourth, EFX’s holographic technology contains algorithms and frequencies that interact positively with this energy field in both humans and animals at the cellular level. When placed near the body, especially at key energy centers such as the hands and feet, EFX bracelet’s products will harmonize with the body’s naturally occurring bioelectric frequencies.

Fifth, Every child wants a zhu zhu petshamster and we have all of them in stock as well as all the Zhu Zhu accesories for this most wished for of toys. They are also know as Go Go Pets or Go Go Hamsters in the UK and Europe. Enjoy your zhu zhu pets everyone. Sixth,
Pillow Pets is durability, machine washable, no batteries, friends for life and most important children like them. Silicone Watch is not only a fashional, but also healthy product, it is suitable to all people to wear.The designs are fashional and it can be worn whenever,whether you are sit or run. Wearing it, you will feel mental and muscle relax, besides.
barbie girls.

sweet said...

well done. thanks
Supra TK Society Shoes
supra cruizer
supra skytop 2
supra cuban

aiya said...

Office 2010
Microsoft Office 2010
Microsoft word
Office 2007
Microsoft Office
Microsoft Office 2007
Office 2007 key
Office 2007 download
Office 2007 Professional
Outlook 2010
Microsoft outlook
Microsoft outlook 2010
Windows 7

pandorasell said...

Silver pandora jewelry store comprises replacement atomic number 79 equally the metal by choice in that pandora jewelry website flavors manners. .925 alright superlative Ag Jewelry checks 92.5% complete silver pandora jewelry online and comprises assorted with extra debases to beef up them and abbreviate maculating pandora style jewelry coming through a hard-nosed alloy as pandora bracelet beads . The rise in metal prices, especially gold, have begun to alter pandora leather bracelet dashes. Designers are applying sterling pandora style bracelet a lot of today because of its gold pandora bracelet appeal and affordability. Designers care Jacques Louis pandora charm necklace David Yurman and those from pandora’s cause changed their focus and are making A-list assembles by .925 Fine Sterling pandora necklace charms Although Silver is affordable its price has quietly risen 300% inch the last 5 years and is astir across 50% pandora silver beads these class entirely. Many investment advisers* recommend a portion of your wealth be inward Ag and amber. Trend setters who comprised the first to begin wearing pandora necklace leather metal to match tatto last word and additional electric current styles as well do good along accepting pandora bracelet charms worth more than they paid for it.

qinbincai123 said...

This rain that blinds the windows with its mists,Will gladden in suburbs no more to be found,
the kirefg88 black grapes on a vine there overhead.
Wholesale New Era Hats
Cheap 59fifty Hats
Cheap New Era Hats
New Era Snapback Hats
New Era Fitted Hats

Jerry Gene said...

I really like your writing style. Nice Post keep it up.

Asus - K53E-DS31 15.6" LED Notebook - Intel Core i3 i3-2350M 2.30 GHz - Mocha

Asus - 14" Notebook 4 GB Memory - 500 GB Hard Drive - Black (P43E-XH31)