A badge for a very long name
A college prints visitor badges such as "Ann in B12". It works for every name in testing.
Then a visitor called Christopher-Robin arrives for Lecture Theatre Two. Three lines of the program were never safe; they were only lucky.
By the end of this lesson
Note
I can replace an unsafe C call with a bounded one and prove the fix with a sanitizer.
Key words
| Word | What it means | Example |
|---|---|---|
| Unbounded copy | a copy that never checks the space it writes to | strcpy |
| Bounded call | a call that is told the size of its target | snprintf |
| Truncation | cutting text short to fit | |
| Format string | the first argument of printf, which says how to print | |
| Length check | refusing input that will not fit |
The cells students fill in are left blank in this preview.
Starter
Have a go
Starter
4 questionsThree unsafe calls in one function
strcpy copies the name with no idea how big label is. sprintf writes the line with no idea how big line is. printf(line) treats text the user typed as instructions for printing.
Write the program and build it with warnings on.
Write badge.c and build it
mkdir -p ~/mem/fix && cd ~/mem/fix && cat > badge.c <<'END'
#include <stdio.h>
#include <string.h>
void badge(const char *name, const char *room) {
char label[12];
char line[24];
strcpy(label, name);
sprintf(line, "%s in %s", label, room);
printf(line);
printf("\n");
}
int main(int argc, char **argv) {
if (argc < 3) return 1;
badge(argv[1], argv[2]);
return 0;
}
END
gcc -Wall -O2 -o badge badge.c && ./badge Ann B12Shown here, not run. Press Start lab to type it into your own lab’s terminal.
A long name under AddressSanitizer
cd ~/mem/fix && gcc -g -fsanitize=address,undefined -fno-omit-frame-pointer -Wno-format-security -o badge-asan badge.c && DEBUGINFOD_URLS= ./badge-asan Christopher-Robin B12 2>&1 | grep -E 'ERROR|of size|SUMMARY'Shown here, not run. Press Start lab to type it into your own lab’s terminal.
A long room under AddressSanitizer
cd ~/mem/fix && DEBUGINFOD_URLS= ./badge-asan Ann Lecture-Theatre-Two 2>&1 | grep -E 'ERROR|of size|SUMMARY'Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Check
Have a go
Check
3 questionsText is data, never a format
A % in a name would make printf(line) look for arguments that were never passed. That prints the wrong thing or crashes.
The fix is always the same: printf("%s\n", line). Keep -Wformat-security on so the compiler flags every case.
gets cannot be used safely at all
gets reads a line into a buffer it was never told the size of. No caller can make it safe, so C removed it in 2011.
Today's gcc will not even build a program that uses it. Try it.
Try to build a program that uses gets
mkdir -p ~/mem/fix && cd ~/mem/fix && cat > ask.c <<'END'
#include <stdio.h>
int main(void) {
char name[16];
gets(name);
printf("hello %s\n", name);
return 0;
}
END
gcc -o ask ask.c 2>&1 | grep -E 'error'Shown here, not run. Press Start lab to type it into your own lab’s terminal.
A common mistake
Warning
Many people think strncpy is the safe strcpy. When the source is too long it copies no ending zero, so the next read runs past the buffer. Check the length first, or use snprintf, which always ends the text.
Worked example: each unsafe call and its replacement
| Unsafe | Why | Use instead |
|---|---|---|
| gets(buf) | Never knows the size | fgets(buf, sizeof buf, stdin) |
| strcpy(dst, src) | Never checks the space | a length check, then snprintf(dst, sizeof dst, "%s", src) |
| sprintf(dst, ...) | Never checks the space | snprintf(dst, sizeof dst, ...) and check what it returns |
| printf(text) | Text read as a format | printf("%s", text) or puts(text) |
| strcat(dst, src) | Never checks the space | track the length used, then snprintf |
The cells students fill in are left blank in this preview.
Check, bound, then print
badge now refuses a name that will not fit, copies with snprintf, and checks that snprintf did not have to cut the line short. It prints with "%s".
It returns -1 so main can say "refused: too long" instead of printing half a badge.
Rewrite badge.c and build it
cd ~/mem/fix && cat > badge.c <<'END'
#include <stdio.h>
#include <string.h>
int badge(const char *name, const char *room) {
char label[12];
char line[24];
if (strlen(name) >= sizeof label) return -1;
snprintf(label, sizeof label, "%s", name);
int n = snprintf(line, sizeof line, "%s in %s", label, room);
if (n < 0 || (size_t)n >= sizeof line) return -1;
printf("%s\n", line);
return 0;
}
int main(int argc, char **argv) {
if (argc < 3) return 1;
if (badge(argv[1], argv[2]) < 0) puts("refused: too long");
return 0;
}
END
gcc -Wall -Wextra -Wformat-security -O2 -o badge badge.c && ./badge Ann B12Shown here, not run. Press Start lab to type it into your own lab’s terminal.
Prove it with the same three inputs
cd ~/mem/fix && gcc -g -fsanitize=address,undefined -fno-omit-frame-pointer -o badge-asan badge.c && for who in "Ann B12" "Christopher-Robin B12" "Ann Lecture-Theatre-Two"; do DEBUGINFOD_URLS= ./badge-asan $who; doneShown here, not run. Press Start lab to type it into your own lab’s terminal.
Replace gets with fgets
cd ~/mem/fix && cat > ask.c <<'END'
#include <stdio.h>
#include <string.h>
int main(void) {
char name[16];
if (fgets(name, sizeof name, stdin) == NULL) return 1;
name[strcspn(name, "\n")] = 0;
printf("hello %s\n", name);
return 0;
}
END
gcc -Wall -g -fsanitize=address -o ask ask.c && echo Bartholomew-Fitzwilliam | DEBUGINFOD_URLS= ./askShown here, not run. Press Start lab to type it into your own lab’s terminal.
Check
Have a go
Check
3 questionsAssignment: flag unsafe calls
A reviewer wants a quick list of risky calls in a C file. Write two functions.
findings(source) returns a list of (line_number, call) pairs, counting lines from 1, in order. Flag gets(, strcpy(, strcat( and sprintf( wherever they appear (but not fgets(, snprintf( or strncpy(). Also flag printf when the text after printf( does not start with a double quote: report it as "printf".
fix_for(call) returns the replacement from the lesson's table: "fgets", "snprintf" for strcpy, strcat and sprintf, and "printf(\"%s\", ...)" for printf.
def findings(source):
return []
def fix_for(call):
return ""
Make a free account to save your work and track your progress.
Exit quiz
Have a go