VC ++ 2005 quickly build secure applications

Abstract: This paper provides a discussion of some of the new features of Microsoft Visual C ++ 2005 release versions of the language and libraries that will help you more effectively create safe, reliable code.

  I. Introduction

  Microsoft Visual C ++ 2005 release version for those who want to easily and quickly write secure applications programming enthusiasts is the correct choice. As you have heard, Visual C ++ language and libraries so that developers of new features safe, reliable applications easier than ever. That is, it provides a powerful and flexible standard C ++, and provides the most powerful development language suitable for programming under the .NET framework.

  In this article, I discuss the main Visual C ++ 2005 release features a new version of languages ​​and libraries, both for teaching programs or large application projects, which will help you improve productivity when writing secure code.

  Two, C runtime library security features

  If you are creating applications that use the C run-time library using Visual C ++, you will be very pleased to learn that you now depend on a number of library functions have a more secure version. The need for one or more buffer as a function of the inputs, the length parameter has been added in order to make sure that does not function beyond the boundaries of the buffer. Now more functions began to check the legality of the parameters, will invoke the invalid parameter processor if necessary. Let's look at some simple examples:

  C runtime library is the most unreliable gets function, which reads a line from the standard input. Consider the following simple example:

char buffer[10] = { 0 };
gets(buffer);

  The first line declares a buffer variables, characters and initializes the buffer is set to 0. To avoid accidents from happening initialized variable to a well-known value is a very good idea. Then, seemingly innocent gets function reads a line from the standard input stream is written into the buffer and the buffer. Is there anything wrong? For an array of type C function is passed by value can not be achieved, but the transfer point to the first element in the array. Therefore, the function opinion, char [] is equivalent char * pointer, and a pointer to the original not included any additional information may decide the size of the buffer pointed to by size. Then gets function is how to make it? It is assumed infinite buffer (UINT_MAX have precise dimensions), and will continue to be copied from the input stream of characters in a buffer. An attacker can easily use this weakness, this error is not well-known type known as a buffer overflow.

  Many original C runtime library functions suffer from the same problems associated with the confirmation parameters, and therefore now under attack. Be sure to keep in mind for the application of the write current, the performance of secondary importance, we now live in a world of safety first. Each function has been criticized a function to provide the same functionality, but with the addition of safety features replaced the function. Of course, under the old library function of how much you use the code already exists, you may want to take some time to replacement of code to a new, safer version. These new functions have a _s suffix, for example, gets function is replaced by gets_s function; strcpy function is subject to criticism function instead strcpy_s. Here is an example:

char buffer[10] = { 0 };
gets_s(buffer, sizeof (buffer) / sizeof (buffer[0]));

  gets_s function has an additional parameter, to display the maximum number of characters that can be written here comprises a NULL terminator. I use the sizeof operator, it determines the length of the array, because the compiler decides the result of the sizeof operator returns at compile time. Remember, sizeof returns the length of the operand in bytes, so the length of the array divided by the array length of the first element will return the number of elements in the array. This simple method can be ported to the case of using _getws_s in Unicode encoding, this function also requires that the length of the buffer in bytes.

  As I have mentioned, a further security checks common function strcpy function gets function as, as it is no way to ensure the effective buffer size, so it can only assume a buffer large enough to hold the string to be copied . The program is running, this will lead to unpredictable behavior, as I mentioned, the need for safety to avoid these unpredictable behavior, which is an example of the use of safe strcpy_s function.

char source[] = "Hello world!";
char destination[20] = { 0 };
strcpy_s(destination, sizeof (destination) / sizeof (destination[0]), source);

  There are many reasons to like this new strcpy_s function. The most obvious difference is that additional, in bytes of the parameter which is used to confirm the size of the buffer. This allows strcpy_s check function can be run to determine the character is written does not exceed the boundaries of the destination buffer. There are other ways to determine the effectiveness of inspection parameters. In the debug version of these detection methods, including the display of the debug report "assertion" (assertions) method, if their conditions are not met, they will appear commissioning report. Whether debug or release if a specific condition is not met, an invalid parameter manager will be called, its default behavior is to throw an access violation to terminate the application. This allows you to achieve a very good applications continue to run without producing unexpected results. Of course, this situation can not call invalid parameters to ensure the function is similar to strcpy_s to avoid.

  The previous example can be further simplified by _countof new macro, macro aside the need for shifting sizeof operator is error prone. C _countof macro returns the number of elements of the array type. This macro itself corresponds to a template, if you pass a pointer to the original, it will not compile. Here's an example:

