Show contents
Chapter 5 of 7 · 20 min
Writing C that resists attacks
By the end of this chapter, you'll be able to
- Replace strcpy, strcat and sprintf with bounded, checked copies
- Detect truncation with snprintf's return value
- Check that a size calculation doesn't overflow before allocating
- Recognise a format-string vulnerability and avoid it
Copies that are always bounded
strcpy, strcat and sprintf write as much as the source requires, without knowing the destination's size. snprintf receives that size and never exceeds it. Better: it returns the length the complete text would have had, which lets you detect truncation.
#include <stdio.h>
/* Builds "Hello <name>!" in out. Returns 0, or -1 if the message would be truncated. */
int greet(char *out, size_t size, const char *name) {
int n = snprintf(out, size, "Hello %s!", name);
if (n < 0 || (size_t)n >= size) return -1;
return 0;
}
int main(void) {
char message[20];
const char *names[] = {"Ana", "Maximilienne-Aurore"};
for (int i = 0; i < 2; i++) {
if (greet(message, sizeof message, names[i]) == 0) {
printf("%s\n", message);
} else {
printf("too long, truncated to: \"%s\"\n", message);
}
}
return 0;
}
Hello Ana!
too long, truncated to: "Hello Maximilienne-"
The complete text would be 26 characters; message only holds 19, plus the '\0'. Memory didn't overflow, and the function knows the result is incomplete: it's up to you to decide whether to refuse, retry with a bigger array, or display the truncated text.
strncpy, often presented as "the safe version", has a trap: if the source is too long, it doesn't add a final '\0'. Prefer snprintf(dest, size, "%s", source).
Sizes that don't overflow
Allocating n * size bytes is dangerous if n comes from outside (a file header, a network request). If the product exceeds the maximum value of a size_t, it "wraps round" and becomes small: malloc allocates a tiny block, and the program then writes far beyond it.
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
/* Allocates an array of n items of size t, or returns NULL if n * t overflows. */
void *alloc_array(size_t n, size_t t) {
if (t != 0 && n > SIZE_MAX / t) {
return NULL;
}
return malloc(n * t);
}
int main(void) {
double *readings = alloc_array(1000, sizeof *readings);
printf("1000 readings: %s\n", readings ? "allocated" : "refused");
free(readings);
void *huge = alloc_array(SIZE_MAX / 4, 8);
printf("absurd size: %s\n", huge ? "allocated" : "refused");
free(huge);
return 0;
}
1000 readings: allocated
absurd size: refused
n > SIZE_MAX / t checks for overflow without causing it: we divide instead of multiplying. calloc(n, t) also does this check, and fills the memory with zeros as well. free(NULL) does nothing, which simplifies clean-up.
With the check, the dangerous calculation never happens: the function returns NULL.
Text description of the animation
- A booby-trapped file announces a huge number of items.
- On 64 bits, the product exceeds SIZE_MAX and wraps round: it's 0.
- The program allocates a tiny block, believing it has room for n items.
- The following writes overwrite neighbouring memory: that's the attack's way in.
- With the check, the dangerous calculation never happens: the function returns NULL.
Format strings
printf(text) interprets text as a format. If text comes from the user and contains %x or %n, printf will read, even write, in the program's memory.
char name[64];
fgets(name, sizeof name, stdin);
printf(name); /* vulnerability: the user controls the format */
printf("%s", name); /* correct: the format is fixed, name is just data */
GCC reports this case with -Wformat-security. The rule is simple: the first argument of printf, fprintf or snprintf is always a string literal written by you.
Your turn
Worked exercise
Worked exercise: concatenating without overflowing
Write a function int append_word(char *sentence, size_t size, const char *word) that adds a space then word to the end of sentence (or just word if sentence is empty). It must never exceed size bytes, '\0' included, and returns -1 without changing anything if the word doesn't fit. Build the sentence Millet grows well in a 20-character array, then check that "today" is refused.
Hint 1
strlen(sentence), then the room needed: the word's length, plus 1 for the space if the sentence isn't empty, plus 1 for the '\0'.Hint 2
sentence + length with snprintf, giving it the remaining room size - length.Show the solution and common mistakes
#include <stdio.h>
#include <string.h>
int append_word(char *sentence, size_t size, const char *word) {
size_t length = strlen(sentence);
size_t space = length > 0 ? 1 : 0;
if (length + space + strlen(word) + 1 > size) {
return -1;
}
snprintf(sentence + length, size - length, "%s%s", space ? " " : "", word);
return 0;
}
int main(void) {
char sentence[20] = "";
const char *words[] = {"Millet", "grows", "well", "today"};
for (int i = 0; i < 4; i++) {
if (append_word(sentence, sizeof sentence, words[i]) != 0) {
printf("refused: %s\n", words[i]);
}
}
printf("[%s] (%zu characters)\n", sentence, strlen(sentence));
return 0;
}
refused: today
[Millet grows well] (17 characters)
"Millet grows well" takes 17 characters, plus the '\0': 18 bytes out of 20. Adding "today" would need 24: the function refuses, and the sentence stays intact.
Common mistakes:
- Using
strcat(sentence, word): no size check, the fourth word would write beyond the array. - Forgetting the
+ 1for the'\0'in the calculation: a word that exactly fills the array would be accepted, and the null character would overflow by one byte.
Summary
- 1All data from outside is hostile: sizes, lengths and texts are checked.
- 2snprintf bounds every copy and its return value reveals truncation.
- 3Check n > SIZE_MAX / t before allocating n * t bytes (or use calloc).
- 4printf's format is always a string literal: printf("%s", text).
- 5Compare a received length with the destination's size before any copy.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.