Return to HomePage



Anti-Pattern Example


Contextual Causes

The target application is written in a language that does not provide automated memory management, buffer length checking and array bounds checking. This is most often C/C++ but could include any language that is not type safe. Furthermore, input validation is missing or there is a lack of proper input validation.

AntiPattern Solution

The most common forms are:

* Use of an unbounded copy
		        char buf[1024];
		        strcpy(buf, s);
	

* Use of a bounded copy with incorrect calculations
		        char buf[1024];
		        strncpy(buf, s, 1025);
	

* Failure to null terminate a string
		        char srcBuf[3];
		        char destBuf[3];
		        srcBuf[0] = 'a';
		        strcpy(destBuf, srcBuf);
	

* Copy based on size of source not destination
		        void myCopy(char *string)
		        {
		          char *destBuf = new char[MY_MAX_STRING_SIZE];
		         while (string != NULL)
		          {
		                     *destBuf = *srcBuf;
		                     destBuf++;
		                     srcBuf++;
		          }
		        }
	

* Using untrusted input to allocate buffer size
		        void myCopy(char *srcString, int untrustworthySize)
		        {
		                  char *destBuf[untrustworthySize];
		                  strcpy(destBuf, srcString)
		        }
	

Also see Integer Overflow, Improper String Length Checking, Ignored Function Return Value, Use of sizeof() on a Pointer Type. Each of these vulnerabilities can lead to a buffer overflow.

Symptoms and Consequences

An unchecked buffer that can lead to a process crash or execution of malicious code.

Refactored Solution

* Use of a bounded copy
		        char buf[BUF_SIZE];
		        strncpy(buf, s, BUF_SIZE);
	

* Null terminate string before use
		        char srcBuf[3];
		        char destBuf[3];
		        srcBuf[0] = 'a';
		        srcBuf[1] = '\0';
		        strcpy(destBuf, srcBuf);
	

* Copy based on size of destination buffer
		        void myCopy(char *string)
		        {
		          char *destBuf = new char[MY_MAX_STRING_SIZE];
		          int i = 0;
		          while (string != NULL) && (i < MY_MAX_STRING_SIZE)
		          {
		             *destBuf = *srcBuf;
		             destBuf++;
		             srcBuf++;
		             i++;
		          }
		        }
	

* Check memory allocation and use bounded copy
		        void myCopy(char *srcString, int untrustworthySize)
		        {
		          char *destBuf[untrustworthySize];
		          if (destBuf != null)
		            strncpy(destBuf, srcString, untrustworthySize)
		        }
	

Benefits

* Process stability
* Protection from arbitrary code execution

Liabilities




Return to HomePage
Microsoft Communities