diff --git a/firmware/src/sgx/src/untrusted/keyvalue_store.c b/firmware/src/sgx/src/untrusted/keyvalue_store.c index 164aeaa4..44ac674a 100644 --- a/firmware/src/sgx/src/untrusted/keyvalue_store.c +++ b/firmware/src/sgx/src/untrusted/keyvalue_store.c @@ -34,7 +34,8 @@ #define KVSTORE_MAX_KEY_LEN 150 -// Sanitizes a key by allowing only [a-zA-Z0-9]. Anything else is replaced by an '-' +// Sanitizes a key by allowing only [a-zA-Z0-9]. If one or more invalid characters are +// found, Replace them with a single hyphen. static void sanitize_key(char* key, char *sanitized_key) { if (!key || !sanitized_key) return; @@ -45,14 +46,18 @@ static void sanitize_key(char* key, char *sanitized_key) { key_len = KVSTORE_MAX_KEY_LEN; } + bool prev_char_valid = false; + size_t sanitized_key_len = 0; for (size_t i = 0; i < key_len; i++) { if (isalnum(key[i])) { - sanitized_key[i] = key[i]; - } else { - sanitized_key[i] = '-'; + sanitized_key[sanitized_key_len++] = key[i]; + prev_char_valid = true; + } else if (prev_char_valid) { + sanitized_key[sanitized_key_len++] = '-'; + prev_char_valid = false; } } - sanitized_key[key_len] = '\0'; + sanitized_key[sanitized_key_len] = '\0'; } static char* filename_for(char* key) { diff --git a/firmware/src/sgx/test/keyvalue_store/test_keyvalue_store.c b/firmware/src/sgx/test/keyvalue_store/test_keyvalue_store.c index f2aa498a..2b0be7f6 100644 --- a/firmware/src/sgx/test/keyvalue_store/test_keyvalue_store.c +++ b/firmware/src/sgx/test/keyvalue_store/test_keyvalue_store.c @@ -206,8 +206,9 @@ void test_sanitize_key() { {"lettersandnumbers123", "kvstore-lettersandnumbers123.dat", "data3"}, {"letters-and-numbers-with-hyphen-123", "kvstore-letters-and-numbers-with-hyphen-123.dat", "data4"}, {"key containing spaces", "kvstore-key-containing-spaces.dat", "data5"}, - {"key containing special characters!@#$%^&*()", "kvstore-key-containing-special-characters----------.dat", "data6"}, - {"../../../../../etc/passwd", "kvstore----------------etc-passwd.dat", "data7"}, + {"key containing special characters!@#$%^&*()", "kvstore-key-containing-special-characters-.dat", "data6"}, + {"../../../../../etc/passwd", "kvstore-etc-passwd.dat", "data7"}, + {"some@#£_&-(_./file#£+-:;name", "kvstore-some-file-name.dat", "data8"}, }; size_t num_inputs = sizeof(input_data) / sizeof(input_data[0]);