flash_encrypt.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. // Copyright 2015-2020 Espressif Systems (Shanghai) PTE LTD
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <strings.h>
  15. #include "bootloader_flash_priv.h"
  16. #include "bootloader_random.h"
  17. #include "bootloader_utility.h"
  18. #include "esp_image_format.h"
  19. #include "esp_flash_encrypt.h"
  20. #include "esp_flash_partitions.h"
  21. #include "esp_secure_boot.h"
  22. #include "esp_log.h"
  23. #include "esp32c3/rom/secure_boot.h"
  24. #include "esp_efuse.h"
  25. #include "esp_efuse_table.h"
  26. #include "hal/wdt_hal.h"
  27. static const char *TAG = "flash_encrypt";
  28. /* Static functions for stages of flash encryption */
  29. static esp_err_t initialise_flash_encryption(void);
  30. static esp_err_t encrypt_flash_contents(uint32_t flash_crypt_cnt, bool flash_crypt_wr_dis) __attribute__((unused));
  31. static esp_err_t encrypt_bootloader(void);
  32. static esp_err_t encrypt_and_load_partition_table(esp_partition_info_t *partition_table, int *num_partitions);
  33. static esp_err_t encrypt_partition(int index, const esp_partition_info_t *partition);
  34. esp_err_t esp_flash_encrypt_check_and_update(void)
  35. {
  36. uint8_t flash_crypt_wr_dis = 0;
  37. uint32_t flash_crypt_cnt = 0;
  38. esp_efuse_read_field_blob(ESP_EFUSE_SPI_BOOT_CRYPT_CNT, &flash_crypt_cnt, 3);
  39. esp_efuse_read_field_blob(ESP_EFUSE_WR_DIS_SPI_BOOT_CRYPT_CNT, &flash_crypt_wr_dis, 1);
  40. ESP_LOGV(TAG, "SPI_BOOT_CRYPT_CNT 0x%x", flash_crypt_cnt);
  41. ESP_LOGV(TAG, "EFUSE_WR_DIS_SPI_BOOT_CRYPT_CNT 0x%x", flash_crypt_wr_dis);
  42. if (__builtin_parity(flash_crypt_cnt) == 1) {
  43. /* Flash is already encrypted */
  44. int left = (flash_crypt_cnt == 1) ? 1 : 0;
  45. if (flash_crypt_wr_dis) {
  46. left = 0; /* can't update FLASH_CRYPT_CNT, no more flashes */
  47. }
  48. ESP_LOGI(TAG, "flash encryption is enabled (%d plaintext flashes left)", left);
  49. return ESP_OK;
  50. } else {
  51. #ifndef CONFIG_SECURE_FLASH_REQUIRE_ALREADY_ENABLED
  52. /* Flash is not encrypted, so encrypt it! */
  53. return encrypt_flash_contents(flash_crypt_cnt, flash_crypt_wr_dis);
  54. #else
  55. ESP_LOGE(TAG, "flash encryption is not enabled, and SECURE_FLASH_REQUIRE_ALREADY_ENABLED "
  56. "is set, refusing to boot.");
  57. return ESP_ERR_INVALID_STATE;
  58. #endif // CONFIG_SECURE_FLASH_REQUIRE_ALREADY_ENABLED
  59. }
  60. }
  61. static esp_err_t check_and_generate_encryption_keys(void)
  62. {
  63. esp_efuse_block_t aes_128_key_block;
  64. bool has_key = esp_efuse_find_purpose(ESP_EFUSE_KEY_PURPOSE_XTS_AES_128_KEY, &aes_128_key_block);
  65. bool dis_write = false;
  66. bool dis_read = false;
  67. // If there are keys set, they must be write and read protected!
  68. if(has_key) {
  69. dis_write = esp_efuse_get_key_dis_write(aes_128_key_block);
  70. dis_read = esp_efuse_get_key_dis_read(aes_128_key_block);
  71. }
  72. if(has_key && (!dis_read || !dis_write)) {
  73. ESP_LOGE(TAG, "Invalid key state, a key was set but not read and write protected.");
  74. return ESP_ERR_INVALID_STATE;
  75. }
  76. if(!has_key && !dis_write && !dis_read) {
  77. ESP_LOGI(TAG, "Generating new flash encryption key...");
  78. enum { BLOCKS_NEEDED = 1 };
  79. esp_efuse_purpose_t purposes[BLOCKS_NEEDED] = {
  80. ESP_EFUSE_KEY_PURPOSE_XTS_AES_128_KEY,
  81. };
  82. uint8_t keys[BLOCKS_NEEDED][32] = { 0 };
  83. for (int i = 0; i < BLOCKS_NEEDED; ++i) {
  84. bootloader_fill_random(keys[i], 32);
  85. }
  86. esp_err_t err = esp_efuse_write_keys(purposes, keys, BLOCKS_NEEDED);
  87. if (err != ESP_OK) {
  88. if (err == ESP_ERR_NOT_ENOUGH_UNUSED_KEY_BLOCKS) {
  89. ESP_LOGE(TAG, "Not enough free efuse key blocks (need %d) to continue", BLOCKS_NEEDED);
  90. } else {
  91. ESP_LOGE(TAG, "Failed to write efuse block with purpose (err=0x%x). Can't continue.", err);
  92. }
  93. return err;
  94. }
  95. ESP_LOGD(TAG, "Key generation complete");
  96. return ESP_OK;
  97. } else {
  98. ESP_LOGI(TAG, "Using pre-existing key in efuse");
  99. return ESP_OK;
  100. }
  101. }
  102. static esp_err_t initialise_flash_encryption(void)
  103. {
  104. esp_efuse_batch_write_begin(); /* Batch all efuse writes at the end of this function */
  105. esp_err_t key_state = check_and_generate_encryption_keys();
  106. if(key_state != ESP_OK) {
  107. esp_efuse_batch_write_cancel();
  108. return key_state;
  109. }
  110. #ifndef CONFIG_SECURE_FLASH_UART_BOOTLOADER_ALLOW_ENC
  111. ESP_LOGI(TAG, "Disable UART bootloader encryption...");
  112. esp_efuse_write_field_bit(ESP_EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPT);
  113. #else
  114. ESP_LOGW(TAG, "Not disabling UART bootloader encryption");
  115. #endif
  116. #ifndef CONFIG_SECURE_FLASH_UART_BOOTLOADER_ALLOW_CACHE
  117. ESP_LOGI(TAG, "Disable UART bootloader cache...");
  118. esp_efuse_write_field_bit(ESP_EFUSE_DIS_DOWNLOAD_ICACHE);
  119. #else
  120. ESP_LOGW(TAG, "Not disabling UART bootloader cache - SECURITY COMPROMISED");
  121. #endif
  122. #ifndef CONFIG_SECURE_BOOT_ALLOW_JTAG
  123. ESP_LOGI(TAG, "Disable JTAG...");
  124. esp_efuse_write_field_bit(ESP_EFUSE_DIS_PAD_JTAG);
  125. esp_efuse_write_field_bit(ESP_EFUSE_DIS_USB_JTAG);
  126. #else
  127. ESP_LOGW(TAG, "Not disabling JTAG - SECURITY COMPROMISED");
  128. #endif
  129. esp_efuse_write_field_bit(ESP_EFUSE_DIS_LEGACY_SPI_BOOT);
  130. esp_err_t err = esp_efuse_batch_write_commit();
  131. if (err != ESP_OK) {
  132. ESP_LOGE(TAG, "Error programming security eFuses (err=0x%x).", err);
  133. }
  134. return err;
  135. }
  136. /* Encrypt all flash data that should be encrypted */
  137. static esp_err_t encrypt_flash_contents(uint32_t spi_boot_crypt_cnt, bool flash_crypt_wr_dis)
  138. {
  139. esp_err_t err;
  140. esp_partition_info_t partition_table[ESP_PARTITION_TABLE_MAX_ENTRIES];
  141. int num_partitions;
  142. /* If the last spi_boot_crypt_cnt bit is burned or write-disabled, the
  143. device can't re-encrypt itself. */
  144. if (flash_crypt_wr_dis || spi_boot_crypt_cnt == EFUSE_SPI_BOOT_CRYPT_CNT) {
  145. ESP_LOGE(TAG, "Cannot re-encrypt data SPI_BOOT_CRYPT_CNT 0x%02x write disabled %d", spi_boot_crypt_cnt, flash_crypt_wr_dis);
  146. return ESP_FAIL;
  147. }
  148. if (spi_boot_crypt_cnt == 0) {
  149. /* Very first flash of encrypted data: generate keys, etc. */
  150. err = initialise_flash_encryption();
  151. if (err != ESP_OK) {
  152. return err;
  153. }
  154. }
  155. err = encrypt_bootloader();
  156. if (err != ESP_OK) {
  157. return err;
  158. }
  159. err = encrypt_and_load_partition_table(partition_table, &num_partitions);
  160. if (err != ESP_OK) {
  161. return err;
  162. }
  163. /* Now iterate the just-loaded partition table, looking for entries to encrypt
  164. */
  165. /* Go through each partition and encrypt if necessary */
  166. for (int i = 0; i < num_partitions; i++) {
  167. err = encrypt_partition(i, &partition_table[i]);
  168. if (err != ESP_OK) {
  169. return err;
  170. }
  171. }
  172. ESP_LOGD(TAG, "All flash regions checked for encryption pass");
  173. /* Set least significant 0-bit in spi_boot_crypt_cnt */
  174. int ffs_inv = __builtin_ffs((~spi_boot_crypt_cnt) & 0x7);
  175. /* ffs_inv shouldn't be zero, as zero implies spi_boot_crypt_cnt == 0xFF */
  176. uint32_t new_spi_boot_crypt_cnt = (1 << (ffs_inv - 1));
  177. ESP_LOGD(TAG, "SPI_BOOT_CRYPT_CNT 0x%x -> 0x%x", spi_boot_crypt_cnt, new_spi_boot_crypt_cnt + spi_boot_crypt_cnt);
  178. esp_efuse_write_field_blob(ESP_EFUSE_SPI_BOOT_CRYPT_CNT, &new_spi_boot_crypt_cnt, 3);
  179. #ifdef CONFIG_SECURE_FLASH_ENCRYPTION_MODE_RELEASE
  180. //Secure SPI boot cnt after its update if needed.
  181. const uint32_t spi_boot_cnt_wr_dis = 1;
  182. ESP_LOGI(TAG, "Write protecting SPI_CRYPT_CNT eFuse");
  183. esp_efuse_write_field_blob(ESP_EFUSE_WR_DIS_SPI_BOOT_CRYPT_CNT, &spi_boot_cnt_wr_dis, 1);
  184. #endif
  185. ESP_LOGI(TAG, "Flash encryption completed");
  186. return ESP_OK;
  187. }
  188. static esp_err_t encrypt_bootloader(void)
  189. {
  190. esp_err_t err;
  191. uint32_t image_length;
  192. /* Check for plaintext bootloader (verification will fail if it's already encrypted) */
  193. if (esp_image_verify_bootloader(&image_length) == ESP_OK) {
  194. ESP_LOGD(TAG, "bootloader is plaintext. Encrypting...");
  195. #if CONFIG_SECURE_BOOT_V2_ENABLED
  196. /* The image length obtained from esp_image_verify_bootloader includes the sector boundary padding and the signature block lengths */
  197. if (ESP_BOOTLOADER_OFFSET + image_length > ESP_PARTITION_TABLE_OFFSET) {
  198. ESP_LOGE(TAG, "Bootloader is too large to fit Secure Boot V2 signature sector and partition table (configured offset 0x%x)", ESP_PARTITION_TABLE_OFFSET);
  199. return ESP_ERR_INVALID_SIZE;
  200. }
  201. #endif // CONFIG_SECURE_BOOT_V2_ENABLED
  202. err = esp_flash_encrypt_region(ESP_BOOTLOADER_OFFSET, image_length);
  203. if (err != ESP_OK) {
  204. ESP_LOGE(TAG, "Failed to encrypt bootloader in place: 0x%x", err);
  205. return err;
  206. }
  207. ESP_LOGI(TAG, "bootloader encrypted successfully");
  208. return err;
  209. }
  210. else {
  211. ESP_LOGW(TAG, "no valid bootloader was found");
  212. return ESP_ERR_NOT_FOUND;
  213. }
  214. }
  215. static esp_err_t encrypt_and_load_partition_table(esp_partition_info_t *partition_table, int *num_partitions)
  216. {
  217. esp_err_t err;
  218. /* Check for plaintext partition table */
  219. err = bootloader_flash_read(ESP_PARTITION_TABLE_OFFSET, partition_table, ESP_PARTITION_TABLE_MAX_LEN, false);
  220. if (err != ESP_OK) {
  221. ESP_LOGE(TAG, "Failed to read partition table data");
  222. return err;
  223. }
  224. if (esp_partition_table_verify(partition_table, false, num_partitions) == ESP_OK) {
  225. ESP_LOGD(TAG, "partition table is plaintext. Encrypting...");
  226. esp_err_t err = esp_flash_encrypt_region(ESP_PARTITION_TABLE_OFFSET,
  227. FLASH_SECTOR_SIZE);
  228. if (err != ESP_OK) {
  229. ESP_LOGE(TAG, "Failed to encrypt partition table in place. %x", err);
  230. return err;
  231. }
  232. } else {
  233. ESP_LOGE(TAG, "Failed to read partition table data - not plaintext?");
  234. return ESP_ERR_INVALID_STATE;
  235. }
  236. /* Valid partition table loaded */
  237. ESP_LOGI(TAG, "partition table encrypted and loaded successfully");
  238. return ESP_OK;
  239. }
  240. static esp_err_t encrypt_partition(int index, const esp_partition_info_t *partition)
  241. {
  242. esp_err_t err;
  243. bool should_encrypt = (partition->flags & PART_FLAG_ENCRYPTED);
  244. if (partition->type == PART_TYPE_APP) {
  245. /* check if the partition holds a valid unencrypted app */
  246. esp_image_metadata_t data_ignored;
  247. err = esp_image_verify(ESP_IMAGE_VERIFY,
  248. &partition->pos,
  249. &data_ignored);
  250. should_encrypt = (err == ESP_OK);
  251. } else if (partition->type == PART_TYPE_DATA && partition->subtype == PART_SUBTYPE_DATA_OTA) {
  252. /* check if we have ota data partition and the partition should be encrypted unconditionally */
  253. should_encrypt = true;
  254. }
  255. if (!should_encrypt) {
  256. return ESP_OK;
  257. } else {
  258. /* should_encrypt */
  259. ESP_LOGI(TAG, "Encrypting partition %d at offset 0x%x (length 0x%x)...", index, partition->pos.offset, partition->pos.size);
  260. err = esp_flash_encrypt_region(partition->pos.offset, partition->pos.size);
  261. ESP_LOGI(TAG, "Done encrypting");
  262. if (err != ESP_OK) {
  263. ESP_LOGE(TAG, "Failed to encrypt partition %d", index);
  264. }
  265. return err;
  266. }
  267. }
  268. esp_err_t esp_flash_encrypt_region(uint32_t src_addr, size_t data_length)
  269. {
  270. esp_err_t err;
  271. uint32_t buf[FLASH_SECTOR_SIZE / sizeof(uint32_t)];
  272. if (src_addr % FLASH_SECTOR_SIZE != 0) {
  273. ESP_LOGE(TAG, "esp_flash_encrypt_region bad src_addr 0x%x", src_addr);
  274. return ESP_FAIL;
  275. }
  276. wdt_hal_context_t rtc_wdt_ctx = {.inst = WDT_RWDT, .rwdt_dev = &RTCCNTL};
  277. for (size_t i = 0; i < data_length; i += FLASH_SECTOR_SIZE) {
  278. wdt_hal_write_protect_disable(&rtc_wdt_ctx);
  279. wdt_hal_feed(&rtc_wdt_ctx);
  280. wdt_hal_write_protect_enable(&rtc_wdt_ctx);
  281. uint32_t sec_start = i + src_addr;
  282. err = bootloader_flash_read(sec_start, buf, FLASH_SECTOR_SIZE, false);
  283. if (err != ESP_OK) {
  284. goto flash_failed;
  285. }
  286. err = bootloader_flash_erase_sector(sec_start / FLASH_SECTOR_SIZE);
  287. if (err != ESP_OK) {
  288. goto flash_failed;
  289. }
  290. err = bootloader_flash_write(sec_start, buf, FLASH_SECTOR_SIZE, true);
  291. if (err != ESP_OK) {
  292. goto flash_failed;
  293. }
  294. }
  295. return ESP_OK;
  296. flash_failed:
  297. ESP_LOGE(TAG, "flash operation failed: 0x%x", err);
  298. return err;
  299. }