Prevent Visual C ++ Application Buffer Overflow

Source: Internet
Author: User
Currently, the most common security problem is buffer overflow. This particular security issue may cause more viruses than the total number of Viruses Infected by other causes. Almost every application and operating system on the market has a buffer overflow vulnerability that hackers may exploit. This problem is so serious for Microsoft Windows that Microsoft has adopted a completely different solution in the new version of the product (such as Windows XP Service Pack 2. The purpose of this article is to help you better understand buffer overflow and provide several techniques to reduce (or eliminate) the buffer overflow problem of Visual C ++ applications.

  Navigation:

  What is buffer overflow?

Buffer overflow proves that you do not know what data the user will input to your application unless you look at the user's interaction with your application.

  Verification data range

Most of the data provided by programming languages reflects the actual situation of underlying hardware, rather than the needs of the real world. For example, when you define a value in the Code as int32, it means that the value entered by the user should be between-2,147,483,648 and 2,147,483,647.

  Verification Data Length

Some data types are not easy to perform quick checks. For example, a string can contain any number of characters. The maximum number of characters is limited by. NET Framework components and machines. Of course, few really need such a long string. Generally, developers require the string to have a minimum and maximum length range.

  Exclude invalid characters

Hackers often include some illegal characters in the input information to learn what will happen. For example, hackers usually create scripts by adding specific characters. In many cases, the system executes the script without providing any warning and grants the hacker the right to access the system.

  Provide advanced user help

Many developers cannot associate help with good security, but good help can reduce user errors to improve security.
  What is buffer overflow?

Buffer overflow proves that you do not know what data the user will input to your application unless you look at the user's interaction with your application. These attacks depend on some strange ideas: the input information that hackers provide to applications may exceed the length of the buffer, and the results will be extra (beyond the buffer length) the information overwrites the memory outside the buffer control. In some cases, the memory actually stores executable information (heap memory overrun, Heap Storage flooding), so that the application does not run the original executable code, in other cases, hackers overwrite the stack pages of applications (stack memory overrun, stack storage flooding ).

Some hackers even analyze your code and find the location for the exploitation of heap or stack storage. However, in some cases, when a hacker attempts to enter some information into a field to check what happens, such exploitation may be discovered. For example, a hacker may try to enter a simple piece of code to check whether your application will execute it. No matter how the hacker discovers the vulnerability, the results are the same: your application loses control of the hacker code-hackers can now enjoy the power that your application once enjoyed.

Many developers think that hackers will exploit their programs through some secret channels, however, a lot of exploitation methods are very simple-in some cases, it is enough to allow the operating system to display command prompts. If the system security is a little lax, hackers can gain control of the server. At least, the command prompt allows hackers to detect system conditions and use other methods to obtain more access. Hackers do not need to gain control of the system during the first attempt. What they need is to obtain the accumulated control of drib and D.

Obviously, if you want to protect your application from a buffer flooding, you must provide some protection measures for the application. The best way to control buffer overflow is to check all input information received by the program, even if it comes from a trusted source. This article considers the four basic checks that each program should perform: checking the data range, verifying the data length, excluding illegal characters, and providing enough help for users to ensure good input.

  Verification data range

Most of the data provided by programming languages reflects the actual situation of underlying hardware, rather than the needs of the real world. For example, when you define a value in the Code as int32, it means that the value entered by the user should be between-2,147,483,648 and 2,147,483,647. This number depends on hardware conditions. The computer uses 31-bit storage data and 1-bit storage symbols (2 ^ 31 = 2,147,483,648 ). However, your application may not find the acceptable range.

When the hardware requirements are inconsistent with the actual requirements of the application, you must include specific code in the application to check for potential error conditions. In the code, you may want to accept numbers ranging from 1 to 40,000. It is beyond the int16 value range, but within the int32 value range. List 1 shows examples of such checks.

List 1. Check for data range errors

System: void btndatarange_click (System: object * sender, system: eventargs * E)
{
Int32 testdata; // keep the input value

Try
{
// Always try to analyze the data first
Testdata = int32: parse (txtinput1-> text );
}
Catch (System: overflowexception * OE)
{
// Handle overflow errors
MessageBox: Show (S "Type a value between 1 and 40,000.", s "input error ",
Messageboxbuttons: OK, messageboxicon: Error );
Return;
}
Catch (System: formatexception * Fe)
{
// Handle overflow errors
MessageBox: Show (S "type the number without extra charaters.", s "input error ",
Messageboxbuttons: OK, messageboxicon: Error );
Return;
}

// Test the specific data range
If (testdata <1 || testdata> 40000)

// Handle overflow errors
MessageBox: Show (S "Type a value between 1 and 40,000.", s "input error ",
Messageboxbuttons: OK, messageboxicon: Error );
}

Please note that this code first converts the input information to int32 type using the parse () method. This simple conversion can be used to locate many input problems. In this example, the Code uses the system: overflowexception exception to check whether the value is too large or too small. Use the system: formatexception exception to check whether the value format is correct. After the Code ensures that the input information is a reasonable int32 value, check the actual input range.

The Data Types of values are the easiest to check because they all have specific ranges. The value is different from the object. It does not have any hidden elements, so developers are rarely surprised.

Generally, all transactions used to verify the value data type define the upper and lower boundary in the code and then check the value.

When we use an object, the data value verification problem occurs. For example, if you want the user to take one of several strings as the input information, it is helpful to use the list box to reduce the user's input selection. When a user faces a list box with only several options, they cannot enter invalid information (such as scripts.

Sometimes you have to design a unique solution for the problem. For example, How do you ensure that a specific method receives a fixed number of input information with a non-consecutive range? In this case, enumeration may save time. List 2 shows how to use enumeration in the code to automate data range changes.

Class Table 2: Use enumeration to check the data range


Note that the displaystring () Declaration requires an input (parameter) of the somestrings Enumeration type ). The caller cannot use any other input type, which means the displaystring () method is automatically protected. For example, you cannot use a script as input because it is not of the correct type.
  Verification Data Length