strcpy_s(destination, _countof(destination), source);

Third, the use of C ++ Standard Library

  C runtime libraries have seen a new enhanced security features, let's look at how to use the C ++ standard library to further reduce similar errors in your code.

  When you run from the C library turned C ++ standard library, so that one of the most effective ways you begin to benefit from the use of C ++ class library vector (Vector class). Vector class is a container class imitation of a one-dimensional array T C ++ Standard Library, where T may be any type of fact, the use of your code where the buffer can be used instead of vector objects. Let us consider the example of the previous section, we use the first example gets_s function to read a line from the standard input, consider the following code is replaced by:

std::vector<char> buffer(10);
gets_s(&buffer[0], buffer.size());

  One difference is most notable with a buffer variable is now available methods and operators vector objects, the object initialization vector length is 10 bytes, and each element constructor is initialized to 0, the expression & buffer address of the first element [0] to obtain vector objects, a simple buffer is transmitted to the C function expects a vector object is a correct way. And sizeof operator except that the size of the container is measured based on all the elements, and not the group of bytes. For example, size of the vector method returns the number of elements of the container.

  In the second example in the previous section, we use strcpy_s function from the source buffer to copy characters to the destination buffer. It should be clear how the place of the original vector object array of type C, in order to better illustrate this point, let us consider another very useful container C ++ standard library.

  basic_string classes provided in C ++ so that the string can be operated as a normal type. It provides a wide range of overloaded operators, provides a natural programming model for C ++ developers. Due to superior strcopy_s and other functions to manipulate strings, you should be the first choice basic_string function. byte type T basic_string container units. Where T is the character type. The C ++ standard library provides type definitions for commonly used character types. wstring string element type and are defined as the char and wchar type. The following example illustrates how simple and safe basic_string class is:

std::string source = "Hello world!";
std::string destination = source;

  basic_string class also provides you want, common string manipulation methods and operators, and the combined string as a substring search.

  Finally, C ++ standard library provides a very powerful I / O library for safe, simple and standard input and output, file stream interact. Although vector objects is better than for the array using gets_s function of type C, but you can be further simplified by using a defined class basic_istream and basic_ostream. In fact, you can write simple and type-safe code to read any type, including a string from the stream.

std::string word;
int number = 0;
std::cin >> word >> number;
std::cout << word
<< std::endl
<< number
<< std::endl;

  cin basic_istream is defined as a stream extracted from the input character type element Standard. wcin for wchar_t elements. On the other hand, it is defined as a COUT basic_ostream stream, for a write operation to the standard output stream. As you can imagine, this model than gets_s and puts functions can be infinitely extended. But the real value is that it is very difficult to produce applications that let you crack a security error.

  Fourth, the border inspection C ++ Standard Library

  By default, C ++ standard library objects and a large number of container iteration object that does not provide bounds checking. For example, the vector subscript operator is usually a faster, but potentially dangerous methods of operation of the individual elements. If you're looking to check the method of operation is confirmed, you can turn "at" method. Increase security at the expense of performance for the price. Of course, the vast majority of cases at reduced performance is negligible, but for the first performance requirements of the code, this can be very harmful, consider the following simple function:

