Skip to content

Commit

Permalink
libsepol: use checked arithmetic builtin to perform safe addition
Browse files Browse the repository at this point in the history
Checking whether an overflow occurred after adding two values can be
achieved using checked arithmetic builtin functions such as:

    bool __builtin_add_overflow(type1 x, type2 y, type3 *sum);

This function is available at least in clang
(at least since clang 3.8.0,
https://releases.llvm.org/3.8.0/tools/clang/docs/LanguageExtensions.html#checked-arithmetic-builtins)
and gcc
(https://gcc.gnu.org/onlinedocs/gcc/Integer-Overflow-Builtins.html,
since gcc 5 according to https://gcc.gnu.org/gcc-5/changes.html)

Signed-off-by: Nicolas Iooss <nicolas.iooss@m4x.org>
  • Loading branch information
fishilico committed Apr 30, 2021
1 parent f63263c commit 0744fa4
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 27 deletions.
29 changes: 6 additions & 23 deletions libsepol/src/context_record.c
Expand Up @@ -267,31 +267,13 @@ int sepol_context_from_string(sepol_handle_t * handle,
return STATUS_ERR;
}


static inline int safe_sum(size_t *sum, const size_t augends[], const size_t cnt) {

size_t a, i;

*sum = 0;
for(i=0; i < cnt; i++) {
/* sum should not be smaller than the addend */
a = augends[i];
*sum += a;
if (*sum < a) {
return i;
}
}

return 0;
}

int sepol_context_to_string(sepol_handle_t * handle,
const sepol_context_t * con, char **str_ptr)
{

int rc;
char *str = NULL;
size_t total_sz, err;
size_t total_sz = 0, i;
const size_t sizes[] = {
strlen(con->user), /* user length */
strlen(con->role), /* role length */
Expand All @@ -300,10 +282,11 @@ int sepol_context_to_string(sepol_handle_t * handle,
((con->mls) ? 3 : 2) + 1 /* mls has extra ":" also null byte */
};

err = safe_sum(&total_sz, sizes, ARRAY_SIZE(sizes));
if (err) {
ERR(handle, "invalid size, overflow at position: %zu", err);
goto err;
for (i = 0; i < ARRAY_SIZE(sizes); i++) {
if (__builtin_add_overflow(total_sz, sizes[i], &total_sz)) {
ERR(handle, "invalid size, overflow at position: %zu", i);
goto err;
}
}

str = (char *)malloc(total_sz);
Expand Down
6 changes: 2 additions & 4 deletions libsepol/src/module_to_cil.c
Expand Up @@ -1134,16 +1134,14 @@ static int name_list_to_string(char **names, unsigned int num_names, char **stri
char *strpos;

for (i = 0; i < num_names; i++) {
len += strlen(names[i]);
if (len < strlen(names[i])) {
if (__builtin_add_overflow(len, strlen(names[i]), &len)) {
log_err("Overflow");
return -1;
}
}

// add spaces + null terminator
len += num_names;
if (len < (size_t)num_names) {
if (__builtin_add_overflow(len, (size_t)num_names, &len)) {
log_err("Overflow");
return -1;
}
Expand Down

0 comments on commit 0744fa4

Please sign in to comment.