首页 > 其他分享 >Understanding Buffer Overflow Bugs

Understanding Buffer Overflow Bugs

时间:2024-06-10 09:13:07浏览次数:14  
标签:code string Buffer byte line Bugs will Overflow your

Attack Lab: Understanding Buffer Overflow Bugs

1    Introduction

This assignment involves generating a total of five attacks on two programs which have different security vulnerabilities. In this lab, you will:

•  Learn different ways that attackers can exploit security vulnerabilities when programs do not safe- guard themselves well enough against buffer overflows.

•  Gain a better understanding of how to write programs that are more secure, as well as some of the features provided by compilers and operating systems to make programs less vulnerable.

•  Gain a deeper understanding of the stack and parameter-passing mechanisms of x86-64 machine code.

•  Gain a deeper understanding of how x86-64 instructions are encoded.

•  Gain more experience with debugging tools such as GDB and OBJDUMP.

Note: In this lab, you will gain firsthand experience with methods used to exploit security weaknesses in operating systems and network servers. Our purpose is to help you learn about the runtime operation of programs and to understand the nature of these security weaknesses so that you can avoid them when you write system code. We do not condone the use of any other form of attack to gain unauthorized access to any system resources.

You will want to study Sections 3.10.3 and 3.10.4 of the book as reference material for this lab.

2    Logistics

As usual, this is an individual project. You will generate attacks for target programs that are custom gener- ated for you.

2.1    Getting Files

You can obtain your files from the Autolab site

https://ics.autolabproject.com

After logging in to Autolab, select Attacklab  ->  Download  handout.   The Autolab server will build your files and return them to your browser in a tar file called targetk .tar, where k is the unique number of your target programs.

Note: It takes about 15 seconds to build and download your target, so please be patient.

Save the targetk .tar file in a (protected) Andrew directory in which you plan to do your work.  Then login to a shark machine and give the command: tar  -xvf  targetk .tar. This will extract a directory targetk containing the files described below.

You should only download one set of files. If for some reason you download multiple targets, choose one target to work on and delete the rest.

Warning: If you expand your targetk .tar on a PC, by using a utility such as Winzip, or letting your browser do the extraction, you’ll risk resetting permission bits on the executable files.

The files in targetk include:

README .txt: A file describing the contents of the directory

ctarget: An executable program vulnerable to code-injection attacks

rtarget: An executable program vulnerable to return-oriented-programming attacks

cookie .txt: An 8-digit hex code that you will use as a unique identifier in your attacks.

farm .c: The source code of your target’s “gadget farm,” which you will use in generating return-oriented programming attacks.

hex2raw: A utility to generate attack strings.

In the following instructions, we will assume that you have already copied the files to a protected local directory, and that you are executing the programs in that local directory.

2.2    Important Points

Here is a summary of some important rules regarding valid solutions for this lab. These points will not make much sense when you read this document for the first time.  They are presented here as a central reference of rules once you get started.

•  You must do the assignment on one of the class shark machines. There are ten machines available to students to use, a full list of which can be found on the course Web site at:

http://www.cs.cmu.edu/ ˜18213/labmachines.html

•  Your solutions may not use attacks to circumvent the validation code in the programs.

•  You may only construct gadgets from filertarget with addresses ranging between those for func- tions start_farm and end_farm.

•  You can use any gadgets you discover in the farm, not just those for which we give the bytecodes in Figure 3.

•  You are allowed to use the standard tools for this assignment: gdb (or lldb), objdump, and any tool that you create (from scratch) on your own.

•  You are not allowed to use tools or gdb plugins that are designed to assist in implementing buffer overflow and ROP attacks.

•  It is highly recommended that you gdb to confirm that your exploit is placed on the stack with the correct byte ordering

•  It is not uncommon for gdb to get lost while performing exploit code. You may be unable to step through your exploitingdb while seeing all of the usual diagnostic information.

3    Target Programs

Both CTARGET and RTARGET read strings from standard input. They do so with the function read   and process   line defined below:

1   / *  read_and_process_line  -  Read  a  line  from  INFILE  and  process  it .

2        This  function  has  a  buffer  overflow  vulnerability .    */

3  void  read_and_process_line(FILE  *infile)  {

4            unsigned  char  buf[BUFFER_SIZE];

5              unsigned  char  *sp  =  buf;

6              int  c;

7              while   ((c  =  getc(infile))  !=  EOF  &&  c  !=  ’\n’)   { 8                          *sp++  =  c;

9               }

10              process_line(buf,  sp  -  buf);

11   }

