Fixed the buffer overflow problem.

Source: Internet
Author: User

When David leblc and I confirm the directory of writing secure code, we are aware that we must focus on Buffer Overflow, because too many developers make too many such errors when writing code, these errors lead to buffer overflow that can be exploited. In this article, I will focus on why buffer overflow occurs and how to fix it.Why is there buffer overflow?

Buffer overflow requires many conditions, including:

  • Use a non-type security language, such as C/C ++.
  • Access or copy the buffer in an insecure way.
  • The compiler places the buffer zone next to or adjacent to the key data structure in the memory.

Now let's take a closer look at each of the above conditions.

First, buffer overflow mainly occurs in C and C ++, because these languages do not perform array boundary check and type security check. C/C ++ allows developers to create programs that are very close to hardware and allow direct access to memory and computer registers. The results provide excellent performance. It is difficult to have any application that runs as fast as a well-written C/C ++ application. Buffer overflow occurs in other languages, but it is rare. If this error occurs, it is usually not caused by the developer, but the runtime environment error.
Second, if the application obtains data from the user (or attacker) and copies the data to the buffer maintained by the application without considering the size of the target buffer, it may cause a buffer overflow. In other words, the Code allocates a bufferNBytes, but more than N bytes of data are copied to the buffer. This is like injecting 16 ounces of water into a 12-ounce glass. So where are the 4 ounces of water going? All overflows!
Last and most importantly, the compiler usually places the buffer area next to the "interesting" data structure. For example, when the buffer of a function is close to the stack, the return address of the function in the memory is close to the buffer. At this time, if an attacker can cause the buffer to overflow, the attacker can overwrite the return address of the function and return the address defined by the attacker when returning the function. Other interesting data structures include C ++ v tables, exception handling program addresses, and function pointers.

Here is an example.

What are the following code errors?

