Skip to content

Commit

Permalink
workbook: fix buffer underflow in defined names
Browse files Browse the repository at this point in the history
Closes #444
  • Loading branch information
jmcnamara committed May 15, 2024
1 parent 284b61b commit af0b03a
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/workbook.c
Original file line number Diff line number Diff line change
Expand Up @@ -678,6 +678,9 @@ _store_defined_name(lxw_workbook *self, const char *name,
if (!name || !formula)
return LXW_ERROR_NULL_PARAMETER_IGNORED;

if (strlen(name) == 0 || strlen(formula) == 0)
return LXW_ERROR_PARAMETER_VALIDATION;

if (lxw_utf8_strlen(name) > LXW_DEFINED_NAME_LENGTH ||
lxw_utf8_strlen(formula) > LXW_DEFINED_NAME_LENGTH) {
return LXW_ERROR_128_STRING_LENGTH_EXCEEDED;
Expand Down Expand Up @@ -710,6 +713,9 @@ _store_defined_name(lxw_workbook *self, const char *name,
tmp_str++;
worksheet_name = name_copy;

if (strlen(tmp_str) == 0 || strlen(worksheet_name) == 0)
goto mem_error;

/* Remove any worksheet quoting. */
if (worksheet_name[0] == '\'')
worksheet_name++;
Expand Down Expand Up @@ -933,11 +939,22 @@ _populate_range_dimensions(lxw_workbook *self, lxw_series_range *range)
return;
}
else {
/* Peek forward to check for empty string. */
if (tmp_str[1] == '\0') {
range->ignore_cache = LXW_TRUE;
return;
}

/* Split the formulas into sheetname and row-col data. */
*tmp_str = '\0';
tmp_str++;
sheetname = formula;

if (strlen(tmp_str) == 0 || strlen(sheetname) == 0) {
range->ignore_cache = LXW_TRUE;
return;
}

/* Remove any worksheet quoting. */
if (sheetname[0] == '\'')
sheetname++;
Expand Down
25 changes: 25 additions & 0 deletions test/unit/workbook/test_workbook_write_defined_names.c
Original file line number Diff line number Diff line change
Expand Up @@ -65,3 +65,28 @@ CTEST(workbook, write_defined_names_sorted) {

lxw_workbook_free(workbook);
}

/* Test invalid names formats. */
CTEST(workbook, write_defined_names_invalid) {
char* got;
char exp[] = "";
FILE* testfile = lxw_tmpfile(NULL);


lxw_workbook *workbook = workbook_new(NULL);
workbook->file = testfile;

workbook_add_worksheet(workbook, NULL);

workbook_define_name(workbook, "", "=123");
workbook_define_name(workbook, "Foo", "");
workbook_define_name(workbook, "Sheet1!", "=123");
workbook_define_name(workbook, "!", "=123");

_write_defined_names(workbook);

RUN_XLSX_STREQ(exp, got);

lxw_workbook_free(workbook);
}

0 comments on commit af0b03a

Please sign in to comment.