void PrintAll(const std::vector<int>& numbers)
{
 for (size_t index = 0; index < numbers.size(); ++index)
 {
  std::cout << numbers[index] << std::endl;
 }
}
void PrintN(const std::vector<int>& numbers, size_t index)
{
 std::cout << numbers.at(index) << std::endl;
}

  PrintAll function uses the subscript operator, as controlled by the indexing function, and may be confirmed to be safe. On the other hand, PrintN function can not guarantee the validity of the index, so it uses more secure "at" method instead. Of course, not all of the access operation of the vessel as such are clear and concise.

  Ensuring the safety features of the C ++ standard library at the same time, Visual C ++ 2005 continue to adhere to and improve the operational characteristics of the C ++ Standard Library, in many cases, while providing adjustment features C ++ standard library security. A welcome improvement is the addition of a range checking in debug builds, this shall not affect the performance of your distribution. But it does help you capture bounds errors in the commissioning phase, and even unsafe traditionally subscript operator code uses.

  Unsafe function, as a subscript operator of the vector, and other functions, like its front function, if not properly call, usually leads to undefined behavior. If you're lucky, it will soon lead to an access conflict that will make your application crashes. If you are not so lucky, it may continue to operate silently and cause side effects unpredictable, which will destroy the data and could be exploited attackers. To protect your release version of the application, Visual C ++ 2005 introduces _SECURE_SCL symbol, used to add security functions that are not operational check. The following code as simple as to define the symbol in your application can add additional real-time check and prevent inaccurate behavior.

#define _SECURE_SCL 1

  Keep in mind the definition of this symbol impact on your program a lot, a lot of legitimate, but potentially non-secure operation will be at compile time will not be able to avoid potential BUG at runtime. Consideration Copy operation example of the use of the following:

std::copy(first, last, destination);

  Wherein, first and last copy is an iteration parameter defined range, the iteration parameters Where do you want output, indicating the position of the target buffer, the location for the first element in the copy range. There is a danger that the target destination corresponding buffer or container is not large enough to hold the elements to be copied. If Destination is an iterative parameter requires a security check, similar error will be captured. However, this is only a hypothesis. If the destination is a simple pointer, it will not guarantee the correct operation of the copy operation function. Then of course you think _SECURE_SCL symbol to avoid this problem, in this case, the code does not even compile, in order to avoid any possible run-time errors. As you can imagine, this will need to be rewritten more perfect efficient code. So, this is a better reason to support the C ++ Standard Library containers, avoid using the C type of the array.

Fifth, security features of the compiler

  While not new to Visual C ++ 2005, the compiler features but still a lot needs to know. And significant difference in previous versions of the compiler is security check current default is open, let's look at the characteristics of compilers and in some cases they are how to prevent attacks in some cases.

  Visual C ++ compiler begins long run provide strict security checks before options, including stack checking, underflow and overflow checks, and identification of uninitialized variables. Checking is controlled by the / RTC compiler options for these runs. Although very useful to catch errors early in development, but for the loss on the release version of performance is unacceptable. Microsoft Visual C ++. NET introduced the / GS compiler switch, add it to release for a limited runtime security checks. / GS switch is inserted in the code compilation switch, typically based on detecting a stack buffer overflow stack data by detecting function. If the problem is found, the application will be terminated. In order to reduce the impact on the performance of the runtime checks, the compiler which function to identify and easy to attack only the security check for these functions. Security check to an increase in a cookie on the stack frame function, it will be overwritten in the case of buffer overflow. Before and after the function instructions are added to the assembly instructions. Before the function execution, from cookie cookie function modules to perform calculations. When the function ended but before the stack space is withdrawn, cookie stack copy is retrieved to determine if it is changed. If the cookie has not been changed, the function ends and proceed to the next program, if the cookie is changed, a security error handler is invoked, it will end the application.
