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_FLASH_UART_BOOTLOADER_ALLOW_CACHE
27     ESP_LOGI(TAG, "Disable UART bootloader cache...");
28     esp_efuse_write_field_bit(ESP_EFUSE_DIS_DOWNLOAD_ICACHE);
29 #else
30     ESP_LOGW(TAG, "Not disabling UART bootloader cache - SECURITY COMPROMISED");
31 #endif
32 
33 #ifndef CONFIG_SECURE_BOOT_ALLOW_JTAG
34     ESP_LOGI(TAG, "Disable JTAG...");
35     esp_efuse_write_field_bit(ESP_EFUSE_DIS_PAD_JTAG);
36     esp_efuse_write_field_bit(ESP_EFUSE_DIS_USB_JTAG);
37 #else
38     ESP_LOGW(TAG, "Not disabling JTAG - SECURITY COMPROMISED");
39 #endif
40 
41     esp_efuse_write_field_bit(ESP_EFUSE_DIS_DIRECT_BOOT);
42 
43 #if defined(CONFIG_SECURE_BOOT_V2_ENABLED) && !defined(CONFIG_SECURE_BOOT_V2_ALLOW_EFUSE_RD_DIS)
44     // This bit is set when enabling Secure Boot V2, but we can't enable it until this later point in the first boot
45     // otherwise the Flash Encryption key cannot be read protected
46     esp_efuse_write_field_bit(ESP_EFUSE_WR_DIS_RD_DIS);
47 #endif
48 
49 #ifndef CONFIG_SECURE_FLASH_SKIP_WRITE_PROTECTION_CACHE
50     // Set write-protection for DIS_ICACHE to prevent bricking chip in case it will be set accidentally.
51     // esp32c6 has DIS_ICACHE. Write-protection bit = 2.
52     // List of eFuses with the same write protection bit:
53     // SWAP_UART_SDIO_EN, DIS_ICACHE, DIS_USB_JTAG, DIS_DOWNLOAD_ICACHE,
54     // DIS_USB_SERIAL_JTAG, DIS_FORCE_DOWNLOAD, DIS_TWAI, JTAG_SEL_ENABLE,
55     // DIS_PAD_JTAG, DIS_DOWNLOAD_MANUAL_ENCRYPT.
56     esp_efuse_write_field_bit(ESP_EFUSE_WR_DIS_DIS_ICACHE);
57 #endif
58 
59     return ESP_OK;
60 }
61