From 0a5cad7ee8e6950f8816b654b41d6bbaa96f6846 Mon Sep 17 00:00:00 2001 From: Mingjie Shen Date: Sat, 22 Apr 2023 00:03:54 -0400 Subject: [PATCH 1/2] Fix unbounded write of sscanf Format string "%s" that does not control the length of data written may overflow. --- src/stlink-lib/chipid.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/stlink-lib/chipid.c b/src/stlink-lib/chipid.c index 3d122a02e..44d93fedd 100644 --- a/src/stlink-lib/chipid.c +++ b/src/stlink-lib/chipid.c @@ -64,7 +64,7 @@ void process_chipfile(char *fname) { (strncmp(buf, " ", strlen(" ")) == 0)) continue; // ignore empty lines - sscanf(buf, "%s %s", word, value); + sscanf(buf, "%63s %63s", word, value); if (strcmp(word, "dev_type") == 0) { buf[strlen(buf) - 1] = 0; // chomp newline From 8f97e62708f5eff3e66669976d17cd0ecbf29125 Mon Sep 17 00:00:00 2001 From: Mingjie Shen Date: Sat, 22 Apr 2023 18:10:31 -0400 Subject: [PATCH 2/2] Check return values of sscanf() Failing to check that a call to 'scanf' actually writes to an output variable can lead to unexpected behavior at reading time. --- src/st-util/gdb-server.c | 6 ++++-- src/stlink-lib/chipid.c | 5 ++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/st-util/gdb-server.c b/src/st-util/gdb-server.c index 802e23c06..d64073cf7 100644 --- a/src/st-util/gdb-server.c +++ b/src/st-util/gdb-server.c @@ -160,8 +160,10 @@ int parse_options(int argc, char** argv, st_state_t *st) { break; case 'p': - sscanf(optarg, "%i", &q); - if (q < 0) { + if (sscanf(optarg, "%i", &q) != 1) { + fprintf(stderr, "Invalid port %s\n", optarg); + exit(EXIT_FAILURE); + } else if (q < 0) { fprintf(stderr, "Can't use a negative port to listen on: %d\n", q); exit(EXIT_FAILURE); } diff --git a/src/stlink-lib/chipid.c b/src/stlink-lib/chipid.c index 44d93fedd..347d89e14 100644 --- a/src/stlink-lib/chipid.c +++ b/src/stlink-lib/chipid.c @@ -64,7 +64,10 @@ void process_chipfile(char *fname) { (strncmp(buf, " ", strlen(" ")) == 0)) continue; // ignore empty lines - sscanf(buf, "%63s %63s", word, value); + if (sscanf(buf, "%63s %63s", word, value) != 2) { + fprintf(stderr, "Failed to read keyword or value\n"); + continue; + } if (strcmp(word, "dev_type") == 0) { buf[strlen(buf) - 1] = 0; // chomp newline