In order to control in Visual C ++ 2005 compiler release versions of these options, open the properties page for the project, click the C / C ++ tab, in the Code occurrence property page, you will find two properties correspond to the features I just described. Basic Runtime Checks property corresponds to the development / RTC compiler option, the compiler version should be set to "BOTH". Buffer Security Check property equivalent to the compiler / GS option for the release version should be set to "YES".

  For developers using Visual C ++ 2005's, these compiler features open by default, which means you can be sure that the compiler is doing it may prevent your code vulnerabilities. However, this does not mean we can totally do not care about security issues. Developers need to continue efforts to correct code, and to consider different, various security threats that may occur. The compiler error only can prevent some types of occurrence.

  To keep in mind these special security checks provided by the compiler applies only to native code, fortunately, we managed code rarely make such mistakes. Here there is even better news, Visual C ++ 2005 introduction of the C ++ / CLI language, it provides the most powerful development language under the .NET framework.

  Sixth, the new C ++ programming language

  Visual C ++ 2005 release version provides a C ++ class implementation / CLI languages. C ++ / CLI is a system designed for the .NET programming language. Compared to other languages, it has more control over the creation and use .NET module and assembly. C ++ / CLI finer for C ++ developers, and naturally, regardless of whether you are familiar with C ++ or .NET Framework, you will find that use managed code written in C ++ ANSI C ++ is a natural extension of elegant, very easy to learn together.

  For the development of applications, there are many reasons for mandatory to let you choose managed code rather than native C ++. The two most important reason is safety and efficiency. Common language runtime (CLR) to your code provides a safe operating environment. As a developer, you do not need to be concerned about the buffer overflow issue and because you did not initialize variables before using. Security issues have not disappeared completely, but using managed to avoid some errors usually occur.

  Another reason to use a hosted .NET Framework is a rich class library. Although the standard C ++ library is more suitable for C ++ programming type, but the .NET framework contains a powerful library, which is the standard C ++ library can not match. The .NET Framework includes many useful collections, a powerful data manipulation library, perform like a lot of popular communication protocols, from SOCKETS to HTTP and web services. Although the native C ++ developers can use these services in a variety of shape, but obtained by using the .NET Framework productivity mainly because of its unity and coherence. Whether you are using System :: Net :: Sockets or using namespace System :: Web, you will face the same type of concept description widely used, such as streams and strings. This is the reason for the .NET Framework has developed a highly efficient primary. This allows programmers to more quickly write more powerful applications while code more reliable.

  Visual C ++ 2005 permits you naturally mix of local and managed code in a project, you can continue to use both local function and class that already exists, start using more and more libraries in the .NET framework, or even write your managed type. You can put your hosting type is defined as a reference type or a value type, although Visual C ++ compiler allows you to choose to use the terms of syntax or to stack control and management of resources using the usual scoping rules, but the type of value on the stack reference type is located in the CLR managed heap.

  It is formed by adding a keyword ref in front of class and struct you define, define a reference type. Acquire and release resources to accomplish the usual manner, by using the constructor and destructor, as described herein:

ref class Connection
{
 public: Connection(String^ server)
 {
  Server = server;
  Console::WriteLine("Aquiring connection to server.");
 }
 ~Connection()
 {
  Console::WriteLine("Disconnecting from server.");
 }
 property String^ Server;
};

  The compiler is responsible Connection reference implementation IDisposable interface type, so use something like C #, Visual Basic.NET developers can use any resource management structures available to them. For C ++ developers, as before with the choice. To simplify resource management, and writing "exception" security code, you can simply declare a Connection object on the stack. When an object is beyond its scope, the Dispose method performed destructor to be called. Below is an example:

void UseStackConnection()
{
 Connection connection("sample.kennyandkarin.com");
 Console::WriteLine("Connection to {0} established!",
 connection.Server);
}

  In this example, the Connection is closed by calling the destructor before returning to the calling function, as you want it in the C ++ like. If you want to control the lifetime of the object, only need to use this keyword to get a handle gcnew connection object. This pointer can be regarded as normal hand (usually containing no defects), and the destructor of the object may be invoked by simply delete operation. This example code is as follows:

void UseHeapConnection()
{
 Connection^ connection = gcnew Connection("sample.kennyandkarin.com");
 try
 {
  Console::WriteLine("Connection to {0} established!",
  connection->Server);
 }
 finally
 {
  delete connection;
 }
}

  As you can see, from the local to the managed code C ++, Visual C ++ 2005 brought a simple and flexible management of resources, you can write strong for writing correct, secure code is a very important resource management code.

  VII Summary

  Whether it is for a small program or a big application, Visual C ++ 2005 release version is a powerful development tools, C runtime library and the C ++ standard library provides a powerful set of tools to publish powerful, strong local applications, while for writing managed code in C ++ a first-class support, Visual C ++ 2005 on a Microsoft Windows development platform is unique and powerful development tools.

Reproduced in: https: //www.cnblogs.com/shelvenn/archive/2008/02/15/1069661.html

Guess you like

Origin blog.csdn.net/weixin_34112208/article/details/93272932