Alert for Buffer Overflow (Insecure library functions in C) and buffer library functions

Source: Internet
Author: User
Tags password protection

Alert for Buffer Overflow (Insecure library functions in C) and buffer library functions

C and C ++ cannot perform border checks automatically. The cost of border checks is efficiency. Generally, C focuses on efficiency in most cases. However, the cost of efficiency is that C programmers must be very alert to avoid Buffer Overflow.

Many string processing and IO stream reading functions in the C language standard library are the culprit of buffer overflow. We need to understand these functions and be careful in programming.

I. string processing functions
  • Strcpy ()

    The strcpy () function copies the source string to the buffer. No specific number of characters to be copied is specified! If the source string happens to come from user input and does not specifically limit its size, it may cause a buffer overflow! We can also use strncpy for the same purpose: strncpy (dst, src, dst_size-1); If src is larger than dst, the function will not throw an error; when the maximum size is reached, it only stops copying characters. Note that-1 in strncpy () is called above. If src is longer than dst, leave space for us to put an empty character at the end of the dst array. But! Strncpy () is not completely secure, and may make things worse. Even if a "safe" call sometimes leaves a string that is not terminated, or a subtle difference may occur. Another way to ensure that strcpy () does not overflow is to allocate space when it is needed and ensure that sufficient space is allocated by calling strlen () on the source string. Dst = (char *) malloc (strlen (src); strcpy (dst, src );
  • Strcat ()

    The strcat () function is very similar to strcpy (), except that it can merge a string to the end of the buffer. It also has a similar, safer alternative to strncat (). If possible, use strncat () instead of strcat ().
  • Sprintf (), vsprintf ()

    Functions sprintf () and vsprintf () are common functions used to format text and store it in the buffer zone. They can directly imitate strcpy () behavior. In other words, using sprintf () and vsprintf () is the same as using strcpy (), it is easy to cause buffer overflow to the program. Many versions of sprintf () come with a safer method to use this function. You can specify the precision of each independent variable of the format string. Sprintf uses "*" to occupy a position that originally requires a constant number with a specified width or accuracy, and the actual width or accuracy can be provided like other printed variables. Example: sprintf (usage, "USAGE: % * s \ n", BUF_SIZE, argv [0]);
Ii. character reading functions
  • Gets ()

    Never use gets (). This function reads a line of text from the standard input. It does not stop reading text before it encounters an EOF character or line feed character. That is, gets () does not perform the boundary check at all. Therefore, using gets () always causes any buffer overflow. As an alternative, you can use the fgets () method (). It can do the same thing as gets (), but it accepts the size parameter used to limit the number of characters to be read. Therefore, it provides a method to prevent Buffer Overflow.
  • Getchar (), fgetc (), getc (), read ()

    If these functions are used in a loop, check the buffer boundary.
  • Scanf () Series

    Sscanf (), fscanf (), vfscanf (), vscanf (), vsscanf ()

    Functions of the scanf series are also poorly designed. The destination buffer may also overflow. Similarly, we can solve this problem by setting the width.
  • Getenv ()

    The biggest problem with using the System Call getenv () is that you cannot assume that special environment variables are of any specific length.
3. Use a secure version of the code library

Microsoft uses the Security version library developed by Microsoft to replace APIs with buffer overflow risks.
SafeCRT is supported since Visual Studio 2005. When Dangerous disabled CRT functions are used in the code, Visual Studio 2005 will report a warning to remind developers to consider replacing them with Safe CRT for security.

Other disabled APIs include scanf, strtok, gets, and itoa. "N" series of string processing functions, such as strncpy, are also disabled.

Example

Crack the following password protection code:

#include <stdio.h>int main(int argc, char *argv[]){    int flag = 0;    char passwd[10];    memset(passwd,0,sizeof(passwd));    strcpy(passwd, argv[1]);     if(0 == strcmp("LinuxGeek", passwd))    {        flag = 1;    }    if(flag)    {        printf("\n Password cracked \n");    }    else    {        printf("\n Incorrect passwd \n");    }    return 0;}

If you use the text entered in the command line as a password, there will be a major vulnerability:
First, if I enter 11 characters and the last character is greater than 0, it will be miserable. strcpy will copy to '/0. He will always copy these 11 characters to the passwd array. When the array is out of bounds, the last character will assign the flag bit value, and the if condition will be met, the password is cracked!
As discussed above, we can dynamically allocate the same size of space for user input, rather than assigning a fixed amount of space in advance.
Passwd = (char *) malloc (strlen (argv [1]);
Strcpy (passwd, argv [1]);
Note:
Do not use strncpy (). It will cause the loss of the last bit and cause hidden errors.

Iv. Buffer Overflow

The function call stack header stores the base address % ebp of the caller stack. If the value of % ebp is damaged, the base register cannot be restored correctly, therefore, the caller cannot correctly reference its local variables or parameters.
If the returned address of the storage is damaged, the ret command will redirect the program to a completely unexpected place.

A more fatal use of buffer overflow is to allow the program to execute functions that are not intended to be executed. This is the most common method to attack system security through computer networks. Generally, input a string to the program, which contains some bytes of executable code, called attack code. In addition, some bytes will overwrite the return address with a pointer pointing to the attack code. The result of executing the ret command is to jump to the attack code.

  • Defends against buffer overflow attacks

    Stack randomization

    To insert attack code into the system, the attacker not only needs to insert the code, but also inserts a pointer to the code, which is also part of the Attack String. To generate this pointer, you need to know the stack address of the string. In the past, the stack address of the program was very easy to predict, and the stack location was quite fixed between different machines. The concept of stack randomization changes the stack position every time the program runs. Therefore, even if many machines run the same code. Their stack addresses are different. Implementation Method: at the beginning of the program, allocate a random size space between 0-n Bytes on the stack. The program does not use this space, but it will change the subsequent stack position during each execution of the program. In Linux, stack randomization has become a standard action. (In linux, the addresses of the same local variables are different each time the same program is run)

    Stack Failure Detection

    In the C language, there is no reliable method to prevent writing arrays out of bounds. However, we can avoid any harmful results when writing arrays out of bounds, try to detect it. The latest GCC version adds a stack protection mechanism to the code generated to detect Buffer Overflow, the idea is to store a special canary value between any partial buffer in the stack and the stack status. The canary value is randomly generated during each running of the program. Therefore, attackers cannot easily know what it is. Before restoring the register status and returning from the function, the program checks whether the canary value is changed by an operation of the function or an operation called by the function. If yes, the program terminates abnormally.

    Restricted executable code area

    Restrict memory areas that can store executable code. In a typical program, only the part of memory that saves the code generated by the compiler needs to be executable, and other parts can be restricted to read and write only. The current 64-bit processor memory protection introduces the "NX" (not executed) bit. With this feature, the stack can be marked as readable and writable, but not executable. Check whether the page can be executed by hardware without any loss of efficiency.

For details about buffer overflow, refer:
Http://blog.csdn.net/yang_yulei/article/details/21407461

[Reference]
Http://www.360doc.com/content/11/0610/16/6295074_126040631.shtml

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.