Commit 6d4bc2a9 authored by Daniel Salzman's avatar Daniel Salzman

dname: fix knot_dname_to_str memory overflow

parent 27182f1b
......@@ -244,6 +244,9 @@ char *knot_dname_to_str(char *dst, const knot_dname_t *name, size_t maxlen)
/* Write label separation. */
if (str_len > 0 || dname_size == 1) {
if (alloc_size <= str_len + 1) {
return NULL;
}
res[str_len++] = '.';
}
......@@ -252,6 +255,9 @@ char *knot_dname_to_str(char *dst, const knot_dname_t *name, size_t maxlen)
if (is_alnum(c) || c == '-' || c == '_' || c == '*' ||
c == '/') {
if (alloc_size <= str_len + 1) {
return NULL;
}
res[str_len++] = c;
} else if (is_punct(c) && c != '#') {
/* Exclusion of '#' character is to avoid possible
......@@ -310,6 +316,7 @@ char *knot_dname_to_str(char *dst, const knot_dname_t *name, size_t maxlen)
}
/* String_termination. */
assert(str_len < alloc_size);
res[str_len] = 0;
return res;
......
......@@ -393,6 +393,24 @@ int main(int argc, char *argv[])
ok(s != NULL, "dname_to_str: dname length > 255");
free(s);
/* output overflow sanity check */
uint8_t in[4] = "\x02""\x00\x00""\x00";
for (uint16_t i = 0; i < UINT16_MAX; i++) {
memcpy(in + 1, &i, sizeof(i));
for (int j = 3; j < 8; j++) {
char tmp[j];
char *out_static = knot_dname_to_str(tmp, in, sizeof(tmp));
char *out_dynamic = knot_dname_to_str_alloc(in);
if (out_dynamic == NULL) {
ok(out_dynamic != NULL, "dname_to_str_alloc: invalid input");
} else if (strlen(out_dynamic) < sizeof(tmp) - 1 &&
out_static == NULL) {
ok(out_static != NULL, "dname_to_str: invalid input");
}
free(out_dynamic);
}
}
/* NULL output, positive maxlen */
s = "aa.";
d = knot_dname_from_str(NULL, s, 1);
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment