diff --git a/src/cli/such.c b/src/cli/such.c index b48995251..61522501f 100644 --- a/src/cli/such.c +++ b/src/cli/such.c @@ -1210,6 +1210,9 @@ int main(int argc, char* argv[]) char* mnemonic_in = 0; char* pass = 0; char* entropy = 0; + /* entropy_size points at a literal, so -e needs somewhere writable. + + 1 for the terminator ENTROPY_SIZE_STRING_SIZE does not include. */ + char entropy_size_buf[ENTROPY_SIZE_STRING_SIZE + 1]; char* entropy_size = "256"; MNEMONIC mnemonic = {0}; SEED seed = {0}; @@ -1252,7 +1255,17 @@ int main(int argc, char* argv[]) return showError("Parameter -e cannot be used with -y"); entropy = optarg; if (entropy != NULL){ - sprintf(entropy_size, "%zu", strlen(entropy) / HEX_CHARS_PER_BYTE * 8); + /* Bound first: unbounded optarg gives four or more + digits and snprintf truncates rather than overflows. */ + size_t entropy_hex_len = strlen(entropy); + if (entropy_hex_len > MAX_ENTROPY_STRING_SIZE - 1) + return showError("Parameter -e exceeds the maximum entropy size"); + + /* sprintf through the "256" literal wrote to read-only + memory and crashed on every use of -e. */ + snprintf(entropy_size_buf, sizeof(entropy_size_buf), "%zu", + entropy_hex_len / HEX_CHARS_PER_BYTE * 8); + entropy_size = entropy_size_buf; } break;