* The key is built up as follows: * - Fetch 32 bytes from NVS storage and store as key data * - Fetch 6-8 MAC bytes and overwrite the first 6-8 bytes of the key with this info * * When flash encryption is disabled: * Without the MAC data, an attack would look like this: * - Retrieve all the partitions from the ESP32 * - Read the key from NVS flash * - Use the key to decrypt * Wi
| 63 | * @param[out] key the output key |
| 64 | */ |
| 65 | static void get_nvs_key(uint8_t key[32]) { |
| 66 | nvs_handle_t handle; |
| 67 | esp_err_t result = nvs_open(TT_NVS_NAMESPACE, NVS_READWRITE, &handle); |
| 68 | |
| 69 | if (result != ESP_OK) { |
| 70 | LOGGER.error("Failed to get key from NVS ({})", esp_err_to_name(result)); |
| 71 | check(false, "NVS error"); |
| 72 | } |
| 73 | |
| 74 | size_t length = 32; |
| 75 | if (nvs_get_blob(handle, "key", key, &length) == ESP_OK) { |
| 76 | LOGGER.info("Fetched key from NVS ({} bytes)", length); |
| 77 | check(length == 32); |
| 78 | } else { |
| 79 | // TODO: Improved randomness |
| 80 | esp_cpu_cycle_count_t cycle_count = esp_cpu_get_cycle_count(); |
| 81 | auto seed = cycle_count; |
| 82 | srand(seed); |
| 83 | for (int i = 0; i < 32; ++i) { |
| 84 | key[i] = (uint8_t)(rand()); |
| 85 | } |
| 86 | ESP_ERROR_CHECK(nvs_set_blob(handle, "key", key, 32)); |
| 87 | LOGGER.info("Stored new key in NVS"); |
| 88 | } |
| 89 | |
| 90 | nvs_close(handle); |
| 91 | } |
| 92 | #endif |
| 93 | |
| 94 | /** |