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