Dataset Viewer
Auto-converted to Parquet Duplicate
language
large_string
page_id
int64
page_url
large_string
chapter
int64
section
int64
rule_id
large_string
title
large_string
intro
large_string
noncompliant_code
large_string
compliant_solution
large_string
risk_assessment
large_string
breadcrumb
large_string
c
87,152,074
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152074
3
13
API00-C
Functions should validate their parameters
Redundant testing by caller and by callee as a style of defensive programming is largely discredited in the C and C++ communities, the main problem being performance. The usual discipline in C and C++ is to require validation on only one side of each interface. Requiring the caller to validate arguments can result in faster code because the caller may understand certain invariants that prevent invalid values from being passed. Requiring the callee to validate arguments allows the validation code to be encapsulated in one location, reducing the size of the code and making it more likely that these checks are performed in a consistent and correct fashion. For safety and security reasons, this standard recommends that the called function validate its parameters. Validity checks allow the function to survive at least some forms of improper usage, enabling an application using the function to likewise survive. Validity checks can also simplify the task of determining the condition that caused the invalid parameter.
/* Sets some internal state in the library */ extern int setfile(FILE *file); /* Performs some action using the file passed earlier */ extern int usefile(); static FILE *myFile; void setfile(FILE *file) { myFile = file; } void usefile(void) { /* Perform some action here */ } ## Noncompliant Code Example In this noncompliant code example, setfile() and usefile() do not validate their parameters. It is possible that an invalid file pointer can be used by the library, corrupting the library's internal state and exposing a vulnerability . #FFcccc c /* Sets some internal state in the library */ extern int setfile(FILE *file); /* Performs some action using the file passed earlier */ extern int usefile(); static FILE *myFile; void setfile(FILE *file) { myFile = file; } void usefile(void) { /* Perform some action here */ } The vulnerability can be more severe if the internal state references sensitive or system-critical data.
/* Sets some internal state in the library */ extern errno_t setfile(FILE *file); /* Performs some action using the file passed earlier */ extern errno_t usefile(void); static FILE *myFile; errno_t setfile(FILE *file) { if (file && !ferror(file) && !feof(file)) { myFile = file; return 0; } /* Error safety: leave myFile unchanged */ return -1; } errno_t usefile(void) { if (!myFile) return -1; /* * Perform other checks if needed; return * error condition.  */ /* Perform some action here */ return 0; } ## Compliant Solution Validating the function parameters and verifying the internal state leads to consistency of program execution and may eliminate potential vulnerabilities. In addition, implementing commit or rollback semantics (leaving program state unchanged on error) is a desirable practice for error safety. #ccccff c /* Sets some internal state in the library */ extern errno_t setfile(FILE *file); /* Performs some action using the file passed earlier */ extern errno_t usefile(void); static FILE *myFile; errno_t setfile(FILE *file) { if (file && !ferror(file) && !feof(file)) { myFile = file; return 0; } /* Error safety: leave myFile unchanged */ return -1; } errno_t usefile(void) { if (!myFile) return -1; /* * Perform other checks if needed; return * error condition. */ /* Perform some action here */ return 0; }
## Risk Assessment Failing to validate the parameters in library functions may result in an access violation or a data integrity violation. Such a scenario indicates a flaw in how the library is used by the calling code. However, the library itself may still be the vector by which the calling code's vulnerability is exploited. Recommendation Severity Likelihood Detectable Repairable Priority Level API00-C Medium Unlikely No No P2 L3 Automated Detection Tool Version Checker Description Supported LANG.STRUCT.UPD Unchecked parameter dereference Parasoft C/C++test CERT_C-API00-a The validity of parameters must be checked inside each function 413, 613, 668 Partially supported: reports use of null pointers including function parameters which are assumed to have the potential to be null PVS-Studio V781 , V1111 Related Vulnerabilities Search for vulnerabilities resulting from the violation of this rule on the CERT website .
SEI CERT C Coding Standard > 3 Recommendations > Rec. 13. Application Programming Interfaces (API)
c
87,151,926
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151926
3
13
API01-C
Avoid laying out strings in memory directly before sensitive data
Strings (both character and wide-character) are often subject to buffer overflows, which will overwrite the memory immediately past the string. Many rules warn against buffer overflows, including . Sometimes the danger of buffer overflows can be minimized by ensuring that arranging memory such that data that might be corrupted by a buffer overflow is not sensitive.
const size_t String_Size = 20; struct node_s { char name[String_Size]; struct node_s* next; } ## Noncompliant Code Example ## This noncompliant code example stores a set of strings using a linked list: #ffcccc c const size_t String_Size = 20; struct node_s { char name[String_Size]; struct node_s* next; } A buffer overflow on name would overwrite the next pointer, which could then be used to read or write to arbitrary memory.
const size_t String_Size = 20; struct node_s { struct node_s* next; char name[String_Size]; } const size_t String_Size = 20; struct node_s { struct node_s* next; char* name; } ## Compliant Solution ## This compliant solution creates a linked list of strings but stores thenextpointer before the string: #ccccff c const size_t String_Size = 20; struct node_s { struct node_s* next; char name[String_Size]; } If buffer overflow occurs on name , the next pointer remains uncorrupted. ## Compliant Solution In this compliant solution, the linked list stores pointers to strings that are stored elsewhere. Storing the strings elsewhere protects the next pointer from buffer overflows on the strings. #ccccff c const size_t String_Size = 20; struct node_s { struct node_s* next; char* name; }
## Risk Assessment Failure to follow this recommendation can result in memory corruption from buffer overflows, which can easily corrupt data or yield remote code execution. Rule Severity Likelihood Detectable Repairable Priority Level API01-C High Likely Yes No P18 L1 Automated Detection Tool Version Checker Description array_out_of_bounds field_overflow_upon_dereference Supported Parasoft C/C++test CERT_C-API01-a CERT_C-API01-b Avoid overflow when writing to a buffer Avoid using unsafe string functions which may cause buffer overflows
SEI CERT C Coding Standard > 3 Recommendations > Rec. 13. Application Programming Interfaces (API)
c
87,152,290
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152290
3
13
API02-C
Functions that read or write to or from an array should take an argument to specify the source or target size
Functions that have an array as a parameter should also have an additional parameter that indicates the maximum number of elements that can be stored in the array. That parameter is required to ensure that the function does not access memory outside the bounds of the array and adversely influence program execution. It should be present for each array parameter (in other words, the existence of each array parameter implies the existence of a complementary parameter that represents the maximum number of elements in the array). Note that array is used in this recommendation to mean array, string, or any other pointer to a contiguous block of memory in which one or more elements of a particular type are (potentially) stored. These terms are all effectively synonymous and represent the same potential for error. Also note that this recommendation suggests the parameter accompanying array parameters indicates the maximum number of elements that can be stored in the array, not the maximum size, in bytes, of the array, because It does not make sense to think of array sizes in bytes in all cases—for example, in the case of an array of integers. If the size in bytes of the array is required, it can be derived from the number of elements in the array. It is better not to add to the cognitive load of the function user by requiring the user to calculate the size in bytes of the array. In most cases, the distinction between the number of elements and number of bytes is moot: there is a clear mapping between the two, and it is easier to think in terms of number of elements anyway. Unfortunately, this issue can become muddled when working with multibyte strings because the logical entity being manipulated differs from that of the type being used to implement it. Here, it is important to remember that the type of the array is a character, not a multibyte character. Accordingly, the number of elements in the array is represented as a number of characters.
char *strncpy(char * restrict s1, const char * restrict s2, size_t n); char *strncat(char * restrict s1, const char * restrict s2, size_t n); ## Noncompliant Code Example It is not necessary to go beyond the standard C library to find examples that violate this recommendation because the C language often prioritizes performance at the expense of robustness . The following are two examples from the C Standard, subclause 7.24 [ ISO/IEC 9899:2011 ]: #FFcccc c char *strncpy(char * restrict s1, const char * restrict s2, size_t n); char *strncat(char * restrict s1, const char * restrict s2, size_t n); These functions have two problems. First, there is no indication of the size of the first array, s1 . As a result, it is not possible to discern within the function how large s1 is and how many elements may be written into it. Second, it appears that a size is supplied for s2 , but the size_t parameter n actually gives the number of elements to copy. Consequently, there is no way for either function to determine the size of the array s2 .
char *improved_strncpy(char * restrict s1, size_t s1count, const char * restrict s2, size_t s2count, size_t n); char *improved_strncat(char * restrict s1, size_t s1count, const char * restrict s2, size_t s2count, size_t n); ## Compliant Solution The C strncpy() and strncat() functions could be improved by adding element count parameters as follows: #ccccff c char *improved_strncpy(char * restrict s1, size_t s1count, const char * restrict s2, size_t s2count, size_t n); char *improved_strncat(char * restrict s1, size_t s1count, const char * restrict s2, size_t s2count, size_t n); The n parameter is used to specify a number of elements to copy that is less than the total number of elements in the source string.
## Risk Assessment Failure to follow this recommendation can result in improper memory accesses and buffer overflows that are detrimental to the correct and continued execution of the program. Rule Severity Likelihood Detectable Repairable Priority Level API02-C High Likely Yes No P18 L1 Automated Detection Tool Version Checker Description BADFUNC.BO.* A collection of checks that report uses of library functions prone to internal buffer overflows. Parasoft C/C++test CERT_C-API02-a CERT_C-API02-b Avoid using unsafe string functions which may cause buffer overflows Don't use unsafe C functions that do write to range-unchecked buffers Related Vulnerabilities Search for vulnerabilities resulting from the violation of this rule on the CERT website .
SEI CERT C Coding Standard > 3 Recommendations > Rec. 13. Application Programming Interfaces (API)
c
87,152,287
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152287
3
13
API03-C
Create consistent interfaces and capabilities across related functions
Related functions, such as those that make up a library, should provide consistent and usable interfaces. Ralph Waldo Emerson said, "A foolish consistency is the hobgoblin of little minds," but inconsistencies in functional interfaces or behavior can lead to erroneous use, so we understand this to be a "wise consistency." One aspect of providing a consistent interface is to provide a consistent and usable error-checking mechanism. For more information, see .
int fputs(const char * restrict s, FILE * restrict stream); int fprintf(FILE * restrict stream, const char * restrict format, ...); #include <stdio.h> #define fputs(X,Y) fputs(Y,X) ## Noncompliant Code Example (Interface) It is not necessary to go beyond the standard C library to find examples of inconsistent interfaces: the standard library is a fusion of multiple libraries with various styles and levels of rigor. For example, the fputs() defined in the C Standard, subclause 7.21.7.4, is closely related to the fprintf() defined in subclause 7.21.6.1. However, fputs() 's file handle is at the end, and fprintf() 's is at the beginning, as shown by their function declarations: #FFcccc c int fputs(const char * restrict s, FILE * restrict stream); int fprintf(FILE * restrict stream, const char * restrict format, ...); The argument order can be easily rearranged using macros; for example: #FFcccc c #include <stdio.h> #define fputs(X,Y) fputs(Y,X) However, according to subclause 7.1.3 of the C Standard, the behavior of a program that defines a symbol, including a macro, with the same name as that of a standard library function, type, macro, or other reserved identifier is undefined . Using inconsistent interfaces makes the code difficult to read, for example, by causing confusion when moving between code that follows this convention and code that does not. In effect, it becomes impossible to modify an interface once that interface has been broadly adopted. Consequently, it is important to get the interface design right the first time. ## Noncompliant Code Example (Behavior) The shared folder and file copy functions in the VMware virtual infrastructure (VIX) API are inconsistent in the set of characters they allow in folder names. As a result, you can create a shared folder that you subsequently cannot use in a file copy function such as VixVM_CopyFileFromHostToGuest() .
/* Initialization of pthread attribute objects */ int pthread_condattr_init(pthread_condattr_t *); int pthread_mutexattr_init(pthread_mutexattr_t *); int pthread_rwlockattr_init(pthread_rwlockattr_t *); ... /* Initialization of pthread objects using attributes */ int pthread_cond_init(pthread_cond_t * restrict, const pthread_condattr_t * restrict); int pthread_mutex_init(pthread_mutex_t * restrict, const pthread_mutexattr_t * restrict); int pthread_rwlock_init(pthread_rwlock_t * restrict, const pthread_rwlockattr_t * restrict); ... ## Compliant Solution (Interface) The POSIX threads library [ Butenhof 1997 ] defines an interface that is both consistent and fits in with established conventions from the rest of the POSIX library. For example, all initialization functions follow the same consistent pattern of the first argument being a pointer to the object to initialize with the subsequent arguments, if any, optionally providing additional attributes for the initialization: #ccccff c /* Initialization of pthread attribute objects */ int pthread_condattr_init(pthread_condattr_t *); int pthread_mutexattr_init(pthread_mutexattr_t *); int pthread_rwlockattr_init(pthread_rwlockattr_t *); ... /* Initialization of pthread objects using attributes */ int pthread_cond_init(pthread_cond_t * restrict, const pthread_condattr_t * restrict); int pthread_mutex_init(pthread_mutex_t * restrict, const pthread_mutexattr_t * restrict); int pthread_rwlock_init(pthread_rwlock_t * restrict, const pthread_rwlockattr_t * restrict); ... Function arguments that refer to objects that are not modified are declared const . Because the object pointed to by the first argument is modified by the function, it is not const . For functions that implement a data abstraction, it is reasonable to define the handle for the data abstraction as the initial parameter. (See .) Finally, initialization functions that accept a pointer to an attribute object allow it to be NULL as an indication that a reasonable default should be used. ## Compliant Solution (Behavior) Try to be consistent in the behavior of related functions that perform operations on common objects so that an object created or modified by one function can be successfully processed by a downstream invocation of a related function.
## Risk Assessment Failure to maintain consistency in interfaces and capabilities across functions can result in type errors in the program. Rule Severity Likelihood Detectable Repairable Priority Level API03-C Medium Unlikely No No P2 L3 Related Vulnerabilities Search for vulnerabilities resulting from the violation of this rule on the CERT website . Automated Detection Tool Version Checker Description
SEI CERT C Coding Standard > 3 Recommendations > Rec. 13. Application Programming Interfaces (API)
c
87,152,244
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152244
3
13
API04-C
Provide a consistent and usable error-checking mechanism
Functions should provide consistent and usable error-checking mechanisms. Complex interfaces are sometimes ignored by programmers, resulting in code that is not error checked. Inconsistent interfaces are frequently misused and difficult to use, resulting in lower-quality code and higher development costs.
char *dir, *file, pname[MAXPATHLEN]; /* ... */ if (strlcpy(pname, dir, sizeof(pname)) >= sizeof(pname)) { /* Handle source-string-too long error */ } ## Noncompliant Code Example (strlcpy()) The strlcpy() function copies a null-terminated source string to a destination array. It is designed to be a safer, more consistent, and less error-prone replacement for strcpy() . The strlcpy() function returns the total length of the string it tried to create (the length of the source string). To detect truncation, perhaps while building a path name, code such as the following might be used: #FFcccc c char *dir, *file, pname[MAXPATHLEN]; /* ... */ if (strlcpy(pname, dir, sizeof(pname)) >= sizeof(pname)) { /* Handle source-string-too long error */ }
errno_t retValue; string_m dest, source; /* ... */ if (retValue = strcpy_m(dest, source)) { fprintf(stderr, "Error %d from strcpy_m.\n", retValue); } ## Compliant Solution (strcpy_m()) The managed string library [ Burch 2006 ] handles errors by consistently returning the status code in the function return value. This approach encourages status checking because the user can insert the function call as the expression in an if statement and take appropriate action on failure. The strcpy_m() function is an example of a managed string function that copies a source-managed string into a destination-managed string: #ccccff c errno_t retValue; string_m dest, source; /* ... */ if (retValue = strcpy_m(dest, source)) { fprintf(stderr, "Error %d from strcpy_m.\n", retValue); } The greatest disadvantage of this approach is that it prevents functions from returning any other value. Consequently, all values (other than the status) returned by a function must be returned as a pass-by-reference parameter, preventing a programmer from nesting function calls. This trade-off is necessary because nesting function calls can conflict with a programmer's willingness to check status codes.
## Risk Assessment Failure to provide a consistent and usable error-checking mechanism can result in type errors in the program. Rule Severity Likelihood Detectable Repairable Priority Level API04-C Medium Unlikely No No P2 L3 Automated Detection Tool Version Checker Description error-information-unused error-information-unused-computed bad-function bad-function-use Supported CERT C: Rec. API04-C Checks for situations where returned value of a sensitive function is not checked (rule partially covered) error-information-unused bad-function bad-function-use Supported 6.02 arithOperationsOnVoidPointer Fully Implemented Related Vulnerabilities Search for vulnerabilities resulting from the violation of this rule on the CERT website .
SEI CERT C Coding Standard > 3 Recommendations > Rec. 13. Application Programming Interfaces (API)
c
87,152,031
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152031
3
13
API05-C
Use conformant array parameters
Traditionally, C arrays are declared with an index that is either a fixed constant or empty. An array with a fixed constant index indicates to the compiler how much space to reserve for the array. An array declaration with an empty index is an incomplete type and indicates that the variable references a pointer to an array of indeterminate size. The term conformant array parameter comes from Pascal; it refers to a function argument that is an array whose size is specified in the function declaration. Since C99, C has supported conformant array parameters by permitting array parameter declarations to use extended syntax. Subclause 6.7.6.2, paragraph 1, of C11 [ ISO/IEC 9899:2011 ] summarizes the array index syntax extensions: The [ and ] may delimit an expression or *. If they delimit an expression (which specifies the size of an array), the  expression shall have an integer type. If the expression is a constant expression, it shall  have a value greater than zero. Consequently, an array declaration that serves as a function argument may have an index that is a variable or an expression. The array argument is demoted to a pointer and is consequently not a variable length array (VLA). Conformant array parameters can be used by developers to indicate the expected bounds of the array. This information may be used by compilers, or it may be ignored. However, such declarations are useful to developers because they serve to document relationships between array sizes and pointers. This information can also be used by static analysis tools to diagnose potential defects. int f(size_t n, int a[n]); /* Documents a relationship between n and a */ ## Standard Examples Subclause 6.7.6.3 of the C Standard [ ISO/IEC 9899:2011 ] has several examples of conformant array parameters. Example 4 (paragraph 20) illustrates a variably modified parameter: void addscalar(int n, int m, double a[n][n*m+300], double x); int main(void) { double b[4][308]; addscalar(4, 2, b, 2.17); return 0; } void addscalar(int n, int m, double a[n][n*m+300], double x) { for (int i = 0; i < n; i++) for (int j = 0, k = n*m+300; j < k; j++) /* a is a pointer to a VLA with n*m+300 elements */ a[i][j] += x; } Example 4 illustrates a set of compatible function prototype declarators double maximum(int n, int m, double a[n][m]); double maximum(int n, int m, double a[*][*]); double maximum(int n, int m, double a[ ][*]); double maximum(int n, int m, double a[ ][m]);
void my_memset(char* p, size_t n, char v) { memset( p, v, n); } void my_memset(char p[n], size_t n, char v) { memset( p, v, n); } ## Noncompliant Code Example This code example provides a function that wraps a call to the standard memset() function and has a similar set of arguments. However, although this function clearly intends that p point to an array of at least n chars, this invariant is not explicitly documented. #ffcccc c void my_memset(char* p, size_t n, char v) { memset( p, v, n); } ## Noncompliant Code Example This noncompliant code example attempts to document the relationship between the pointer and the size using conformant array parameters. However, the variable n is used as the index of the array declaration before n is itself declared. Consequently, this code example is not standards-compliant and will usually fail to compile. #ffcccc c void my_memset(char p[n], size_t n, char v) { memset( p, v, n); }
void my_memset(size_t n; char p[n], size_t n, char v) { memset(p, v, n); } void my_memset(size_t n, char p[n], char v) { memset(p, v, n); } ## Compliant Solution (GCC) This compliant solution uses a GNU extension to forward declare the size_t variable n before using it in the subsequent array declaration. Consequently, this code allows the existing parameter order to be retained and successfully documents the relationship between the array parameter and the size parameter. #ccccff c void my_memset(size_t n; char p[n], size_t n, char v) { memset(p, v, n); } ## Compliant Solution (API change) This compliant solution changes the function's API by moving the size_t variable n to before the subsequent array declaration. Consequently, this code complies with the C99 standard and successfully documents the relationship between the array parameter and the size parameter, but requires all callers to be updated. #ccccff c void my_memset(size_t n, char p[n], char v) { memset(p, v, n); }
## Risk Assessment Failing to specify conformant array dimensions increases the likelihood that another developer will invoke the function with out-of-range integers, which could cause an out-of-bounds memory read or write. Rule Severity Likelihood Detectable Repairable Priority Level API05-C High Probable Yes No P12 L1
SEI CERT C Coding Standard > 3 Recommendations > Rec. 13. Application Programming Interfaces (API)
c
87,152,337
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152337
3
13
API07-C
Enforce type safety
Upon return, functions should guarantee that any object returned by the function, or any modified value referenced by a pointer argument, is a valid object of function return type or argument type. Otherwise, type errors can occur in the program. A good example is the null-terminated byte string type in C. If a string lacks the terminating null character, the program may be tricked into accessing storage after the string as legitimate data. A program may, as a result, process a string it should not process, which might be a security flaw in itself. It may also cause the program to abort, which might be a denial-of-service attack . The emphasis of this recommendation is to avoid producing unterminated strings; it does not address processing of already existing unterminated strings. However, by preventing the creation of unterminated strings, the need to process them is greatly lessened.
char *source; char a[NTBS_SIZE]; /* ... */ if (source) { char* b = strncpy(a, source, 5); // b == a } else { /* Handle null string condition */ } ## Noncompliant Code Example The standard strncpy() function does not guarantee that the resulting string is null-terminated. If there is no null character in the first n characters of the source array, the result may not be null-terminated. #FFcccc c char *source; char a[NTBS_SIZE]; /* ... */ if (source) { char* b = strncpy(a, source, 5); // b == a } else { /* Handle null string condition */ }
char *source; char a[NTBS_SIZE]; /* ... */ if (source) { errno_t err = strncpy_s(a, sizeof(a), source, 5); if (err != 0) { /* Handle error */ } } else { /* Handle null string condition */ } ## Compliant Solution (strncpy_s(), C11 Annex K) The C11 Annex K strncpy_s() function copies up to n characters from the source array to a destination array. If no null character was copied from the source array, the n th position in the destination array is set to a null character, guaranteeing that the resulting string is null-terminated. #ccccff c char *source; char a[NTBS_SIZE]; /* ... */ if (source) { errno_t err = strncpy_s(a, sizeof(a), source, 5); if (err != 0) { /* Handle error */ } } else { /* Handle null string condition */ }
## Risk Assessment Failure to enforce type safety can result in type errors in the program. Rule Severity Likelihood Detectable Repairable Priority Level API07-C Medium Unlikely No No P2 L3 Automated Detection Tool Version Checker Description LANG.CAST.VALUE LANG.CAST.COERCE ALLOC.TM Cast alters value Coercion alters value Type mismatch Related Vulnerabilities Search for vulnerabilities resulting from the violation of this rule on the CERT website .
SEI CERT C Coding Standard > 3 Recommendations > Rec. 13. Application Programming Interfaces (API)
c
87,152,226
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152226
3
13
API09-C
Compatible values should have the same type
Make sure compatible values have the same type. For example, when the return value of one function is used as an argument to another function, make sure they are the same type. Ensuring compatible values have the same type allows the return value to be passed as an argument to the related function without conversion, reducing the potential for conversion errors.
ssize_t atomicio(f, fd, _s, n) ssize_t (*f) (int, void *, size_t); int fd; void *_s; size_t n; { char *s = _s; ssize_t res, pos = 0; while (n > pos) { res = (f) (fd, s + pos, n - pos); switch (res) { case -1: if (errno == EINTR || errno == EAGAIN) continue; case 0: return (res); default: pos += res; } } return (pos); } ## Noncompliant Code Example A source of potential errors may be traced to POSIX's tendency to overload return codes, using −1 to indicate an error condition but 0 for success and positive values as a result indicator (see ). A good example is the read() system call. This leads to a natural mixing of unsigned and signed quantities, potentially leading to conversion errors. OpenSSH performs most I/O calls through a "retry on interrupt" function, atomicio() . The following is a slightly simplified version of atomicio.c , v 1.12 2003/07/31. The function f() is either read() or vwrite() : #FFCCCC c ssize_t atomicio(f, fd, _s, n) ssize_t (*f) (int, void *, size_t); int fd; void *_s; size_t n; { char *s = _s; ssize_t res, pos = 0; while (n > pos) { res = (f) (fd, s + pos, n - pos); switch (res) { case -1: if (errno == EINTR || errno == EAGAIN) continue; case 0: return (res); default: pos += res; } } return (pos); } This function has a large number of flaws. Pertinent to this recommendation, however, are the following: The atomicio() function returns an ssize_t (which must be a signed type). The ssize_t type is a clear indication of poor interface design because a size should never be negative. Both res and pos are declared as ssize_t . The expression n - pos results in the conversion of pos from a signed to an unsigned type because of the usual arithmetic conversions (see ).
size_t atomicio(ssize_t (*f) (int, void *, size_t),  int fd, void *_s, size_t n) { char *s = _s; size_t pos = 0; ssize_t res; struct pollfd pfd; pfd.fd = fd; pfd.events = f == read ? POLLIN : POLLOUT; while (n > pos) { res = (f) (fd, s + pos, n - pos); switch (res) { case -1: if (errno == EINTR) continue; if (errno == EAGAIN) { (void)poll(&pfd, 1, -1); continue; } return 0; case 0: errno = EPIPE; return pos; default: pos += (size_t)res; } } return (pos); } ## Compliant Solution The atomicio() function from atomicio.c , v 1.25 2007/06/25, was modified to always return an unsigned quantity and to instead report its error via errno : #ccccff c size_t atomicio(ssize_t (*f) (int, void *, size_t), int fd, void *_s, size_t n) { char *s = _s; size_t pos = 0; ssize_t res; struct pollfd pfd; pfd.fd = fd; pfd.events = f == read ? POLLIN : POLLOUT; while (n > pos) { res = (f) (fd, s + pos, n - pos); switch (res) { case -1: if (errno == EINTR) continue; if (errno == EAGAIN) { (void)poll(&pfd, 1, -1); continue; } return 0; case 0: errno = EPIPE; return pos; default: pos += (size_t)res; } } return (pos); } Changes to this version of the atomicio() function include the following: The atomicio() function now returns a value of type size_t . pos is now declared as size_t . The assignment pos += (size_t)res now requires an explicit cast to convert from the signed return value of f() to size_t . The expression n - pos no longer requires an implicit conversion. Reducing the need to use signed types makes it easier to enable the compiler's signed/unsigned comparison warnings and fix all of the issues it reports (see ).
## Risk Assessment The risk in using in-band error indicators is difficult to quantify and is consequently given as low. However, if the use of in-band error indicators results in programmers' failing to check status codes or incorrectly checking them, the consequences can be more severe. Recommendation Severity Likelihood Detectable Repairable Priority Level API09-C Low Unlikely No No P1 L3 Automated Detection Tool Version Checker Description 737 Partially supported Related Vulnerabilities Search for vulnerabilities resulting from the violation of this rule on the CERT website .
SEI CERT C Coding Standard > 3 Recommendations > Rec. 13. Application Programming Interfaces (API)
c
87,151,961
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151961
3
13
API10-C
APIs should have security options enabled by default
APIS should have security options enabled by default– for example, having best practice cipher suites enabled by default (something that changes over time) while disabling out-of-favor cipher suites by default. When interface stability is also a design requirement, an interface can meet both goals by providing off-by-default options that produce stable behavior, such as TLS_ENABLE_Y2015_BEST_PRACTICE_CIPHERS_ONLY .
int tls_connect_by_name(const char *host, int port, int option_bitmask); #define TLS_DEFAULT_OPTIONS 0 #define TLS_VALIDATE_HOST 0x0001 #define TLS_DISABLE_V1_0 0x0002 #define TLS_DISABLE_V1_1 0x0004 ## Noncompliant Code Example If the caller of this API in this noncompliant example doesn't understand what the options mean, they will pass 0 or TLS_DEFAULT_OPTIONS and get a connection vulnerable to man-in-the-middle attacks and using old versions of TLS. #ffcccc c int tls_connect_by_name(const char *host, int port, int option_bitmask); #define TLS_DEFAULT_OPTIONS 0 #define TLS_VALIDATE_HOST 0x0001 #define TLS_DISABLE_V1_0 0x0002 #define TLS_DISABLE_V1_1 0x0004
int tls_connect_by_name(const char *host, int port, int option_bitmask); #define TLS_DEFAULT_OPTIONS 0 #define TLS_DISABLE_HOST_VALIDATION 0x0001 // use rarely, subject to man-in-the-middle attack #define TLS_ENABLE_V1_0 0x0002 #define TLS_ENABLE_V1_1 0x0004 ## Compliant Solution If the caller of this API doesn't understand the options and passes 0 or TLS_DEFAULT_OPTIONS they will get certificate validation with only the current version of TLS enabled. #ccccff c int tls_connect_by_name(const char *host, int port, int option_bitmask); #define TLS_DEFAULT_OPTIONS 0 #define TLS_DISABLE_HOST_VALIDATION 0x0001 // use rarely, subject to man-in-the-middle attack #define TLS_ENABLE_V1_0 0x0002 #define TLS_ENABLE_V1_1 0x0004
## Risk Assessment Rule Severity Likelihood Detectable Repairable Priority Level API10-C Medium Likely No No P6 L3
SEI CERT C Coding Standard > 3 Recommendations > Rec. 13. Application Programming Interfaces (API)
c
87,152,117
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152117
3
6
ARR00-C
Understand how arrays work
The incorrect use of arrays has traditionally been a source of exploitable vulnerabilities . Elements referenced within an array using the subscript operator [] are not checked unless the programmer provides adequate bounds checking. As a result, the expression array [pos] = value can be used by an attacker to transfer control to arbitrary code. An attacker who can control the values of both pos and value in the expression array [pos] = value can perform an arbitrary write (which is when the attacker overwrites other storage locations with different content). The consequences range from changing a variable used to determine what permissions the program grants to executing arbitrary code with the permissions of the vulnerable process. Arrays are also a common source of buffer overflows when iterators exceed the bounds of the array. An array is a series of objects, all of which are the same size and type. Each object in an array is called an array element . The entire array is stored contiguously in memory (that is, there are no gaps between elements). Arrays are commonly used to represent a sequence of elements where random access is important but there is little or no need to insert new elements into the sequence (which can be an expensive operation with arrays). Arrays containing a constant number of elements can be declared as follows: enum { ARRAY_SIZE = 12 }; int array[ARRAY_SIZE]; These statements allocate storage for an array of 12 integers referenced by array . Arrays are indexed from 0..n-1 (where n represents an array bound). Arrays can also be declared as follows: int array[]; This array is called an incomplete type because the size is unknown. If an array of unknown size is initialized, its size is determined by the largest indexed element with an explicit initializer. At the end of its initializer list, the array no longer has incomplete type. int array[] = { 1, 2 }; Although these declarations work fine when the size of the array is known at compile time, it is not possible to declare an array in this fashion when the size can be determined only at runtime. The C Standard adds support for variable length arrays or arrays whose size is determined at runtime. Before the introduction of variable length arrays in C99, however, these "arrays" were typically implemented as pointers to their respective element types allocated using malloc() , as shown in this example: int *dis = (int *)malloc(ARRAY_SIZE * sizeof(int)); Always check that malloc() returns a non-null pointer, as per . It is important to retain any pointer value returned by malloc() so that the referenced memory may eventually be deallocated. One possible way to preserve such a value is to use a constant pointer: int * const dat = (int * const)malloc( ARRAY_SIZE * sizeof(int) ); /* ... */ free(dat); Below we consider some techniques for array initialization.  Both dis and dat arrays can be initialized as follows: for (i = 0; i < ARRAY_SIZE; i++) { dis[i] = 42; /* Assigns 42 to each element of dis */ dat[i] = 42; /* Assigns 42 to each element of dat */ } The dis array can also be initialized as follows: for (i = 0; i < ARRAY_SIZE; i++) { *dis = 42; dis++; } dis -= ARRAY_SIZE; This technique, however, will not work for dat .  The dat identifier cannot be incremented (produces a fatal compilation error), as it was declared with type int * const .  This problem can be circumvented by copying dat into a separate pointer: int *p = dat; for (i = 0; i < ARRAY_SIZE; i++) { *p = 42; /* Assigns 42 to each element */ p++; } The variable p is declared as a pointer to an integer, initialized with the value stored in dat , and then incremented in the loop. This technique can be used to initialize both arrays, and is a better style of programming than incrementing the original pointer to the array (e.g., dis++ , in the above example), as it avoids having to reset the pointer back to the start of the array after the loop completes. Obviously, there is a relationship between array subscripts [] and pointers. The expression dis[i] is equivalent to *(dis+i) for all integral values of i . In other words, if dis is an array object (equivalently, a pointer to the initial element of an array object) and i is an integer, dis[i] designates the i th element of dis . In fact, because *(dis+i) can be expressed as *(i+dis) , the expression dis[i] can be represented as i[dis] , although doing so is not encouraged. Because array indices are zero-based, the first element is designated as dis[0] , or equivalently as *(dis+0) or simply *dis .
null
null
## Risk Assessment Arrays are a common source of vulnerabilities in C language programs because they are frequently used but not always fully understood. Recommendation Severity Likelihood Detectable Repairable Priority Level ARR00-C High Probable No No P6 L2 Automated Detection Tool Version Checker Description LANG.CAST.ARRAY.TEMP Array to Pointer Conversion on Temporary Object C0304, C0450, C0453, C0455, C0459, C0464, C0465, C0491, C0590, C0642, C0676, C0677, C0678, C0680, C0686, C0687, C0688, C0691, C0710, C0711, C0941, C1037, C1051, C1052, C1121, C1122, C1123, C1188, C1189, C1312, C2668, C2669, C2781, C2782, C2783, C2810, C2811, C2812, C2813, C2814, C2820, C2821, C2822, C2823, C2824, C2840, C2841, C2842, C2843, C2845, C2846, C2847, C2848, C2950, C2951, C2952, C2953, C3337, C3405, C3639, C3640, C3650, C3651, C3674, C3684, C4500, C4510 ABV.ANY_SIZE_ARRAY ABV.GENERAL ABV.GENERAL.MULTIDIMENSION ABV.ITERATOR ABV.MEMBER ABV.STACK ABV.TAINTED ABV.UNICODE.BOUND_MAP ABV.UNICODE.FAILED_MAP ABV.UNICODE.NNTS_MAP ABV.UNICODE.SELF_MAP ABV.UNKNOWN_SIZE NNTS.MIGHT NNTS.MUST NNTS.TAINTED SV.STRBO.BOUND_COPY.OVERFLOW SV.STRBO.BOUND_COPY.UNTERM SV.STRBO.BOUND_SPRINTF SV.STRBO.UNBOUND_COPY SV.STRBO.UNBOUND_SPRINTF SV.TAINTED.ALLOC_SIZE SV.TAINTED.CALL.INDEX_ACCESS SV.TAINTED.CALL.LOOP_BOUND SV.TAINTED.INDEX_ACCESS SV.TAINTED.LOOP_BOUND SV.UNBOUND_STRING_INPUT.CIN SV.UNBOUND_STRING_INPUT.FUNC LDRA tool suite 45 D, 47 S, 489 S, 567 S, 64 X, 66 X, 68 X, 69 X, 70 X, 71 X Partially implemented 409, 413, 429, 613 Partially supported: conceptually includes all other ARR items which are mapped to their respective guidelines; explicit mappings for ARR00 are present when a situation mentioned in the guideline itself is encountered Related Vulnerabilities Search for vulnerabilities resulting from the violation of this rule on the CERT website .
SEI CERT C Coding Standard > 3 Recommendations > Rec. 06. Arrays (ARR)
c
87,152,137
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152137
3
6
ARR01-C
Do not apply the sizeof operator to a pointer when taking the size of an array
The sizeof operator yields the size (in bytes) of its operand, which can be an expression or the parenthesized name of a type. However, using the sizeof operator to determine the size of arrays is error prone. The sizeof operator is often used in determining how much memory to allocate via malloc() . However using an incorrect size is a violation of .
void clear(int array[]) { for (size_t i = 0; i < sizeof(array) / sizeof(array[0]); ++i) { array[i] = 0; } } void dowork(void) { int dis[12]; clear(dis); /* ... */ } enum {ARR_LEN = 100}; void clear(int a[ARR_LEN]) { memset(a, 0, sizeof(a)); /* Error */ } int main(void) { int b[ARR_LEN]; clear(b); assert(b[ARR_LEN / 2]==0); /* May fail */ return 0; } ## Noncompliant Code Example In this noncompliant code example, the function clear() zeros the elements in an array. The function has one parameter declared as int array[] and is passed a static array consisting of 12 int as the argument. The function clear() uses the idiom sizeof(array) / sizeof(array[0]) to determine the number of elements in the array. However, array has a pointer type because it is a parameter. As a result, sizeof(array) is equal to the sizeof(int *) . For example, on an architecture (such as IA-32) where the sizeof(int) == 4 and the sizeof(int *) == 4 , the expression sizeof(array) / sizeof(array[0]) evaluates to 1, regardless of the length of the array passed, leaving the rest of the array unaffected. #FFcccc c void clear(int array[]) { for (size_t i = 0; i < sizeof(array) / sizeof(array[0]); ++i) { array[i] = 0; } } void dowork(void) { int dis[12]; clear(dis); /* ... */ } Footnote 103 in subclause 6.5.3.4 of the C Standard [ ISO/IEC 9899:2011 ] applies to all array parameters: When applied to a parameter declared to have array or function type, the sizeof operator yields the size of the adjusted (pointer) type. ## Noncompliant Code Example In this noncompliant code example, sizeof(a) does not equal 100 * sizeof(int) , because the sizeof operator, when applied to a parameter declared to have array type, yields the size of the adjusted (pointer) type even if the parameter declaration specifies a length: #FFcccc c enum {ARR_LEN = 100}; void clear(int a[ARR_LEN]) { memset(a, 0, sizeof(a)); /* Error */ } int main(void) { int b[ARR_LEN]; clear(b); assert(b[ARR_LEN / 2]==0); /* May fail */ return 0; }
void clear(int array[], size_t len) { for (size_t i = 0; i < len; i++) { array[i] = 0; } } void dowork(void) { int dis[12]; clear(dis, sizeof(dis) / sizeof(dis[0])); /* ... */ } enum {ARR_LEN = 100}; void clear(int a[], size_t len) { memset(a, 0, len * sizeof(int)); } int main(void) { int b[ARR_LEN]; clear(b, ARR_LEN); assert(b[ARR_LEN / 2]==0); /* Cannot fail */ return 0; } ## Compliant Solution In this compliant solution, the size of the array is determined inside the block in which it is declared and passed as an argument to the function: #ccccff c void clear(int array[], size_t len) { for (size_t i = 0; i < len; i++) { array[i] = 0; } } void dowork(void) { int dis[12]; clear(dis, sizeof(dis) / sizeof(dis[0])); /* ... */ } This sizeof(array) / sizeof(array[0]) idiom will succeed provided the original definition of array is visible. ## Compliant Solution ## In this compliant solution, the size is specified using the expressionlen * sizeof(int): #ccccff c enum {ARR_LEN = 100}; void clear(int a[], size_t len) { memset(a, 0, len * sizeof(int)); } int main(void) { int b[ARR_LEN]; clear(b, ARR_LEN); assert(b[ARR_LEN / 2]==0); /* Cannot fail */ return 0; }
## Risk Assessment Incorrectly using the sizeof operator to determine the size of an array can result in a buffer overflow, allowing the execution of arbitrary code. Recommendation Severity Likelihood Detectable Repairable Priority Level ARR01-C High Probable No Yes P12 L1 Automated Detection Tool Version Checker Description sizeof-array-parameter Fully checked CertC-ARR01 Fully implemented LANG.TYPE.SAP sizeof Array Parameter Compass/ROSE Can detect violations of the recommendation but cannot distinguish between incomplete array declarations and pointer declarations C1321 CWARN.MEMSET.SIZEOF.PTR Fully implemented LDRA tool suite 401 S Fully implemented Parasoft C/C++test CERT_C-ARR01-a Do not call 'sizeof' on a pointer type 682, 882 Fully supported CERT C: Rec. ARR01-C Checks for: Wrong type used in sizeof Possible misuse of sizeof Rec, fully covered. PVS-Studio V511 , V512 , V514 , V568 , V579 , V604 , V697 , V1086 sizeof-array-parameter Fully checked Related Vulnerabilities Search for vulnerabilities resulting from the violation of this rule on the CERT website .
SEI CERT C Coding Standard > 3 Recommendations > Rec. 06. Arrays (ARR)
c
87,152,105
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152105
3
6
ARR02-C
Explicitly specify array bounds, even if implicitly defined by an initializer
The C Standard allows an array variable to be declared both with a bound and with an initialization literal. The initialization literal also implies an array bound in the number of elements specified. The size implied by an initialization literal is usually specified by the number of elements, int array[] = {1, 2, 3}; /* 3-element array */ but it is also possible to use designators to initialize array elements in a noncontiguous fashion. Subclause 6.7.9, Example 12, of the C Standard [ ISO/IEC 9899:2011 ] states: Space can be "allocated" from both ends of an array by using a single designator: int a[MAX] = { 1, 3, 5, 7, 9, [MAX-5] = 8, 6, 4, 2, 0 }; In the above, if MAX is greater than ten, there will be some zero-valued elements in the middle; if it is less than ten, some of the values provided by the first five initializers will be overridden by the second five. The C Standard also dictates how array initialization is handled when the number of initialization elements does not equal the explicit array bound. Subclause 6.7.9, paragraphs 21 and 22, state: If there are fewer initializers in a brace-enclosed list than there are elements or members of an aggregate, or fewer characters in a string literal used to initialize an array of known size than there are elements in the array, the remainder of the aggregate shall be initialized implicitly the same as objects that have static storage duration. If an array of unknown size is initialized, its size is determined by the largest indexed element with an explicit initializer. The array type is completed at the end of its initializer list. Although compilers can compute the size of an array on the basis of its initialization list, explicitly specifying the size of the array provides a redundancy check, ensuring that the array's size is correct. It also enables compilers to emit warnings if the array's size is less than the size implied by the initialization. Note that this recommendation does not apply (in all cases) to character arrays initialized with string literals. See for more information.
int a[3] = {1, 2, 3, 4}; int a[] = {1, 2, 3, 4}; ## Noncompliant Code Example (Incorrect Size) This noncompliant code example initializes an array of integers using an initialization with too many elements for the array: #FFCCCC c int a[3] = {1, 2, 3, 4}; The size of the array a is 3, although the size of the initialization is 4. The last element of the initialization ( 4 ) is ignored. Most compilers will diagnose this error. Implementation Details This noncompliant code example generates a warning in GCC. Microsoft Visual Studio generates a fatal diagnostic: error C2078: too many initializers . ## Noncompliant Code Example (Implicit Size) In this example, the compiler allocates an array of four integer elements and, because an array bound is not explicitly specified by the programmer, sets the array bound to 4 . However, if the initializer changes, the array bound may also change, causing unexpected results. #FFCCCC c int a[] = {1, 2, 3, 4};
int a[4] = {1, 2, 3, 4}; ## Compliant Solution ## This compliant solution explicitly specifies the array bound: #ccccff c int a[4] = {1, 2, 3, 4}; Explicitly specifying the array bound, although it is implicitly defined by an initializer, allows a compiler or other static analysis tool to issue a diagnostic if these values do not agree.
## Risk Assessment Recommendation Severity Likelihood Detectable Repairable Priority Level ARR02-C Medium Unlikely Yes Yes P6 L2 Automated Detection Tool Version Checker Description array-size-global Partially checked CertC-ARR02 Fully implemented Compass/ROSE CC2.ARR02 Fully implemented C0678, C0688, C3674, C3684 LDRA tool suite 127 S 397 S 404 S Fully  implemented Parasoft C/C++test CERT_C-ARR02-a Explicitly specify array bounds in array declarations with initializers 576 Partially supported CERT C: Rec. ARR02-C Checks for improper array initialization (rec, partially covered). PVS-Studio V798 array-size-global Partially checked S834 Related Vulnerabilities Search for vulnerabilities resulting from the violation of this rule on the CERT website .
SEI CERT C Coding Standard > 3 Recommendations > Rec. 06. Arrays (ARR)
c
87,152,322
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152322
2
6
ARR30-C
Do not form or use out-of-bounds pointers or array subscripts
The C Standard identifies the following distinct situations in which undefined behavior (UB) can arise as a result of invalid pointer operations: UB Description Example Code 43 Addition or subtraction of a pointer into, or just beyond, an array object and an integer type produces a result that does not point into, or just beyond, the same array object. , Null Pointer Arithmetic 44 Addition or subtraction of a pointer into, or just beyond, an array object and an integer type produces a result that points just beyond the array object and is used as the operand of a unary * operator that is evaluated. Dereferencing Past the End Pointer , 46 An array subscript is out of range, even if an object is apparently accessible with the given subscript, for example, in the lvalue expression a[1][7] given the declaration int a[4][5] ). 59 An attempt is made to access, or generate a pointer to just past, a flexible array member of a structure when the referenced object provides no elements for that array.
enum { TABLESIZE = 100 }; static int table[TABLESIZE]; int *f(int index) { if (index < TABLESIZE) { return table + index; } return NULL; } error_status_t _RemoteActivation( /* ... */, WCHAR *pwszObjectName, ... ) { *phr = GetServerPath( pwszObjectName, &pwszObjectName); /* ... */ } HRESULT GetServerPath( WCHAR *pwszPath, WCHAR **pwszServerPath ){ WCHAR *pwszFinalPath = pwszPath; WCHAR wszMachineName[MAX_COMPUTERNAME_LENGTH_FQDN+1]; hr = GetMachineName(pwszPath, wszMachineName); *pwszServerPath = pwszFinalPath; } HRESULT GetMachineName( WCHAR *pwszPath, WCHAR wszMachineName[MAX_COMPUTERNAME_LENGTH_FQDN+1]) { pwszServerName = wszMachineName; LPWSTR pwszTemp = pwszPath + 2; while (*pwszTemp != L'\\') *pwszServerName++ = *pwszTemp++; /* ... */ } #include <stdlib.h>   static int *table = NULL; static size_t size = 0; int insert_in_table(size_t pos, int value) { if (size < pos) { int *tmp; size = pos + 1; tmp = (int *)realloc(table, sizeof(*table) * size); if (tmp == NULL) { return -1; /* Failure */ } table = tmp; } table[pos] = value; return 0; } #include <stddef.h> #define COLS 5 #define ROWS 7 static int matrix[ROWS][COLS]; void init_matrix(int x) { for (size_t i = 0; i < COLS; i++) { for (size_t j = 0; j < ROWS; j++) { matrix[i][j] = x; } } } #include <stdlib.h>   struct S { size_t len; char buf[]; /* Flexible array member */ }; const char *find(const struct S *s, int c) { const char *first = s->buf; const char *last = s->buf + s->len; while (first++ != last) { /* Undefined behavior */ if (*first == c) { return first; } } return NULL; }   void g(void) { struct S *s = (struct S *)malloc(sizeof(struct S)); if (s == NULL) { /* Handle error */ } s->len = 0; find(s, 'a'); } #include <string.h> #include <stdlib.h> char *init_block(size_t block_size, size_t offset, char *data, size_t data_size) { char *buffer = malloc(block_size); if (data_size > block_size || block_size - data_size < offset) { /* Data won't fit in buffer, handle error */ } memcpy(buffer + offset, data, data_size); return buffer; } ## Forming Out-of-Bounds PointerNoncompliant Code Example (Forming Out-of-Bounds Pointer) In this noncompliant code example, the function f() attempts to validate the index before using it as an offset to the statically allocated table of integers. However, the function fails to reject negative index values. When index is less than zero, the behavior of the addition expression in the return statement of the function is undefined behavior 43 . On some implementations, the addition alone can trigger a hardware trap. On other implementations, the addition may produce a result that when dereferenced triggers a hardware trap. Other implementations still may produce a dereferenceable pointer that points to an object distinct from table . Using such a pointer to access the object may lead to information exposure or cause the wrong object to be modified. #ffcccc c enum { TABLESIZE = 100 }; static int table[TABLESIZE]; int *f(int index) { if (index < TABLESIZE) { return table + index; } return NULL; } ## Dereferencing Past the End PointerNoncompliant Code Example (Dereferencing Past-the-End Pointer) This noncompliant code example shows the flawed logic in the Windows Distributed Component Object Model (DCOM) Remote Procedure Call (RPC) interface that was exploited by the W32.Blaster.Worm. The error is that the while loop in the GetMachineName() function (used to extract the host name from a longer string) is not sufficiently bounded. When the character array pointed to by pwszTemp does not contain the backslash character among the first MAX_COMPUTERNAME_LENGTH_FQDN + 1 elements, the final valid iteration of the loop will dereference past the end pointer, resulting in exploitable undefined behavior 44 . In this case, the actual exploit allowed the attacker to inject executable code into a running program. Economic damage from the Blaster worm has been estimated to be at least $525 million [ Pethia 2003 ]. For a discussion of this programming error in the Common Weakness Enumeration database, see CWE-119 , "Improper Restriction of Operations within the Bounds of a Memory Buffer," and CWE-121 , "Stack-based Buffer Overflow" [ MITRE 2013 ]. #ffcccc c error_status_t _RemoteActivation( /* ... */, WCHAR *pwszObjectName, ... ) { *phr = GetServerPath( pwszObjectName, &pwszObjectName); /* ... */ } HRESULT GetServerPath( WCHAR *pwszPath, WCHAR **pwszServerPath ){ WCHAR *pwszFinalPath = pwszPath; WCHAR wszMachineName[MAX_COMPUTERNAME_LENGTH_FQDN+1]; hr = GetMachineName(pwszPath, wszMachineName); *pwszServerPath = pwszFinalPath; } HRESULT GetMachineName( WCHAR *pwszPath, WCHAR wszMachineName[MAX_COMPUTERNAME_LENGTH_FQDN+1]) { pwszServerName = wszMachineName; LPWSTR pwszTemp = pwszPath + 2; while (*pwszTemp != L'\\') *pwszServerName++ = *pwszTemp++; /* ... */ } ## Using Past the End IndexNoncompliant Code Example (Using Past-the-End Index) Similar to the dereferencing-past-the-end-pointer error, the function insert_in_table() in this noncompliant code example uses an otherwise valid index to attempt to store a value in an element just past the end of an array. First, the function incorrectly validates the index pos against the size of the buffer. When pos is initially equal to size , the function attempts to store value in a memory location just past the end of the buffer. Second, when the index is greater than size , the function modifies size before growing the size of the buffer. If the call to realloc() fails to increase the size of the buffer, the next call to the function with a value of pos equal to or greater than the original value of size will again attempt to store value in a memory location just past the end of the buffer or beyond. Third, the function violates , which could lead to wrapping when 1 is added to pos or when size is multiplied by the size of int . For a discussion of this programming error in the Common Weakness Enumeration database, see CWE-122 , "Heap-based Buffer Overflow," and CWE-129 , "Improper Validation of Array Index" [ MITRE 2013 ]. #ffcccc c #include <stdlib.h> static int *table = NULL; static size_t size = 0; int insert_in_table(size_t pos, int value) { if (size < pos) { int *tmp; size = pos + 1; tmp = (int *)realloc(table, sizeof(*table) * size); if (tmp == NULL) { return -1; /* Failure */ } table = tmp; } table[pos] = value; return 0; } ## Apparently Accessible Out-of-Range IndexNoncompliant Code Example (Apparently Accessible Out-of-Range Index) This noncompliant code example declares matrix to consist of 7 rows and 5 columns in row-major order. The function init_matrix iterates over all 35 elements in an attempt to initialize each to the value given by the function argument x . However, because multidimensional arrays are declared in C in row-major order, the function iterates over the elements in column-major order, and when the value of j reaches the value COLS during the first iteration of the outer loop, the function attempts to access element matrix[0][5] . Because the type of matrix is int[7][5] , the j subscript is out of range, and the access has undefined behavior 46 . #ffcccc c #include <stddef.h> #define COLS 5 #define ROWS 7 static int matrix[ROWS][COLS]; void init_matrix(int x) { for (size_t i = 0; i < COLS; i++) { for (size_t j = 0; j < ROWS; j++) { matrix[i][j] = x; } } } ## Pointer Past Flexible Array MemberNoncompliant Code Example (Pointer Past Flexible Array Member) In this noncompliant code example, the function find() attempts to iterate over the elements of the flexible array member buf , starting with the second element. However, because function g() does not allocate any storage for the member, the expression first++ in find() attempts to form a pointer just past the end of buf when there are no elements. This attempt is undefined behavior 59 . (See for more information.) #ffcccc c #include <stdlib.h> struct S { size_t len; char buf[]; /* Flexible array member */ }; const char *find(const struct S *s, int c) { const char *first = s->buf; const char *last = s->buf + s->len; while (first++ != last) { /* Undefined behavior */ if (*first == c) { return first; } } return NULL; } void g(void) { struct S *s = (struct S *)malloc(sizeof(struct S)); if (s == NULL) { /* Handle error */ } s->len = 0; find(s, 'a'); } ## Null Pointer ArithmeticNoncompliant Code Example (Null Pointer Arithmetic) This noncompliant code example is similar to an Adobe Flash Player vulnerability that was first exploited in 2008. This code allocates a block of memory and initializes it with some data. The data does not belong at the beginning of the block, which is left uninitialized. Instead, it is placed offset bytes within the block. The function ensures that the data fits within the allocated block. #ffcccc c #include <string.h> #include <stdlib.h> char *init_block(size_t block_size, size_t offset, char *data, size_t data_size) { char *buffer = malloc(block_size); if (data_size > block_size || block_size - data_size < offset) { /* Data won't fit in buffer, handle error */ } memcpy(buffer + offset, data, data_size); return buffer; } This function fails to check if the allocation succeeds, which is a violation of . If the allocation fails, then malloc() returns a null pointer. The null pointer is added to offset and passed as the destination argument to memcpy() . Because a null pointer does not point to a valid object, the result of the pointer arithmetic is undefined behavior 43 . An attacker who can supply the arguments to this function can exploit it to execute arbitrary code. This can be accomplished by providing an overly large value for block_size , which causes malloc() to fail and return a null pointer. The offset argument will then serve as the destination address to the call to memcpy() . The attacker can specify the data and data_size arguments to provide the address and length of the address, respectively, that the attacker wishes to write into the memory referenced by offset . The overall result is that the call to memcpy() can be exploited by an attacker to overwrite an arbitrary memory location with an attacker-supplied address, typically resulting in arbitrary code execution.
enum { TABLESIZE = 100 }; static int table[TABLESIZE]; int *f(int index) { if (index >= 0 && index < TABLESIZE) { return table + index; } return NULL; } #include <stddef.h>   enum { TABLESIZE = 100 }; static int table[TABLESIZE]; int *f(size_t index) { if (index < TABLESIZE) { return table + index; } return NULL; } HRESULT GetMachineName( wchar_t *pwszPath, wchar_t wszMachineName[MAX_COMPUTERNAME_LENGTH_FQDN+1]) { wchar_t *pwszServerName = wszMachineName; wchar_t *pwszTemp = pwszPath + 2; wchar_t *end_addr = pwszServerName + MAX_COMPUTERNAME_LENGTH_FQDN; while ((*pwszTemp != L'\\') && (*pwszTemp != L'\0') && (pwszServerName < end_addr)) { *pwszServerName++ = *pwszTemp++; } /* ... */ } #include <stdint.h> #include <stdlib.h>   static int *table = NULL; static size_t size = 0; int insert_in_table(size_t pos, int value) { if (size <= pos) { if ((SIZE_MAX - 1 < pos) || ((pos + 1) > SIZE_MAX / sizeof(*table))) { return -1; } int *tmp = (int *)realloc(table, sizeof(*table) * (pos + 1)); if (tmp == NULL) { return -1; } /* Modify size only after realloc() succeeds */ size = pos + 1; table = tmp; } table[pos] = value; return 0; } #include <stddef.h> #define COLS 5 #define ROWS 7 static int matrix[ROWS][COLS]; void init_matrix(int x) { for (size_t i = 0; i < ROWS; i++) { for (size_t j = 0; j < COLS; j++) { matrix[i][j] = x; } } } #include <stdlib.h>   struct S { size_t len; char buf[]; /* Flexible array member */ }; const char *find(const struct S *s, int c) { const char *first = s->buf; const char *last = s->buf + s->len; while (first != last) { /* Avoid incrementing here */ if (*++first == c) { return first; } } return NULL; }   void g(void) { struct S *s = (struct S *)malloc(sizeof(struct S)); if (s == NULL) { /* Handle error */ } s->len = 0; find(s, 'a'); } #include <string.h> #include <stdlib.h> char *init_block(size_t block_size, size_t offset, char *data, size_t data_size) { char *buffer = malloc(block_size); if (NULL == buffer) { /* Handle error */ } if (data_size > block_size || block_size - data_size < offset) { /* Data won't fit in buffer, handle error */ } memcpy(buffer + offset, data, data_size); return buffer; } ## Compliant Solution One compliant solution is to detect and reject invalid values of index if using them in pointer arithmetic would result in an invalid pointer: #ccccff c enum { TABLESIZE = 100 }; static int table[TABLESIZE]; int *f(int index) { if (index >= 0 && index < TABLESIZE) { return table + index; } return NULL; } ## Compliant Solution Another slightly simpler and potentially more efficient compliant solution is to use an unsigned type to avoid having to check for negative values while still rejecting out-of-bounds positive values of index : #ccccff c #include <stddef.h> enum { TABLESIZE = 100 }; static int table[TABLESIZE]; int *f(size_t index) { if (index < TABLESIZE) { return table + index; } return NULL; } ## Compliant Solution In this compliant solution, the while loop in the GetMachineName() function is bounded so that the loop terminates when a backslash character is found, the null-termination character ( L'\0' ) is discovered, or the end of the buffer is reached. Or, as coded, the while loop continues as long as each character is neither a backslash nor a null character and is not at the end of the buffer. This code does not result in a buffer overflow even if no backslash character is found in wszMachineName . #ccccff c HRESULT GetMachineName( wchar_t *pwszPath, wchar_t wszMachineName[MAX_COMPUTERNAME_LENGTH_FQDN+1]) { wchar_t *pwszServerName = wszMachineName; wchar_t *pwszTemp = pwszPath + 2; wchar_t *end_addr = pwszServerName + MAX_COMPUTERNAME_LENGTH_FQDN; while ((*pwszTemp != L'\\') && (*pwszTemp != L'\0') && (pwszServerName < end_addr)) { *pwszServerName++ = *pwszTemp++; } /* ... */ } This compliant solution is for illustrative purposes and is not necessarily the solution implemented by Microsoft. This particular solution may not be correct because there is no guarantee that a backslash is found. ## Compliant Solution This compliant solution correctly validates the index pos by using the <= relational operator, ensures the multiplication will not overflow, and avoids modifying size until it has verified that the call to realloc() was successful: #ccccff c #include <stdint.h> #include <stdlib.h> static int *table = NULL; static size_t size = 0; int insert_in_table(size_t pos, int value) { if (size <= pos) { if ((SIZE_MAX - 1 < pos) || ((pos + 1) > SIZE_MAX / sizeof(*table))) { return -1; } int *tmp = (int *)realloc(table, sizeof(*table) * (pos + 1)); if (tmp == NULL) { return -1; } /* Modify size only after realloc() succeeds */ size = pos + 1; table = tmp; } table[pos] = value; return 0; } ## Compliant Solution This compliant solution avoids using out-of-range indices by initializing matrix elements in the same row-major order as multidimensional objects are declared in C: #ccccff c #include <stddef.h> #define COLS 5 #define ROWS 7 static int matrix[ROWS][COLS]; void init_matrix(int x) { for (size_t i = 0; i < ROWS; i++) { for (size_t j = 0; j < COLS; j++) { matrix[i][j] = x; } } } ## Compliant Solution This compliant solution avoids incrementing the pointer unless a value past the pointer's current value is known to exist: #ccccff c #include <stdlib.h> struct S { size_t len; char buf[]; /* Flexible array member */ }; const char *find(const struct S *s, int c) { const char *first = s->buf; const char *last = s->buf + s->len; while (first != last) { /* Avoid incrementing here */ if (*++first == c) { return first; } } return NULL; } void g(void) { struct S *s = (struct S *)malloc(sizeof(struct S)); if (s == NULL) { /* Handle error */ } s->len = 0; find(s, 'a'); } ## Compliant Solution  (Null Pointer Arithmetic) ## This compliant solution ensures that the call tomalloc()succeeds: #ccccff c #include <string.h> #include <stdlib.h> char *init_block(size_t block_size, size_t offset, char *data, size_t data_size) { char *buffer = malloc(block_size); if (NULL == buffer) { /* Handle error */ } if (data_size > block_size || block_size - data_size < offset) { /* Data won't fit in buffer, handle error */ } memcpy(buffer + offset, data, data_size); return buffer; }
## Risk Assessment Writing to out-of-range pointers or array subscripts can result in a buffer overflow and the execution of arbitrary code with the permissions of the vulnerable process. Reading from out-of-range pointers or array subscripts can result in unintended information disclosure. Rule Severity Likelihood Detectable Repairable Priority Level ARR30-C High Likely No No P9 L2 Automated Detection Tool Version Checker Description array-index-range array-index-range-constant null-dereferencing pointered-deallocation return-reference-local csa-stack-address-escape (C++) Partially checked Can detect all accesses to invalid pointers as well as array index out-of-bounds accesses and prove their absence. This rule is only partially checked as invalid but unused pointers may not be reported. CertC-ARR30 Can detect out-of-bound access to array / buffer PWR014 PWD004 PWD005 PWD006 PWD008 Out-of-dimension-bounds matrix access Out-of-memory-bounds array access Array range copied to or from the GPU does not cover the used range Missing deep copy of non-contiguous data to the GPU Unprotected multithreading recurrence due to out-of-dimension-bounds array access LANG.MEM.BO LANG.MEM.BU LANG.MEM.TBA LANG.MEM.TO LANG.MEM.TU LANG.STRUCT.PARITH LANG.STRUCT.PBB LANG.STRUCT.PPE BADFUNC.BO.* Buffer overrun Buffer underrun Tainted buffer access Type overrun Type underrun Pointer Arithmetic Pointer before beginning of object Pointer past end of object A collection of warning classes that report uses of library functions prone to internal buffer overflows. Compass/ROSE Could be configured to catch violations of this rule. The way to catch the noncompliant code example is to first hunt for example code that follows this pattern: for (LPWSTR pwszTemp = pwszPath + 2; *pwszTemp != L'\\'; *pwszTemp++;) In particular, the iteration variable is a pointer, it gets incremented, and the loop condition does not set an upper bound on the pointer. Once this case is handled, ROSE can handle cases like the real noncompliant code example, which is effectively the same semantics, just different syntax OVERRUN NEGATIVE_RETURNS ARRAY_VS_SINGLETON BUFFER_SIZE Can detect the access of memory past the end of a memory buffer/array Can detect when the loop bound may become negative Can detect the out-of-bound read/write to array allocated statically or dynamically Can detect buffer overflows arrayIndexOutOfBounds, outOfBounds, negativeIndex, arrayIndexThenCheck, arrayIndexOutOfBoundsCond,  possibleBufferAccessOutOfBounds arrayIndexOutOfBounds, outOfBounds, negativeIndex, arrayIndexThenCheck, arrayIndexOutOfBoundsCond,  possibleBufferAccessOutOfBounds premium-cert-arr30-c C2840 DF2820, DF2821, DF2822, DF2823, DF2840, DF2841, DF2842, DF2843, DF2930, DF2931, DF2932, DF2933, DF2935, DF2936, DF2937, DF2938, DF2950, DF2951, DF2952, DF2953 ABV.ANY_SIZE_ARRAY ABV.GENERAL ABV.GENERAL.MULTIDIMENSION ABV.NON_ARRAY ABV.STACK ABV.TAINTED ABV.UNICODE.BOUND_MAP ABV.UNICODE.FAILED_MAP ABV.UNICODE.NNTS_MAP ABV.UNICODE.SELF_MAP ABV.UNKNOWN_SIZE NNTS.MIGHT NNTS.MUST NNTS.TAINTED NPD.FUNC.CALL.MIGHT SV.TAINTED.INDEX_ACCESS SV.TAINTED.LOOP_BOUND LDRA tool suite 45 D, 47 S, 476 S, 489 S, 64 X, 66 X, 68 X, 69 X, 70 X, 71 X , 79 X Partially implemented Parasoft C/C++test CERT_C-ARR30-a Avoid accessing arrays out of bounds Parasoft Insure++ Runtime analysis 413, 415, 416, 613, 661, 662, 676 Fully supported CERT C: Rule ARR30-C Checks for: Array access out of bounds Pointer access out of bounds Array access with tainted index Use of tainted pointer Pointer dereference with tainted offset Rule partially covered. PVS-Studio V512 , V557 , V582 , V594 , V643 , V645 , V694 array-index-range-constant return-reference-local csa-stack-address-escape (C++) Partially checked arrayIndexOutOfBoundsCond assignmentInAssert autoVariables autovarInvalidDeallocation C01 C02 C03 C04 C05 C06 C07 C08 C08 C09 C10 C49 Fully Implemented index_in_address Exhaustively verified (see one compliant and one non-compliant example ). Related Vulnerabilities CVE-2008-1517 results from a violation of this rule. Before Mac OSX version 10.5.7, the XNU kernel accessed an array at an unverified user-input index, allowing an attacker to execute arbitrary code by passing an index greater than the length of the array and therefore accessing outside memory [ xorl 2009 ]. Search for vulnerabilities resulting from the violation of this rule on the CERT website .
SEI CERT C Coding Standard > 2 Rules > Rule 06. Arrays (ARR)
c
87,152,385
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152385
2
6
ARR32-C
Ensure size arguments for variable length arrays are in a valid range
Variable length arrays (VLAs), a conditionally supported language feature, are essentially the same as traditional C arrays except that they are declared with a size that is not a constant integer expression and can be declared only at block scope or function prototype scope and no linkage. When supported, a variable length array can be declared { /* Block scope */ char vla[size]; } where the integer expression size and the declaration of vla are both evaluated at runtime. If the size argument supplied to a variable length array is not a positive integer value, the behavior is undefined. (See undefined behavior 72 .)  Additionally, if the magnitude of the argument is excessive, the program may behave in an unexpected way. An attacker may be able to leverage this behavior to overwrite critical program data [ Griffiths 2006 ]. The programmer must ensure that size arguments to variable length arrays, especially those derived from untrusted data, are in a valid range. Because variable length arrays are a conditionally supported feature of C11, their use in portable code should be guarded by testing the value of the macro __STDC_NO_VLA__ . Implementations that do not support variable length arrays indicate it by setting __STDC_NO_VLA__ to the integer constant 1.
#include <stddef.h> extern void do_work(int *array, size_t size);   void func(size_t size) { int vla[size]; do_work(vla, size); } #include <stdlib.h> #include <string.h>   enum { N1 = 4096 }; void *func(size_t n2) { typedef int A[n2][N1]; A *array = malloc(sizeof(A)); if (!array) { /* Handle error */ return NULL; } for (size_t i = 0; i != n2; ++i) { memset(array[i], 0, N1 * sizeof(int)); } return array; } ## Noncompliant Code Example In this noncompliant code example, a variable length array of size size is declared. The size is declared as size_t in compliance with . #FFCCCC c #include <stddef.h> extern void do_work(int *array, size_t size); void func(size_t size) { int vla[size]; do_work(vla, size); } However, the value of size may be zero or excessive, potentially giving rise to a security vulnerability . ## Noncompliant Code Example (sizeof) The following noncompliant code example defines A to be a variable length array and then uses the sizeof operator to compute its size at runtime. When the function is called with an argument greater than SIZE_MAX / (N1 * sizeof (int)) , the runtime sizeof expression may wrap around, yielding a result that is smaller than the mathematical product N1 * n2 * sizeof (int) . The call to malloc() , when successful, will then allocate storage for fewer than n2 elements of the array, causing one or more of the final memset() calls in the for loop to write past the end of that storage. #FFCCCC c #include <stdlib.h> #include <string.h> enum { N1 = 4096 }; void *func(size_t n2) { typedef int A[n2][N1]; A *array = malloc(sizeof(A)); if (!array) { /* Handle error */ return NULL; } for (size_t i = 0; i != n2; ++i) { memset(array[i], 0, N1 * sizeof(int)); } return array; } Furthermore, this code also violates , where array is a pointer to the two-dimensional array, where it should really be a pointer to the latter dimension instead. This means that the memset() call does out-of-bounds writes on all of its invocations except the first.
#include <stdint.h> #include <stdlib.h>   enum { MAX_ARRAY = 1024 }; extern void do_work(int *array, size_t size);   void func(size_t size) { if (0 == size || SIZE_MAX / sizeof(int) < size) { /* Handle error */ return; } if (size < MAX_ARRAY) { int vla[size]; do_work(vla, size); } else { int *array = (int *)malloc(size * sizeof(int)); if (array == NULL) { /* Handle error */ } do_work(array, size); free(array); } } #include <stdint.h> #include <stdlib.h> #include <string.h> enum { N1 = 4096 }; void *func(size_t n2) { if (n2 > SIZE_MAX / (N1 * sizeof(int))) { /* Prevent sizeof wrapping */ return NULL;   } typedef int A1[N1]; typedef A1 A[n2]; A1 *array = (A1*) malloc(sizeof(A)); if (!array) { /* Handle error */ return NULL; } for (size_t i = 0; i != n2; ++i) { memset(array[i], 0, N1 * sizeof(int)); } return array; } ## Compliant Solution This compliant solution ensures the size argument used to allocate vla is in a valid range (between 1 and a programmer-defined maximum); otherwise, it uses an algorithm that relies on dynamic memory allocation. The solution also avoids unsigned integer wrapping that, given a sufficiently large value of size , would cause malloc to allocate insufficient storage for the array. #ccccff c #include <stdint.h> #include <stdlib.h> enum { MAX_ARRAY = 1024 }; extern void do_work(int *array, size_t size); void func(size_t size) { if (0 == size || SIZE_MAX / sizeof(int) < size) { /* Handle error */ return; } if (size < MAX_ARRAY) { int vla[size]; do_work(vla, size); } else { int *array = (int *)malloc(size * sizeof(int)); if (array == NULL) { /* Handle error */ } do_work(array, size); free(array); } } ## Compliant Solution (sizeof) This compliant solution prevents sizeof wrapping by detecting the condition before it occurs and avoiding the subsequent computation when the condition is detected. The code also uses an additional typedef to fix the type of array so that memset() never writes past the two-dimensional array. #ccccff c #include <stdint.h> #include <stdlib.h> #include <string.h> enum { N1 = 4096 }; void *func(size_t n2) { if (n2 > SIZE_MAX / (N1 * sizeof(int))) { /* Prevent sizeof wrapping */ return NULL; } typedef int A1[N1]; typedef A1 A[n2]; A1 *array = (A1*) malloc(sizeof(A)); if (!array) { /* Handle error */ return NULL; } for (size_t i = 0; i != n2; ++i) { memset(array[i], 0, N1 * sizeof(int)); } return array; } Implementation Details Microsoft Variable length arrays are not supported by Microsoft compilers.
## Risk Assessment Failure to properly specify the size of a variable length array may allow arbitrary code execution or result in stack exhaustion. Rule Severity Likelihood Detectable Repairable Priority Level ARR32-C High Probable No No P6 L2 Automated Detection Tool Version Checker Description variable-array-length Supported, absence of variable length arrays can be enforced using MISRA C:2023 Rule 18.8. ALLOC.SIZE.IOFLOW ALLOC.SIZE.MULOFLOW MISC.MEM.SIZE.BAD Integer Overflow of Allocation Size Multiplication Overflow of Allocation Size Unreasonable Size Argument REVERSE_NEGATIVE Fully implemented negativeArraySize negativeArraySize premium-cert-arr32-c C1051 MISRA.ARRAY.VAR_LENGTH.2012 LDRA tool suite 621 S Enhanced enforcement Parasoft C/C++test CERT_C-ARR32-a Ensure the size of the variable length array is in valid range 9035 Assistance provided CERT C: Rule ARR32-C Checks for: Memory allocation with tainted size Tainted size of variable length array Rule fully covered. variable-array-length Supported, absence of variable length arrays can be enforced using MISRA C:2023 Rule 18.8. 6.02 C101 Fully Implemented alloca_bounds Exhaustively verified. Related Vulnerabilities Search for vulnerabilities resulting from the violation of this rule on the CERT website .
SEI CERT C Coding Standard > 2 Rules > Rule 06. Arrays (ARR)
c
87,152,341
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152341
2
6
ARR36-C
Do not subtract or compare two pointers that do not refer to the same array
When two pointers are subtracted, both must point to elements of the same array object or just one past the last element of the array object (C Standard, 6.5.7 [ ISO/IEC 9899:2024 ]); the result is the difference of the subscripts of the two array elements. Otherwise, the operation is undefined behavior . (See undefined behavior 45 .) Similarly, comparing pointers using the relational operators < , <= , >= , and > gives the positions of the pointers relative to each other. Subtracting or comparing pointers that do not refer to the same array is undefined behavior. (See undefined behavior 45 and undefined behavior 50 .) Comparing pointers using the equality operators == and != has well-defined semantics regardless of whether or not either of the pointers is null, points into the same object, or points one past the last element of an array object or function.
#include <stddef.h>   enum { SIZE = 32 };   void func(void) { int nums[SIZE]; int end; int *next_num_ptr = nums; size_t free_elements; /* Increment next_num_ptr as array fills */ free_elements = &end - next_num_ptr; } ## Noncompliant Code Example In this noncompliant code example, pointer subtraction is used to determine how many free elements are left in the nums array: #ffcccc c #include <stddef.h> enum { SIZE = 32 }; void func(void) { int nums[SIZE]; int end; int *next_num_ptr = nums; size_t free_elements; /* Increment next_num_ptr as array fills */ free_elements = &end - next_num_ptr; } This program incorrectly assumes that the nums array is adjacent to the end variable in memory. A compiler is permitted to insert padding bits between these two variables or even reorder them in memory.
#include <stddef.h> enum { SIZE = 32 };   void func(void) { int nums[SIZE]; int *next_num_ptr = nums; size_t free_elements; /* Increment next_num_ptr as array fills */ free_elements = &(nums[SIZE]) - next_num_ptr; } ## Compliant Solution In this compliant solution, the number of free elements is computed by subtracting next_num_ptr from the address of the pointer past the nums array. While this pointer may not be dereferenced, it may be used in pointer arithmetic. #ccccff c #include <stddef.h> enum { SIZE = 32 }; void func(void) { int nums[SIZE]; int *next_num_ptr = nums; size_t free_elements; /* Increment next_num_ptr as array fills */ free_elements = &(nums[SIZE]) - next_num_ptr; }
## Risk Assessment Rule Severity Likelihood Detectable Repairable Priority Level ARR36-C Medium Probable No No P4 L3 Automated Detection Tool Version Checker Description pointer-subtraction pointer-comparison Partially checked CertC-ARR36 Can detect operations on pointers that are unrelated LANG.STRUCT.CUP LANG.STRUCT.SUP Comparison of Unrelated Pointers Subtraction of Unrelated Pointers MISRA C 2004 17.2 MISRA C 2004 17.3 MISRA C 2012 18.2 MISRA C 2012 18.3 Implemented Cppcheck comparePointers comparePointers C0487, C0513 DF2668, DF2669, DF2761, DF2762, DF2763, DF2766, DF2767, DF2768, DF2771, DF2772, DF2773 MISRA.PTR.ARITH LDRA tool suite 437 S, 438 S Fully implemented Parasoft C/C++test CERT_C-ARR36-a CERT_C-ARR36-b Do not subtract two pointers that do not address elements of the same array Do not compare two unrelated pointers Polyspace Bug Finder CERT C: Rule ARR36-C Checks for subtraction or comparison between pointers to different arrays (rule partially covered) PVS-Studio V736 , V782 pointer-subtraction pointer-comparison Partially checked 6.02 C24 C107 Fully Implemented differing_blocks Exhaustively verified (see the compliant and the non-compliant example ). Related Vulnerabilities Search for vulnerabilities resulting from the violation of this rule on the CERT website .
SEI CERT C Coding Standard > 2 Rules > Rule 06. Arrays (ARR)
c
87,152,085
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152085
2
6
ARR37-C
Do not add or subtract an integer to a pointer to a non-array object
Pointer arithmetic must be performed only on pointers that reference elements of array objects. The C Standard, 6.5.7 [ ISO/IEC 9899:2024 ], states the following about pointer arithmetic: When an expression that has integer type is added to or subtracted from a pointer, the result has the type of the pointer operand. If the pointer operand points to an element of an array object, and the array is large enough, the result points to an element offset from the original element such that the difference of the subscripts of the resulting and original array elements equals the integer expression.
struct numbers { short num_a, num_b, num_c; }; int sum_numbers(const struct numbers *numb){ int total = 0; const short *numb_ptr; for (numb_ptr = &numb->num_a; numb_ptr <= &numb->num_c; numb_ptr++) { total += *(numb_ptr); } return total; } int main(void) { struct numbers my_numbers = { 1, 2, 3 }; sum_numbers(&my_numbers); return 0; } ## Noncompliant Code Example This noncompliant code example attempts to access structure members using pointer arithmetic. This practice is dangerous because structure members are not guaranteed to be contiguous. #ffcccc c struct numbers { short num_a, num_b, num_c; }; int sum_numbers(const struct numbers *numb){ int total = 0; const short *numb_ptr; for (numb_ptr = &numb->num_a; numb_ptr <= &numb->num_c; numb_ptr++) { total += *(numb_ptr); } return total; } int main(void) { struct numbers my_numbers = { 1, 2, 3 }; sum_numbers(&my_numbers); return 0; }
total = numb->num_a + numb->num_b + numb->num_c; #include <stddef.h> struct numbers { short a[3]; }; int sum_numbers(const short *numb, size_t dim) { int total = 0; for (size_t i = 0; i < dim; ++i) { total += numb[i];  } return total; } int main(void) { struct numbers my_numbers = { .a[0]= 1, .a[1]= 2, .a[2]= 3}; sum_numbers( my_numbers.a, sizeof(my_numbers.a)/sizeof(my_numbers.a[0]) ); return 0; } ## Compliant Solution It is possible to use the -> operator to dereference each structure member: #ccccff c total = numb->num_a + numb->num_b + numb->num_c; However, this solution results in code that is hard to write and hard to maintain (especially if there are many more structure members), which is exactly what the author of the noncompliant code example was likely trying to avoid. ## Compliant Solution A better solution is to define the structure to contain an array member to store the numbers in an array rather than a structure, as in this compliant solution: #ccccff c #include <stddef.h> struct numbers { short a[3]; }; int sum_numbers(const short *numb, size_t dim) { int total = 0; for (size_t i = 0; i < dim; ++i) { total += numb[i]; } return total; } int main(void) { struct numbers my_numbers = { .a[0]= 1, .a[1]= 2, .a[2]= 3}; sum_numbers( my_numbers.a, sizeof(my_numbers.a)/sizeof(my_numbers.a[0]) ); return 0; } Array elements are guaranteed to be contiguous in memory, so this solution is completely portable.
## Risk Assessment Rule Severity Likelihood Detectable Repairable Priority Level ARR37-C Medium Probable Yes No P8 L2 Automated Detection Tool Version Checker Description Supported indirectly via MISRA C:2004 Rule 17.4. CertC-ARR37 Fully implemented LANG.MEM.BO LANG.MEM.BU LANG.STRUCT.PARITH LANG.STRUCT.PBB LANG.STRUCT.PPE LANG.MEM.TBA LANG.MEM.TO LANG.MEM.TU Buffer Overrun Buffer Underrun Pointer Arithmetic Pointer Before Beginning of Object Pointer Past End of Object Tainted Buffer Access Type Overrun Type Underrun Compass/ROSE ARRAY_VS_SINGLETON Implemented premium-cert-arr37-c DF2930, DF2931, DF2932, DF2933 C++3705, C++3706, C++3707 CERT.ARR.PTR.ARITH LDRA tool suite 567 S Partially implemented Parasoft C/C++test CERT_C-ARR37-a Pointer arithmetic shall not be applied to pointers that address variables of non-array type 2662 Partially supported CERT C: Rule ARR37-C Checks for invalid assumptions about memory organization (rule partially covered) Supported indirectly via MISRA C:2004 Rule 17.4. Related Vulnerabilities Search for vulnerabilities resulting from the violation of this rule on the CERT website .
SEI CERT C Coding Standard > 2 Rules > Rule 06. Arrays (ARR)
c
87,151,963
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151963
2
6
ARR38-C
Guarantee that library functions do not form invalid pointers
C library functions that make changes to arrays or objects take at least two arguments: a pointer to the array or object and an integer indicating the number of elements or bytes to be manipulated. For the purposes of this rule, the element count of a pointer is the size of the object to which it points, expressed by the number of elements that are valid to access. Supplying arguments to such a function might cause the function to form a pointer that does not point into or just past the end of the object, resulting in undefined behavior . Annex J of the C Standard [ ISO/IEC 9899:2024 ] states that it is undefined behavior if the "pointer passed to a library function array parameter does not have a value such that all address computations and object accesses are valid." (See undefined behavior 108 .) In the following code, int arr[5]; int *p = arr; unsigned char *p2 = (unsigned char *)arr; unsigned char *p3 = arr + 2; void *p4 = arr; the element count of the pointer p is sizeof(arr) / sizeof(arr[0]) , that is, 5 . The element count of the pointer p2 is sizeof(arr) , that is, 20 , on implementations where sizeof(int) == 4 . The element count of the pointer p3 is 12 on implementations where sizeof(int) == 4 , because p3 points two elements past the start of the array arr .  The element count of p4 is treated as though it were unsigned char * instead of void * , so it is the same as p2 . ## Pointer + Integer The following standard library functions take a pointer argument and a size argument, with the constraint that the pointer must point to a valid memory object of at least the number of elements indicated by the size argument. fgets() fgetws() mbstowcs() 1 wcstombs() 1 mbrtoc16() 2 mbrtoc32() 2 mbsrtowcs() 1 wcsrtombs() 1 mbtowc() 2 mbrtowc() 2 mblen() mbrlen() memchr() wmemchr() memset() wmemset() strftime() wcsftime() strxfrm() 1 wcsxfrm() 1 strncat() 2 wcsncat() 2 snprintf() vsnprintf() swprintf() vswprintf() setvbuf() tmpnam_s() snprintf_s() sprintf_s() vsnprintf_s() vsprintf_s() gets_s() getenv_s() wctomb_s() mbstowcs_s() 3 wcstombs_s() 3 memcpy_s() 3 memmove_s() 3 strncpy_s() 3 strncat_s() 3 strtok_s() 2 strerror_s() strnlen_s() asctime_s() ctime_s() snwprintf_s() swprintf_s() vsnwprintf_s() vswprintf_s() wcsncpy_s() 3 wmemcpy_s() 3 wmemmove_s() 3 wcsncat_s() 3 wcstok_s() 2 wcsnlen_s() wcrtomb_s() mbsrtowcs_s() 3 wcsrtombs_s() 3 memset_s() 4 1 Takes two pointers and an integer, but the integer specifies the element count only of the output buffer, not of the input buffer. 2 Takes two pointers and an integer, but the integer specifies the element count only of the input buffer, not of the output buffer. 3 Takes two pointers and two integers; each integer corresponds to the element count of one of the pointers. 4 Takes a pointer and two size-related integers; the first size-related integer parameter specifies the number of bytes available in the buffer; the second size-related integer parameter specifies the number of bytes to write within the buffer. For calls that take a pointer and an integer size, the given size should not be greater than the element count of the pointer. Noncompliant Code Example (Element Count) In this noncompliant code example, the incorrect element count is used in a call to wmemcpy() . The sizeof operator returns the size expressed in bytes, but wmemcpy() uses an element count based on wchar_t * . #FFcccc #include <string.h> #include <wchar.h> static const char str[] = "Hello world"; static const wchar_t w_str[] = L"Hello world"; void func(void) { char buffer[32]; wchar_t w_buffer[32]; memcpy(buffer, str, sizeof(str)); /* Compliant */ wmemcpy(w_buffer, w_str, sizeof(w_str)); /* Noncompliant */ } Compliant Solution (Element Count) When using functions that operate on pointed-to regions, programmers must always express the integer size in terms of the element count expected by the function. For example, memcpy() expects the element count expressed in terms of void * , but wmemcpy() expects the element count expressed in terms of wchar_t * .  Instead of the sizeof operator, functions that return the number of elements in the string are called, which matches the expected element count for the copy functions. In the case of this compliant solution, where the argument is an array A of type T , the expression sizeof(A) / sizeof(T) , or equivalently sizeof(A) / sizeof(*A) , can be used to compute the number of elements in the array. #ccccff #include <string.h> #include <wchar.h> static const char str[] = "Hello world"; static const wchar_t w_str[] = L"Hello world"; void func(void) { char buffer[32]; wchar_t w_buffer[32]; memcpy(buffer, str, strlen(str) + 1); wmemcpy(w_buffer, w_str, wcslen(w_str) + 1); } Noncompliant Code Example (Pointer + Integer) This noncompliant code example assigns a value greater than the number of bytes of available memory to n , which is then passed to memset() : #FFcccc #include <stdlib.h> #include <string.h> void f1(size_t nchars) { char *p = (char *)malloc(nchars); /* ... */ const size_t n = nchars + 1; /* ... */ memset(p, 0, n); } Compliant Solution (Pointer + Integer) This compliant solution ensures that the value of n is not greater than the number of bytes of the dynamic memory pointed to by the pointer p : #ccccff #include <stdlib.h> #include <string.h> void f1(size_t nchars) { char *p = (char *)malloc(nchars); /* ... */ const size_t n = nchars; /* ... */ memset(p, 0, n); } Noncompliant Code Example (Pointer + Integer) In this noncompliant code example, the element count of the array a is ARR_SIZE elements. Because memset() expects a byte count, the size of the array is scaled incorrectly by sizeof(int) instead of sizeof(long) , which can form an invalid pointer on architectures where sizeof(int) != sizeof(long) . #FFcccc #include <string.h> void f2(void) { const size_t ARR_SIZE = 4; long a[ARR_SIZE]; const size_t n = sizeof(int) * ARR_SIZE; void *p = a; memset(p, 0, n); } Compliant Solution (Pointer + Integer)
null
#include <string.h>   void f2(void) { const size_t ARR_SIZE = 4; long a[ARR_SIZE]; const size_t n = sizeof(a); void *p = a; memset(p, 0, n); } #include <string.h> void f4() { char p[40]; const char *q = "Too short"; size_t n = sizeof(p) < strlen(q) + 1 ? sizeof(p) : strlen(q) + 1; memcpy(p, q, n); } #include <stddef.h> #include <stdio.h>   void f(FILE *file) { enum { BUFFER_SIZE = 1024 }; wchar_t wbuf[BUFFER_SIZE]; const size_t size = sizeof(*wbuf); const size_t nitems = sizeof(wbuf) / size; size_t nread = fread(wbuf, size, nitems, file); /* ... */ } int dtls1_process_heartbeat(SSL *s) { unsigned char *p = &s->s3->rrec.data[0], *pl; unsigned short hbtype; unsigned int payload; unsigned int padding = 16; /* Use minimum padding */ /* Read type and payload length first */ hbtype = *p++; n2s(p, payload); pl = p; /* ... More code ... */ if (hbtype == TLS1_HB_REQUEST) { unsigned char *buffer, *bp; int r; /* * Allocate memory for the response; size is 1 byte * message type, plus 2 bytes payload length, plus * payload, plus padding. */ buffer = OPENSSL_malloc(1 + 2 + payload + padding); bp = buffer; /* Enter response type, length, and copy payload */ *bp++ = TLS1_HB_RESPONSE; s2n(payload, bp); memcpy(bp, pl, payload); /* ... More code ... */ } /* ... More code ... */ } int dtls1_process_heartbeat(SSL *s) { unsigned char *p = &s->s3->rrec.data[0], *pl; unsigned short hbtype; unsigned int payload; unsigned int padding = 16; /* Use minimum padding */ /* ... More code ... */ /* Read type and payload length first */ if (1 + 2 + 16 > s->s3->rrec.length) return 0; /* Silently discard */ hbtype = *p++; n2s(p, payload); if (1 + 2 + payload + 16 > s->s3->rrec.length) return 0; /* Silently discard per RFC 6520 */ pl = p; /* ... More code ... */ if (hbtype == TLS1_HB_REQUEST) { unsigned char *buffer, *bp; int r; /* * Allocate memory for the response; size is 1 byte * message type, plus 2 bytes payload length, plus * payload, plus padding. */ buffer = OPENSSL_malloc(1 + 2 + payload + padding); bp = buffer; /* Enter response type, length, and copy payload */ *bp++ = TLS1_HB_RESPONSE; s2n(payload, bp); memcpy(bp, pl, payload); /* ... More code ... */ } /* ... More code ... */ } ## In this compliant solution, the element count required bymemset()is properly calculated without resorting to scaling: #ccccff #include <string.h> void f2(void) { const size_t ARR_SIZE = 4; long a[ARR_SIZE]; const size_t n = sizeof(a); void *p = a; memset(p, 0, n); } ## This compliant solution ensures thatnis equal to the size of the character array: #ccccff #include <string.h> void f4() { char p[40]; const char *q = "Too short"; size_t n = sizeof(p) < strlen(q) + 1 ? sizeof(p) : strlen(q) + 1; memcpy(p, q, n); } ## This compliant solution correctly computes the maximum number of items forfread()to read from the file: #ccccff c #include <stddef.h> #include <stdio.h> void f(FILE *file) { enum { BUFFER_SIZE = 1024 }; wchar_t wbuf[BUFFER_SIZE]; const size_t size = sizeof(*wbuf); const size_t nitems = sizeof(wbuf) / size; size_t nread = fread(wbuf, size, nitems, file); /* ... */ } Noncompliant Code Example (Heartbleed) CERT vulnerability 720951 describes a vulnerability in OpenSSL versions 1.0.1 through 1.0.1f, popularly known as "Heartbleed." This vulnerability allows an attacker to steal information that under normal conditions would be protected by Secure Socket Layer/Transport Layer Security (SSL/TLS) encryption. Despite the seriousness of the vulnerability, Heartbleed is the result of a common programming error and an apparent lack of awareness of secure coding principles. Following is the vulnerable code: #ffcccc c int dtls1_process_heartbeat(SSL *s) { unsigned char *p = &s->s3->rrec.data[0], *pl; unsigned short hbtype; unsigned int payload; unsigned int padding = 16; /* Use minimum padding */ /* Read type and payload length first */ hbtype = *p++; n2s(p, payload); pl = p; /* ... More code ... */ if (hbtype == TLS1_HB_REQUEST) { unsigned char *buffer, *bp; int r; /* * Allocate memory for the response; size is 1 byte * message type, plus 2 bytes payload length, plus * payload, plus padding. */ buffer = OPENSSL_malloc(1 + 2 + payload + padding); bp = buffer; /* Enter response type, length, and copy payload */ *bp++ = TLS1_HB_RESPONSE; s2n(payload, bp); memcpy(bp, pl, payload); /* ... More code ... */ } /* ... More code ... */ } This code processes a "heartbeat" packet from a client. As specified in RFC 6520 , when the program receives a heartbeat packet, it must echo the packet's data back to the client. In addition to the data, the packet contains a length field that conventionally indicates the number of bytes in the packet data, but there is nothing to prevent a malicious packet from lying about its data length. The p pointer, along with payload and p1 , contains data from a packet. The code allocates a buffer sufficient to contain payload bytes, with some overhead, then copies payload bytes starting at p1 into this buffer and sends it to the client. Notably absent from this code are any checks that the payload integer variable extracted from the heartbeat packet corresponds to the size of the packet data. Because the client can specify an arbitrary value of payload , an attacker can cause the server to read and return the contents of memory beyond the end of the packet data, which violates . The resulting call to memcpy() can then copy the contents of memory past the end of the packet data and the packet itself, potentially exposing sensitive data to the attacker. This call to memcpy() violates . A version of ARR38-C also appears in ISO/IEC TS 17961:2013 , "Forming invalid pointers by library functions [libptr]." This rule would require a conforming analyzer to diagnose the Heartbleed vulnerability. Compliant Solution (Heartbleed) OpenSSL version 1.0.1g contains the following patch, which guarantees that payload is within a valid range. The range is limited by the size of the input record. #ccccff c int dtls1_process_heartbeat(SSL *s) { unsigned char *p = &s->s3->rrec.data[0], *pl; unsigned short hbtype; unsigned int payload; unsigned int padding = 16; /* Use minimum padding */ /* ... More code ... */ /* Read type and payload length first */ if (1 + 2 + 16 > s->s3->rrec.length) return 0; /* Silently discard */ hbtype = *p++; n2s(p, payload); if (1 + 2 + payload + 16 > s->s3->rrec.length) return 0; /* Silently discard per RFC 6520 */ pl = p; /* ... More code ... */ if (hbtype == TLS1_HB_REQUEST) { unsigned char *buffer, *bp; int r; /* * Allocate memory for the response; size is 1 byte * message type, plus 2 bytes payload length, plus * payload, plus padding. */ buffer = OPENSSL_malloc(1 + 2 + payload + padding); bp = buffer; /* Enter response type, length, and copy payload */ *bp++ = TLS1_HB_RESPONSE; s2n(payload, bp); memcpy(bp, pl, payload); /* ... More code ... */ } /* ... More code ... */ } Risk Assessment Depending on the library function called, an attacker may be able to use a heap or stack overflow vulnerability to run arbitrary code. Rule Severity Likelihood Detectable Repairable Priority Level ARR38-C High Likely No No P9 L2 Automated Detection Tool Version Checker Description stdlib-array-size stdlib-string-size strcpy-limits array_out_of_bounds Partially checked + soundly supported LANG.MEM.BO LANG.MEM.BU Buffer overrun Buffer underrun Compass/ROSE BUFFER_SIZE BAD_SIZEOF BAD_ALLOC_STRLEN BAD_ALLOC_ARITHMETIC Implemented premium-cert-arr38-c Fortify SCA 5.0 Can detect violations of this rule with CERT C Rule Pack C2840 DF2840, DF2841, DF2842, DF2843, DF2845, DF2846, DF2847, DF2848, DF2935, DF2936, DF2937, DF2938, DF4880, DF4881, DF4882, DF4883 Klocwork ABV.GENERAL ABV.GENERAL.MULTIDIMENSION LDRA tool suite 64 X, 66 X, 68 X, 69 X, 70 X, 71 X, 79 X Partially Implmented Parasoft C/C++test CERT_C-ARR38-a CERT_C-ARR38-b CERT_C-ARR38-c CERT_C-ARR38-d Avoid overflow when reading from a buffer Avoid overflow when writing to a buffer Avoid buffer overflow due to defining incorrect format limits Avoid overflow due to reading a not zero terminated string Parasoft Insure++ Runtime analysis 419, 420 Partially supported Polyspace Bug Finder CERT C: Rule ARR38-C Checks for: Mismatch between data length and size Invalid use of standard library memory routine Possible misuse of sizeof Buffer overflow from incorrect string format specifier Invalid use of standard library string routine Destination buffer overflow in string manipulation Destination buffer underflow in string manipulation Rule partially covered. 6.02 C109 Fully Implemented Splint stdlib-array-size stdlib-string-size strcpy-limits Partially checked out of bounds read Partially verified. Related Vulnerabilities CVE-2016-2208 results from a violation of this rule. The attacker can supply a value used to determine how much data is copied into a buffer via memcpy() , resulting in a buffer overlow of attacker-controlled data. Search for vulnerabilities resulting from the violation of this rule on the CERT website .
null
SEI CERT C Coding Standard > 2 Rules > Rule 06. Arrays (ARR)
c
87,152,330
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152330
2
6
ARR39-C
Do not add or subtract a scaled integer to a pointer
Pointer arithmetic is appropriate only when the pointer argument refers to an array (see ), including an array of bytes. When performing pointer arithmetic, the size of the value to add to or subtract from a pointer is automatically scaled to the size of the type of the referenced array object. Adding or subtracting a scaled integer value to or from a pointer is invalid because it may yield a pointer that does not point to an element within or one past the end of the array. (See .) Adding a pointer to an array of a type other than character to the result of the sizeof operator or offsetof macro, which returns a size and an offset, respectively, violates this rule. However, adding an array pointer to the number of array elements, for example, by using the arr[sizeof(arr)/sizeof(arr[0])]) idiom, is allowed provided that arr refers to an array and not a pointer.
enum { INTBUFSIZE = 80 }; extern int getdata(void); int buf[INTBUFSIZE];   void func(void) { int *buf_ptr = buf; while (buf_ptr < (buf + sizeof(buf))) { *buf_ptr++ = getdata(); } } #include <string.h> #include <stdlib.h> #include <stddef.h>   struct big { unsigned long long ull_a; unsigned long long ull_b; unsigned long long ull_c; int si_e; int si_f; }; void func(void) { size_t skip = offsetof(struct big, ull_b); struct big *s = (struct big *)malloc(sizeof(struct big)); if (s == NULL) { /* Handle malloc() error */ } memset(s + skip, 0, sizeof(struct big) - skip); /* ... */ free(s); s = NULL; } #include <wchar.h> #include <stdio.h>   enum { WCHAR_BUF = 128 };   void func(void) { wchar_t error_msg[WCHAR_BUF]; wcscpy(error_msg, L"Error: "); fgetws(error_msg + wcslen(error_msg) * sizeof(wchar_t), WCHAR_BUF - 7, stdin); /* ... */ } ## Noncompliant Code Example In this noncompliant code example, sizeof(buf) is added to the array buf . This example is noncompliant because sizeof(buf) is scaled by int and then scaled again when added to buf . #FFCCCC c enum { INTBUFSIZE = 80 }; extern int getdata(void); int buf[INTBUFSIZE]; void func(void) { int *buf_ptr = buf; while (buf_ptr < (buf + sizeof(buf))) { *buf_ptr++ = getdata(); } } ## Noncompliant Code Example In this noncompliant code example, skip is added to the pointer s . However, skip represents the byte offset of ull_b in struct big . When added to s , skip is scaled by the size of struct big . #FFCCCC c #include <string.h> #include <stdlib.h> #include <stddef.h> struct big { unsigned long long ull_a; unsigned long long ull_b; unsigned long long ull_c; int si_e; int si_f; }; void func(void) { size_t skip = offsetof(struct big, ull_b); struct big *s = (struct big *)malloc(sizeof(struct big)); if (s == NULL) { /* Handle malloc() error */ } memset(s + skip, 0, sizeof(struct big) - skip); /* ... */ free(s); s = NULL; } ## Noncompliant Code Example In this noncompliant code example, wcslen(error_msg) * sizeof(wchar_t) bytes are scaled by the size of wchar_t when added to error_msg : #FFCCCC c #include <wchar.h> #include <stdio.h> enum { WCHAR_BUF = 128 }; void func(void) { wchar_t error_msg[WCHAR_BUF]; wcscpy(error_msg, L"Error: "); fgetws(error_msg + wcslen(error_msg) * sizeof(wchar_t), WCHAR_BUF - 7, stdin); /* ... */ }
enum { INTBUFSIZE = 80 }; extern int getdata(void); int buf[INTBUFSIZE]; void func(void) { int *buf_ptr = buf; while (buf_ptr < (buf + INTBUFSIZE)) { *buf_ptr++ = getdata(); } } #include <string.h> #include <stdlib.h> #include <stddef.h>   struct big { unsigned long long ull_a; unsigned long long ull_b; unsigned long long ull_c; int si_d; int si_e; }; void func(void) { size_t skip = offsetof(struct big, ull_b); unsigned char *ptr = (unsigned char *)malloc( sizeof(struct big) ); if (ptr == NULL) { /* Handle malloc() error */ } memset(ptr + skip, 0, sizeof(struct big) - skip); /* ... */ free(ptr); ptr = NULL; } #include <wchar.h> #include <stdio.h> enum { WCHAR_BUF = 128 }; const wchar_t ERROR_PREFIX[7] = L"Error: "; void func(void) { const size_t prefix_len = wcslen(ERROR_PREFIX);  wchar_t error_msg[WCHAR_BUF]; wcscpy(error_msg, ERROR_PREFIX); fgetws(error_msg + prefix_len, WCHAR_BUF - prefix_len, stdin); /* ... */ } ## Compliant Solution ## This compliant solution uses an unscaled integer to obtain a pointer to the end of the array: #ccccff c enum { INTBUFSIZE = 80 }; extern int getdata(void); int buf[INTBUFSIZE]; void func(void) { int *buf_ptr = buf; while (buf_ptr < (buf + INTBUFSIZE)) { *buf_ptr++ = getdata(); } } ## Compliant Solution This compliant solution uses an unsigned char * to calculate the offset instead of using a struct big * , which would result in scaled arithmetic: #ccccff c #include <string.h> #include <stdlib.h> #include <stddef.h> struct big { unsigned long long ull_a; unsigned long long ull_b; unsigned long long ull_c; int si_d; int si_e; }; void func(void) { size_t skip = offsetof(struct big, ull_b); unsigned char *ptr = (unsigned char *)malloc( sizeof(struct big) ); if (ptr == NULL) { /* Handle malloc() error */ } memset(ptr + skip, 0, sizeof(struct big) - skip); /* ... */ free(ptr); ptr = NULL; } ## Compliant Solution This compliant solution does not scale the length of the string; wcslen() returns the number of characters and the addition to error_msg is scaled: #ccccff c #include <wchar.h> #include <stdio.h> enum { WCHAR_BUF = 128 }; const wchar_t ERROR_PREFIX[7] = L"Error: "; void func(void) { const size_t prefix_len = wcslen(ERROR_PREFIX); wchar_t error_msg[WCHAR_BUF]; wcscpy(error_msg, ERROR_PREFIX); fgetws(error_msg + prefix_len, WCHAR_BUF - prefix_len, stdin); /* ... */ }
## Risk Assessment Failure to understand and properly use pointer arithmetic can allow an attacker to execute arbitrary code. Rule Severity Likelihood Detectable Repairable Priority Level ARR39-C High Probable No No P6 L2 Automated Detection Tool Version Checker Description scaled-pointer-arithmetic Partially checked Besides direct rule violations, Astrée reports all (resulting) out-of-bound array accesses. CertC-ARR39 Fully implemented LANG.MEM.BO LANG.MEM.BU LANG.MEM.TBA LANG.MEM.TO LANG.MEM.TU LANG.STRUCT.PARITH LANG.STRUCT.PBB LANG.STRUCT.PPE Buffer overrun Buffer underrun Tainted buffer access Type overrun Type underrun Pointer Arithmetic Pointer before beginning of object Pointer past end of object BAD_SIZEOF Partially implemented premium-cert-arr39-c DF4955, DF4956, DF4957 CERT.ARR.PTR.ARITH LDRA tool suite 47 S, 489 S, 567 S, 64 X, 66 X, 68 X, 69 X, 70 X, 71 X Partially implemented Parasoft C/C++test CERT_C-ARR39-a CERT_C-ARR39-b CERT_C-ARR39-c Avoid accessing arrays out of bounds Pointer arithmetic should not be used Do not add or subtract a scaled integer to a pointer CERT C: Rule ARR39-C Checks for incorrect pointer scaling (rule fully covered). scaled-pointer-arithmetic Partially checked index_in_address Exhaustively detects undefined behavior (see one compliant and one non-compliant example ). Related Vulnerabilities Search for vulnerabilities resulting from the violation of this rule on the CERT website .
SEI CERT C Coding Standard > 2 Rules > Rule 06. Arrays (ARR)
c
87,152,303
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152303
3
14
CON01-C
Acquire and release synchronization primitives in the same module, at the same level of abstraction
All locking and unlocking of mutexes should be performed in the same module and at the same level of abstraction. Failure to follow this recommendation can lead to some lock or unlock operations not being executed by the multithreaded program as designed, eventually resulting in deadlock, race conditions, or other security vulnerabilities , depending on the mutex type. A common consequence of improper locking is for a mutex to be unlocked twice, via two calls to mtx_unlock() . This can cause the unlock operation to return errors. In the case of recursive mutexes, an error is returned only if the lock count is 0 (making the mutex available to other threads) and a call to mtx_unlock() is made.
#include <threads.h> enum { MIN_BALANCE = 50 }; int account_balance; mtx_t mp; /* Initialize mp */ int verify_balance(int amount) { if (account_balance - amount < MIN_BALANCE) { /* Handle error condition */ if (mtx_unlock(&mp) == thrd_error) { /* Handle error */ } return -1; } return 0; } void debit(int amount) { if (mtx_lock(&mp) == thrd_error) { /* Handle error */ } if (verify_balance(amount) == -1) { if (mtx_unlock(&mp) == thrd_error) { /* Handle error */ } return; } account_balance -= amount; if (mtx_unlock(&mp) == thrd_error) { /* Handle error */ } } ## Noncompliant Code Example In this noncompliant code example for a simplified multithreaded banking system, imagine an account with a required minimum balance. The code would need to verify that all debit transactions are allowable. Suppose a call is made to debit() asking to withdraw funds that would bring account_balance below MIN_BALANCE , which would result in two calls to mtx_unlock() . In this example, because the mutex is defined statically, the mutex type is implementation-defined . #ffcccc c #include <threads.h> enum { MIN_BALANCE = 50 }; int account_balance; mtx_t mp; /* Initialize mp */ int verify_balance(int amount) { if (account_balance - amount < MIN_BALANCE) { /* Handle error condition */ if (mtx_unlock(&mp) == thrd_error) { /* Handle error */ } return -1; } return 0; } void debit(int amount) { if (mtx_lock(&mp) == thrd_error) { /* Handle error */ } if (verify_balance(amount) == -1) { if (mtx_unlock(&mp) == thrd_error) { /* Handle error */ } return; } account_balance -= amount; if (mtx_unlock(&mp) == thrd_error) { /* Handle error */ } }
#include <threads.h> enum { MIN_BALANCE = 50 }; static int account_balance; static mtx_t mp; /* Initialize mp */ static int verify_balance(int amount) { if (account_balance - amount < MIN_BALANCE) { return -1; /* Indicate error to caller */ }  return 0; /* Indicate success to caller */ } int debit(int amount) { if (mtx_lock(&mp) == thrd_error) { return -1; /* Indicate error to caller */ }  if (verify_balance(amount)) { mtx_unlock(&mp); return -1; /* Indicate error to caller */ } account_balance -= amount; if (mtx_unlock(&mp) == thrd_error) { return -1; /* Indicate error to caller */ }  return 0; /* Indicate success */ } ## Compliant Solution This compliant solution unlocks the mutex only in the same module and at the same level of abstraction at which it is locked. This technique ensures that the code will not attempt to unlock the mutex twice. #ccccff c #include <threads.h> enum { MIN_BALANCE = 50 }; static int account_balance; static mtx_t mp; /* Initialize mp */ static int verify_balance(int amount) { if (account_balance - amount < MIN_BALANCE) { return -1; /* Indicate error to caller */ } return 0; /* Indicate success to caller */ } int debit(int amount) { if (mtx_lock(&mp) == thrd_error) { return -1; /* Indicate error to caller */ } if (verify_balance(amount)) { mtx_unlock(&mp); return -1; /* Indicate error to caller */ } account_balance -= amount; if (mtx_unlock(&mp) == thrd_error) { return -1; /* Indicate error to caller */ } return 0; /* Indicate success */ }
## Risk Assessment Improper use of mutexes can result in denial-of-service attacks or the unexpected termination of a multithreaded program. Recommendation Severity Likelihood Detectable Repairable Priority Level CON01-C Low Probable Yes No P4 L3
SEI CERT C Coding Standard > 3 Recommendations > Rec. 14. Concurrency (CON)
c
87,152,314
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152314
3
14
CON02-C
Do not use volatile as a synchronization primitive
The C Standard, subclause 5.1.2.3, paragraph 2 [ ISO/IEC 9899:2011 ], says: Accessing a volatile object, modifying an object, modifying a file, or calling a function that does any of those operations are all side effects, which are changes in the state of the execution environment. Evaluation of an expression in general includes both value computations and initiation of side effects. Value computation for an lvalue expression includes determining the identity of the designated object. The volatile keyword informs the compiler that the qualified variable may change in ways that cannot be determined; consequently, compiler optimizations must be restricted for memory areas marked as volatile . For example, the compiler is forbidden to load the value into a register and subsequently reuse the loaded value rather than accessing memory directly. This concept relates to multithreading because incorrect caching of a shared variable may interfere with the propagation of modified values between threads, causing some threads to view stale data. The volatile keyword is sometimes misunderstood to provide atomicity for variables that are shared between threads in a multithreaded program. Because the compiler is forbidden to either cache variables declared as volatile in registers or to reorder the sequence of reads and writes to any given volatile variable, many programmers mistakenly believe that volatile variables can correctly serve as synchronization primitives. Although the compiler is forbidden to reorder the sequence of reads and writes to a particular volatile variable, it may legally reorder these reads and writes with respect to reads and writes to other memory locations. This reordering alone is sufficient to make volatile variables unsuitable for use as synchronization primitives. Further, the volatile qualifier lacks any guarantees regarding the following desired properties necessary for a multithreaded program: Atomicity: Indivisible memory operations. Visibility: The effects of a write action by a thread are visible to other threads. Ordering: Sequences of memory operations by a thread are guaranteed to be seen in the same order by other threads. The volatile qualifier lacks guarantees for any of these properties, both by definition and by the way it is implemented in various platforms. For more information on how volatile is implemented, consult .
bool flag = false; void test() { while (!flag) { sleep(1000); } } void wakeup(){ flag = true; } void debit(unsigned int amount){ test(); account_balance -= amount; } volatile bool flag = false; void test() { while (!flag){ sleep(1000); } } void wakeup(){ flag = true; } void debit(unsigned int amount) { test(); account_balance -= amount; } ## Noncompliant Code Example ## This noncompliant code example attempts to useflagas a synchronization primitive: #ffcccc c bool flag = false; void test() { while (!flag) { sleep(1000); } } void wakeup(){ flag = true; } void debit(unsigned int amount){ test(); account_balance -= amount; } In this example, the value of flag is used to determine whether the critical section can be executed. Because the flag variable is not declared volatile , it may be cached in registers. Before the value in the register is written to memory, another thread might be scheduled to run, resulting in that thread reading stale data. ## Noncompliant Code Example ## This noncompliant code example usesflagas a synchronization primitive but qualifiesflagas avolatiletype: #ffcccc c volatile bool flag = false; void test() { while (!flag){ sleep(1000); } } void wakeup(){ flag = true; } void debit(unsigned int amount) { test(); account_balance -= amount; } Declaring flag as volatile solves the problem of values being cached, which causes stale data to be read. However, volatile flag still fails to provide the atomicity and visibility guarantees needed for synchronization primitives to work correctly. The volatile keyword does not promise to provide the guarantees needed for synchronization primitives.
#include <threads.h> int account_balance; mtx_t flag; /* Initialize flag */ int debit(unsigned int amount) { if (mtx_lock(&flag) == thrd_error) { return -1; /* Indicate error */ }  account_balance -= amount; /* Inside critical section */  if (mtx_unlock(&flag) == thrd_error) { return -1; /* Indicate error */ } return 0; } #include <Windows.h> static volatile LONG account_balance; CRITICAL_SECTION flag; /* Initialize flag */ InitializeCriticalSection(&flag);   int debit(unsigned int amount) { EnterCriticalSection(&flag);  account_balance -= amount; /* Inside critical section */ LeaveCriticalSection(&flag);   return 0; } ## Compliant Solution This code uses a mutex to protect critical sections: #ccccff c #include <threads.h> int account_balance; mtx_t flag; /* Initialize flag */ int debit(unsigned int amount) { if (mtx_lock(&flag) == thrd_error) { return -1; /* Indicate error */ } account_balance -= amount; /* Inside critical section */ if (mtx_unlock(&flag) == thrd_error) { return -1; /* Indicate error */ } return 0; } ## Compliant Solution (Critical Section, Windows) This compliant solution uses a Microsoft Windows critical section object to make operations involving account_balance atomic [ MSDN ]. #ccccff c #include <Windows.h> static volatile LONG account_balance; CRITICAL_SECTION flag; /* Initialize flag */ InitializeCriticalSection(&flag); int debit(unsigned int amount) { EnterCriticalSection(&flag); account_balance -= amount; /* Inside critical section */ LeaveCriticalSection(&flag); return 0; }
## Risk Assessment Recommendation Severity Likelihood Detectable Repairable Priority Level CON02-C Medium Probable No No P4 L3
SEI CERT C Coding Standard > 3 Recommendations > Rec. 14. Concurrency (CON)
c
87,152,036
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152036
3
14
CON03-C
Ensure visibility when accessing shared variables
Reading a shared primitive variable in one thread may not yield the value of the most recent write to the variable from another thread. Consequently, the thread may observe a stale value of the shared variable. To ensure the visibility of the most recent update, the write to the variable must happen before the read (C Standard, subclause 5.1.2.4, paragraph 18 [ ISO/IEC 9899:2011 ]). Atomic operations—other than relaxed atomic operations—trivially satisfy the happens before relationship. Where atomic operations are inappropriate, protecting both reads and writes with a mutex also satisfies the happens before relationship. ## *********** Text below this note not yet converted from Java to C! ************
final class ControlledStop implements Runnable { private boolean done = false; @Override public void run() { while (!done) { try { // ... Thread.currentThread().sleep(1000); // Do something } catch(InterruptedException ie) { Thread.currentThread().interrupt(); // Reset interrupted status } } } public void shutdown() { done = true; } } ## Noncompliant Code Example (Non-volatile Flag) ## This noncompliant code example uses ashutdown()method to set the non-volatiledoneflag that is checked in therun()method. #FFcccc final class ControlledStop implements Runnable { private boolean done = false; @Override public void run() { while (!done) { try { // ... Thread.currentThread().sleep(1000); // Do something } catch(InterruptedException ie) { Thread.currentThread().interrupt(); // Reset interrupted status } } } public void shutdown() { done = true; } } If one thread invokes the shutdown() method to set the flag, a second thread might not observe that change. Consequently, the second thread might observe that done is still false and incorrectly invoke the sleep() method. Compilers and just-in-time compilers (JITs) are allowed to optimize the code when they determine that the value of done is never modified by the same thread, resulting in an infinite loop.
final class ControlledStop implements Runnable { private volatile boolean done = false; @Override public void run() { while (!done) { try { // ... Thread.currentThread().sleep(1000); // Do something } catch(InterruptedException ie) { Thread.currentThread().interrupt(); // Reset interrupted status } } } public void shutdown() { done = true; } } final class ControlledStop implements Runnable { private final AtomicBoolean done = new AtomicBoolean(false); @Override public void run() { while (!done.get()) { try { // ... Thread.currentThread().sleep(1000); // Do something } catch(InterruptedException ie) { Thread.currentThread().interrupt(); // Reset interrupted status } } } public void shutdown() { done.set(true); } } final class ControlledStop implements Runnable { private boolean done = false; @Override public void run() { while (!isDone()) { try { // ... Thread.currentThread().sleep(1000); // Do something } catch(InterruptedException ie) { Thread.currentThread().interrupt(); // Reset interrupted status } } } public synchronized boolean isDone() { return done; } public synchronized void shutdown() { done = true; } } ## Compliant Solution (Volatile) ## In this compliant solution, thedoneflag is declared volatile to ensure that writes are visible to other threads. #ccccff final class ControlledStop implements Runnable { private volatile boolean done = false; @Override public void run() { while (!done) { try { // ... Thread.currentThread().sleep(1000); // Do something } catch(InterruptedException ie) { Thread.currentThread().interrupt(); // Reset interrupted status } } } public void shutdown() { done = true; } } ## Compliant Solution (AtomicBoolean) In this compliant solution, the done flag is declared to be of type java.util.concurrent.atomic.AtomicBoolean . Atomic types also guarantee that writes are visible to other threads. #ccccff final class ControlledStop implements Runnable { private final AtomicBoolean done = new AtomicBoolean(false); @Override public void run() { while (!done.get()) { try { // ... Thread.currentThread().sleep(1000); // Do something } catch(InterruptedException ie) { Thread.currentThread().interrupt(); // Reset interrupted status } } } public void shutdown() { done.set(true); } } ## Compliant Solution (synchronized) ## This compliant solution uses the intrinsic lock of theClassobject to ensure that updates are visible to other threads. #ccccff final class ControlledStop implements Runnable { private boolean done = false; @Override public void run() { while (!isDone()) { try { // ... Thread.currentThread().sleep(1000); // Do something } catch(InterruptedException ie) { Thread.currentThread().interrupt(); // Reset interrupted status } } } public synchronized boolean isDone() { return done; } public synchronized void shutdown() { done = true; } } While this is an acceptable compliant solution, intrinsic locks cause threads to block and may introduce contention. On the other hand, volatile-qualified shared variables do not block. Excessive synchronization can also make the program prone to deadlock. Synchronization is a more secure alternative in situations where the volatile keyword or a java.util.concurrent.atomic.Atomic* field is inappropriate, such as when a variable's new value depends on its current value. See rule for more information. Compliance with rule can reduce the likelihood of misuse by ensuring that untrusted callers cannot access the lock object.
## Risk Assessment Rule Severity Likelihood Detectable Repairable Priority Level CON03-C Medium Probable No No P4 L3 Automated Detection Tool Version Checker Description Supported, but no explicit checker C1765 C1766
SEI CERT C Coding Standard > 3 Recommendations > Rec. 14. Concurrency (CON)
c
87,152,305
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152305
3
14
CON04-C
Join or detach threads even if their exit status is unimportant
The thrd_detach() function is used to tell the underlying system that resources allocated to a particular thread can be reclaimed once it terminates. This function should be used when a thread's exit status is not required by other threads (and no other thread needs to use thrd_join() to wait for it to complete). Whenever a thread terminates without detaching, the thread's stack is deallocated, but some other resources, including the thread ID and exit status, are left until it is destroyed by either thrd_join() or thrd_detach() . These resources can be vital for systems with limited resources and can lead to various "resource unavailable" errors, depending on which critical resource gets used up first. For example, if the system has a limit (either per-process or system wide) on the number of thread IDs it can keep track of, failure to release the thread ID of a terminated thread may lead to thrd_create() being unable to create another thread.
#include <stdio.h> #include <threads.h>   const size_t thread_no = 5; const char mess[] = "This is a test"; int message_print(void *ptr){ const char *msg = (const char *) ptr; printf("THREAD: This is the Message %s\n", msg); return 0; } int main(void){ /* Create a pool of threads */ thrd_t thr[thread_no]; for (size_t i = 0; i < thread_no; ++i) { if (thrd_create(&(thr[i]), message_print, (void *)mess) != thrd_success) { fprintf(stderr, "Creation of thread %zu failed\n", i); /* Handle error */ } } printf("MAIN: Thread Message: %s\n", mess); return 0; } ## Noncompliant Code Example ## This noncompliant code example shows a pool of threads that are not exited correctly: #FFcccc c #include <stdio.h> #include <threads.h> const size_t thread_no = 5; const char mess[] = "This is a test"; int message_print(void *ptr){ const char *msg = (const char *) ptr; printf("THREAD: This is the Message %s\n", msg); return 0; } int main(void){ /* Create a pool of threads */ thrd_t thr[thread_no]; for (size_t i = 0; i < thread_no; ++i) { if (thrd_create(&(thr[i]), message_print, (void *)mess) != thrd_success) { fprintf(stderr, "Creation of thread %zu failed\n", i); /* Handle error */ } } printf("MAIN: Thread Message: %s\n", mess); return 0; }
#include <stdio.h> #include <threads.h>   const size_t thread_no = 5; const char mess[] = "This is a test"; int message_print(void *ptr){ const char *msg = (const char *)ptr; printf("THREAD: This is the Message %s\n", msg);   /* Detach the thread, check the return code for errors */ if (thrd_detach(thrd_current()) != thrd_success) { /* Handle error */ } return 0; } int main(void) { /* Create a pool of threads */ thrd_t thr[thread_no]; for(size_t i = 0; i < thread_no; ++i) { if (thrd_create(&(thr[i]), message_print, (void *)mess) != thrd_success) { fprintf(stderr, "Creation of thread %zu failed\n", i); /* Handle error */ } } printf("MAIN: Thread Message: %s\n", mess); return 0; } ## Compliant Solution In this compliant solution, the message_print() function is replaced by a similar function that correctly detaches the threads so that the associated resources can be reclaimed on exit: #ccccff c #include <stdio.h> #include <threads.h> const size_t thread_no = 5; const char mess[] = "This is a test"; int message_print(void *ptr){ const char *msg = (const char *)ptr; printf("THREAD: This is the Message %s\n", msg); /* Detach the thread, check the return code for errors */ if (thrd_detach(thrd_current()) != thrd_success) { /* Handle error */ } return 0; } int main(void) { /* Create a pool of threads */ thrd_t thr[thread_no]; for(size_t i = 0; i < thread_no; ++i) { if (thrd_create(&(thr[i]), message_print, (void *)mess) != thrd_success) { fprintf(stderr, "Creation of thread %zu failed\n", i); /* Handle error */ } } printf("MAIN: Thread Message: %s\n", mess); return 0; }
## Risk Assessment Recommendation Severity Likelihood Detectable Repairable Priority Level CON04-C Low Unlikely Yes No P2 L3 Related Vulnerabilities Search for vulnerabilities resulting from the violation of this rule on the CERT website .
SEI CERT C Coding Standard > 3 Recommendations > Rec. 14. Concurrency (CON)
c
87,151,981
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151981
3
14
CON05-C
Do not perform operations that can block while holding a lock
If a lock is being held and an operation that can block is performed, any other thread that needs to acquire that lock may also block. This condition can degrade system performance or cause a deadlock to occur.  Blocking calls include, but are not limited to, network, file, and console I/O. Using a blocking operation while holding a lock may be unavoidable for a portable solution. For instance, file access could be protected via a lock to prevent multiple threads from mutating the contents of the file. Or, a thread may be required to block while holding one or more locks and waiting to acquire another lock. In these cases, attempt to hold the lock for the least time required. Additionally, if acquiring multiple locks, the order of locking must avoid deadlock, as specified in .
#include <stdio.h> #include <threads.h>   mtx_t mutex; int thread_foo(void *ptr) { int result; FILE *fp; if ((result = mtx_lock(&mutex)) != thrd_success) { /* Handle error */ }   fp = fopen("SomeNetworkFile", "r"); if (fp != NULL) { /* Work with the file */ fclose(fp); }   if ((result = mtx_unlock(&mutex)) != thrd_success) { /* Handle error */ } return 0; } int main(void) { thrd_t thread; int result; if ((result = mtx_init(&mutex, mtx_plain)) != thrd_success) { /* Handle error */ } if (thrd_create(&thread, thread_foo, NULL) != thrd_success) { /* Handle error */ } /* ... */ if (thrd_join(thread, NULL) != thrd_success) { /* Handle error */ } mtx_destroy(&mutex); return 0; } ## Noncompliant Code Example This noncompliant example calls fopen() while a mutex is locked. The calls to fopen() and fclose() are blocking and may block for an extended period of time if the file resides on a network drive. While the call is blocked, other threads that are waiting for the lock are also blocked. #ffcccc c #include <stdio.h> #include <threads.h> mtx_t mutex; int thread_foo(void *ptr) { int result; FILE *fp; if ((result = mtx_lock(&mutex)) != thrd_success) { /* Handle error */ } fp = fopen("SomeNetworkFile", "r"); if (fp != NULL) { /* Work with the file */ fclose(fp); } if ((result = mtx_unlock(&mutex)) != thrd_success) { /* Handle error */ } return 0; } int main(void) { thrd_t thread; int result; if ((result = mtx_init(&mutex, mtx_plain)) != thrd_success) { /* Handle error */ } if (thrd_create(&thread, thread_foo, NULL) != thrd_success) { /* Handle error */ } /* ... */ if (thrd_join(thread, NULL) != thrd_success) { /* Handle error */ } mtx_destroy(&mutex); return 0; }
#include <stdio.h> #include <threads.h>   mtx_t mutex;   int thread_foo(void *ptr) { int result; FILE *fp = fopen("SomeNetworkFile", "r");   if (fp != NULL) { /* Work with the file */ fclose(fp); } if ((result = mtx_lock(&mutex)) != thrd_success) { /* Handle error */ } /* ... */ if ((result = pthread_mutex_unlock(&mutex)) != 0) { /* Handle error */ } return 0; } ## Compliant Solution (Block while Not Locked) This compliant solution performs the file operations when the lock has not been acquired. The blocking behavior consequently affects only the thread that called the blocking function. #ccccff c #include <stdio.h> #include <threads.h> mtx_t mutex; int thread_foo(void *ptr) { int result; FILE *fp = fopen("SomeNetworkFile", "r"); if (fp != NULL) { /* Work with the file */ fclose(fp); } if ((result = mtx_lock(&mutex)) != thrd_success) { /* Handle error */ } /* ... */ if ((result = pthread_mutex_unlock(&mutex)) != 0) { /* Handle error */ } return 0; }
## Risk Assessment Blocking or lengthy operations performed within synchronized regions could result in a deadlocked or an unresponsive system. Recommendation Severity Likelihood Detectable Repairable Priority Level CON05-C Low Probable No No P2 L3 Automated Detection Tool Version Checker Description CONCURRENCY.STARVE.BLOCKING Blocking in critical section CONC.SLEEP Parasoft C/C++test CERT_C-CON05-a Do not use blocking functions while holding a lock CERT C: Rec. CON05-C Checks for blocking operation while holding lock (Rec. partially covered) 6.02 C12 Fully Implemented Related Vulnerabilities Search for vulnerabilities resulting from the violation of this rule on the CERT website .
SEI CERT C Coding Standard > 3 Recommendations > Rec. 14. Concurrency (CON)
c
87,151,935
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151935
3
14
CON06-C
Ensure that every mutex outlives the data it protects
## ********** Text below this note not yet converted from Java to C! ************ Programs must not use instance locks to protect static shared data because instance locks are ineffective when two or more instances of the class are created. Consequently, failure to use a static lock object leaves the shared state unprotected against concurrent access. Lock objects for classes that can interact with untrusted code must also be private and final, as shown in rule LCK00-J. Use private final lock objects to synchronize classes that may interact with untrusted code .
## Noncompliant Code Example (Nonstatic Lock Object for Static Data) This noncompliant code example attempts to guard access to the static counter field using a non-static lock object. When two Runnable tasks are started, they create two instances of the lock object and lock on each instance separately. public final class CountBoxes implements Runnable { private static volatile int counter; // ... private final Object lock = new Object(); @Override public void run() { synchronized (lock) { counter++; // ... } } public static void main(String[] args) { for ( int i = 0 ; i < 2 ; i++) { new Thread( new CountBoxes()).start(); } } } This example fails to prevent either thread from observing an inconsistent value of counter because the increment operation on volatile fields fails to be atomic in the absence of proper synchronization. (See rule VNA02-J. Ensure that compound operations on shared variables are atomic for more information.) ## Noncompliant Code Example (Method Synchronization for Static Data) ## This noncompliant code example uses method synchronization to protect access to a static classcounterfield. public final class CountBoxes implements Runnable { private static volatile int counter; // ... public synchronized void run() { counter++; // ... } // ... } In this case, the method synchronization uses the intrinsic lock associated with each instance of the class rather than the intrinsic lock associated with the class itself. Consequently, threads constructed using different Runnable instances may observe inconsistent values of counter .
## Compliant Solution (Static Lock Object) ## This compliant solution ensures the atomicity of the increment operation by locking on a static object. public class CountBoxes implements Runnable { private static int counter; // ... private static final Object lock = new Object(); public void run() { synchronized (lock) { counter++; // ... } } // ... } It is unnecessary to declare the counter variable volatile when using synchronization.
## Risk Assessment Using an instance lock to protect static shared data can result in nondeterministic behavior. Rule Severity Likelihood Detectable Repairable Priority Level CON06-C Medium Probable No No P4 L3 Automated Detection Tool Version Checker Description Supported, but no explicit checker
SEI CERT C Coding Standard > 3 Recommendations > Rec. 14. Concurrency (CON)
c
87,151,920
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151920
3
14
CON07-C
Ensure that compound operations on shared variables are atomic
Compound operations are operations that consist of more than one discrete operation. Expressions that include postfix or prefix increment ( ++ ), postfix or prefix decrement ( -- ), or compound assignment operators always result in compound operations. Compound assignment expressions use operators such as *= , /= , %= , += , -= , <<= , >>= , ^= , and |= . Compound operations on shared variables must be performed atomically to prevent data races . Noncompliant Code Example (Logical Negation) This noncompliant code example declares a shared _Bool flag variable and provides a toggle_flag() method that negates the current value of flag : #FFCCCC c #include <stdbool.h> static bool flag = false; void toggle_flag(void) { flag = !flag; } bool get_flag(void) { return flag; } Execution of this code may result in a data race because the value of flag is read, negated, and written back. Consider, for example, two threads that call toggle_flag() . The expected effect of toggling flag twice is that it is restored to its original value. However, the following scenario leaves flag in the incorrect state: Time flag= Thread Action 1 true t 1 Reads the current value of flag , true , into a cache 2 true t 2 Reads the current value of flag , (still) true , into a different cache 3 true t 1 Toggles the temporary variable in the cache to false 4 true t 2 Toggles the temporary variable in the different cache to false 5 false t 1 Writes the cache variable's value to flag 6 false t 2 Writes the different cache variable's value to flag As a result, the effect of the call by t 2 is not reflected in flag ; the program behaves as if toggle_flag() was called only once, not twice. Compliant Solution (Mutex) This compliant solution restricts access to flag under a mutex lock: #ccccff c #include <threads.h> #include <stdbool.h> static bool flag = false; mtx_t flag_mutex; /* Initialize flag_mutex */ bool init_mutex(int type) { /* Check mutex type */ if (thrd_success != mtx_init(&flag_mutex, type)) { return false; /* Report error */ } return true; } void toggle_flag(void) { if (thrd_success != mtx_lock(&flag_mutex)) { /* Handle error */ } flag = !flag; if (thrd_success != mtx_unlock(&flag_mutex)) { /* Handle error */ } } bool get_flag(void) { bool temp_flag; if (thrd_success != mtx_lock(&flag_mutex)) { /* Handle error */ } temp_flag = flag; if (thrd_success != mtx_unlock(&flag_mutex)) { /* Handle error */ } return temp_flag; } This solution guards reads and writes to the flag field with a lock on the flag_mutex . This lock ensures that changes to flag are visible to all threads. Now, only two execution orders are possible. In one execution order, t 1 obtains the mutex and completes the operation before t 2 can acquire the mutex, as shown here: Time flag= Thread Action 1 true t 1 Reads the current value of flag , true , into a cache variable 2 true t 1 Toggles the cache variable to false 3 false t 1 Writes the cache variable's value to flag 4 false t 2 Reads the current value of flag , false , into a different cache variable 5 false t 2 Toggles the different cache variable to true 6 true t 2 Writes the different cache variable's value to flag The other execution order is similar, except that t 2 starts and finishes before t 1 . Compliant Solution ( atomic_compare_exchange_weak() ) This compliant solution uses atomic variables and a compare-and-exchange operation to guarantee that the correct value is stored in flag . All updates are visible to other threads. #ccccff c #include <stdatomic.h> #include <stdbool.h> static atomic_bool flag; void init_flag(void) { atomic_init(&flag, false); } void toggle_flag(void) { bool old_flag = atomic_load(&flag); bool new_flag; do { new_flag = !old_flag; } while (!atomic_compare_exchange_weak(&flag, &old_flag, new_flag)); } bool get_flag(void) { return atomic_load(&flag); } An alternative solution is to use the atomic_flag data type for managing Boolean values atomically. Noncompliant Code Example (Addition of Primitives) In this noncompliant code example, multiple threads can invoke the set_values() method to set the a and b fields. Because this code fails to test for integer overflow, users of this code must also ensure that the arguments to the set_values() method can be added without overflow (see for more information). #FFCCCC c static int a; static int b; int get_sum(void) { return a + b; } void set_values(int new_a, int new_b) { a = new_a; b = new_b; } The get_sum() method contains a race condition. For example, when a and b currently have the values 0 and INT_MAX , respectively, and one thread calls get_sum() while another calls set_values(INT_MAX, 0) , the get_sum() method might return either 0 or INT_MAX , or it might overflow. Overflow will occur when the first thread reads a and b after the second thread has set the value of a to INT_MAX but before it has set the value of b to 0 . Noncompliant Code Example (Addition of Atomic Integers) In this noncompliant code example, a and b are replaced with atomic integers. #FFCCCC c #include <stdatomic.h> static atomic_int a; static atomic_int b; void init_ab(void) { atomic_init(&a, 0); atomic_init(&b, 0); } int get_sum(void) { return atomic_load(&a) + atomic_load(&b); } void set_values(int new_a, int new_b) { atomic_store(&a, new_a); atomic_store(&b, new_b); } The simple replacement of the two int fields with atomic integers fails to eliminate the race condition in the sum because the compound operation a.get() + b.get() is still non-atomic. While a sum of some value of a and some value of b will be returned, there is no guarantee that this value represents the sum of the values of a and b at any particular moment. Compliant Solution ( _Atomic struct ) This compliant solution uses an atomic struct, which guarantees that both numbers are read and written together. #ccccff c #include <stdatomic.h> static _Atomic struct ab_s { int a, b; } ab; void init_ab(void) { struct ab_s new_ab = {0, 0}; atomic_init(&ab, new_ab); } int get_sum(void) { struct ab_s new_ab = atomic_load(&ab); return new_ab.a + new_ab.b; } void set_values(int new_a, int new_b) { struct ab_s new_ab = {new_a, new_b}; atomic_store(&ab, new_ab); } On most modern platforms, this will compile to be lock-free. Compliant Solution (Mutex) This compliant solution protects the set_values() and get_sum() methods with a mutex to ensure atomicity: #ccccff c #include <threads.h> #include <stdbool.h> static int a; static int b; mtx_t flag_mutex; /* Initialize everything */ bool init_all(int type) { /* Check mutex type */ a = 0; b = 0; if (thrd_success != mtx_init(&flag_mutex, type)) { return false; /* Report error */ } return true; } int get_sum(void) { if (thrd_success != mtx_lock(&flag_mutex)) { /* Handle error */ } int sum = a + b; if (thrd_success != mtx_unlock(&flag_mutex)) { /* Handle error */ } return sum; } void set_values(int new_a, int new_b) { if (thrd_success != mtx_lock(&flag_mutex)) { /* Handle error */ } a = new_a; b = new_b; if (thrd_success != mtx_unlock(&flag_mutex)) { /* Handle error */ } } Thanks to the mutex, it is now possible to add overflow checking to the get_sum() function without introducing the possibility of a race condition. Risk Assessment When operations on shared variables are not atomic, unexpected results can be produced. For example, information can be disclosed inadvertently because one user can receive information about other users. Rule Severity Likelihood Detectable Repairable Priority Level CON07-C Medium Probable Yes No P8 L2 Automated Detection Tool Version Checker Description PWD002 Unprotected multithreading reduction operation CONCURRENCY.DATARACE Data Race C1765 C1114 C1115 C1116 Related Guidelines CERT Oracle Secure Coding Standard for Java MITRE CWE CWE-366 , Race condition within a thread CWE-413, Improper resource locking CWE-567, Unsynchronized access to shared data in a multithreaded context CWE-667 , Improper locking Bibliography [ ISO/IEC 14882:2011 ] Subclause 7.17, "Atomics"
null
null
null
SEI CERT C Coding Standard > 3 Recommendations > Rec. 14. Concurrency (CON)
c
87,151,947
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151947
3
14
CON08-C
Do not assume that a group of calls to independently atomic methods is atomic
A consistent locking policy guarantees that multiple threads cannot simultaneously access or modify shared data. When two or more operations must be performed as a single atomic operation, a consistent locking policy must be implemented using some form of locking, such as a mutex. In the absence of such a policy, the code is susceptible to race conditions. When presented with a set of operations, where each is guaranteed to be atomic, it is tempting to assume that a single operation consisting of individually-atomic operations is guaranteed to be collectively atomic without additional locking. A grouping of calls to such methods requires additional synchronization for the group. Compound operations on shared variables are also non-atomic. See for more information. Noncompliant Code Example This noncompliant code example stores two integers atomically. It also provides atomic methods to obtain their sum and product. All methods are locked with the same mutex to provide their atomicity. #ffcccc c #include <threads.h> #include <stdio.h> #include <stdbool.h> static int a = 0; static int b = 0; mtx_t lock; bool init_mutex(int type) { /* Validate type */ if (thrd_success != mtx_init(&lock, type)) { return false; /* Report error */ } return true; } void set_values(int new_a, int new_b) { if (thrd_success != mtx_lock(&lock)) { /* Handle error */ } a = new_a; b = new_b; if (thrd_success != mtx_unlock(&lock)) { /* Handle error */ } } int get_sum(void) { if (thrd_success != mtx_lock(&lock)) { /* Handle error */ } int sum = a + b; if (thrd_success != mtx_unlock(&lock)) { /* Handle error */ } return sum; } int get_product(void) { if (thrd_success != mtx_lock(&lock)) { /* Handle error */ } int product = a * b; if (thrd_success != mtx_unlock(&lock)) { /* Handle error */ } return product; } /* Can be called by multiple threads */ void multiply_monomials(int x1, int x2) { printf("(x + %d)(x + %d)\n", x1, x2); set_values( x1, x2); printf("= x^2 + %dx + %d\n", get_sum(), get_product()); } Unfortunately, the multiply_monomials() function is still subject to race conditions, despite relying exclusively on atomic function calls. It is quite possible for get_sum() and get_product() to work with different numbers than the ones that were set by set_values() . It is even possible for get_sum() to operate with different numbers than get_product() . Compliant Solution This compliant solution locks the multiply_monomials() function with the same mutex lock that is used by the other functions. For this code to work, the mutex must be recursive. This is accomplished by making it recursive in the init_mutex() function. #ccccff c #include <threads.h> #include <stdio.h> #include <stdbool.h> extern void set_values(int, int); extern int get_sum(void); extern int get_product(void); mtx_t lock; bool init_mutex(int type) { /* Validate type */ if (thrd_success != mtx_init(&lock, type | mtx_recursive)) { return false; /* Report error */ } return true; } /* Can be called by multiple threads */ void multiply_monomials(int x1, int x2) { if (thrd_success != mtx_lock(&lock)) { /* Handle error */ } set_values( x1, x2); int sum = get_sum(); int product = get_product(); if (thrd_success != mtx_unlock(&lock)) { /* Handle error */ } printf("(x + %d)(x + %d)\n", x1, x2); printf("= x^2 + %dx + %d\n", sum, product); } Noncompliant Code Example Function chaining is a useful design pattern for building an object and setting its optional fields. The output of one function serves as an argument (typically the last) in the next function. However, if accessed concurrently, a thread may observe shared fields to contain inconsistent values. This noncompliant code example demonstrates a race condition that can occur when multiple threads can variables with no thread protection. #FFcccc c #include <threads.h> #include <stdio.h> typedef struct currency_s { int quarters; int dimes; int nickels; int pennies; } currency_t; currency_t *set_quarters(int quantity, currency_t *currency) { currency->quarters += quantity; return currency; } currency_t *set_dimes(int quantity, currency_t *currency) { currency->dimes += quantity; return currency; } currency_t *set_nickels(int quantity, currency_t *currency) { currency->nickels += quantity; return currency; } currency_t *set_pennies(int quantity, currency_t *currency) { currency->pennies += quantity; return currency; } int init_45_cents(void *currency) { currency_t *c = set_quarters(1, set_dimes(2, currency)); /* Validate values are correct */ return 0; } int init_60_cents(void* currency) { currency_t *c = set_quarters(2, set_dimes(1, currency)); /* Validate values are correct */ return 0; } int main(void) { thrd_t thrd1; thrd_t thrd2; currency_t currency = {0, 0, 0, 0}; if (thrd_success != thrd_create(&thrd1, init_45_cents, ¤cy)) { /* Handle error */ } if (thrd_success != thrd_create(&thrd2, init_60_cents, ¤cy)) { /* Handle error */ } if (thrd_success != thrd_join(thrd1, NULL)) { /* Handle error */ } if (thrd_success != thrd_join(thrd2, NULL)) { /* Handle error */ } printf("%d quarters, %d dimes, %d nickels, %d pennies\n", currency.quarters, currency.dimes, currency.nickels, currency.pennies); return 0; } In this noncompliant code example, the program constructs a currency struct and starts two threads that use method chaining to set the optional values of the structure. This example code might result in the currency struct being left in an inconsistent state, for example, with two quarters and one dime or one quarter and two dimes. Noncompliant Code Example This code remains unsafe even if it uses a mutex on the set functions to guard modification of the currency: #FFcccc c #include <threads.h> #include <stdio.h> typedef struct currency_s { int quarters; int dimes; int nickels; int pennies; mtx_t lock; } currency_t; currency_t *set_quarters(int quantity, currency_t *currency) { if (thrd_success != mtx_lock(¤cy->lock)) { /* Handle error */ } currency->quarters += quantity; if (thrd_success != mtx_unlock(¤cy->lock)) { /* Handle error */ } return currency; } currency_t *set_dimes(int quantity, currency_t *currency) { if (thrd_success != mtx_lock(¤cy->lock)) { /* Handle error */ } currency->dimes += quantity; if (thrd_success != mtx_unlock(¤cy->lock)) { /* Handle error */ } return currency; } currency_t *set_nickels(int quantity, currency_t *currency) { if (thrd_success != mtx_lock(¤cy->lock)) { /* Handle error */ } currency->nickels += quantity; if (thrd_success != mtx_unlock(¤cy->lock)) { /* Handle error */ } return currency; } currency_t *set_pennies(int quantity, currency_t *currency) { if (thrd_success != mtx_lock(¤cy->lock)) { /* Handle error */ } currency->pennies += quantity; if (thrd_success != mtx_unlock(¤cy->lock)) { /* Handle error */ } return currency; } int init_45_cents(void *currency) { currency_t *c = set_quarters(1, set_dimes(2, currency)); /* Validate values are correct */ return 0; } int init_60_cents(void* currency) { currency_t *c = set_quarters(2, set_dimes(1, currency)); /* Validate values are correct */ return 0; } int main(void) { int result; thrd_t thrd1; thrd_t thrd2; currency_t currency = {0, 0, 0, 0}; if (thrd_success != mtx_init(¤cy.lock, mtx_plain)) { /* Handle error */ } if (thrd_success != thrd_create(&thrd1, init_45_cents, ¤cy)) { /* Handle error */ } if (thrd_success != thrd_create(&thrd2, init_60_cents, ¤cy)) { /* Handle error */ } if (thrd_success != thrd_join(thrd1, NULL)) { /* Handle error */ } if (thrd_success != thrd_join(thrd2, NULL)) { /* Handle error */ } printf("%d quarters, %d dimes, %d nickels, %d pennies\n", currency.quarters, currency.dimes, currency.nickels, currency.pennies); mtx_destroy( ¤cy.lock); return 0; } Compliant Solution This compliant solution uses a mutex, but instead of guarding the set functions, it guards the init functions, which are invoked at thread creation. #ccccff c #include <threads.h> #include <stdio.h> typedef struct currency_s { int quarters; int dimes; int nickels; int pennies; mtx_t lock; } currency_t; currency_t *set_quarters(int quantity, currency_t *currency) { currency->quarters += quantity; return currency; } currency_t *set_dimes(int quantity, currency_t *currency) { currency->dimes += quantity; return currency; } currency_t *set_nickels(int quantity, currency_t *currency) { currency->nickels += quantity; return currency; } currency_t *set_pennies(int quantity, currency_t *currency) { currency->pennies += quantity; return currency; } int init_45_cents(void *currency) { currency_t *c = (currency_t *)currency; if (thrd_success != mtx_lock(&c->lock)) { /* Handle error */ } set_quarters(1, set_dimes(2, currency)); if (thrd_success != mtx_unlock(&c->lock)) { /* Handle error */ } return 0; } int init_60_cents(void *currency) { currency_t *c = (currency_t *)currency; if (thrd_success != mtx_lock(&c->lock)) { /* Handle error */ } set_quarters(2, set_dimes(1, currency)); if (thrd_success != mtx_unlock(&c->lock)) { /* Handle error */ } return 0; } int main(void) { int result; thrd_t thrd1; thrd_t thrd2; currency_t currency = {0, 0, 0, 0}; if (thrd_success != mtx_init(¤cy.lock, mtx_plain)) { /* Handle error */ } if (thrd_success != thrd_create(&thrd1, init_45_cents, ¤cy)) { /* Handle error */ } if (thrd_success != thrd_create(&thrd2, init_60_cents, ¤cy)) { /* Handle error */ } if (thrd_success != thrd_join(thrd1, NULL)) { /* Handle error */ } if (thrd_success != thrd_join(thrd2, NULL)) { /* Handle error */ } printf("%d quarters, %d dimes, %d nickels, %d pennies\n", currency.quarters, currency.dimes, currency.nickels, currency.pennies); mtx_destroy(¤cy.lock); return 0; } Consequently this compliant solution is thread-safe, and will always print out the same number of quarters as dimes. Risk Assessment Failure to ensure the atomicity of two or more operations that must be performed as a single atomic operation can result in race conditions in multithreaded applications. Rule Severity Likelihood Detectable Repairable Priority Level CON08-C Low Probable No No P2 L3 Related Guidelines CERT Oracle Secure Coding Standard for Java VNA03-J. Do not assume that a group of calls to independently atomic methods is atomic VNA04-J. Ensure that calls to chained methods are atomic MITRE CWE CWE-362 , Concurrent execution using shared resource with improper synchronization ("race condition") CWE-366, Race condition within a thread CWE-662 , Improper synchronization Bibliography [ ISO/IEC 9899:2011 ] Subclause 7.26, "Threads <threads.h>"
null
null
null
SEI CERT C Coding Standard > 3 Recommendations > Rec. 14. Concurrency (CON)
c
87,151,982
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87151982
3
14
CON09-C
Avoid the ABA problem when using lock-free algorithms
Lock-free programming is a technique that allows concurrent updates of shared data structures without using explicit locks. This method ensures that no threads block for arbitrarily long times, and it thereby boosts performance. Lock-free programming has the following advantages: Can be used in places where locks must be avoided, such as interrupt handlers Efficiency benefits compared to lock-based algorithms for some workloads, including potential scalability benefits on multiprocessor machines Avoidance of priority inversion in real-time systems Lock-free programming requires the use of special atomic processor instructions, such as CAS (compare and swap), LL/SC (load linked/store conditional), or the C Standard atomic_compare_exchange generic functions. Applications for lock-free programming include Read-copy-update€ (RCU) in Linux 2.5 kernel Lock-free programming on AMD multicore systems The ABA problem occurs during synchronization: a memory location is read twice and has the same value for both reads. However, another thread has modified the value, performed other work, then modified the value back between the two reads, thereby tricking the first thread into thinking that the value never changed.
#include <stdatomic.h>   /* * Sets index to point to index of maximum element in array * and value to contain maximum array value.  */ void find_max_element(atomic_int array[], size_t *index, int *value); static atomic_int array[]; void func(void) { size_t index; int value; find_max_element(array, &index, &value); /* ... */ if (!atomic_compare_exchange_strong(array[index], &value, 0)) { /* Handle error */ } } #include <glib.h> #include <glib-object.h> typedef struct node_s { void *data; Node *next; } Node; typedef struct queue_s { Node *head; Node *tail; } Queue; Queue* queue_new(void) { Queue *q = g_slice_new(sizeof(Queue)); q->head = q->tail = g_slice_new(sizeof(Node)); return q; } void queue_enqueue(Queue *q, gpointer data) { Node *node; Node *tail; Node *next; node = g_slice_new(Node); node->data = data; node->next = NULL; while (TRUE) { tail = q->tail; next = tail->next; if (tail != q->tail) { continue; } if (next != NULL) { CAS(&q->tail, tail, next); continue; } if (CAS(&tail->next, NULL, node)) { break; } } CAS(&q->tail, tail, node); } gpointer queue_dequeue(Queue *q) { Node *node; Node *head; Node *tail; Node *next; gpointer data; while (TRUE) { head = q->head; tail = q->tail; next = head->next; if (head != q->head) { continue; } if (next == NULL) { return NULL; /* Empty */ } if (head == tail) { CAS(&q->tail, tail, next); continue; } data = next->data; if (CAS(&q->head, head, next)) { break; } } g_slice_free(Node, head); return data; } ## Noncompliant Code Example This noncompliant code example attempts to zero the maximum element of an array. The example is assumed to run in a multithreaded environment, where all variables are accessed by other threads. #ffcccc c #include <stdatomic.h> /* * Sets index to point to index of maximum element in array * and value to contain maximum array value. */ void find_max_element(atomic_int array[], size_t *index, int *value); static atomic_int array[]; void func(void) { size_t index; int value; find_max_element(array, &index, &value); /* ... */ if (!atomic_compare_exchange_strong(array[index], &value, 0)) { /* Handle error */ } } The compare-and-swap operation sets array[index] to 0 if and only if it is currently set to value . However, this code does not necessarily zero out the maximum value of the array because index may have changed. value may have changed (that is, the value of the value variable). value may no longer be the maximum value in the array. ## Noncompliant Code Example (GNU Glib) This code implements a queue data structure using lock-free programming. It is implemented using glib. The function CAS() internally uses g_atomic_pointer_compare_and_exchange() . #FFcccc c #include <glib.h> #include <glib-object.h> typedef struct node_s { void *data; Node *next; } Node; typedef struct queue_s { Node *head; Node *tail; } Queue; Queue* queue_new(void) { Queue *q = g_slice_new(sizeof(Queue)); q->head = q->tail = g_slice_new(sizeof(Node)); return q; } void queue_enqueue(Queue *q, gpointer data) { Node *node; Node *tail; Node *next; node = g_slice_new(Node); node->data = data; node->next = NULL; while (TRUE) { tail = q->tail; next = tail->next; if (tail != q->tail) { continue; } if (next != NULL) { CAS(&q->tail, tail, next); continue; } if (CAS(&tail->next, NULL, node)) { break; } } CAS(&q->tail, tail, node); } gpointer queue_dequeue(Queue *q) { Node *node; Node *head; Node *tail; Node *next; gpointer data; while (TRUE) { head = q->head; tail = q->tail; next = head->next; if (head != q->head) { continue; } if (next == NULL) { return NULL; /* Empty */ } if (head == tail) { CAS(&q->tail, tail, next); continue; } data = next->data; if (CAS(&q->head, head, next)) { break; } } g_slice_free(Node, head); return data; } Assume there are two threads ( T1 and T2 ) operating simultaneously on the queue. The queue looks like this: head -> A -> B -> C -> tail The following sequence of operations occurs: Thread Queue Before Operation Queue After T1 head -> A -> B -> C -> tail Enters queue_dequeue() function head = A, tail = C next = B after executing data = next->data; This thread gets preempted head -> A -> B -> C -> tail T2 head -> A -> B -> C -> tail Removes node A head -> B -> C -> tail T2 head -> B -> C -> tail Removes node B head -> C -> tail T2 head -> C -> tail Enqueues node A back into the queue head -> C -> A -> tail T2 head -> C -> A -> tail Removes node C head -> A -> tail T2 head -> A -> tail Enqueues a new node D After enqueue operation, thread 2 gets preempted head -> A -> D -> tail T1 head -> A -> D -> tail Thread 1 starts execution Compares the local head = q->head = A (true in this case) Updates q->head with node B (but node B is removed) undefined {} According to the sequence of events in this table, head will now point to memory that was freed. Also, if reclaimed memory is returned to the operating system (for example, using munmap() ), access to such memory locations can result in fatal access violation errors. The ABA problem occurred because of the internal reuse of nodes that have been popped off the list or the reclamation of memory occupied by removed nodes .
#include <stdatomic.h> #include <threads.h>   static atomic_int array[]; static mtx_t array_mutex; void func(void) { size_t index; int value; if (thrd_success != mtx_lock(&array_mutex)) { /* Handle error */ } find_max_element(array, &index, &value); /* ... */ if (!atomic_compare_exchange_strong(array[index], &value, 0)) { /* Handle error */ } if (thrd_success != mtx_unlock(&array_mutex)) { /* Handle error */ } } /* Hazard pointers types and structure */ structure HPRecType { HP[K]:*Nodetype; Next:*HPRecType; }   /* The header of the HPRec list */ HeadHPRec: *HPRecType; /* Per-thread private variables */ rlist: listType; /* Initially empty */ rcount: integer; /* Initially 0 */ /* The retired node routine */ RetiredNode(node:*NodeType) { rlist.push(node); rcount++; if(rcount >= R) Scan(HeadHPRec); } /* The scan routine */ Scan(head:*HPRecType) { /* Stage 1: Scan HP list and insert non-null values in plist */ plist.init(); hprec<-head; while (hprec != NULL) { for (i<-0 to K-1) { hptr<-hprec^HP[i]; if (hptr!= NULL) plist.insert(hptr); } hprec<-hprec^Next; } /* Stage 2: search plist */ tmplist<-rlist.popAll(); rcount<-0; node<-tmplist.pop(); while (node != NULL) { if (plist.lookup(node)) { rlist.push(node); rcount++; } else { PrepareForReuse(node); } node<-tmplist.pop(); } plist.free(); } #include <glib.h> #include <glib-object.h>   void queue_enqueue(Queue *q, gpointer data) { Node *node; Node *tail; Node *next; node = g_slice_new(Node); node->data = data; node->next = NULL; while (TRUE) { tail = q->tail; HAZARD_SET(0, tail); /* Mark tail as hazardous */ if (tail != q->tail) { /* Check tail hasn't changed */ continue; } next = tail->next; if (tail != q->tail) { continue; } if (next != NULL) { CAS(&q->tail, tail, next); continue; } if (CAS(&tail->next, null, node) { break; } } CAS(&q->tail, tail, node); } gpointer queue_dequeue(Queue *q) { Node *node; Node *head; Node *tail; Node *next; gpointer data; while (TRUE) { head = q->head; LF_HAZARD_SET(0, head); /* Mark head as hazardous */ if (head != q->head) { /* Check head hasn't changed */ continue; } tail = q->tail; next = head->next; LF_HAZARD_SET(1, next); /* Mark next as hazardous */ if (head != q->head) { continue; } if (next == NULL) { return NULL; /* Empty */ } if (head == tail) { CAS(&q->tail, tail, next); continue; } data = next->data; if (CAS(&q->head, head, next)) { break; } } LF_HAZARD_UNSET(head); /* * Retire head, and perform * reclamation if needed.  */ return data; } #include <threads.h> #include <glib-object.h> typedef struct node_s { void *data; Node *next; } Node; typedef struct queue_s { Node *head; Node *tail; mtx_t mutex; } Queue; Queue* queue_new(void) { Queue *q = g_slice_new(sizeof(Queue)); q->head = q->tail = g_slice_new(sizeof(Node)); return q; } int queue_enqueue(Queue *q, gpointer data) { Node *node; Node *tail; Node *next; /* * Lock the queue before accessing the contents and * check the return code for success.  */ if (thrd_success != mtx_lock(&(q->mutex))) { return -1; /* Indicate failure */ } else {   node = g_slice_new(Node); node->data = data; node->next = NULL; if(q->head == NULL) { q->head = node; q->tail = node; } else { q->tail->next = node; q->tail = node; } /* Unlock the mutex and check the return code */ if (thrd_success != mtx_unlock(&(queue->mutex))) { return -1; /* Indicate failure */ } } return 0; } gpointer queue_dequeue(Queue *q) { Node *node; Node *head; Node *tail; Node *next; gpointer data; if (thrd_success != mtx_lock(&(q->mutex)) { return NULL; /* Indicate failure */ } else { head = q->head; tail = q->tail; next = head->next; data = next->data; q->head = next; g_slice_free(Node, head); if (thrd_success != mtx_unlock(&(queue->mutex))) { return NULL; /* Indicate failure */ } } return data; } ## Compliant Solution (Mutex) This compliant solution uses a mutex to prevent the data from being modified during the operation. Although this code is thread-safe, it is no longer lock-free. #ccccff c #include <stdatomic.h> #include <threads.h> static atomic_int array[]; static mtx_t array_mutex; void func(void) { size_t index; int value; if (thrd_success != mtx_lock(&array_mutex)) { /* Handle error */ } find_max_element(array, &index, &value); /* ... */ if (!atomic_compare_exchange_strong(array[index], &value, 0)) { /* Handle error */ } if (thrd_success != mtx_unlock(&array_mutex)) { /* Handle error */ } } ## Compliant Solution (GNU Glib, Hazard Pointers) According to [ Michael 2004 ], t he core idea is to associate a number (typically one or two) of single-writer, multi-reader shared pointers, called hazard pointers, with each thread that intends to access lock-free dynamic objects. A hazard pointer either has a null value or points to a node that may be accessed later by that thread without further validation that the reference to the node is still valid. Each hazard pointer may be written only by its owner thread but may be read by other threads. In this solution, communication with the associated algorithms is accomplished only through hazard pointers and a procedure RetireNode() that is called by threads to pass the addresses of retired nodes. PSEUDOCODE #ccccff c /* Hazard pointers types and structure */ structure HPRecType { HP[K]:*Nodetype; Next:*HPRecType; } /* The header of the HPRec list */ HeadHPRec: *HPRecType; /* Per-thread private variables */ rlist: listType; /* Initially empty */ rcount: integer; /* Initially 0 */ /* The retired node routine */ RetiredNode(node:*NodeType) { rlist.push(node); rcount++; if(rcount >= R) Scan(HeadHPRec); } /* The scan routine */ Scan(head:*HPRecType) { /* Stage 1: Scan HP list and insert non-null values in plist */ plist.init(); hprec<-head; while (hprec != NULL) { for (i<-0 to K-1) { hptr<-hprec^HP[i]; if (hptr!= NULL) plist.insert(hptr); } hprec<-hprec^Next; } /* Stage 2: search plist */ tmplist<-rlist.popAll(); rcount<-0; node<-tmplist.pop(); while (node != NULL) { if (plist.lookup(node)) { rlist.push(node); rcount++; } else { PrepareForReuse(node); } node<-tmplist.pop(); } plist.free(); } The scan consists of two stages. The first stage involves scanning the hazard pointer list for non-null values. Whenever a non-null value is encountered, it is inserted in a local list, plist , which can be implemented as a hash table. The second stage involves checking each node in rlist against the pointers in plist . If the lookup yields no match, the node is identified to be ready for arbitrary reuse. Otherwise, it is retained in rlist until the next scan by the current thread. Insertion and lookup in plist take constant expected time. The task of the memory reclamation method is to determine when a retired node is safely eligible for reuse while allowing memory reclamation. In the implementation , the pointer being removed is stored in the hazard pointer, preventing other threads from reusing it and thereby avoiding the ABA problem. CODE #ccccff c #include <glib.h> #include <glib-object.h> void queue_enqueue(Queue *q, gpointer data) { Node *node; Node *tail; Node *next; node = g_slice_new(Node); node->data = data; node->next = NULL; while (TRUE) { tail = q->tail; HAZARD_SET(0, tail); /* Mark tail as hazardous */ if (tail != q->tail) { /* Check tail hasn't changed */ continue; } next = tail->next; if (tail != q->tail) { continue; } if (next != NULL) { CAS(&q->tail, tail, next); continue; } if (CAS(&tail->next, null, node) { break; } } CAS(&q->tail, tail, node); } gpointer queue_dequeue(Queue *q) { Node *node; Node *head; Node *tail; Node *next; gpointer data; while (TRUE) { head = q->head; LF_HAZARD_SET(0, head); /* Mark head as hazardous */ if (head != q->head) { /* Check head hasn't changed */ continue; } tail = q->tail; next = head->next; LF_HAZARD_SET(1, next); /* Mark next as hazardous */ if (head != q->head) { continue; } if (next == NULL) { return NULL; /* Empty */ } if (head == tail) { CAS(&q->tail, tail, next); continue; } data = next->data; if (CAS(&q->head, head, next)) { break; } } LF_HAZARD_UNSET(head); /* * Retire head, and perform * reclamation if needed. */ return data; } ## Compliant Solution (GNU Glib, Mutex) In this compliant solution, mtx_lock() is used to lock the queue. When thread 1 locks on the queue to perform any operation, thread 2 cannot perform any operation on the queue, which prevents the ABA problem. #ccccff c #include <threads.h> #include <glib-object.h> typedef struct node_s { void *data; Node *next; } Node; typedef struct queue_s { Node *head; Node *tail; mtx_t mutex; } Queue; Queue* queue_new(void) { Queue *q = g_slice_new(sizeof(Queue)); q->head = q->tail = g_slice_new(sizeof(Node)); return q; } int queue_enqueue(Queue *q, gpointer data) { Node *node; Node *tail; Node *next; /* * Lock the queue before accessing the contents and * check the return code for success. */ if (thrd_success != mtx_lock(&(q->mutex))) { return -1; /* Indicate failure */ } else { node = g_slice_new(Node); node->data = data; node->next = NULL; if(q->head == NULL) { q->head = node; q->tail = node; } else { q->tail->next = node; q->tail = node; } /* Unlock the mutex and check the return code */ if (thrd_success != mtx_unlock(&(queue->mutex))) { return -1; /* Indicate failure */ } } return 0; } gpointer queue_dequeue(Queue *q) { Node *node; Node *head; Node *tail; Node *next; gpointer data; if (thrd_success != mtx_lock(&(q->mutex)) { return NULL; /* Indicate failure */ } else { head = q->head; tail = q->tail; next = head->next; data = next->data; q->head = next; g_slice_free(Node, head); if (thrd_success != mtx_unlock(&(queue->mutex))) { return NULL; /* Indicate failure */ } } return data; }
## Risk Assessment The likelihood of having a race condition is low. Once the race condition occurs, the reading memory that has already been freed can lead to abnormal program termination or unintended information disclosure. Recommendation Severity Likelihood Detectable Repairable Priority Level CON09-C Medium Unlikely No No P2 L3
SEI CERT C Coding Standard > 3 Recommendations > Rec. 14. Concurrency (CON)
c
87,152,258
https://wiki.sei.cmu.edu/confluence/pages/viewpage.action?pageId=87152258
2
14
CON30-C
Clean up thread-specific storage
The tss_create() function creates a thread-specific storage pointer identified by a key. Threads can allocate thread-specific storage and associate the storage with a key that uniquely identifies the storage by calling the tss_set() function. If not properly freed, this memory may be leaked. Ensure that thread-specific storage is freed.
#include <threads.h> #include <stdlib.h> /* Global key to the thread-specific storage */ tss_t key; enum { MAX_THREADS = 3 }; int *get_data(void) { int *arr = (int *)malloc(2 * sizeof(int)); if (arr == NULL) { return arr; /* Report error */ } arr[0] = 10; arr[1] = 42; return arr; } int add_data(void) { int *data = get_data(); if (data == NULL) { return -1; /* Report error */ }   if (thrd_success != tss_set(key, (void *)data)) { /* Handle error */ } return 0; } void print_data(void) { /* Get this thread's global data from key */ int *data = tss_get(key); if (data != NULL) {  /* Print data */ } } int function(void *dummy) { if (add_data() != 0) { return -1; /* Report error */ }  print_data(); return 0; } int main(void) { thrd_t thread_id[MAX_THREADS]; /* Create the key before creating the threads */ if (thrd_success != tss_create(&key, NULL)) { /* Handle error */ } /* Create threads that would store specific storage */ for (size_t i = 0; i < MAX_THREADS; i++) { if (thrd_success != thrd_create(&thread_id[i], function, NULL)) { /* Handle error */ } } for (size_t i = 0; i < MAX_THREADS; i++) { if (thrd_success != thrd_join(thread_id[i], NULL)) { /* Handle error */ } } tss_delete(key); return 0; } ## Noncompliant Code Example In this noncompliant code example, each thread dynamically allocates storage in the get_data() function, which is then associated with the global key by the call to tss_set() in the add_data() function. This memory is subsequently leaked when the threads terminate. #ffcccc c #include <threads.h> #include <stdlib.h> /* Global key to the thread-specific storage */ tss_t key; enum { MAX_THREADS = 3 }; int *get_data(void) { int *arr = (int *)malloc(2 * sizeof(int)); if (arr == NULL) { return arr; /* Report error */ } arr[0] = 10; arr[1] = 42; return arr; } int add_data(void) { int *data = get_data(); if (data == NULL) { return -1; /* Report error */ } if (thrd_success != tss_set(key, (void *)data)) { /* Handle error */ } return 0; } void print_data(void) { /* Get this thread's global data from key */ int *data = tss_get(key); if (data != NULL) { /* Print data */ } } int function(void *dummy) { if (add_data() != 0) { return -1; /* Report error */ } print_data(); return 0; } int main(void) { thrd_t thread_id[MAX_THREADS]; /* Create the key before creating the threads */ if (thrd_success != tss_create(&key, NULL)) { /* Handle error */ } /* Create threads that would store specific storage */ for (size_t i = 0; i < MAX_THREADS; i++) { if (thrd_success != thrd_create(&thread_id[i], function, NULL)) { /* Handle error */ } } for (size_t i = 0; i < MAX_THREADS; i++) { if (thrd_success != thrd_join(thread_id[i], NULL)) { /* Handle error */ } } tss_delete(key); return 0; }
#include <threads.h> #include <stdlib.h> /* Global key to the thread-specific storage */ tss_t key; int function(void *dummy) { if (add_data() != 0) { return -1; /* Report error */ } print_data(); free(tss_get(key)); return 0; } /* ... Other functions are unchanged */ #include <threads.h> #include <stdlib.h> /* Global key to the thread-specific storage */ tss_t key; enum { MAX_THREADS = 3 }; /* ... Other functions are unchanged */ void destructor(void *data) { free(data); }   int main(void) { thrd_t thread_id[MAX_THREADS]; /* Create the key before creating the threads */ if (thrd_success != tss_create(&key, destructor)) { /* Handle error */ } /* Create threads that would store specific storage */ for (size_t i = 0; i < MAX_THREADS; i++) { if (thrd_success != thrd_create(&thread_id[i], function, NULL)) { /* Handle error */ } } for (size_t i = 0; i < MAX_THREADS; i++) { if (thrd_success != thrd_join(thread_id[i], NULL)) { /* Handle error */ } } tss_delete(key); return 0; } ## Compliant Solution In this compliant solution, each thread explicitly frees the thread-specific storage returned by the tss_get() function before terminating: #ccccff c #include <threads.h> #include <stdlib.h> /* Global key to the thread-specific storage */ tss_t key; int function(void *dummy) { if (add_data() != 0) { return -1; /* Report error */ } print_data(); free(tss_get(key)); return 0; } /* ... Other functions are unchanged */ ## Compliant Solution This compliant solution invokes a destructor function registered during the call to tss_create() to automatically free any thread-specific storage: #ccccff c #include <threads.h> #include <stdlib.h> /* Global key to the thread-specific storage */ tss_t key; enum { MAX_THREADS = 3 }; /* ... Other functions are unchanged */ void destructor(void *data) { free(data); } int main(void) { thrd_t thread_id[MAX_THREADS]; /* Create the key before creating the threads */ if (thrd_success != tss_create(&key, destructor)) { /* Handle error */ } /* Create threads that would store specific storage */ for (size_t i = 0; i < MAX_THREADS; i++) { if (thrd_success != thrd_create(&thread_id[i], function, NULL)) { /* Handle error */ } } for (size_t i = 0; i < MAX_THREADS; i++) { if (thrd_success != thrd_join(thread_id[i], NULL)) { /* Handle error */ } } tss_delete(key); return 0; }
## Risk Assessment Failing to free thread-specific objects results in memory leaks and could result in a denial-of-service attack . Rule Severity Likelihood Detectable Repairable Priority Level CON30-C Medium Unlikely No No P2 L3
SEI CERT C Coding Standard > 2 Rules > Rule 14. Concurrency (CON)
End of preview. Expand in Data Studio

Dataset Card for SEI CERT C Coding Standard (Wiki rules)

Structured export of the SEI CERT C Coding Standard rules from the official SEI wiki: one row per rule with titles, prose, and code examples.

Dataset Details

Dataset Description

This dataset is a tabular snapshot of CERT C secure coding guidance as published on the SEI Confluence wiki. It is intended for retrieval, training data for code assistants, lint-rule authoring, and security education—not as a substitute for the authoritative standard.

  • Curated by: Derived from public SEI CERT wiki pages; packaged as CSV by the dataset maintainer.
  • Funded by [optional]: [More Information Needed]
  • Shared by [optional]: [More Information Needed]
  • Language(s) (NLP): English (rule text and embedded code).
  • License: Compilation distributed as other; source material is the publicly published SEI CERT standard on the CMU SEI wiki. Verify licensing for your use case with CMU SEI / the wiki terms.

Dataset Sources [optional]

Uses

Direct Use

Secure coding education, semantic search over rules, benchmarking static analyzers, and supervised fine-tuning for security-focused models.

Out-of-Scope Use

Not a legal or compliance certification. Do not treat scraped wiki text as legally binding; always consult the current official standard and your policies.

Dataset Structure

All rows share the same columns (scraped from the SEI CERT Confluence wiki):

Column Description
language Language identifier for the rule set
page_id Confluence page id
page_url Canonical wiki URL for the rule page
chapter Chapter label when present
section Section label when present
rule_id Rule identifier (e.g. API00-C, CON50-J)
title Short rule title
intro Normative / explanatory text
noncompliant_code Noncompliant example(s) when present
compliant_solution Compliant example(s) when present
risk_assessment Risk / severity notes when present
breadcrumb Wiki breadcrumb trail when present

Dataset Creation

Curation Rationale

Machine-readable rule text lowers the barrier to tooling and research aligned with CERT guidance.

Source Data

Data Collection and Processing

Pages were scraped from the SEI wiki; fields were normalized into CSV columns. See the companion scrape_sei_wiki.py in the source project if applicable.

Who are the source data producers?

[More Information Needed]

Annotations [optional]

Annotation process

[More Information Needed]

Who are the annotators?

[More Information Needed]

Personal and Sensitive Information

[More Information Needed]

Bias, Risks, and Limitations

[More Information Needed]

Recommendations

Users should be made aware of the risks, biases and limitations of the dataset. More information needed for further recommendations.

Citation [optional]

BibTeX:

[More Information Needed]

APA:

[More Information Needed]

Glossary [optional]

[More Information Needed]

More Information [optional]

[More Information Needed]

Dataset Card Authors [optional]

[More Information Needed]

Dataset Card Contact

[More Information Needed]

Downloads last month
-