This function reads a byte sequence from standard input, terminated by either a newline (’\n’), or end of file (EOF). Then it calls another function, process   line, passing it the bytes that were read. (It does not add a NUL terminator to the bytes it reads, so what it passes to process   line is not a “string.” Instead, it passes the number of bytes read as process   line’s second argument.)

In the code sample, you can see that read   and process   line stores the byte sequence in a local vari- able buf, an array of BUFFER_SIZE bytes. (BUFFER_SIZE is a compile-time constant, specific to your version of CTARGET and RTARGET.) Notice that the while loop does not stop when BUFFER_SIZE bytes have been read. This is the same bug that’s found in the C library function gets: it keeps reading data until end of line or file,possibly overrunning the bounds of the storage allocated for the data.

If the input read by read   and process   line is sufficiently short, nothing interesting will happen:

$   . /ctarget

Cookie:  0x599051eb

Type  string:    Keep  it  short!

No  exploit,  read_and_process_line  returned  normally.

Typically an error occurs if you type a long string:

$unix   ./ctarget

Cookie:  0x599051eb

Type  string:     This  is  not  a  very  interesting  string,  but  it  is  quite  long Ouch!:  You  caused  a  segmentation  fault!

Better  luck  next  time

(Note that the value on the Cookie: line will differ from yours.)

of the cookie shown will differ from yours.)  Program RTARGET will have the same behavior.  As the error message indicates, overrunning the buffer typically causes the program state to be corrupted, leading to a memory access error. Your task is to be more clever with the strings you feed CTARGET  and RTARGET  so that they do more interesting things. These are called exploit strings.

Both CTARGET and RTARGET take several different command line arguments: -h:  Print list of possible command line arguments

-i  FILE:  Supply input from a file, rather than from standard input

Your exploit strings will typically contain byte values that do not correspond to the ASCII values for printing characters. The program HEX2RAW will enable you to generate these raw strings. See Appendix A for more information on how to use HEX2RAW.

Important points:

•  Your exploit string must not contain byte value  0x0a at any intermediate position, since this is the ASCII code for newline (‘\n’).  When Gets encounters this byte, it will assume you intended to terminate the string.

•  HEX2RAW  expects two-digit hex values separated by one or more white spaces.  So if you want to create a byte with a hex value of 0, you need to write it as 00.  To create the word  0xdeadbeef you should pass “ef  be  ad  de” to HEX2RAW  (note the reversal required for little-endian byte ordering).

When you have correctly solved one of the levels, your target program will automatically send a notification to Autolab. For example:

Phase

Program

Level

Method

Function

Points

1

CTARGET

1

CI

touch1

10

2

CTARGET

2

CI

touch2

25

3

CTARGET

3

CI

touch3

25

4

5

RTARGET RTARGET

2

3

ROP ROP

touch2 touch3

35

5

CI:         Code injection

ROP:     Return-oriented programming

Figure 1: Summary of attack lab phases

$unix  ./hex2raw  <  ctarget .l2 . txt  |   ./ctarget

Cookie:  0x1a7dd803

Type  string:Touch2!:  You  called  touch2(0x1a7dd803) Valid  solution  for  level  2  with  target  ctarget

PASSED:  Sent  exploit  string  to  server  to  be  validated . NICE  JOB!

Unlike the Bomb Lab, there is no penalty for making mistakes in this lab. Feel free to fire away at CTARGET and RTARGET with any strings you like.1

Figure 1 summarizes the five phases of the lab.  As can be seen, the first three involve code-injection (CI) attacks on CTARGET, while the last two involve return-oriented-programming (ROP) attacks on RTARGET.

4    Part ICode Injection Attacks

For the first three phases, your exploit strings will attack CTARGET.  This program is set up in a way that the stack positions will be consistent from one run to the next and so that data on the stack can be treated as executable code. These features make the program vulnerable to attacks where the exploit strings contain the byte encodings of executable code.

4.1    Level 1

For Phase 1, you will not inject new code. Instead, your exploit string will redirect the program to execute an existing procedure.

Function read   and process   line is called within CTARGET by a function test having the following C code:

1  void  test(FILE  *infile)  {

2              read_and_process_line(infile);

3              notify_fail(0,  "No  exploit,  read_and_process_line  returned  normally . ");

4   }

When read   and process   line executes its return statement (line 5 of read   and process   line), the program ordinarily resumes execution within function test (at line 5 of this function).  We want to change this behavior. Within the file ctarget, there is code for a function touch1 having the following C representation:

1   TOUCH_FN  touch1(void)   {

2              vlevel  =  1;  / *  Part  of  validation  protocol  */

3              printf("Touch1!:  You  called  touch1()\n");

4              validate(1); 5   }

Your task is to get CTARGET to execute the code for touch1 when read   and process   line executes its return statement, rather than returning to test.  Note that your exploit string may also corrupt parts of the stack not directly related to this stage, but this will not cause a problem, since touch1 causes the program to exit directly.

Some Advice:

•  All the information you need to devise your exploit string for this level can be determined by exam- ining a disassembled version of CTARGET. Use objdump  -d to get this dissembled version.

•  The idea is to position a byte representation of the starting address for touch1 so that the ret instruction at the end of the code for read   and process   line will transfer control to touch1.

•  Be careful about byte ordering.  Remember, arrays (such as strings) are saved in index order, but values like integers are evaluated in little-endian.

•  You might want to use GDB to step the program through the last few instructions of read   and process   line to make sure it is doing the right thing.

•  The placement of buf within the stack frame. for read   and process   line depends on the value of compile-time constant BUFFER_SIZE, as well the allocation strategy used by GCC. You will need to examine the disassembled code to determine its position.

4.2    Level 2

Phase 2 involves injecting a small amount of code as part of your exploit string.

Within the file ctarget there is code for a function touch2 having the following C representation:

1   TOUCH_FN  touch2(unsigned  val)   {

2              vlevel  =  2;  / *  Part  of  validation  protocol  */

3           if   (val  ==  cookie)   {

4                         printf("Touch2!:  You  called  touch2(0x% . 8x)\n",  val);

 

 

5                         validate(2); 6               }  else   {

7                          notify_fail(2,  "Misfire:  You  called  touch2(0x% . 8x)",  val);

8               }

9   }

Your task is to get CTARGET to execute the code for touch2 rather than returning to test.  In this case, however, you must make it appear to touch2 as if you have passed your cookie as its argument.

Some Advice:

•  You will want to position a byte representation of the address of your injected code in such a way that ret instruction at the end of the code for read   and process   line will transfer control to it.

•  Recall that the first argument to a function is passed in register %rdi.

•  Your injected code should set the register to your cookie, and then use a ret instruction to transfer control to the first instruction in touch2.

•  Do not attempt to use  jmp or call instructions in your exploit code.  The encodings of destination addresses for these instructions are difficult to formulate.  Use ret instructions for all transfers of control, even when you are not returning from a call.

•  See the discussion in Appendix B on how to use tools to generate the byte-level representations of instruction sequences.

4.3    Level 3

Phase 3 also involves a code injection attack, but passing a string as argument.

Within the file ctarget there is code for functions hexmatch and touch3 having the following C representations:

1   / *  Compare  string  to  hex  represention  of  unsigned  value  */

2  static  int  hexmatch(unsigned  val,  char  *sval)  {

3              char  *endp;

4              unsigned  long  cval  =  strtoul(sval,  &endp,  16);

5           return   (cval  ==   (unsigned  long)  val 6                                     &&  endp   !=  sval

7                                    &&  *endp  ==  ’\0’);

8   } 9

10   TOUCH_FN  touch3(char  *sval)   {

11              vlevel  =  3;  / *  Part  of  validation  protocol  */

12           if   (hexmatch(cookie,  sval))  {

13                          report_touch3("Touch3!",  sval);

14                         validate(3);

15               }  else   {

 

16                          report_touch3("Misfire",  sval);

17                          notify_fail(3,  "touch3  called  with  the  wrong  cookie"); 18               }

19   }

Your task is to get CTARGET to execute the code for touch3 rather than returning to test. You must make it appear to touch3 as if you have passed a string representation of your cookie as its argument.

Some Advice:

•  You will need to include a string representation of your cookie in your exploit string. The string should  consist of the eight hexadecimal digits (ordered from most to least significant) without a leading “ 0x.”

•  Recall that a string is represented in C as a sequence of bytes followed by a byte with value 0. Type “man  ascii” on any Linux machine to see the byte representations of the characters you need.

•  Your injected code should set register %rdi to the address of this string.

•  When functions hexmatch and strncmp are called, they push data onto the stack, overwriting portions of memory that held the buffer used by read   and process   line. As a result, you will need to be careful where you place the string representation of your cookie.

5    Part IIReturn-Oriented Programming

Performing code-injection attacks on program RTARGET  is much more difficult than it is for CTARGET, because it uses two techniques to thwart such attacks:

•  It uses randomization so that the stack positions differ from one run to another. This makes it impos- sible to determine where your injected code will be located.

•  It marks the section of memory holding the stack as nonexecutable, so even if you could set the program counter to the start of your injected code, the program would fail with a segmentation fault.

Fortunately, clever people have devised strategies for getting useful things done in a program by executing existing code, rather than injecting new code. The most general form. of this is referred to as return-oriented programming (ROP) [1, 2]. The strategy with ROP is to identify byte sequences within an existing program that consist of one or more instructions followed by the instruction ret. Such a segment is referred to as a gadget. Figure 2 illustrateshow the stack can be set up to execute a sequence of n gadgets. In this figure, the stack contains a sequence of gadget addresses. Each gadget consists of a series of instruction bytes, with the final one being 0xc3, encoding theret instruction. When the program executes a ret instruction starting with this configuration, it will initiate a chain of gadget executions, with the ret instruction at the end of each gadget causing the program to jump to the beginning of the next.

A gadget can make use of code corresponding to assembly-language statements generated by the compiler, especially ones at the ends of functions. In practice, there may be some useful gadgets of this form, but not enough to implement many important operations. For example, it is highly unlikely that a compiled function

Figure 2: Setting up sequence of gadgets for execution. Byte value 0xc3 encodes theret instruction.

would have popq  %rdi as its last instruction before ret.  Fortunately, with a byte-oriented instruction set, such as x86-64, a gadget can often be found by extracting patterns from other parts of the instruction byte sequence.

For example, one version of rtarget contains code generated for the following C function:

void  setval_210(unsigned  *p)

{

*p  =  3347663060U;

}

The chances of this function being useful for attacking a system seem pretty slim.  But, the disassembled machine code for this function shows an interesting byte sequence:

0000000000400f15  <setval   210>:

400f15:              c7  07  d4  48  89  c7

movl

$0xc78948d4,(%rdi)

400f1b:                c3

retq

 

The byte sequence  48  89  c7 encodes the instruction movq  %rax,  %rdi.   (See Figure  3A for the encodings of useful movq instructions.)  This sequence is followed by byte value c3, which encodes the ret instruction.  The function starts at address 0x400f15, and the sequence starts on the fourth byte of the function. Thus, this code contains a gadget, having a starting address of 0x400f18, that will copy the 64-bit value in register %rax to register %rdi.

Your code for RTARGET contains a number of functions similar to the setval_210 function shown above in a region we refer to as the gadget farm. Your job will be to identify useful gadgets in the gadget farm and use these to perform attacks similar to those you did in Phases 2 and 3.

Important: The gadget farm is demarcated by functions start_farm and end_farm in your copy of rtarget. Do not attempt to construct gadgets from other portions of the program code.

A. Encodings of movq instructions

movq  S ,  D

Figure 3: Byte encodings of instructions. All values are shown in hexadecimal.

5.1    Level 2

For Phase 4, you will repeat the attack of Phase 2, but do so on program RTARGET using gadgets from your gadget farm.  You can construct your solution using gadgets consisting of the following instruction types, and using only the first eight x86-64 registers (%rax–%rdi).

movq  : The codes for these are shown in Figure 3A.

popq  : The codes for these are shown in Figure 3B.

ret  : This instruction is encoded by the single byte 0xc3.

nop  : This instruction (pronounced “no op,” which is short for “no operation”) is encoded by the single

byte 0x90. Its only effect is to cause the program counter to be incremented by 1. Some Advice:

•  All the gadgets you need can be found in the region of the code for rtarget demarcated by the functions start_farm and mid_farm.

•  You can do this attack with just two gadgets.

•  When a gadget uses a popq instruction, it will pop data from the stack.  As a result, your exploit string will contain a combination of gadget addresses and data.

5.2    Level 3

Before you take on the Phase 5, pause to consider what you have accomplished so far.  In Phases 2 and 3, you caused a program to execute machine code of your own design. If CTARGET had been a network server, you could have injected your own code into a distant machine.  In Phase 4, you circumvented two of the main devices modern systems use to thwart buffer overflow attacks. Although you did not inject your own code, you were able inject a type of program that operates by stitching together sequences of existing code. You have also gotten 95/100 points for the lab. That’s a good score. If you have other pressing obligations consider stopping right now.

Phase 5 requires you to do an ROP attack on RTARGET to invoke function touch3 with a pointer to a string representation of your cookie. That may not seem significantly more difficult than using an ROP attack to invoke touch2, except that we have made it so. Moreover, Phase 5 counts for only 5 points, which is not a true measure of the effort it will require. Think of it as more an extra credit problem for those who want to go beyond the normal expectations for the course.

To solve Phase 5, you can use gadgets in the region of the code in rtarget demarcated by functions start_farm and end_farm.  In addition to the gadgets used in Phase 4, this expanded farm includes the encodings of different movl instructions, as shown in Figure 3C. The byte sequences in this part of the farm also contain 2-byte instructions that serve as functional nops, i.e., they do not change any register or memory values. These include instructions, shown in Figure 3D, such as andb  %al,%al, that operate on the low-order bytes of some of the registers but do not change their values.

