Google makes Linux more secure
Google has taken a proactive step to bolster Linux security with the introduction of the counted_by attribute for flexible array members. This enhancement addresses a critical vulnerability in C programming related to buffer overflows, particularly those involving flexible array members whose sizes are determined at runtime.
Buffer overflows have long been a notorious source of security issues in software development. While sanitizers have mitigated some of these vulnerabilities by automatically inserting bounds checking, flexible array members have remained a challenging exception. The size of these arrays is typically opaque to the compiler, making it difficult to perform bounds checking outside the allocation function.
Google's solution, implemented in Clang and GCC, introduces the counted_by attribute. This attribute explicitly references the field that stores the number of elements in a flexible array member, enabling the array bounds sanitizer to verify operations on these arrays. This approach creates an implicit relationship between the flexible array member and the count field, enhancing the ability of sanitizers to catch potential overflows.
To effectively use the counted_by attribute, developers must adhere to specific rules:
- The count field must be within the same non-anonymous, enclosing struct as the flexible array member.
- The count field must be set before any array access.
- The array field must have at least the count number of elements available at all times.
- The count field may change but must never exceed the number of elements originally allocated.
An example allocation of a structure utilizing the counted_by attribute is as follows:
struct foo {
size_t count;
int array[] __attribute__((counted_by(count)));
};
struct foo *foo_alloc(size_t count) {
struct foo *ptr = NULL;
size_t size = MAX(sizeof(struct foo),
offsetof(struct foo, array[0]) +
count * sizeof(p->array[0]));
ptr = calloc(1, size);
ptr->count = count;
return ptr;
}
This attribute has significant implications for fortification, an ongoing project aimed at making the Linux kernel more secure by preventing buffer overflows in memory and string operations. Fortification relies on built-in functions like __builtin_object_size() and __builtin_dynamic_object_size() to validate input sizes. With the counted_by attribute, these functions can now accurately determine the size of flexible array members, further enhancing security.
Already in use within the Linux kernel, the counted_by attribute is proving instrumental in catching issues such as integer overflows that lead to heap buffer overflows. Google plans to expand its use to more flexible array members and enforce its application in future developments.