shared: assert that nm_utils_buf_utf8safe_unescape() doesn't reallocate memory

We want to use the function to unescape (compress) secrets. As such, we want
to be sure that no secrets are leaked in memory due to growing the buffer with
realloc. In fact, reallocation should never happen. Assert for that.

As reallocation cannot happen, we could directly fill a buffer with
API like nm_utils_strbuf_*(). But NMStrBuf has low overhead even in this
case.
This commit is contained in:
Thomas Haller 2020-05-04 09:17:19 +02:00
parent 79f254850c
commit 5fe447d4a6
No known key found for this signature in database
GPG key ID: 29C2366E4DFC5728
2 changed files with 23 additions and 2 deletions

View file

@ -2480,7 +2480,7 @@ nm_utils_buf_utf8safe_unescape (const char *str, gsize *out_len, gpointer *to_fr
return str;
}
nm_str_buf_init (&strbuf, len, FALSE);
nm_str_buf_init (&strbuf, len + 1u, FALSE);
nm_str_buf_append_len (&strbuf, str, s - str);
str = s;
@ -2541,6 +2541,11 @@ nm_utils_buf_utf8safe_unescape (const char *str, gsize *out_len, gpointer *to_fr
str = s;
}
/* assert that no reallocation was necessary. For one, unescaping should
* never result in a longer string than the input. Also, when unescaping
* secrets, we want to ensure that we don't leak secrets in memory. */
nm_assert (strbuf.allocated == len + 1u);
return (*to_free = nm_str_buf_finalize (&strbuf,
out_len));
}
@ -2675,11 +2680,17 @@ nm_utils_buf_utf8safe_escape_bytes (GBytes *bytes, NMUtilsStrUtf8SafeFlags flags
const char *
nm_utils_str_utf8safe_unescape (const char *str, char **to_free)
{
const char *res;
gsize len;
g_return_val_if_fail (to_free, NULL);
return nm_utils_buf_utf8safe_unescape (str, &len, (gpointer *) to_free);
res = nm_utils_buf_utf8safe_unescape (str, &len, (gpointer *) to_free);
nm_assert ( (!res && len == 0)
|| (strlen (res) <= len));
return res;
}
/**

View file

@ -1184,8 +1184,18 @@ GType nm_g_type_find_implementing_class_for_property (GType gtype,
typedef enum {
NM_UTILS_STR_UTF8_SAFE_FLAG_NONE = 0,
/* This flag only has an effect during escaping. */
NM_UTILS_STR_UTF8_SAFE_FLAG_ESCAPE_CTRL = 0x0001,
/* This flag only has an effect during escaping. */
NM_UTILS_STR_UTF8_SAFE_FLAG_ESCAPE_NON_ASCII = 0x0002,
/* This flag only has an effect during escaping to ensure we
* don't leak secrets in memory. Note that during unescape we
* know the maximum result size from the beginning, and no
* reallocation happens. Thus, unescape always avoids leaking
* secrets already. */
NM_UTILS_STR_UTF8_SAFE_FLAG_SECRET = 0x0004,
} NMUtilsStrUtf8SafeFlags;