The principle and example of formatting string attacks. Rp

Source: Internet
Author: User

principles and examples of formatting string attacksThe realization principle of class printf function cluster

The biggest feature of the class printf function is the inability to know the number and type of function arguments at the time of function definition.

For this case, you can use the ellipsis to specify the parameter table.

In the function definition with ellipsis, the parameter table is divided into two parts, the first half is the number, the parameter of determining type, the second part is the ellipsis, the parameter table that represents the number and type are indeterminate, the number of parameters in the ellipsis parameter table and the type of the parameter are calculated by the prior contract. The address (pointer) of each argument is calculated based on the address of the last argument in the parameter table.

This involves the stack operation at the time of the function call. The stack bottom of the function stack is a high address, and the top of the stack is the bottom address. In a function call

When a function argument is pressed from the last parameter (the rightmost parameter) to the first parameter (the leftmost parameter), it is pushed into the top direction of the stack in turn. That is, when the function is called, the address of the function argument is connected, and the left-to-right address is incremented sequentially. Such as:

1#include <stdio.h>2#include <stdlib.h>3   4 voidFunintA, ...) 5 {  6     inti; 7     int*temp = &A; 8temp++; 9      for(i =0; i < A; ++i)Ten     {   Oneprintf"%d",*temp);  Atemp++;  -     }   -printf"/ N");  the }   -    - intMain () - {   +     intA =1;  -     intb =2;  +     intc =3;  A     intD =4;  atFun4, A, B, C, D);  -     return 0;  -}

In the example above, void fun (int a, ...) Function conventions The first determined parameter represents the number of parameters in the ellipsis parameter table, the parameters in the ellipsis parameter table are all int types, so the fun function works.

The class printf function cluster works the same way as the fun function, but is more complex and sophisticated.

Functions such as printf are in the form of int printf (const char *FMT, ...). )。

Because the function of printf function is more complicated, we look at a myprintf function that we implement ourselves, the function does not involve the low-level system IO operation.

1#include <stdio.h>2#include <stdlib.h>3   4 voidmyprintf (Char* FMT, ...)//a simple implementation similar to printf,//parameters must all be of type int5 {  6     Char* PARG=NULL;//va_list equivalent to the original implementation of printf7     CharC; 8PARG = (Char*) &fmt;//Be careful not to write P = fmt!! Because it's going to be//parameter fetch, not value9PARG + =sizeof(FMT);//equivalent to the original Va_startTen    One      Do   A     {   -C =*FMT;  -         if(c! ='%')   the         {   -Putchar (c);//output characters as-is -           }   -         Else   +         {   -             //output data by format character +                Switch(*++FMT) A             {   at                  Case 'D':   -printf"%d",*((int*) (PARG)) ;  -                      Break;  -                  Case 'x':   -printf"% #x",*((int*) (PARG)) ;  -                      Break;  in                 default:   -                      Break;  to             }   +PARG + =sizeof(int);//equivalent to the original Va_arg -         }   the++FMT;  *} while(*fmt! ='/0');  $PARG = NULL;//equivalent to Va_endPanax Notoginseng     return;  - }   the    + intMainintargcChar*argv[]) A {   the     inti =1;  +     intj =2;  -myprintf ("The first test:i=%d/n", i,j);  $myprintf ("The secend test:i=%d;%x;j=%d;/n"I0XABCD, J);  $     return 0;  -}

There is a similar convention in the MYPRINTF function, which determines that the last parameter in the parameter table is a const char* type string, where the number of "%d" and "%x" occurrences in the string is the number of parameters in the ellipsis parameter table, and the parameter types in the ellipsis parameter table are also int types.

Similarly, the actual printf function has the same convention: To determine that the last parameter in the parameter table is a const char* type string, the number of arguments in the ellipsis parameter table is "%d", "%x", "%s", which appears in this string ... The number of occurrences and the type of the parameter in the ellipsis parameter table is also determined by "%d", "%x", "%s" ... The format characters are indicated.

Therefore, the number and type of parameters in the ellipsis parameter table in the class printf function are determined by the format string in the class printf function.