Some Advice:

•  You’ll want to review the effect a movl instruction has on the upper 4 bytes of a register, as is described on page 183 of the text.

•  The official solution requires a sequence of eight gadgets.  Depending on the contents of your farm (each target has a different one), you may be able find a shorter one.

•  Remember: Your exploit string must not contain the newline character (byte value 0x0a) at any inter- mediate position

标签:code,string,Buffer,byte,line,Bugs,will,Overflow,your
From: https://www.cnblogs.com/qq99515681/p/18240382

相关文章

  • Android Media Framework(四)Non-Tunneled组件的状态转换与buffer分配过程分析
    本篇将继续深入OpenMAXILSpec,详细解析Non-tunneled(非隧道)组件的初始化、数据传递以及组件销毁过程。通过阅读本篇内容,我们应能对Non-tunneled组件的buffer分配与状态转换过程有一个清晰的了解。1、组件初始化以下是ILSpec给的Non-tunneled组件初始化时序图:ILClient首先......
  • Java基础——数组应用之StringBuilder类和StringBuffer类
    系列文章目录文章目录系列文章目录前言一、StringBuffer类二、StringBuffer概述三、StringBuffer方法四、StringBuilder类五、String、StringBuffer、StringBuilder的区别前言前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点......
  • String、StringBuilder和StringBuffer是处理字符串的三个不同的类
    在Java中,String、StringBuilder和StringBuffer是处理字符串的三个不同的类,它们各自具有不同的特点和使用场景。下面将具体分析这三个类的异同点:不可变性与可变性String:String是一个不可变的字符串,这意味着一旦一个String对象被创建,其值就不能改变。这种设计提供了值的恒定性,使......
  • mysql中InnoDB存储引擎的Buffer Pool
    大家好。众所周知,对于使用InnoDB作为存储引擎的表来说,不管是用于存储用户数据的索引(包括聚簇索引和二级索引),还是各种系统数据,都是存储在磁盘上的。在处理客户端的请求时,当需要访问某个页的数据时,就会把完整的页的数据全部加载到内存中。将整个页加载到内存中后就可以进行读......
  • css30 CSS Layout - Overflow
    https://www.w3schools.com/css/css_overflow.aspCSSLayout-Overflow  TheCSSoverflowpropertycontrolswhathappenstocontentthatistoobigtofitintoanarea. <!DOCTYPEhtml><html><head><style>#overflowTest{b......
  • Nginx:a client request body is buffered to a temporary file
    https://www.cnblogs.com/iAmSoScArEd/p/18225191Nginxwarn:2024/05/3119:28:37[warn]8467#0:*9505669aclientrequestbodyisbufferedtoatemporaryfile/usr/local/openresty/nginx/client_body_temp/0002098837,client:10.xx.xx.xx,server:xxx.xx.com,r......
  • 嵌入式linux系统中framebuffer应用开发详解
    大家好,今天给大家详细分析一下,利用framebuffer进行linux应用开发的详细方法。第一:LCD屏Framebuffer基本原理LCDFramebuffer就是一块显存.在嵌入式系统中.显存是被包含在内存中。LCDFramebuffer里的若干字节〈根据驱动程序对LCD控制器的配置而定〉表示LCD屏幕中的一个像素点.......
  • nginx fastcgi_buffers 缓存
    nginxfastcgi_buffers设置打开nginx的warn级别error_log,看到如下信息:2011/04/2317:24:08[warn]9639#0:*44anupstreamresponseisbufferedtoatemporaryfile/tmp/fastcgi_temp/8/0/0000000008whilereadingupstream,client:118.118.118.118,server:sealing......
  • 测试C#GDI+双缓冲高效绘图--BufferedGraphicsContext
    奥斯卡好的b、测试C#GDI+双缓冲高效绘图```#regionC#GDI+双缓冲高效绘图#regiontemp//Rectanglerectangle=e.ClipRectangle;//取出次窗体或者画布的有效区的矩形区域//BufferedGraphicsContextGraphicsContext=BufferedGraphicsM......
  • StringBuffer和StringBuilder方法
    StringBuffer:可变长字符串,jdk1.0提供,运行效率满、线程安全。StringBuilder:可变长字符串,jdk5.0提供,运行效率快、线程不安全。(单线程推荐使用)效率:StringBuilder>StringBuffer>String//验证StringBuilder效率高于StringpublicclassString{publicstaticvoidmain(java.lang.......