You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 6 Next »

Insecure compiler optimizations can occur leaving sensitive data (such as passwords or cryptographic keys) in memory. 

Non Compliant Code Example 1

void getPassword() {
	char pwd[64];
	if( GetPassword(pwd, sizeof(pwd)) {
		/* checking of password, secure operations, etc */
	}
 	memset(pwd, 0, sizeof(pwd));
}

Some compiler optimization modes may remove code sections if the optimizer determines that doing so will not alter the behavior of the program. In this example, this can cause the call to memset() (which the programmer had hoped would clear sensitive memory) to be removed because after the store to pwd, pwd is never accessed again. Check compiler documentation for information about this compiler specific behavior and which optimization levels can cause this behavior to occur.

For all of the below listed compliant code examples, it is strongly recommended that the programmer inspect the generated assembly code to ensure that memory is actually zeroed and none of the function calls were optimized out.

Non-Compliant Code Example 1

void getPassword() {
	char pwd[64];
	if(GetPassword(pwd, sizeof(pwd)) {
		/*checking of password, secure operations, etc */
	}
	memset(pwd, 0, sizeof(pwd));
	*(volatile char*)buffer = *(volatile char*)buffer;
}

 This compliant solution accesses the buffer again after the call to memset and should cause most compilers not to optimize out the call to memset. Check compiler documentation to guarantee this behavior for a specific platform.

Compliant Code Example 2 (Windows)

void getPassword() {
	char pwd[64];
	if(GetPassword(pwd, sizeof(pwd)) {
		/* checking of password, secure operations, etc */
	}
	SecureZeroMemory(pwd, sizeof(pwd));
}

This compliant solution uses a SecureZeroMemory() function provided by many version of the Microsoft Visual Studio compiler. The documentation for the SecureZeroMemory() function guarantees that the compiler will not optimize out this call when zeroing memory.

Compliant Code Example 3 (Windows)

void getPassword() {
	char pwd[64];
	if(GetPassword(pwd, sizeof(pwd)) {
		/* checking of password, secure operations, etc */
	}
	#pragma optimize("", off)
	memset(pwd, 0, sizeof(pwd));
	 #pragma optimize("", on)
}

The #pragma directives here instructs the compiler to avoid optimizing the enclosed code. This #pragma directive is support on some versions of Microsoft Visual Studio, and may be supported on other compilers. Check compiler documentation to ensure its availability and its optimization guarantees.

Risk Assessment

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

DRAFT

2 (Medium)

2 (Probable)

2 (Medium) 

P8

L2

References

  • No labels