Second, the principle of formatting string attack

Because the number and type of parameters in the ellipsis parameter table in the class printf function are determined by the format string in the class printf function, the attacker can use the programmer's negligence or vulnerability to cleverly construct the formatted string for the purpose of the attack.

If the task of a programmer is to print out a string or copy that string into a buffer. He can write the following code: printf ("%s", str), but in order to save time and improve efficiency, and in the source code to enter a few 6 bytes, he would write: printf (str);

Why did the programmer write the wrong thing? He passed in a string that he wanted to print verbatim. In fact, the string is interpreted by the printf function as a formatted character (formatstring), and printf determines the format and type of the parameters in the ellipsis parameter table in the printf function based on that string, if the programmer wants to print exactly "%d" in the string, "%x Format character, then the parameter value of a variable is taken out of the stack.

Like what:

1#include <stdio.h>2#include <stdlib.h>3   4 intMainintargcChar*argv[])5 {  6     if(ARGC! =2)  7         return 0; 8printf (argv[1]); 9     return 0; Ten}

When./a.out "Hello World" everything is OK, but when the./a.out "%x", there will be inexplicable numbers are printed out.

Obviously, an attacker could at least peek at the program's memory by printing out the values in the stack. But some things are less obvious, and this simple error allows you to write arbitrary values to the memory of the running program.

printf has a more alternative usage:%n, when the "%n" is encountered in the formatted string, the number of characters output before the%n field is saved to the next parameter. For example, in order to get a partial amount of space between two formatted numbers:

1 intMainintargcChar*argv[])2 {  3     intPOS, x =235, y = the; 4printf"%d%n%d/n", X, &pos, y); 5printf"The offset was%d/n", POS); 6     return 0; 7}

Output 4 (Length of "235")

The%n format returns the number of characters that should be output, rather than the number of characters actually output. When a string is formatted to output to a fixed-length buffer, the output string may be truncated. Regardless of the truncation effect, the%n format represents the offset value (the number of output characters) if not truncated. To illustrate this, the following code outputs 100 instead of 20:

1 intMain ()2 {  3     Charbuf[ -]; 4     intPOS, x =0; 5snprintf (BUF,sizeof(BUF),"%.100d%n", X, &POS); 6printf"Position:%d/n", POS); 7     return 0; 8}

The significant difference between%n and%d,%x,%s is that%n changes the value of the variable, which is the point of the burst of the formatted string attack.

A City practical examples

The following example can be shown below at least X86 Redhat and Arch Linux.

1#include <stdio.h>2#include <stdlib.h>3#include <string.h>4   5 Chardaddr[ -]; 6   7 intMainintargcChar**argv)8 {  9     Charbuf[ -]; Ten     intx;  Onex =1;  Amemset (DADDR,'/0', -);  -printf"before format string x is%d/% #x (@%p)/n", x, X, &x);  -strncpy (DADDR,"ppppppp%n",9);  thesnprintf (BUF,sizeof(BUF), daddr);//implementing a formatted string attack -    -buf[sizeof(BUF)-1] =0;  -printf"After format string x is%d/% #x (@%p)/n", x, X, &x);  +     return 0;  -}

The result of the operation is that X was successfully changed to 7.

The above example takes advantage of the memory remnants of a Linux function call to implement a formatted string attack. (Refer to the classic article is to use the method of guessing address, guess confused)

Let's examine the stack changes in the main function:

As shown, before calling the snprintf function, the printf function is called first, and the fourth parameter of the printf function is &x, which leaves the &x memory residue in the stack memory of the main function. When calling snprintf, the system would have prepared only 3 parameters for snprintf, but due to the format of the string attack, so that the snprinf think there should be four parameters passed to it, so snprintf secretly &x memory as a 4th parameter read away, and snprintf called the 4th parameter corresponding to the "%n", so snprintf succeeded in modifying the value of the variable x.

There are also many formatting string attacks that can be exploited in a real-world network environment. is a real cyber attack.

Text. RP. URL:http://blog.csdn.net/immcss/article/details/6267849

The principle and example of formatting string attacks. Rp

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.