Protect your code by using Visual C + + defense features __c++

Source: Internet
Author: User
Tags closure mul
 
Protect your code with Visual C + + defense features Michael Howard   directory based on stack buffer overflow detection (/GS) Security exception Handling (/SAFESEH) DEP compatibility (/NXCOMPAT) image randomization (/dynamic Base) A more secure function calls C + + Operator::new What happens if it fails. Many of the code is written in C and C + +, but unfortunately many of these types of code have security vulnerabilities that even developers do not know about. Programs written in any language have vulnerabilities that can cause their users to be attacked. But the C and C + + languages have a special place in the history of the Internet because many of their vulnerabilities stem from features that make them popular: Unlimited access to computer hardware and consequent performance benefits. When reading information about security and C or C + +, it is often easy to see terms like "buffering" and "overflow," since buffering is usually an example of direct access to memory. This type of direct access, while very powerful, is very, very dangerous. Many of the buffer overflow problems that occur during the generation of C and C + + code can be caused by a variety of reasons. The first reason I have mentioned above is that the programming language provides direct access to vulnerable memory. The second reason is the developer error. A third reason is that the compiler does not usually provide defensive functionality. It is easy to provide a remedy for the first problem, but since C and C + + have been different languages. Developer error issues can be partially addressed through training, but I haven't really seen the rise of educational institutions in this area. There are also some security training agencies in the industry, but we can only provide some solutions or part of the problem, and I would like to see more education about software security for students at universities. You may want to ask "why educational institutions do not attempt to train this very important topic." "To tell you the truth, I don't know why. But it's really frustrating. Finally, even with top-notch training, some of the security issues are really complicated, and even well-educated engineers can't be completely solved. We humans are not perfect. Building more defenses in the compiler is a problem that the Microsoft Visual C + + team has been trying to solve for years and is being improved with the help of our security team. This column outlines some of the buffer overflow defenses and other content available in Visual c++®2005. Note that some other compilers also provide defensive measures, but Visual C + + has two major advantages over compilers such as GCC. First, all of these defenses are integrated by default in the Toolset, without downloading some of the curious ancientStrange add-ins. Second, these options are easy to use. The defensive measures provided by the Visual C + + toolset include, in no order: stack-based buffer overflow detection (/GS) Security exception handling (/SAFESEH) Data Execution Protection (DEP) compatibility (/NXCOMPAT) image randomization (/dynamicbase) automatic Using a more secure function to invoke C + + operator::new before discussing each item in detail, I would point out that these defenses do not compensate for unsafe code. You should always try your best to write the safest code, and if you don't know what to do, you can read some professional books on this topic first. Typical Stack Compared to one Compiled with/gs   (Click the image for a larger view) I would also like to point out that these are the requirements of Microsoft's "Secure Development Lifecycle" (SDL), which means that you must use these options when writing C and C + + code, otherwise you cannot deliver. There are occasional exceptions, but very few, so do not discuss them in detail here. The final point to keep in mind is that these elaborate defensive measures can be bypassed, depending on the code. The more defenses the code uses, the harder it will be to solve it, but there is no defensive measure to be perfect. They are all meant to reduce the chance of being invaded. You must have known about this. The only solution is to use a more secure function call, which is the defensive measure that can really plug the vulnerability. Let's look at the various defensive measures in detail. Stack based buffer overflow detection (/GS) stack based buffer overflow detection is the oldest and most common defensive measure available in Visual C + +. The goal of the/GS compiler flag is simple: reduce the chance that malicious code executes correctly. By default, the/GS option is enabled in Visual C + + 2003 and later, and it detects a specific kind of stack overflow at run time. For instrumentation, it includes a random number in the function stack (before the return address of the stack), and when the function returns, the function closure code examines the value to make sure it has not been changed. If the cookie it calls has changed, the execution will be aborted. The function leader code to set cookies is as follows: copying code
Sub    ESP, 8
mov    eax, DWORD ptr ___security_cookie
xor    eax, esp
mov-    DWORD ptr __$arraypad$[ ESP+8], eax
mov    eax, DWORD PTR _input$[esp+4]
The function closure code to check cookies is shown here: Copying code
mov    ecx, DWORD PTR __$arraypad$[esp+12]
add    ESP, 4
XOR    ECX, esp
call    @__security_check_ Cookie@4
Add    ESP, 8
Visual C + + 2005 also moves the data on the stack, making the data less vulnerable to damage. Examples include moving buffers into memory that is higher than the non-buffer. For example, this step helps protect function pointers on the stack. In addition, moving the pointer and buffer parameters to lower memory at run time can mitigate various buffer overflow attacks. See comparison charts for typical stacks and/GS stacks. The/GS compiler option cannot be applied to any of the following situations: The function does not contain a buffer. Optimization is not enabled. A function is defined as having a variable argument list. The function uses unprotected keyword tags (c + +). function contains inline assembly code in the first statement. The buffer is not a 8-byte type and is less than 4 bytes in size. A new option in Visual C + + SP1 is to make/GS heuristics more proactive so that more functions can be protected. Microsoft added this option because a small number of security letters are published in a stack-overrun code with stacks and the code, even compiled with/GS, is not protected by cookies. This new option greatly increases the number of protected functions. To use this option, you can place the following line of code in the module where you need to add protection, such as code to handle Internet data: Copying code
#pragma strict_gs_check (ON)
This is just an example of how Microsoft is evolving the/GS feature. The initial version in Visual C + + 2003 was very simple and later updated in Visual C + + SP1, and we updated it again in Visual C + + 2008 after learning about new attacks and new ways to bypass existing attacks. In the analysis, we found that/GS can cause untrue compatibility or performance problems. The CodeRED worm that is affected by security exception handling (/SAFESEH) for Internet information Server (IIS) 4.0 is caused by a stack-based buffer overflow. Interestingly,/GS does not detect worm intrusion problems because the code does not overflow the return address of the affected function, but rather destroys the exception handler on the stack. This example is a good illustration of why you must always emphasize writing security code and not rely entirely on the various defenses based on the compiler. An exception handler is code that executes when an exception occurs, such as 0. The address of the handler is saved in the function stack frame and is therefore corrupted. The link program in Visual studio®2003 and later contains an option to store a list of valid exception handlers at compile time in the PE header of the image. If an exception is thrown at run time, the operating system checks the image headers to determine whether the address of the exception handler is correct, and if not, the application is terminated. If you use this technique when linking code, you can prevent codered. In addition to exceptions, the/SAFESEH option does not cause performance degradation, so you should always use this option when linking. DEP compatibility (/NXCOMPAT) now almost every CPU that is produced supports the No Execute (NX) feature, which means that the CPU does not execute a non code page. Consider the meaning of this feature: almost every buffer overflow vulnerability is a data error; An attacker uses a buffer overflow to inject data into a process and then continue execution in a malicious data buffer. Why the CPU is running data. The link/nxcompat option means that your executable file will be protected by the no execute feature of the CPU. Based on our experience, with this option, Microsoft security teams rarely have any more compatibility issues and performance has not decreased. Windows VISTA®SP1 also has a new API that enables DEP for your running process, and it can be set up to cancel again: Copy code
Setprocessdeppolicy (process_dep_enable);
Image randomization (/dynamicbase) Windows Vista and Windows server®2008 support image randomization, which means that when the system starts, it blends the operating system image in memory. The purpose of this feature is simply to eliminate some of the predictability from attackers. It is also known as "address space layout randomization" (ASLR). Note that DEP must be enabled for any ASLR that you want to use. By default, windows® will only adjust the associated system components. If you want the image to be moved by the operating system (strongly recommended), you should link the/dynamicbase option. (This option is available in Visual Studio, SP1, and later in the tool set.) There is an interesting side-effect of linking/dynamicbase-the operating system also randomization your stack, which helps reduce predictability and makes it more difficult for attackers to compromise the system. Also note that the heap is also randomized in Windows Vista and Windows Server 2008, but this is the default setting and no special options need to be compiled or linked. More secure function calls see the following lines of code: copying code
void func (char *p) {
    char d[20];
    strcpy (d,p);
    Etc
}
Assuming *p contains untrusted data, this code represents a security vulnerability. The problem with this code is that the compiler may promote a call to strcpy to a more secure function call (this more secure function binds the copy operation to the size of the destination buffer). Why, then? Because the buffer size is static and is known at compile time. With Visual C + +, you can add the following lines of code to the stdafx.h header file: Copying code
#define _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES 1
The compiler will then continue to run and generate the following code, which comes from the initial, unsafe function: Copying the code
void func (char *p) {
    char d[20];
    strcpy_s (D,__countof (d), p);
    Etc
}
As you can see, the code is now secure and the developer has only added #define, and no processing has been done. This is one of my favorite new Visual C + + features, because about 50% of unsafe function calls can be automatically promoted to security calls. C + + Operator::new Finally, Visual C + + 2005 and later also has a new defense feature that detects integer overflows when calling Operator::new. You can start with the following code: copying code
Cfoo *p = new Cfoo[count];
Visual C + + compiles it to: copy code
00004    C9           xor    ecx, ecx
00006    8b c6 mov eax    , esi
00008 ba (  mov)    edx, 4
0000d    F7 E2           mul    edx
0000f    0f C1       Seto    cl
00012    F7 D9           neg    ecx
00014    0b C8            or    ecx, eax
00016    wuyi             push    ecx
00017    E8 call    ? 2@yapaxi@z    ; operator new
After calculating the amount of memory to allocate (Mul edx), the CL register is determined based on the value of the overflow flag multiplied, so the ECX will be 0x00000000 or 0xFFFFFFFF. Because of the next operation (or ECX), the ECX register will be 0xFFFFFFFF or the value contained in EAX, the result of the initial multiplication. It is then passed to Operator::new, which fails when the 2^n-1 is assigned. This defensive feature is unlimited. Without a compiler switch, it's just the work that the compiler does. What would happen if it failed. Oh. This is a thorny issue. If any of the defenses listed above are triggered, it will have a very nasty result: the application exits. This is not the ideal solution, but it's always much better than running the attacker's malicious code. SDL forces new code to use all of these defenses, simply because there are so many external attacks, and you can never be sure that code 100% is free of vulnerabilities. One popular term for SDL is "what to do with code failure." "What to do in real life" means perseverance. Don't let an attacker's code run amok, making it impossible for an attacker to do so. Never give up. So compile with the latest version of the C + + compiler for better/GS, and link using the latest linker to take advantage of the defensive capabilities provided by the CPU and operating system.
Related Article

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.