Void copydata (char * szdata) {char cdest [32]; strcpy (cdest, szdata); // use cdest ...}

Surprisingly, this Code may have no errors! This depends entirely on how copydata () is called. For example, the following code is secure:

char *szNames[] = {"Michael","Cheryl","Blake"};CopyData(szName[1]);

This code is safe because the name is hard-coded and each string can contain no more than 32 characters. Therefore, it is always safe to call strcpy. However, if the unique parameters of copydata and szdata come from unreliable sources (such as sockets or files), strcpy will copy the data until it encounters null characters; if the data length is greater than 32 characters, the cdest buffer overflows and any data other than the buffer in the memory will be damaged. Unfortunately, the corrupted data is returned from copydata, which means that when copydata is completed, it continues to be executed at a location specified by the attacker. This is really bad!

Other data structures are also sensitive. Suppose the V Table of a C ++ class is damaged, as shown in the following code:

void CopyData(char *szData) {   char cDest[32];   CFoo foo;   strcpy(cDest,szData);   foo.Init();}

This example assumes that the cfoo class has a virtual method and a list of addresses of a V table or the class method (the same as all c ++ classes ). If the V Table is damaged because the cdest buffer is overwritten, any virtual method (Init () in this example) of this class may call the address specified by the attacker, instead of Init (). By the way, if you think your code is safe without calling any c ++ method, it will be wrong, because a method will always be called, that is, the virtual destructor of this class! Of course, if a class does not call any method, you should think about its necessity.

Fix Buffer Overflow

Now, we will continue to discuss more practical content-how to delete and prevent Buffer Overflow in your code.

Migrate to managed code

Microsoft Windows Security push was held in February 2002 and March. During this period, my working group trained more than 8,500 people in designing, writing, testing, and recording security functions. One of our suggestions for all our designers is to develop a plan to migrate the corresponding applications and tools from the local Win32 C ++ code to the managed code. There are multiple reasons for doing so, mainly to help reduce Buffer Overflow. In managed code, it is difficult to create code that contains buffer overflow because the written code cannot directly access pointers, computer registers, or memory. You should consider, or at least plan to migrate some applications and tools to managed code. For example, a management tool is a good migration object. Of course, we also need to be realistic, because it is impossible to migrate all applications from C ++ to C # or other hosting languages one night.

Follow the following important rules

When writing C and C ++ code, pay attention to how to manage data from users. If a function has a buffer from an unreliable source, follow these rules:

  • The length of the buffer required for code transfer.
  • Probe memory.
  • Take preventive measures.

Now let's take a closer look at each of the above situations.

Length of the buffer required for code transfer

If any function call has similar features, an error occurs:

Void function (char * szname) {char szbuff [max_name]; // copy and use szname strcpy (szbuff, szname );}

The problem with this Code is that the function cannot determine the length of szname, which means that data cannot be copied safely. The function should know the size of szname:

Void function (char * szname, DWORD cbname) {char szbuff [max_name]; // copy and use szname if (cbname <max_name) strncpy (szbuff, szname, MAX_NAME-1 );}

However, you cannot trust the cbname. Attackers can set the name and buffer size. Therefore, they must check the buffer size!

Probe memory

How can we determine whether szname and cbname are valid? Do you believe that the user will provide valid values? In general, the answer is no. One easy way to verify the buffer size is to detect memory. The following code snippet shows how to complete this verification process in the debug version of the Code:

Void function (char * szname, DWORD cbname) {char szbuff [max_name]; # ifdef _ debug // test memset (szbuff, 0x42, cbname ); # endif // copy and use szname if (cbname <max_name) strncpy (szbuff, szname, MAX_NAME-1 );}

This code will try to write a value of 0x42 to the target buffer zone. You may wonder, why not copy the buffer directly? By writing a fixed known value to the end of the target buffer, you can force Code failure when the source buffer area is too large. In this way, you can also find development errors early in the development process. It is better to let the program fail than to run the malicious and effective code of the attacker. This is why the attacker's buffer zone is not copied.

Note: You can only do this in the debug version to capture Buffer Overflow during the test.

Take preventive measures

To be honest, although the probe is useful, it does not protect you from attacks. The real security solution is to write preventive code. You will notice that the code is already preventive. It checks whether the data entering the function cannot exceed the internal buffer zone szbuff. However, some functions may have serious security problems if they are improperly used to process or copy unreliable data. The key here is unreliable data. When checking the buffer overflow error of the code, you should track the flow of data in the Code and check various data assumptions. When you realize that some assumptions are incorrect, you may be surprised to find the errors.
The functions that need attention include common functions such as strcpy, strcat, and gets. However, the so-called strcpy and strcat "Safe n versions"-strncpy and strncat cannot be ruled out. These functions are considered safer and more reliable because they allow developers to limit the size of Data copied to the target buffer zone. However, developers also encounter errors when using these functions! See the following code. Can you see the disadvantages?

#define SIZE(b) (sizeof(b))char buff[128];strncpy(buff,szSomeData,SIZE(buff));strncat(buff,szMoreData,SIZE(buff));strncat(buff,szEvenMoreData,SIZE(buff));

If you need to prompt, pay attention to the last parameter of each string processing function. Do you want to give up? Before I give the answer, I often joke that if you disable the "insecure" string processing function and use the more secure version n, i'm afraid you will spend the rest of your life fixing new errors. The following are the reasons. First, the final parameter is not the overall size of the target buffer. It is the size of the remaining buffer space. Every time the Code adds content to the buff, the buff will actually decrease. The second problem is that even if the user passes the buffer size, they usually decrease one by one. So when the string size is calculated, do you have any null characters at the end? When I conduct a reader survey on this issue, it is usually half a cent. Half of them think that empty characters at the end of the computing buffer hour must be considered, while the other half do not. Third, in some cases,NThe version may not end with a null character as the result string, so be sure to read the document.
If you write c ++ code, consider using ATL, STL, MFC, or your favorite string processing class to process strings instead of bytes. The only potential deficiency is the possibility of performance degradation, but in general, the use of most of these classes will make the code more powerful and maintainable.

Use/Gs for compilation

This new compile-time option in Visual C ++. Net inserts a value in the stack framework of some functions, helping reduce the potential weakness of stack-based buffer overflow. Remember that this option does not fix your code or delete any errors. It is just like a baseball catcher. It helps you reduce the possibility that some classes of buffer overflow may become usable buffer overflow, so that attackers can write and execute code in the process. It can be regarded as a small insurance measure. Note that this option is enabled by default for the new Win32 C ++ project created using the Win32 Application Wizard. This option is also used during windows. NET Server compilation. For more information, see compiler security checks in depth in Brandon Bray ).

Eliminate risks

The following code contains at least one security risk. Can you find it? I will post the answer in the next article!

Wchar g_wszcomputername [internet_max_host_name_length + 1]; // obtain the server name and convert it to a unicode string. Bool getservername (extension_control_block * PeCB) {DWORD dwsize = sizeof (bytes); char szcomputername [bytes + 1]; If (PeCB-> getservervariable (PeCB-> connid, "SERVER_NAME ", szcomputername, & dwsize) {// The remaining code is skipped.

Michael HowardIs the Security Program Manager of the Microsoft secure windows initiative team and one of the authors of writing secure code. His main task is to ensure that people design, build, test, and record defect-free security systems. His favorite words are "limited in size and limited in size ".

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.