Abstract data types, private data types, and information hiding are not restricted to object-oriented languages like C++ and Java. These concepts can and should be implemented in C language programs as well.
Non-Compliant Code Example
Wiki Markup |
---|
This non-compliant code example is based on the managed string library developed by CERT \[[Burch 06|AA. C References#Seacord 06]\]. In this non-compliant example, the managed string type is defined in the include file "string_m.h" as follows: |
Code Block |
---|
struct string_mx {
size_t size;
size_t maxsize;
unsigned char strtype;
char *cstr;
};
typedef struct string_mx *string_m;
|
The implementation of the string_m type is fully visible to the user of the data type, after including the "string_m.h" file. Programmers are consequently more likely to directly manipulate the fields within the structure, violating the software engineering principles of information hiding and data encapsulation and increases the probability of developing incorrect or non-portable code.
Compliant Solution
This compliant solution reimplements the string_m
type as a private type, hiding the implementation of the data type from the user of the managed string library. This can be accomplished the following manner.
The developer of the private data type creates two include files: an external "string_m.h" include file that is included by the user of the data type and an internal file that is only included in files that implement the managed string abstract data eype.
In the external "string_m.h"
the string_m
Compliant Solution
In the first compilation module, which is included by the user, the abstract data type is declared as a pointer to a struct
. The struct string_mx
, which in turn is declared as an incomplete structure type.
Code Block |
---|
struct string_mx; typedef struct string_mx *string_m; |
...
Code Block |
---|
struct string_mx {
size_t size;
size_t maxsize;
unsigned char strtype;
char *cstr;
};
|
#include "string_m.h"
Risk Assessment
String handling functions defined in C99 Section 7.21 and elsewhere are susceptible to common programming errors that can lead to serious, exploitable vulnerabilities. Managed strings, when used properly, can eliminate many of these errors--particularly in new development.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
STR01-A | 1 (low) | 1 (unlikely) | 1 (high) | P1 | L3 |
Related Vulnerabilities
Search for vulnerabilities resulting from the violation of this rule on the CERT website.
References
Wiki Markup |
---|
\[[Burch 06|AA. C References#Seacord 06]\] \[[ISO/IEC 9899-1999|AA. C References#ISO/IEC 9899-1999]\] Section 6.2.5, "Types" \[[Seacord 05a|AA. C References#Seacord 05a]\] Chapter 5, "Integer Security" |