1 /*
2 * SPDX-FileCopyrightText: 2022-2023 Espressif Systems (Shanghai) CO LTD
3 *
4 * SPDX-License-Identifier: Apache-2.0
5 */
6
7 #include <strings.h>
8 #include "esp_flash_encrypt.h"
9 #include "esp_secure_boot.h"
10 #include "esp_efuse.h"
11 #include "esp_efuse_table.h"
12 #include "esp_log.h"
13 #include "sdkconfig.h"
14
15 static __attribute__((unused)) const char *TAG = "flash_encrypt";
16
esp_flash_encryption_enable_secure_features(void)17 esp_err_t esp_flash_encryption_enable_secure_features(void)
18 {
19 #ifndef CONFIG_SECURE_FLASH_UART_BOOTLOADER_ALLOW_ENC
20 ESP_LOGI(TAG, "Disable UART bootloader encryption...");
21 esp_efuse_write_field_bit(ESP_EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPT);
22 #else
23 ESP_LOGW(TAG, "Not disabling UART bootloader encryption");
24 #endif
25
26 #ifndef CONFIG_SECURE_BOOT_ALLOW_JTAG
27 ESP_LOGI(TAG, "Disable JTAG...");
28 esp_efuse_write_field_bit(ESP_EFUSE_DIS_PAD_JTAG);
29 esp_efuse_write_field_bit(ESP_EFUSE_DIS_USB_JTAG);
30 #else
31 ESP_LOGW(TAG, "Not disabling JTAG - SECURITY COMPROMISED");
32 #endif
33
34 esp_efuse_write_field_bit(ESP_EFUSE_DIS_DIRECT_BOOT);
35
36 #if defined(CONFIG_SECURE_BOOT_V2_ENABLED) && !defined(CONFIG_SECURE_BOOT_V2_ALLOW_EFUSE_RD_DIS)
37 // This bit is set when enabling Secure Boot V2, but we can't enable it until this later point in the first boot
38 // otherwise the Flash Encryption key cannot be read protected
39 esp_efuse_write_field_bit(ESP_EFUSE_WR_DIS_RD_DIS);
40 #endif
41
42 #ifndef CONFIG_SECURE_FLASH_SKIP_WRITE_PROTECTION_CACHE
43 // Set write-protection for DIS_ICACHE to prevent bricking chip in case it will be set accidentally.
44 // esp32h2 has DIS_ICACHE. Write-protection bit = 2.
45 // List of eFuses with the same write protection bit:
46 // DIS_ICACHE, DIS_USB_JTAG, POWERGLITCH_EN, DIS_FORCE_DOWNLOAD, SPI_DOWNLOAD_MSPI_DIS,
47 // DIS_TWAI, JTAG_SEL_ENABLE, DIS_PAD_JTAG, DIS_DOWNLOAD_MANUAL_ENCRYPT
48 esp_efuse_write_field_bit(ESP_EFUSE_WR_DIS_DIS_ICACHE);
49 #endif
50
51 return ESP_OK;
52 }
53