Some data types are not easy to perform quick checks. For example, a string can contain any number of characters. The maximum number of characters is limited by. NET Framework components and machines. Of course, few really need such a long string. Generally, developers require the string to have a minimum and maximum length range. Therefore, you do not need to verify whether the received string is correct, but you only need to verify that its length is correct. Otherwise, other people may send strings of any length, which will cause a buffer overflow. List 3 shows an example of how to prevent problems by verifying the data length of each parameter.

List 3: verification data length

System: Boolean processdata (string * input, int32 upperlimit, int32 lowerlimit)
{
Stringbuilder * errormsg; // error message

// Check that the input information is incorrect.
If (upperlimit <lowerlimit)
{
// Create an error message
Errormsg = new stringbuilder ();
Errormsg-> append (S "The upperlimit input must be greater ");
Errormsg-> append (S "The lowerlimit number .");

// Define a new error
System: argumentexception * AE;
AE = new argumentexception (errormsg-> tostring (), s "upperlimit ");

// Throw an error
Throw (AE );
}

// Check the Data Length error conditions
If (input-> length <lowerlimit | input-> length> upperlimit)
{
// Create an error message
Errormsg = new stringbuilder ();
Errormsg-> append (S "string is the wrong length. Use a string ");
Errormsg-> append (S "between 4 and 8 characters long .");

// Define a new error
System: Security: securityexception * se;
Se = new securityexception (errormsg-> tostring ());

// Throw an error
Throw (SE );
}

// Returns true if the data is correct.
Return true;
}

System: void btndatalength_click (System: object * sender, system: eventargs * E)
{
Try
{
// Process input text
If (processdata (txtinput2-> text, 8, 4 ))

// Display the correct input result
MessageBox: Show (txtinput2-> text, "input string ",
Messageboxbuttons: OK, messageboxicon: information );
}
Catch (System: Security: securityexception * SE)
{
// Display error message of incorrect input
MessageBox: Show (Se-> message, "input error ",
Messageboxbuttons: OK, messageboxicon: Error );
}
Catch (System: argumentexception * AE)
{
// Display error message of incorrect input
MessageBox: Show (AE-> message, "argument error ",
Messageboxbuttons: OK, messageboxicon: Error );
}
}

The verification process occurs in the processdata () method. This method uses the input string, minimum string length, and maximum string length as the input information. Note that this code first verifies that the input parameters are correct. The upperlimit parameter must be greater than the lowerlimit parameter. This part of the Code demonstrates good programming habits-Never trust the input information you receive. Note that this part of the code generates a system: argumentexception exception instead of a common exception. Although specific exceptions do better, most developers still use common exceptions. If the. NET Framework component cannot provide specific exceptions for your code requirements, you should create custom exceptions.

The Code then verifies the string. If the number of characters in a string is too large or too small, the Code generates system: Security: securityexception. It is correct to use security exceptions here, because such events will cause security exceptions. You may decide to enter a long string to create a buffer overflow condition. Even if the user just made a mistake, your triggering of this security exception means that you can at least verify the cause of this exception, rather than simply jump over.

The test code in this example is in the btndatalength_click () method. This code is executed in the try... catch code block to ensure that exceptions are caught. The real check is just a simple if statement. This Code contains a catch statement for each exception. If you want to ensure that your application notices any security exceptions and properly handles them, capturing exceptions is important.
  Exclude invalid characters

Hackers often include some illegal characters in the input information to learn what will happen. For example, hackers usually create scripts by adding specific characters. In many cases, the system executes the script without providing any warning and grants the hacker the right to access the system. In this way, web applications are more affected than desktop applications, but both of them must be protected.
Fortunately, the. NET Framework component provides powerful regular expressions. A qualified expression defines acceptable string input, so you can easily detect invalid characters. List 4 shows a method that uses a qualified expression.

List 4: Use a qualified expression


The Code starts with a RegEx object. In this case, the only accepted input is a letter (or even a space ). The pass expression bypasses a large amount of input information. In fact, many default templates are defined in many authentication support provided for ASP. NET applications. The main point is that you can create a string that defines acceptable input information, including input styles (such as phone numbers ).
The RegEx object can perform many comparison operations. In the example, it uses the matches () method to compare the length of the string with the reference number. When the two numbers match, the input information is correct. Otherwise, the input information contains invalid characters, and the checkchars () method causes an exception.

  Provide advanced user help

Many developers cannot associate help with good security, but good help can reduce user errors to improve security. For example, a good help file can display the information the application wants to receive, so as to prevent some users from entering error information. Reducing Input errors allows us to thoroughly analyze the legacy error information and ultimately reduce the security risks caused by incorrect input.

Help can come from all forms, including useful error messages. Some data types pose special challenges, and your application must handle these issues to ensure data integrity and security. For example, a date is a data input entry that often causes problems. First, you must consider the date format. You may enter 1 June 2003, 06/01/2003, June 1, 2003, 2003/06/01, or other acceptable variables. You should restrict your applications and only allow one date format to check the validity of date information. However, the error message and help file can tell the user which format must be used, so that the user will not be frustrated when entering a valid date using the error format (because of the help reminder format ).

No matter what you do, there are still some users trying to abuse the system. They may use the wrong format to enter the date, or even enter information that does not contain the date at all. However, by providing good help, you have the basic elements used to ask users. You can call security measures to ensure that users know that such behavior is unacceptable. Reducing buffer overflow is an active process. You must prevent invalid input, provide good help to users, and provide punitive measures to users who are determined to ignore rules.

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.