text
stringlengths
1
3.82k
__index_level_0__
int64
0
366
- 4 - If set, disable flash encryption when in download bootmodes. - 1 - Enable encryption and decryption, when an SPI boot mode is set. Feature is enabled if 1 or 3 bits are set in the eFuse, disabled otherwise. - 3 .. only:: SOC_FLASH_ENCRYPTION_XTS_AES_128 and SOC_EFUSE_CONSISTS_OF_ONE_KEY_BLOCK .. list-table:: eFuses Used in Flash Encryption :widths: 25 40 10 :header-rows: 0 - **Description** - **Bit Depth** - Controls actual number of eFuse bits used to derive final 256-bit AES key. Possible values: ``1`` use all 256 bits of the eFuse block for the key, ``0`` use the lower 128 bits of the eFuse block for the key (the higher 128 bits are reserved for Secure Boot key). For 128 bits option, the final AES key is derived as SHA256(EFUSE_KEY0_FE_128BIT). - 1 - AES key storage - 256 or 128 key block - If set, disable flash encryption when in download bootmodes.
40
- 1 - Enables encryption and decryption, when an SPI boot mode is set. Feature is enabled if 1 or 3 bits are set in the eFuse, disabled otherwise. - 3 .. note:: Read and write access to eFuse bits is controlled by appropriate fields in the registers ``WR_DIS`` and ``RD_DIS``. For more information on {IDF_TARGET_NAME} eFuses, see :doc:`eFuse manager `. To change protection bits of eFuse field using espefuse.py, use these two commands: read_protect_efuse and write_protect_efuse. Example ``espefuse.py write_protect_efuse DISABLE_DL_ENCRYPT``. .. only:: esp32c2 .. important:: {IDF_TARGET_NAME} has only one eFuse key block for both keys: Secure Boot and Flash Encryption. As the eFuse key block can only be burned once, these keys should be burned together at the same time. Please note that "Secure Boot" and "Flash Encryption" can not be enabled separately as subsequent writes to eFuse key block shall return an error. Flash Encryption Process Assuming that the eFuse values are in their default states and the firmware bootloader is compiled to support flash encryption, the flash encryption process executes as shown below: .
40
. only:: not SOC_FLASH_ENCRYPTION_XTS_AES .. only:: SOC_FLASH_ENCRYPTION_XTS_AES_256 .. list:: :esp32s2: - ``DIS_BOOT_REMAP`` - ``DIS_DOWNLOAD_ICACHE`` - ``DIS_DOWNLOAD_DCACHE`` - ``HARD_DIS_JTAG`` - ``DIS_LEGACY_SPI_BOOT`` .. only:: SOC_FLASH_ENCRYPTION_XTS_AES_128 and not SOC_FLASH_ENCRYPTION_XTS_AES_256 and not SOC_EFUSE_CONSISTS_OF_ONE_KEY_BLOCK .. only:: SOC_FLASH_ENCRYPTION_XTS_AES_128 and SOC_EFUSE_CONSISTS_OF_ONE_KEY_BLOCK During the development stage, there is a frequent need to program different plaintext flash images and test the flash encryption process. This requires that Firmware Download mode is able to load new plaintext images as many times as it might be needed. However, during manufacturing or production stages, Firmware Download mode should not be allowed to access flash contents for security reasons. Hence, two different flash encryption configurations were created: for development and for production. For details on these configurations, see Section `Flash Encryption Configuration`_.
40
Flash Encryption Configuration The following flash encryption modes are available: - :ref:`flash-enc-development-mode` - recommended for use only during development. In this mode, it is still possible to flash new plaintext firmware to the device, and the bootloader will transparently encrypt this firmware using the key stored in hardware. This allows, indirectly, to read out the plaintext of the firmware in flash. - :ref:`flash-enc-release-mode` - recommended for manufacturing and production. In this mode, flashing plaintext firmware to the device without knowing the encryption key is no longer possible. This section provides information on the mentioned flash encryption modes and step by step instructions on how to use them. .. _flash-enc-development-mode: Development Mode During development, you can encrypt flash using either an {IDF_TARGET_NAME} generated key or external host-generated key. Using {IDF_TARGET_NAME} Generated Key """"""""""""""""""""""""""""""""""""" Development mode allows you to download multiple plaintext images using Firmware Download mode.
40
To test flash encryption process, take the following steps: See how to check :ref:`flash-encryption-status`. .. list:: - :ref:`Enable flash encryption on boot `. - :ref:`Select encryption mode ` (**Development mode** by default). :esp32: - :ref:`Select UART ROM download mode ` (**enabled** by default). Note that for the ESP32 target, the choice is only available when :ref:`CONFIG_ESP32_REV_MIN` level is set to 3 (ESP32 V3). :not esp32: - :ref:`Select UART ROM download mode ` (**enabled** by default). :esp32s2 or esp32s3 or esp32c2: - Set :ref:`Size of generated XTS-AES key `. - :ref:`Select the appropriate bootloader log verbosity `. - Save the configuration and exit. Enabling flash encryption will increase the size of bootloader, which might require updating partition table offset. See :ref:`bootloader-size`. .. code-block:: bash idf.py flash monitor .. note:: This command does not include any user files which should be written to the partitions on the flash memory.
40
Please write them manually before running this command otherwise the files should be encrypted separately before writing. This command will write to flash memory unencrypted images: the firmware bootloader, the partition table and applications. Once the flashing is complete, {IDF_TARGET_NAME} will reset. On the next boot, the firmware bootloader encrypts: the firmware bootloader, application partitions and partitions marked as ``encrypted`` then resets. Encrypting in-place can take time, up to a minute for large partitions. After that, the application is decrypted at runtime and executed. A sample output of the first {IDF_TARGET_NAME} boot after enabling flash encryption is given below: .. include:: {IDF_TARGET_PATH_NAME}_log.inc :start-after: first_boot_enc :end-before: A sample output of subsequent {IDF_TARGET_NAME} boots just mentions that flash encryption is already enabled: .. include:: {IDF_TARGET_PATH_NAME}_log.inc :start-after: already_en_enc :end-before: At this stage, if you need to update and re-flash binaries, see :ref:`encrypt-partitions`.
40
.. _pregenerated-flash-encryption-key: Using Host Generated Key """""""""""""""""""""""" It is possible to pre-generate a flash encryption key on the host computer and burn it into the eFuse. This allows you to pre-encrypt data on the host and flash already encrypted data without needing a plaintext flash update. This feature can be used in both :ref:`flash-enc-development-mode` and :ref:`flash-enc-release-mode`. Without a pre-generated key, data is flashed in plaintext and then {IDF_TARGET_NAME} encrypts the data in-place. .. note:: This option is not recommended for production, unless a separate key is generated for each individual device. .. only:: esp32c2 .. note:: Note that {IDF_TARGET_NAME} only has one eFuse key block for both Secure Boot and Flash Encryption keys. Therefore, writing the host-generated Flash Encryption key must be done with Secure Boot key (if used), otherwise Secure Boot cannot be used. To use a host generated key, take the following steps: See how to check :ref:`flash-encryption-status`.
40
.. only:: not SOC_FLASH_ENCRYPTION_XTS_AES .. code-block:: bash espsecure.py generate_flash_encryption_key my_flash_encryption_key.bin .. only:: SOC_FLASH_ENCRYPTION_XTS_AES_256 If :ref:`Size of generated XTS-AES key ` is AES-128 (256-bit key): .. code-block:: bash espsecure.py generate_flash_encryption_key my_flash_encryption_key.bin else if :ref:`Size of generated XTS-AES key ` is AES-256 (512-bit key): .. code-block:: bash espsecure.py generate_flash_encryption_key --keylen 512 my_flash_encryption_key.bin .. only:: SOC_FLASH_ENCRYPTION_XTS_AES_128 and not SOC_FLASH_ENCRYPTION_XTS_AES_256 and not SOC_EFUSE_CONSISTS_OF_ONE_KEY_BLOCK .. code-block:: bash espsecure.py generate_flash_encryption_key my_flash_encryption_key.bin .. only:: SOC_FLASH_ENCRYPTION_XTS_AES_128 and SOC_EFUSE_CONSISTS_OF_ONE_KEY_BLOCK If :ref:`Size of generated XTS-AES key ` is AES-128 (256-bit key): .. code-block:: bash espsecure.
40
py generate_flash_encryption_key my_flash_encryption_key.bin else if :ref:`Size of generated XTS-AES key ` is AES-128 key derived from 128 bits (SHA256(128 bits)): .. code-block:: bash espsecure.py generate_flash_encryption_key --keylen 128 my_flash_encryption_key.bin .. only:: not SOC_FLASH_ENCRYPTION_XTS_AES .. code-block:: bash espefuse.py --port PORT burn_key flash_encryption my_flash_encryption_key.bin .. only:: SOC_FLASH_ENCRYPTION_XTS_AES_256 .. code-block:: bash espefuse.py --port PORT burn_key BLOCK my_flash_encryption_key.bin KEYPURPOSE where ``BLOCK`` is a free keyblock between ``BLOCK_KEY0`` and ``BLOCK_KEY5``. And ``KEYPURPOSE`` is either ``AES_256_KEY_1``, ``XTS_AES_256_KEY_2``, ``XTS_AES_128_KEY``. See `{IDF_TARGET_NAME} Technical Reference Manual `_ for a description of the key purposes. For AES-128 (256-bit key) - ``XTS_AES_128_KEY``: .. code-block:: bash espefuse.py --port PORT burn_key BLOCK my_flash_encryption_key.
40
bin XTS_AES_128_KEY For AES-256 (512-bit key) - ``XTS_AES_256_KEY_1`` and ``XTS_AES_256_KEY_2``. ``espefuse.py`` supports burning both these two key purposes together with a 512 bit key to two separate key blocks via the virtual key purpose ``XTS_AES_256_KEY``. When this is used ``espefuse.py`` will burn the first 256 bit of the key to the specified ``BLOCK`` and burn the corresponding block key purpose to ``XTS_AES_256_KEY_1``. The last 256 bit of the key will be burned to the first free key block after ``BLOCK`` and the corresponding block key purpose to ``XTS_AES_256_KEY_2`` .. code-block:: bash espefuse.py --port PORT burn_key BLOCK my_flash_encryption_key.bin XTS_AES_256_KEY If you wish to specify exactly which two blocks are used then it is possible to divide key into two 256 bit keys, and manually burn each half with ``XTS_AES_256_KEY_1`` and ``XTS_AES_256_KEY_2`` as key purposes: .. code-block:: bash split -b 32 my_flash_encryption_key.bin my_flash_encryption_key.
40
bin. espefuse.py --port PORT burn_key BLOCK my_flash_encryption_key.bin.aa XTS_AES_256_KEY_1 espefuse.py --port PORT burn_key BLOCK+1 my_flash_encryption_key.bin.ab XTS_AES_256_KEY_2 .. only:: SOC_FLASH_ENCRYPTION_XTS_AES_128 and not SOC_FLASH_ENCRYPTION_XTS_AES_256 and not SOC_EFUSE_CONSISTS_OF_ONE_KEY_BLOCK .. code-block:: bash espefuse.py --port PORT burn_key BLOCK my_flash_encryption_key.bin XTS_AES_128_KEY where ``BLOCK`` is a free keyblock between ``BLOCK_KEY0`` and ``BLOCK_KEY5``. .. only:: SOC_FLASH_ENCRYPTION_XTS_AES_128 and SOC_EFUSE_CONSISTS_OF_ONE_KEY_BLOCK For AES-128 (256-bit key) - ``XTS_AES_128_KEY`` (the ``XTS_KEY_LENGTH_256`` eFuse will be burn to 1): .. code-block:: bash espefuse.py --port PORT burn_key BLOCK_KEY0 flash_encryption_key256.bin XTS_AES_128_KEY For AES-128 key derived from 128 bits (SHA256(128 bits)) - ``XTS_AES_128_KEY_DERIVED_FROM_128_EFUSE_BITS``. The FE key will be written in the lower part of eFuse BLOCK_KEY0.
40
The upper 128 bits are not used and will remain available for reading by software. Using the special mode of the espefuse tool, shown in the ``For burning both keys together`` section below, the user can write their data to it using any espefuse commands. .. code-block:: bash espefuse.py --port PORT burn_key BLOCK_KEY0 flash_encryption_key128.bin XTS_AES_128_KEY_DERIVED_FROM_128_EFUSE_BITS For burning both keys together (Secure Boot and Flash Encryption): .. code-block:: bash espefuse.py --port PORT --chip esp32c2 burn_key_digest secure_boot_signing_key.pem \ burn_key BLOCK_KEY0 flash_encryption_key128.bin XTS_AES_128_KEY_DERIVED_FROM_128_EFUSE_BITS If the key is not burned and the device is started after enabling flash encryption, the {IDF_TARGET_NAME} will generate a random key that software cannot access or modify. - :ref:`Enable flash encryption on boot ` - :ref:`Select encryption mode ` (**Development mode** by default) - :ref:`Select the appropriate bootloader log verbosity ` - Save the configuration and exit.
40
Enabling flash encryption will increase the size of bootloader, which might require updating partition table offset. See :ref:`bootloader-size`. .. code-block:: bash idf.py flash monitor .. note:: This command does not include any user files which should be written to the partitions on the flash memory. Please write them manually before running this command otherwise the files should be encrypted separately before writing. This command will write to flash memory unencrypted images: the firmware bootloader, the partition table and applications. Once the flashing is complete, {IDF_TARGET_NAME} will reset. On the next boot, the firmware bootloader encrypts: the firmware bootloader, application partitions and partitions marked as ``encrypted`` then resets. Encrypting in-place can take time, up to a minute for large partitions. After that, the application is decrypted at runtime and executed. If using Development Mode, then the easiest way to update and re-flash binaries is :ref:`encrypt-partitions`.
40
If using Release Mode, then it is possible to pre-encrypt the binaries on the host and then flash them as ciphertext. See :ref:`manual-encryption`. .. _encrypt-partitions: Re-flashing Updated Partitions """""""""""""""""""""""""""""" If you update your application code (done in plaintext) and want to re-flash it, you will need to encrypt it before flashing. To encrypt the application and flash it in one step, run: .. code-block:: bash idf.py encrypted-app-flash monitor If all partitions needs to be updated in encrypted format, run: .. code-block:: bash idf.py encrypted-flash monitor .. _flash-enc-release-mode: Release Mode In Release mode, UART bootloader cannot perform flash encryption operations. New plaintext images can ONLY be downloaded using the over-the-air (OTA) scheme which will encrypt the plaintext image before writing to flash. To use this mode, take the following steps: See how to check :ref:`flash-encryption-status`. .. list:: - :ref:`Enable flash encryption on boot ` :esp32: - :ref:`Select Release mode ` (Note that once Release mode is selected, the ``DISABLE_DL_ENCRYPT`` and ``DISABLE_DL_DECRYPT`` eFuse bits will be burned to disable flash encryption hardware in ROM Download Mode.
40
) :esp32: - :ref:`Select UART ROM download mode (Permanently disabled (recommended)) ` (Note that this option is only available when :ref:`CONFIG_ESP32_REV_MIN` is set to 3 (ESP32 V3).) The default choice is to keep UART ROM download mode enabled, however it is recommended to permanently disable this mode to reduce the options available to an attacker. :not esp32: - :ref:`Select Release mode ` (Note that once Release mode is selected, the ``EFUSE_DIS_DOWNLOAD_MANUAL_ENCRYPT`` eFuse bit will be burned to disable flash encryption hardware in ROM Download Mode.) :not esp32: - :ref:`Select UART ROM download mode (Permanently switch to Secure mode (recommended)) `. This is the default option, and is recommended. It is also possible to change this configuration setting to permanently disable UART ROM download mode, if this mode is not needed. - :ref:`Select the appropriate bootloader log verbosity ` - Save the configuration and exit. Enabling flash encryption will increase the size of bootloader, which might require updating partition table offset.
40
See :ref:`bootloader-size`. .. code-block:: bash idf.py flash monitor .. note:: This command does not include any user files which should be written to the partitions on the flash memory. Please write them manually before running this command otherwise the files should be encrypted separately before writing. This command will write to flash memory unencrypted images: the firmware bootloader, the partition table and applications. Once the flashing is complete, {IDF_TARGET_NAME} will reset. On the next boot, the firmware bootloader encrypts: the firmware bootloader, application partitions and partitions marked as ``encrypted`` then resets. Encrypting in-place can take time, up to a minute for large partitions. After that, the application is decrypted at runtime and executed. Once the flash encryption is enabled in Release mode, the bootloader will write-protect the ``{IDF_TARGET_CRYPT_CNT}`` eFuse. For subsequent plaintext field updates, use :ref:`OTA scheme `.
40
.. note:: If you have pre-generated the flash encryption key and stored a copy, and the UART download mode is not permanently disabled via :ref:`CONFIG_SECURE_UART_ROM_DL_MODE` {IDF_TARGET_ESP32_V3_ONLY}, then it is possible to update the flash locally by pre-encrypting the files and then flashing the ciphertext. See :ref:`manual-encryption`. .. _flash-encrypt-best-practices: Best Practices When using Flash Encryption in production: .. list:: - Do not reuse the same flash encryption key between multiple devices. This means that an attacker who copies encrypted data from one device cannot transfer it to a second device. :esp32: - When using ESP32 V3, if the UART ROM Download Mode is not needed for a production device then it should be disabled to provide an extra level of protection. Do this by calling :cpp:func:`esp_efuse_disable_rom_download_mode` during application startup. Alternatively, configure the project :ref:`CONFIG_ESP32_REV_MIN` level to 3 (targeting ESP32 V3 only) and select the :ref:`CONFIG_SECURE_UART_ROM_DL_MODE` to "Permanently disable ROM Download Mode (recommended)".
40
The ability to disable ROM Download Mode is not available on earlier ESP32 versions. :not esp32: - The UART ROM Download Mode should be disabled entirely if it is not needed, or permanently set to "Secure Download Mode" otherwise. Secure Download Mode permanently limits the available commands to updating SPI config, changing baud rate, basic flash write, and returning a summary of the currently enabled security features with the `get_security_info` command. The default behaviour is to set Secure Download Mode on first boot in Release mode. To disable Download Mode entirely, select :ref:`CONFIG_SECURE_UART_ROM_DL_MODE` to "Permanently disable ROM Download Mode (recommended)" or call :cpp:func:`esp_efuse_disable_rom_download_mode` at runtime. - Enable :doc:`Secure Boot ` as an extra layer of protection, and to prevent an attacker from selectively corrupting any part of the flash before boot. Enable Flash Encryption Externally In the process mentioned above, flash encryption related eFuses which ultimately enable flash encryption are programmed through the firmware bootloader.
40
Alternatively, all the eFuses can be programmed with the help of ``espefuse`` tool. Please refer :ref:`enable-flash-encryption-externally` for more details. Possible Failures Once flash encryption is enabled, the ``{IDF_TARGET_CRYPT_CNT}`` eFuse value will have an odd number of bits set. It means that all the partitions marked with the encryption flag are expected to contain encrypted ciphertext. Below are the three typical failure cases if the {IDF_TARGET_NAME} is erroneously loaded with plaintext data: .. only:: esp32 .. code-block:: bash rst:0x3 (SW_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) flash read err, 1000 ets_main.c 371 ets Jun 8 2016 00:22:57 rst:0x7 (TG0WDT_SYS_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) flash read err, 1000 ets_main.c 371 ets Jun 8 2016 00:22:57 rst:0x7 (TG0WDT_SYS_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) flash read err, 1000 ets_main.c 371 ets Jun 8 2016 00:22:57 rst:0x7 (TG0WDT_SYS_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) flash read err, 1000 ets_main.
40
c 371 ets Jun 8 2016 00:22:57 rst:0x7 (TG0WDT_SYS_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) flash read err, 1000 ets_main.c 371 ets Jun 8 2016 00:22:57 .. only:: not esp32 .. code-block:: bash rst:0x3 (SW_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) invalid header: 0xb414f76b invalid header: 0xb414f76b invalid header: 0xb414f76b invalid header: 0xb414f76b invalid header: 0xb414f76b invalid header: 0xb414f76b invalid header: 0xb414f76b .. note:: The value of invalid header will be different for every application. .. note:: This error also appears if the flash contents are erased or corrupted. .. code-block:: bash rst:0x3 (SW_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) configsip: 0, SPIWP:0xee clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00 mode:DIO, clock div:2 load:0x3fff0018,len:4 load:0x3fff001c,len:10464 ho 0 tail 12 room 4 load:0x40078000,len:19168 load:0x40080400,len:6664 entry 0x40080764 I (60) boot: ESP-IDF v4.
40
0-dev-763-g2c55fae6c-dirty 2nd stage bootloader I (60) boot: compile time 19:15:54 I (62) boot: Enabling RNG early entropy source... I (67) boot: SPI Speed : 40MHz I (72) boot: SPI Mode : DIO I (76) boot: SPI Flash Size : 4MB E (80) flash_parts: partition 0 invalid magic number 0x94f6 E (86) boot: Failed to verify partition table E (91) boot: load partition table error! .. code-block:: bash rst:0x3 (SW_RESET),boot:0x13 (SPI_FAST_FLASH_BOOT) configsip: 0, SPIWP:0xee clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00 mode:DIO, clock div:2 load:0x3fff0018,len:4 load:0x3fff001c,len:8452 load:0x40078000,len:13616 load:0x40080400,len:6664 entry 0x40080764 I (56) boot: ESP-IDF v4.0-dev-850-gc4447462d-dirty 2nd stage bootloader I (56) boot: compile time 15:37:14 I (58) boot: Enabling RNG early entropy source... I (64) boot: SPI Speed : 40MHz I (68) boot: SPI Mode : DIO I (72) boot: SPI Flash Size : 4MB I (76) boot: Partition Table: I (79) boot: ## Label Usage Type ST Offset Length I (87) boot: 0 nvs WiFi data 01 02 0000a000 00006000 I (94) boot: 1 phy_init RF data 01 01 00010000 00001000 I (102) boot: 2 factory factory app 00 00 00020000 00100000 I (109) boot: End of partition table E (113) esp_image: image at 0x20000 has invalid magic byte W (120) esp_image: image at 0x20000 has invalid SPI mode 108 W (126) esp_image: image at 0x20000 has invalid SPI size 11 E (132) boot: Factory app partition is not bootable E (138) boot: No bootable app partitions in the partition table .
40
. _flash-encryption-status: {IDF_TARGET_NAME} Flash Encryption Status To check if flash encryption on your {IDF_TARGET_NAME} device is enabled, do one of the following: - flash the application example :example:`security/flash_encryption` onto your device. This application prints the ``{IDF_TARGET_CRYPT_CNT}`` eFuse value and if flash encryption is enabled or disabled. - :doc:`Find the serial port name ` under which your {IDF_TARGET_NAME} device is connected, replace ``PORT`` with your port name in the following command, and run it: .. code-block:: bash espefuse.py -p PORT summary .. _reading-writing-content: Reading and Writing Data in Encrypted Flash {IDF_TARGET_NAME} application code can check if flash encryption is currently enabled by calling :cpp:func:`esp_flash_encryption_enabled`. Also, a device can identify the flash encryption mode by calling :cpp:func:`esp_get_flash_encryption_mode`. Once flash encryption is enabled, be more careful with accessing flash contents from code.
40
Scope of Flash Encryption Whenever the ``{IDF_TARGET_CRYPT_CNT}`` eFuse is set to a value with an odd number of bits, all flash content accessed via the MMU's flash cache is transparently decrypted. It includes: - Executable application code in flash (IROM). - All read-only data stored in flash (DROM). - Any data accessed via :cpp:func:`spi_flash_mmap`. - The firmware bootloader image when it is read by the ROM bootloader. .. important:: The MMU flash cache unconditionally decrypts all existing data. Data which is stored unencrypted in flash memory will also be "transparently decrypted" via the flash cache and will appear to software as random garbage. Reading from Encrypted Flash To read data without using a flash cache MMU mapping, you can use the partition read function :cpp:func:`esp_partition_read`. This function will only decrypt data when it is read from an encrypted partition. Data read from unencrypted partitions will not be decrypted. In this way, software can access encrypted and non-encrypted flash in the same way.
40
You can also use the following SPI flash API functions: - :cpp:func:`esp_flash_read` to read raw (encrypted) data which will not be decrypted - :cpp:func:`esp_flash_read_encrypted` to read and decrypt data Data stored using the Non-Volatile Storage (NVS) API is always stored and read decrypted from the perspective of flash encryption. It is up to the library to provide encryption feature if required. Refer to :doc:`../api-reference/storage/nvs_encryption` for more details. Writing to Encrypted Flash It is recommended to use the partition write function :cpp:func:`esp_partition_write`. This function will only encrypt data when it is written to an encrypted partition. Data written to unencrypted partitions will not be encrypted. In this way, software can access encrypted and non-encrypted flash in the same way. You can also pre-encrypt and write data using the function :cpp:func:`esp_flash_write_encrypted` Also, the following ROM function exist but not supported in esp-idf applications: - ``esp_rom_spiflash_write_encrypted`` pre-encrypts and writes data to flash - ``SPIWrite`` writes unencrypted data to flash Since data is encrypted in blocks, the minimum write size for encrypted data is 16 bytes and the alignment is also 16 bytes.
40
.. _updating-encrypted-flash: Updating Encrypted Flash .. _updating-encrypted-flash-ota: OTA Updates OTA updates to encrypted partitions will automatically write encrypted data if the function :cpp:func:`esp_partition_write` is used. Before building the application image for OTA updating of an already encrypted device, enable the option :ref:`Enable flash encryption on boot ` in project configuration menu. For general information about ESP-IDF OTA updates, please refer to :doc:`OTA ` .. _updating-encrypted-flash-serial: Updating Encrypted Flash via Serial Flashing an encrypted device via serial bootloader requires that the serial bootloader download interface has not been permanently disabled via eFuse. In Development Mode, the recommended method is :ref:`encrypt-partitions`. In Release Mode, if a copy of the same key stored in eFuse is available on the host then it is possible to pre-encrypt files on the host and then flash them. See :ref:`manual-encryption`. Disabling Flash Encryption If flash encryption was enabled accidentally, flashing of plaintext data will soft-brick the {IDF_TARGET_NAME}.
40
The device will reboot continuously, printing the error ``flash read err, 1000`` or ``invalid header: 0xXXXXXX``. .. only:: esp32 For flash encryption in Development mode, encryption can be disabled by burning the ``{IDF_TARGET_CRYPT_CNT}`` eFuse. It can only be done three times per chip by taking the following steps: .. only:: not esp32 For flash encryption in Development mode, encryption can be disabled by burning the ``{IDF_TARGET_CRYPT_CNT}`` eFuse. It can only be done one time per chip by taking the following steps: #. In :ref:`project-configuration-menu`, disable :ref:`Enable flash encryption on boot `, then save and exit. #. Open project configuration menu again and **double-check** that you have disabled this option! If this option is left enabled, the bootloader will immediately re-enable encryption when it boots. #. With flash encryption disabled, build and flash the new bootloader and application by running ``idf.py flash``. #. Use ``espefuse.py`` (in ``components/esptool_py/esptool``) to disable the ``{IDF_TARGET_CRYPT_CNT}`` by running: .
40
. code-block:: bash espefuse.py burn_efuse {IDF_TARGET_CRYPT_CNT} Reset the {IDF_TARGET_NAME}. Flash encryption will be disabled, and the bootloader will boot as usual. Key Points About Flash Encryption .. list:: :esp32: - Flash memory contents is encrypted using AES-256. The flash encryption key is stored in the ``flash_encryption`` eFuse internal to the chip and, by default, is protected from software access. :esp32: - The flash encryption algorithm is AES-256, where the key is "tweaked" with the offset address of each 32 byte block of flash. This means that every 32-byte block (two consecutive 16 byte AES blocks) is encrypted with a unique key derived from the flash encryption key. :SOC_FLASH_ENCRYPTION_XTS_AES_256: - Flash memory contents is encrypted using XTS-AES-128 or XTS-AES-256. The flash encryption key is 256 bits and 512 bits respectively and stored in one or two ``BLOCK_KEYN`` eFuses internal to the chip and, by default, is protected from software access.
40
:SOC_FLASH_ENCRYPTION_XTS_AES_128 and not SOC_FLASH_ENCRYPTION_XTS_AES_256 and not SOC_FLASH_ENCRYPTION_XTS_AES_128_DERIVED: - Flash memory contents is encrypted using XTS-AES-128. The flash encryption key is 256 bits and stored in one ``BLOCK_KEYN`` eFuse internal to the chip and, by default, is protected from software access. :SOC_FLASH_ENCRYPTION_XTS_AES_128_DERIVED: - Flash memory contents is encrypted using XTS-AES-128. The flash encryption key is 256 or 128 bits and stored in ``BLOCK_KEY0`` eFuse internal to the chip and, by default, is protected from software access. - Flash access is transparent via the flash cache mapping feature of {IDF_TARGET_NAME} - any flash regions which are mapped to the address space will be transparently decrypted when read. Some data partitions might need to remain unencrypted for ease of access or might require the use of flash-friendly update algorithms which are ineffective if the data is encrypted. NVS partitions for non-volatile storage cannot be encrypted since the NVS library is not directly compatible with flash encryption.
40
For details, refer to :doc:`NVS Encryption `. - If flash encryption might be used in future, the programmer must keep it in mind and take certain precautions when writing code that :ref:`uses encrypted flash `. - If secure boot is enabled, re-flashing the bootloader of an encrypted device requires a "Re-flashable" secure boot digest (see :ref:`flash-encryption-and-secure-boot`). Enabling flash encryption will increase the size of bootloader, which might require updating partition table offset. See :ref:`bootloader-size`. .. important:: Do not interrupt power to the {IDF_TARGET_NAME} while the first boot encryption pass is running. If power is interrupted, the flash contents will be corrupted and will require flashing with unencrypted data again. In this case, re-flashing will not count towards the flashing limit. .. _flash-encryption-limitations: Limitations of Flash Encryption Flash encryption protects firmware against unauthorised readout and modification. It is important to understand the limitations of the flash encryption feature: .
40
. list:: - Flash encryption is only as strong as the key. For this reason, we recommend keys are generated on the device during first boot (default behaviour). If generating keys off-device, ensure proper procedure is followed and do not share the same key between all production devices. - Not all data is stored encrypted. If storing data on flash, check if the method you are using (library, API, etc.) supports flash encryption. - Flash encryption does not prevent an attacker from understanding the high-level layout of the flash. This is because the same AES key is used for every pair of adjacent 16 byte AES blocks. When these adjacent 16 byte blocks contain identical content (such as empty or padding areas), these blocks will encrypt to produce matching pairs of encrypted blocks. This may allow an attacker to make high-level comparisons between encrypted devices (i.e., to tell if two devices are probably running the same firmware version). :esp32: - For the same reason, an attacker can always tell when a pair of adjacent 16 byte blocks (32 byte aligned) contain two identical 16 byte sequences.
40
Keep this in mind if storing sensitive data on the flash, design your flash storage so this does not happen (using a counter byte or some other non-identical value every 16 bytes is sufficient). :doc:`NVS Encryption ` deals with this and is suitable for many uses. - Flash encryption alone may not prevent an attacker from modifying the firmware of the device. To prevent unauthorised firmware from running on the device, use flash encryption in combination with :doc:`Secure Boot `. .. _flash-encryption-and-secure-boot: Flash Encryption and Secure Boot It is recommended to use flash encryption in combination with Secure Boot. However, if Secure Boot is enabled, additional restrictions apply to device re-flashing: - :ref:`updating-encrypted-flash-ota` are not restricted, provided that the new app is signed correctly with the Secure Boot signing key. .. only:: esp32 - :ref:`Plaintext serial flash updates ` are only possible if the :ref:`Re-flashable ` Secure Boot mode is selected and a Secure Boot key was pre-generated and burned to the {IDF_TARGET_NAME} (refer to :ref:`Secure Boot `).
40
In such configuration, ``idf.py bootloader`` will produce a pre-digested bootloader and secure boot digest file for flashing at offset 0x0. When following the plaintext serial re-flashing steps it is necessary to re-flash this file before flashing other plaintext data. - :ref:`Re-flashing via Pregenerated Flash Encryption Key ` is still possible, provided the bootloader is not re-flashed. Re-flashing the bootloader requires the same :ref:`Re-flashable ` option to be enabled in the Secure Boot config. .. _flash-encryption-advanced-features: Advanced Features The following section covers advanced features of flash encryption. .. _encrypted-partition-flag: Encrypted Partition Flag Some partitions are encrypted by default. Other partitions can be marked in the partition table description as requiring encryption by adding the flag ``encrypted`` to the partitions' flag field. As a result, data in these marked partitions will be treated as encrypted in the same manner as an app partition.
40
.. code-block:: bash # Name, Type, SubType, Offset, Size, Flags nvs, data, nvs, 0x9000, 0x6000 phy_init, data, phy, 0xf000, 0x1000 factory, app, factory, 0x10000, 1M secret_data, 0x40, 0x01, 0x20000, 256K, encrypted For details on partition table description, see :doc:`partition table `. Further information about encryption of partitions: - Default partition tables do not include any encrypted data partitions. - With flash encryption enabled, the ``app`` partition is always treated as encrypted and does not require marking. - If flash encryption is not enabled, the flag "encrypted" has no effect. - You can also consider protecting ``phy_init`` data from physical access, readout, or modification, by marking the optional ``phy`` partition with the flag ``encrypted``. - The ``nvs`` partition cannot be encrypted, because the NVS library is not directly compatible with flash encryption. .. _uart-bootloader-encryption: Enabling UART Bootloader Encryption/Decryption On the first boot, the flash encryption process burns by default the following eFuses: .
40
. only:: esp32 - ``DISABLE_DL_ENCRYPT`` which disables flash encryption operation when running in UART bootloader boot mode. - ``DISABLE_DL_DECRYPT`` which disables transparent flash decryption when running in UART bootloader mode, even if the eFuse ``{IDF_TARGET_CRYPT_CNT}`` is set to enable it in normal operation. - ``DISABLE_DL_CACHE`` which disables the entire MMU flash cache when running in UART bootloader mode. .. only:: not esp32 .. list:: - ``DIS_DOWNLOAD_MANUAL_ENCRYPT`` which disables flash encryption operation when running in UART bootloader boot mode. :SOC_EFUSE_DIS_DOWNLOAD_ICACHE and SOC_EFUSE_DIS_DOWNLOAD_DCACHE: - ``DIS_DOWNLOAD_ICACHE`` and ``DIS_DOWNLOAD_DCACHE`` which disables the entire MMU flash cache when running in UART bootloader mode. :SOC_EFUSE_DIS_DOWNLOAD_ICACHE and not SOC_EFUSE_DIS_DOWNLOAD_DCACHE: - ``DIS_DOWNLOAD_ICACHE`` which disables the entire MMU flash cache when running in UART bootloader mode. :esp32s2: - ``HARD_DIS_JTAG`` which disables JTAG.
40
:SOC_EFUSE_DIS_PAD_JTAG and SOC_EFUSE_DIS_USB_JTAG: - ``DIS_PAD_JTAG`` and ``DIS_USB_JTAG`` which disables JTAG. :SOC_EFUSE_HARD_DIS_JTAG and SOC_EFUSE_DIS_USB_JTAG: - ``HARD_DIS_JTAG`` and ``DIS_USB_JTAG`` which disables JTAG. - ``DIS_DIRECT_BOOT`` (old name ``DIS_LEGACY_SPI_BOOT``) which disables direct boot mode :SOC_EFUSE_DIS_DOWNLOAD_MSPI: - ``DIS_DOWNLOAD_MSPI`` which disables the MSPI access in download mode. However, before the first boot you can choose to keep any of these features enabled by burning only selected eFuses and write-protect the rest of eFuses with unset value 0. For example: .. only:: esp32 .. code-block:: bash espefuse.py --port PORT burn_efuse DISABLE_DL_DECRYPT espefuse.py --port PORT write_protect_efuse DISABLE_DL_ENCRYPT .. only:: not esp32 .. code-block:: bash espefuse.py --port PORT burn_efuse DIS_DOWNLOAD_MANUAL_ENCRYPT espefuse.py --port PORT write_protect_efuse DIS_DOWNLOAD_MANUAL_ENCRYPT .. note:: Set all appropriate bits before write-protecting!
40
Write protection of all the three eFuses is controlled by one bit. It means that write-protecting one eFuse bit will inevitably write-protect all unset eFuse bits. Write protecting these eFuses to keep them unset is not currently very useful, as ``esptool.py`` does not support reading encrypted flash. .. only:: esp32 .. important:: Leaving ``DISABLE_DL_DECRYPT`` unset (0) makes flash encryption useless. An attacker with physical access to the chip can use UART bootloader mode with custom stub code to read out the flash contents. .. only:: esp32 .. _setting-flash-crypt-config: Setting FLASH_CRYPT_CONFIG The eFuse ``FLASH_CRYPT_CONFIG`` determines the number of bits in the flash encryption key which are "tweaked" with the block offset. For details, see :ref:`flash-encryption-algorithm`. On the first boot of the firmware bootloader, this value is set to the maximum ``0xF``. It is possible to burn this eFuse manually and write protect it before the first boot in order to select different tweak values.
40
However, this is not recommended. It is strongly recommended to never write-protect ``FLASH_CRYPT_CONFIG`` when it is unset. Otherwise, its value will remain zero permanently, and no bits in the flash encryption key will be tweaked. As a result, the flash encryption algorithm will be equivalent to AES ECB mode. JTAG Debugging By default, when Flash Encryption is enabled (in either Development or Release mode) then JTAG debugging is disabled via eFuse. The bootloader does this on first boot, at the same time it enables flash encryption. See :ref:`jtag-debugging-security-features` for more information about using JTAG Debugging with Flash Encryption. .. _manual-encryption: Manually Encrypting Files Manually encrypting or decrypting files requires the flash encryption key to be pre-burned in eFuse (see :ref:`pregenerated-flash-encryption-key`) and a copy to be kept on the host. If the flash encryption is configured in Development Mode then it is not necessary to keep a copy of the key or follow these steps, the simpler :ref:`encrypt-partitions` steps can be used.
40
The key file should be a single raw binary file (example: ``key.bin``). For example, these are the steps to encrypt the file ``build/my-app.bin`` to flash at offset 0x10000. Run espsecure.py as follows: .. only:: esp32 .. code-block:: bash espsecure.py encrypt_flash_data --keyfile /path/to/key.bin --address 0x10000 --output my-app-ciphertext.bin build/my-app.bin .. only:: not esp32 .. code-block:: bash espsecure.py encrypt_flash_data --aes_xts --keyfile /path/to/key.bin --address 0x10000 --output my-app-ciphertext.bin build/my-app.bin The file ``my-app-ciphertext.bin`` can then be flashed to offset 0x10000 using ``esptool.py``. To see all of the command line options recommended for ``esptool.py``, see the output printed when ``idf.py build`` succeeds. .. note:: If the flashed ciphertext file is not recognized by the {IDF_TARGET_NAME} when it boots, check that the keys match and that the command line arguments match exactly, including the correct offset.
40
.. only:: esp32 If your ESP32 uses non-default :ref:`FLASH_CRYPT_CONFIG value in eFuse ` then you will need to pass the ``--flash_crypt_conf`` argument to ``espsecure.py`` to set the matching value. This will not happen if the device configured flash encryption by itself, but may happen if burning eFuses manually to enable flash encryption. The command ``espsecure.py decrypt_flash_data`` can be used with the same options (and different input/output files), to decrypt ciphertext flash contents or a previously encrypted file. .. only:: SOC_SPIRAM_SUPPORTED and not esp32 External RAM When Flash Encryption is enabled any data read from and written to external SPI RAM through the cache will also be encrypted/decrypted. This happens the same way and with the same key as for Flash Encryption. If Flash Encryption is enabled then encryption for external SPI RAM is also always enabled, it is not possible to separately control this functionality. Technical Details The following sections provide some reference information about the operation of flash encryption.
40
.. only:: not SOC_FLASH_ENCRYPTION_XTS_AES .. _flash-encryption-algorithm: Flash Encryption Algorithm - AES-256 operates on 16-byte blocks of data. The flash encryption engine encrypts and decrypts data in 32-byte blocks - two AES blocks in series. - The main flash encryption key is stored in the ``flash_encryption`` eFuse and, by default, is protected from further writes or software readout. - AES-256 key size is 256 bits (32 bytes) read from the ``flash_encryption`` eFuse. The hardware AES engine uses the key in reversed byte order as compared to the storage order in ``flash_encryption``. - If the ``CODING_SCHEME`` eFuse is set to ``0`` (default, "None" Coding Scheme) then the eFuse key block is 256 bits and the key is stored as-is (in reversed byte order). - If the ``CODING_SCHEME`` eFuse is set to ``1`` (3/4 Encoding) then the eFuse key block is 192 bits (in reversed byte order), so overall entropy is reduced. The hardware flash encryption still operates on a 256-bit key, after being read (and un-reversed), the key is extended as ``key = key[0:255] + key[64:127]``.
40
- AES algorithm is used inverted in flash encryption, so the flash encryption "encrypt" operation is AES decrypt and the "decrypt" operation is AES encrypt. This is for performance reasons and does not alter the effeciency of the algorithm. - Each 32-byte block (two adjacent 16-byte AES blocks) is encrypted with a unique key. The key is derived from the main flash encryption key in ``flash_encryption``, XORed with the offset of this block in the flash (a "key tweak"). - The specific tweak depends on the ``FLASH_CRYPT_CONFIG`` eFuse setting. This is a 4-bit eFuse where each bit enables XORing of a particular range of the key bits: - Bit 1, bits 0-66 of the key are XORed. - Bit 2, bits 67-131 of the key are XORed. - Bit 3, bits 132-194 of the key are XORed. - Bit 4, bits 195-256 of the key are XORed. It is recommended that ``FLASH_CRYPT_CONFIG`` is always left at the default value ``0xF``, so that all key bits are XORed with the block offset. For details, see :ref:`setting-flash-crypt-config`.
40
- The high 19 bits of the block offset (bit 5 to bit 23) are XORed with the main flash encryption key. This range is chosen for two reasons: the maximum flash size is 16MB (24 bits), and each block is 32 bytes so the least significant 5 bits are always zero. - There is a particular mapping from each of the 19 block offset bits to the 256 bits of the flash encryption key to determine which bit is XORed with which. See the variable ``_FLASH_ENCRYPTION_TWEAK_PATTERN`` in the ``espsecure.py`` source code for complete mapping. - To see the full flash encryption algorithm implemented in Python, refer to the ``_flash_encryption_operation()`` function in the ``espsecure.py`` source code. .. only:: SOC_FLASH_ENCRYPTION_XTS_AES_256 .. _flash-encryption-algorithm: Flash Encryption Algorithm - {IDF_TARGET_NAME} use the XTS-AES block cipher mode with 256 bit or 512 bit key size for flash encryption. - XTS-AES is a block cipher mode specifically designed for disc encryption and addresses the weaknesses other potential modes (e.
40
g., AES-CTR) have for this use case. A detailed description of the XTS-AES algorithm can be found in `IEEE Std 1619-2007 `_. - The flash encryption key is stored in one or two ``BLOCK_KEYN`` eFuses and, by default, is protected from further writes or software readout. - To see the full flash encryption algorithm implemented in Python, refer to the `_flash_encryption_operation()` function in the ``espsecure.py`` source code. .. only:: SOC_FLASH_ENCRYPTION_XTS_AES_128 and not SOC_FLASH_ENCRYPTION_XTS_AES_256 and not SOC_EFUSE_CONSISTS_OF_ONE_KEY_BLOCK .. _flash-encryption-algorithm: Flash Encryption Algorithm - {IDF_TARGET_NAME} use the XTS-AES block chiper mode with 256 bit size for flash encryption. - XTS-AES is a block chiper mode specifically designed for disc encryption and addresses the weaknesses other potential modes (e.g., AES-CTR) have for this use case. A detailed description of the XTS-AES algorithm can be found in `IEEE Std 1619-2007 `_. - The flash encryption key is stored in one ``BLOCK_KEYN`` eFuse and, by default, is protected from further writes or software readout.
40
- To see the full flash encryption algorithm implemented in Python, refer to the `_flash_encryption_operation()` function in the ``espsecure.py`` source code. .. only:: SOC_FLASH_ENCRYPTION_XTS_AES_128 and SOC_EFUSE_CONSISTS_OF_ONE_KEY_BLOCK .. _flash-encryption-algorithm: Flash Encryption Algorithm - {IDF_TARGET_NAME} use the XTS-AES block chiper mode with 256 bit size for flash encryption. In case the 128-bit key is stored in the eFuse key block, the final 256-bit AES key is obtained as SHA256(EFUSE_KEY0_FE_128BIT). - XTS-AES is a block chiper mode specifically designed for disc encryption and addresses the weaknesses other potential modes (e.g., AES-CTR) have for this use case. A detailed description of the XTS-AES algorithm can be found in `IEEE Std 1619-2007 `_. - The flash encryption key is stored in ``BLOCK_KEY0`` eFuse and, by default, is protected from further writes or software readout. - To see the full flash encryption algorithm implemented in Python, refer to the `_flash_encryption_operation()` function in the ``espsecure.
40
py`` source code.
40
Security {IDF_TARGET_CIPHER_SCHEME:default="RSA", esp32h2="RSA or ECDSA", esp32p4="RSA or ECDSA"} {IDF_TARGET_SIG_PERI:default="DS", esp32h2="DS or ECDSA", esp32p4="DS or ECDSA"} This guide provides an overview of the overall security features available in various Espressif solutions. It is highly recommended to consider this guide while designing the products with the Espressif platform and the ESP-IDF software stack from the **security** perspective. Goals High level security goals are as follows: #. Preventing untrustworthy code from being executed #. Protecting the identity and integrity of the code stored in the off-chip flash memory #. Securing device identity #. Secure storage for confidential data #. Authenticated and encrypted communication from the device Platform Security .. _secure_boot-guide: Secure Boot ~~~~~~~~~~~ The Secure Boot feature ensures that only authenticated software can execute on the device. The Secure Boot process forms a chain of trust by verifying all **mutable** software entities involved in the :doc:`.
41
./api-guides/startup`. Signature verification happens during both boot-up as well as in OTA updates. Please refer to :doc:`secure-boot-v2` for detailed documentation about this feature. .. only:: esp32 For ESP32 before ECO3, please refer to :doc:`secure-boot-v1`. .. important:: It is highly recommended that Secure Boot be enabled on all production devices. Secure Boot Best Practices .. _flash_enc-guide: Flash Encryption ~~~~~~~~~~~~~~~~ The Flash Encryption feature helps to encrypt the contents on the off-chip flash memory and thus provides the **confidentiality** aspect to the software or data stored in the flash memory. Please refer to :doc:`flash-encryption` for detailed information about this feature. .. only:: SOC_SPIRAM_SUPPORTED and not esp32 If {IDF_TARGET_NAME} is connected to an external SPI RAM, the contents written to or read from the SPI RAM will also be encrypted and decrypted respectively (via the MMU's flash cache, provided that FLash Encryption is enabled).
41
This provides an additional safety layer for the data stored in SPI RAM, hence configurations like ``CONFIG_MBEDTLS_EXTERNAL_MEM_ALLOC`` can be safely enabled in this case. Flash Encryption Best Practices .. only:: SOC_DIG_SIGN_SUPPORTED Device Identity ~~~~~~~~~~~~~~~ The Digital Signature peripheral in {IDF_TARGET_NAME} produces hardware-accelerated RSA digital signatures with the assistance of HMAC, without the RSA private key being accessible by software. This allows the private key to be kept secured on the device without anyone other than the device hardware being able to access it. .. only:: SOC_ECDSA_SUPPORTED {IDF_TARGET_NAME} also supportes ECDSA peripheral for generating hardware-accelerated ECDSA digital signatures. ECDSA private key can be directly programmed in an eFuse block and marked as read protected from the software. {IDF_TARGET_SIG_PERI} peripheral can help to establish the **Secure Device Identity** to the remote endpoint, e.g.
41
, in the case of TLS mutual authentication based on the {IDF_TARGET_CIPHER_SCHEME} cipher scheme. .. only:: not SOC_ECDSA_SUPPORTED Please refer to the :doc:`../api-reference/peripherals/ds` for detailed documentation. .. only:: SOC_ECDSA_SUPPORTED Please refer to the :doc:`../api-reference/peripherals/ecdsa` and :doc:`../api-reference/peripherals/ds` guides for detailed documentation. .. only:: SOC_MEMPROT_SUPPORTED or SOC_CPU_IDRAM_SPLIT_USING_PMP Memory Protection ~~~~~~~~~~~~~~~~~ {IDF_TARGET_NAME} supports the **Memory Protection** scheme, either through architecture or special peripheral like PMS, which provides an ability to enforce and monitor permission attributes to memory and, in some cases, peripherals. ESP-IDF application startup code configures the permissions attributes like Read/Write access on data memories and Read/Execute access on instruction memories using the relevant peripheral. If there is any attempt made that breaks these permission attributes, e.
41
g., a write operation to instruction memory region, then a violation interrupt is raised, and it results in system panic. This feature depends on the config option :ref:`CONFIG_ESP_SYSTEM_MEMPROT_FEATURE` and it is kept enabled by default. Please note that the API for this feature is **private** and used exclusively by ESP-IDF code only. .. note:: This feature can help to prevent the possibility of remote code injection due to the existing vulnerabilities in the software. .. only:: SOC_CRYPTO_DPA_PROTECTION_SUPPORTED DPA (Differential Power Analysis) Protection ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ {IDF_TARGET_NAME} has support for protection mechanisms against the Differential Power Analysis related security attacks. DPA protection dynamically adjusts the clock frequency of the crypto peripherals, thereby blurring the power consumption trajectory during its operation. Based on the configured DPA security level, the clock variation range changes.
41
Please refer to the TRM for more details on this topic. :ref:`CONFIG_ESP_CRYPTO_DPA_PROTECTION_LEVEL` can help to select the DPA level. Higher level means better security, but it can also have an associated performance impact. By default, the lowest DPA level is kept enabled but it can be modified based on the security requirement. .. note:: Please note that hardware :doc:`RNG ` must be enabled for DPA protection to work correctly. Debug Interfaces ~~~~~~~~~~~~~~~~ JTAG .. list:: - JTAG interface stays disabled if any of the security features are enabled. Please refer to :ref:`jtag-debugging-security-features` for more information. - JTAG interface can also be disabled in the absence of any other security features using :ref:`efuse_API`. :SOC_HMAC_SUPPORTED: - {IDF_TARGET_NAME} supports soft disabling the JTAG interface and it can be re-enabled by programming a secret key through HMAC. (:ref:`hmac_for_enabling_jtag`) UART Download Mode .. only:: esp32 For ESP32 ECO3 case, UART Download mode stays disabled if any of the security features are enabled in their release configuration.
41
Alternatively, it can also be disabled by calling :cpp:func:`esp_efuse_disable_rom_download_mode` at runtime. .. important:: If UART Download mode is disabled then ``esptool.py`` can not work on the device. .. only:: SOC_SUPPORTS_SECURE_DL_MODE In {IDF_TARGET_NAME}, Secure UART Download mode gets activated if any of the security features are enabled. .. important:: In Secure UART Download mode, ``esptool.py`` can only work with the argument ``--no-stub``. .. only:: SOC_WIFI_SUPPORTED Network Security Wi-Fi ~~~~~ In addition to the traditional security methods (WEP/WPA-TKIP/WPA2-CCMP), Wi-Fi driver in ESP-IDF also supports additional state-of-the-art security protocols. Please refer to the :doc:`../api-guides/wifi-security` for detailed documentation. TLS (Transport Layer Security) ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ It is recommended to use TLS (Transport Layer Security) in all external communications (e.g., cloud communication, OTA updates) from the ESP device.
41
ESP-IDF supports :doc:`../api-reference/protocols/mbedtls` as the official TLS stack. TLS is default integrated in :doc:`../api-reference/protocols/esp_http_client`, :doc:`../api-reference/protocols/esp_https_server` and several other components that ship with ESP-IDF. .. note:: It is recommended to use the ESP-IDF protocol components in their default configuration, which has been ensured to be secure. Disabling of HTTPS and similar security-critical configurations should be avoided. ESP-TLS Abstraction ESP-IDF provides an abstraction layer for the most-used TLS functionalities. Hence, it is recommended that an application uses the API exposed by :doc:`../api-reference/protocols/esp_tls`. :ref:`esp_tls_server_verification` section highlights diverse ways in which the identity of server could be established on the device side. ESP Certificate Bundle The :doc:`../api-reference/protocols/esp_crt_bundle` API provides an easy way to include a bundle of custom x509 root certificates for TLS server verification.
41
The certificate bundle is the easiest way to verify the identity of almost all standard TLS servers. .. important:: It is highly recommended to verify the identity of the server based on X.509 certificates to avoid establishing communication with the **fake** server. Managing Root Certificates Root Certificates embedded inside the application must be managed carefully. Any update to the root certificate list or the :doc:`../api-reference/protocols/esp_crt_bundle` can have an impact on the TLS connection with the remote endpoint. This includes a connection to the OTA update server. In some cases, the problem shall be visible on the next OTA update and it may leave device unable to perform OTA updates forever. Root certificates list update could have following reasons: - New firmware has different set of remote endpoint(s). - The existing certificate has expired. - The certificate has been added or retracted from the upstream certificate bundle.
41
- The certificate list changed due to market share statistics (``CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_CMN`` case). Some guidelines to consider on this topic: - Please consider enabling :ref:`OTA rollback ` and then keep the successful connection to the OTA update server as the checkpoint to cancel the rollback process. This ensures that the newly updated firmware can successfully reach till the OTA update server, otherwise rollback process will go back to the previous firmware on the device. - If you plan to enable the :ref:`CONFIG_MBEDTLS_HAVE_TIME_DATE` option, then please consider to have the time sync mechanism (SNTP) and sufficient number of trusted certificates in place. Product Security .. only:: SOC_WIFI_SUPPORTED Secure Provisioning ~~~~~~~~~~~~~~~~~~~ Secure Provisioning refers to a process of secure on-boarding of the ESP device on to the Wi-Fi network. This mechanism also allows provision of additional custom configuration data during the initial provisioning phase from the provisioning entity, e.
41
g., Smartphone. ESP-IDF provides various security schemes to establish a secure session between ESP and the provisioning entity, they are highlighted at :ref:`provisioning_security_schemes`. Please refer to the :doc:`../api-reference/provisioning/wifi_provisioning` documentation for details and the example code for this feature. .. note:: Espressif provides Android and iOS Phone Apps along with their sources, so that it could be easy to further customize them as per the product requirement. Secure OTA (Over-the-air) Updates ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - OTA Updates must happen over secure transport, e.g., HTTPS. - ESP-IDF provides a simplified abstraction layer :doc:`../api-reference/system/esp_https_ota` for this. - If :ref:`secure_boot-guide` is enabled, then the server should host the signed application image. - If :ref:`flash_enc-guide` is enabled, then no additional steps are required on the server side, encryption shall be taken care on the device itself during flash write.
41
- OTA update :ref:`ota_rollback` can help to switch the application as ``active`` only after its functionality has been verified. Anti-Rollback Protection Anti-rollback protection feature ensures that device only executes the application that meets the security version criteria as stored in its eFuse. So even though the application is trusted and signed by legitimate key, it may contain some revoked security feature or credential. Hence, device must reject any such application. ESP-IDF allows this feature for the application only and it is managed through 2nd stage bootloader. The security version is stored in the device eFuse and it is compared against the application image header during both bootup and over-the-air updates. Please see more information to enable this feature in the :ref:`anti-rollback` guide. Encrypted Firmware Distribution Encrypted firmware distribution during over-the-air updates ensures that the application stays encrypted **in transit** from the server to the the device.
41
This can act as an additional layer of protection on top of the TLS communication during OTA updates and protect the identity of the application. Please see working example for this documented in :ref:`ota_updates_pre-encrypted-firmware` section. Secure Storage ~~~~~~~~~~~~~~ Secure storage refers to the application-specific data that can be stored in a secure manner on the device, i.e., off-chip flash memory. This is typically a read-write flash partition and holds device specific configuration data, e.g., Wi-Fi credentials. ESP-IDF provides the **NVS (Non-volatile Storage)** management component which allows encrypted data partitions. This feature is tied with the platform :ref:`flash_enc-guide` feature described earlier. Please refer to the :ref:`nvs_encryption` for detailed documentation on the working and instructions to enable this feature. .. important:: By default, ESP-IDF components writes the device specific data into the default NVS partition, including Wi-Fi credentials too, and it is recommended to protect this data using **NVS Encryption** feature.
41
Secure Device Control ~~~~~~~~~~~~~~~~~~~~~ ESP-IDF provides capability to control an ESP device over ``Wi-Fi + HTTP`` or ``BLE`` in a secure manner using ESP Local Control component. Please refer to the :doc:`../api-reference/protocols/esp_local_ctrl` for detailed documentation about this feature. Security Policy The ESP-IDF GitHub repository has attached `Security Policy Brief`_. Advisories ~~~~~~~~~~ - Espressif publishes critical `Security Advisories`_, which includes security advisories regarding both hardware and software. - The specific advisories of the ESP-IDF software components are published through the `GitHub repository`_. Software Updates ~~~~~~~~~~~~~~~~ Critical security issues in the ESP-IDF components, and third-party libraries are fixed as and when we find them or when they are reported to us. Gradually, we make the fixes available in all applicable release branches in ESP-IDF. Applicable security issues and CVEs for the ESP-IDF components, third-party libraries are mentioned in the ESP-IDF release notes.
41
.. important:: We recommend periodically updating to the latest bugfix version of the ESP-IDF release to have all critical security fixes available. .. _`Security Policy Brief`: https://github.com/espressif/esp-idf/blob/master/SECURITY.md .. _`Security Advisories`: https://www.espressif.com/en/support/documents/advisories .. _`GitHub repository`: https://github.com/espressif/esp-idf/security/advisories
41
API Reference .. toctree:: :maxdepth: 2 api-conventions protocols/index :SOC_BT_SUPPORTED: bluetooth/index error-codes network/index peripherals/index kconfig provisioning/index storage/index system/index
42
Error Codes Reference This section lists various error code constants defined in ESP-IDF. For general information about error codes in ESP-IDF, see :doc:`Error Handling `. .. include-build-file:: inc/esp_err_defs.inc
43
Project Configuration Introduction The esp-idf-kconfig_ package that ESP-IDF uses is based on kconfiglib_, which is a Python extension to the Kconfig_ system. Kconfig provides a compile-time project configuration mechanism and offers configuration options of several types (e.g., integers, strings, and boolens). Kconfig files specify dependencies between options, default values of options, the way options are grouped together, etc. For the full list of available features, please see Kconfig_ and `kconfiglib extentions`_. .. _project-configuration-menu: Project Configuration Menu Application developers can open a terminal-based project configuration menu with the ``idf.py menuconfig`` build target. After being updated, this configuration is saved in the ``sdkconfig`` file under the project root directory. Based on ``sdkconfig``, application build targets will generate the ``sdkconfig.h`` file under the build directory, and will make the ``sdkconfig`` options available to the project build system and source files.
44
Using ``sdkconfig.defaults`` In some cases, for example, when the ``sdkconfig`` file is under revision control, it may be inconvenient for the build system to change the ``sdkconfig`` file. The build system offers a solution to prevent it from happening, which is to create the ``sdkconfig.defaults`` file. This file is never touched by the build system, and can be created manually or automatically. It contains all the options which matter to the given application and are different from the default ones. The format is the same as that of the ``sdkconfig`` file. ``sdkconfig.defaults`` can be created manually when one remembers all the changed configuration, or it can be generated automatically by running the ``idf.py save-defconfig`` command. Once ``sdkconfig.defaults`` is created, ``sdkconfig`` can be deleted or added to the ignore list of the revision control system (e.g., the ``.gitignore`` file for ``git``). Project build targets will automatically create the ``sdkconfig`` file, populate it with the settings from the ``sdkconfig.
44
defaults`` file, and configure the rest of the settings to their default values. Note that during the build process, settings from ``sdkconfig.defaults`` will not override those already in ``sdkconfig``. For more information, see :ref:`custom-sdkconfig-defaults`. Kconfig Format Rules Format rules for Kconfig files are as follows: - Option names in any menus should have consistent prefixes. The prefix currently should have at least 3 characters. - The unit of indentation should be 4 spaces. All sub-items belonging to a parent item are indented by one level deeper. For example, ``menu`` is indented by 0 spaces, ``config`` ``menu`` by 4 spaces, ``help`` in ``config`` by 8 spaces, and the text under ``help`` by 12 spaces. - No trailing spaces are allowed at the end of the lines. - The maximum length of options is 50 characters. - The maximum length of lines is 120 characters. .. note:: The ``help`` section of each config in the menu is treated as reStructuredText to generate the reference documentation for each option.
44
Format Checker ``kconfcheck`` tool in esp-idf-kconfig_ package is provided for checking Kconfig files against the above format rules. The checker checks all Kconfig and ``Kconfig.projbuild`` files given as arguments, and generates a new file with suffix ``.new`` with some suggestions about how to fix issues (if there are any). Please note that the checker cannot correct all format issues and the responsibility of the developer is to final check and make corrections in order to pass the tests. For example, indentations will be corrected if there is not any misleading formatting, but it cannot come up with a common prefix for options inside a menu. The ``esp-idf-kconfig`` package is available in ESP-IDF environments, where the checker tool can be invoked by running command ``python -m kconfcheck ``. For more information, please refer to `esp-idf-kconfig package documentation `__. .. _configuration-options-compatibility: Backward Compatibility of Kconfig Options The standard Kconfig_ tools ignore unknown options in ``sdkconfig``.
44
So if a developer has custom settings for options which are renamed in newer ESP-IDF releases, then the given setting for the option would be silently ignored. Therefore, several features have been adopted to avoid this: .. _configuration-options-reference: Configuration Options Reference Subsequent sections contain the list of available ESP-IDF options automatically generated from Kconfig files. Note that due to dependencies between options, some options listed here may not be visible by default in ``menuconfig``. By convention, all option names are upper-case letters with underscores. When Kconfig generates ``sdkconfig`` and ``sdkconfig.h`` files, option names are prefixed with ``CONFIG_``. So if an option ``ENABLE_FOO`` is defined in a Kconfig file and selected in ``menuconfig``, then the ``sdkconfig`` and ``sdkconfig.h`` files will have ``CONFIG_ENABLE_FOO`` defined. In the following sections, option names are also prefixed with ``CONFIG_``, same as in the source code. .. include-build-file:: inc/kconfig.
44
inc .. _Kconfig: https://www.kernel.org/doc/Documentation/kbuild/kconfig-language.txt .. _esp-idf-kconfig: https://pypi.org/project/esp-idf-kconfig/ .. _kconfiglib: https://github.com/ulfalizer/Kconfiglib .. _kconfiglib extentions: https://pypi.org/project/kconfiglib/#kconfig-extensions
44
API Documentation Template .. note:: *INSTRUCTIONS* Overview .. note:: *INSTRUCTIONS* Application Example .. note:: *INSTRUCTIONS* API Reference .. highlight:: none .. note:: *INSTRUCTIONS* ## ## Wi-Fi - API Reference ## ../components/esp32/include/esp_wifi.h \ ../components/esp32/include/esp_smartconfig.h \ .. include-build-file:: inc/esp_wifi.inc For example see :idf_file:`docs/en/api-reference/network/esp_wifi.rst` Below is the list of common ``.. doxygen...::`` directives: See `Breathe documentation `_ for additional information. To provide a link to header file, use the `link custom role` directive as follows::
45
API Conventions .. highlight:: c This document describes conventions and assumptions common to ESP-IDF Application Programming Interfaces (APIs). ESP-IDF provides several kinds of programming interfaces: ESP-IDF is made up of multiple components where these components either contain code specifically written for ESP chips, or contain a third-party library (i.e., a third-party component). In some cases, third-party components contain an "ESP-IDF specific" wrapper in order to provide an interface that is either simpler or better integrated with the rest of ESP-IDF's features. In other cases, third-party components present the original API of the underlying library directly. The following sections explain some of the aspects of ESP-IDF APIs and their usage. Error Handling Most ESP-IDF APIs return error codes defined with the :cpp:type:`esp_err_t` type. See :doc:`Error Handling ` section for more information about error handling approaches. :doc:`Error Codes Reference ` contains the list of error codes returned by ESP-IDF components.
46
.. _api_reference_config_structures: Configuration Structures .. important:: Correct initialization of configuration structures is an important part of making the application compatible with future versions of ESP-IDF. Most initialization, configuration, and installation functions in ESP-IDF (typically named ``..._init()``, ``..._config()``, and ``..._install()``) take a configuration structure pointer as an argument. For example:: const esp_timer_create_args_t my_timer_args = { .callback = &my_timer_callback, .arg = callback_arg, .name = "my_timer" }; esp_timer_handle_t my_timer; esp_err_t err = esp_timer_create(&my_timer_args, &my_timer); These functions never store the pointer to the configuration structure, so it is safe to allocate the structure on the stack. The application must initialize all fields of the structure. The following is incorrect:: esp_timer_create_args_t my_timer_args; my_timer_args.callback = &my_timer_callback; /* Incorrect!
46
Fields .arg and .name are not initialized */ esp_timer_create(&my_timer_args, &my_timer); Most ESP-IDF examples use C99 `designated initializers`_ for structure initialization since they provide a concise way of setting a subset of fields, and zero-initializing the remaining fields:: const esp_timer_create_args_t my_timer_args = { .callback = &my_timer_callback, /* Correct, fields .arg and .name are zero-initialized */ }; The C++ language supports designated initializer syntax, too, but the initializers must be in the order of declaration. When using ESP-IDF APIs in C++ code, you may consider using the following pattern:: /* Correct, fields .dispatch_method, .name and .skip_unhandled_events are zero-initialized */ const esp_timer_create_args_t my_timer_args = { .callback = &my_timer_callback, .arg = &my_arg, }; ///* Incorrect, .arg is declared after .callback in esp_timer_create_args_t */ //const esp_timer_create_args_t my_timer_args = { // .
46
arg = &my_arg, // .callback = &my_timer_callback, //}; For more information on designated initializers, see :ref:`cplusplus_designated_initializers`. Note that C++ language versions older than C++20, which are not the default in the current version of ESP-IDF, do not support designated initializers. If you have to compile code with an older C++ standard than C++20, you may use GCC extensions to produce the following pattern:: esp_timer_create_args_t my_timer_args = {}; /* All the fields are zero-initialized */ my_timer_args.callback = &my_timer_callback; Default Initializers For some configuration structures, ESP-IDF provides macros for setting default values of fields:: httpd_config_t config = HTTPD_DEFAULT_CONFIG(); /* HTTPD_DEFAULT_CONFIG expands to a designated initializer. Now all fields are set to the default values, and any field can still be modified: */ config.server_port = 8081; httpd_handle_t server; esp_err_t err = httpd_start(&server, &config); It is recommended to use default initializer macros whenever they are provided for a particular configuration structure.
46
.. _api_reference_private_apis: Private APIs Certain header files in ESP-IDF contain APIs intended to be used only in ESP-IDF source code rather than by the applications. Such header files often contain ``private`` or ``esp_private`` in their name or path. Certain components, such as :doc:`hal ` only contain private APIs. Private APIs may be removed or changed in an incompatible way between minor or patch releases. .. _api_reference_example_components: Components in Example Projects ESP-IDF examples contain a variety of projects demonstrating the usage of ESP-IDF APIs. In order to reduce code duplication in the examples, a few common helpers are defined inside components that are used by multiple examples. This includes components located in :example:`common_components` directory, as well as some of the components located in the examples themselves. These components are not considered to be part of the ESP-IDF API. It is not recommended to reference these components directly in custom projects (via ``EXTRA_COMPONENT_DIRS`` build system variable), as they may change significantly between ESP-IDF versions.
46
When starting a new project based on an ESP-IDF example, copy both the project and the common components it depends on out of ESP-IDF, and treat the common components as part of the project. Note that the common components are written with examples in mind, and might not include all the error handling required for production applications. Before using, take time to read the code and understand if it is applicable to your use case. API Stability ESP-IDF uses `Semantic Versioning `_ as explained in the :ref:`Versioning Scheme `. Minor and bugfix releases of ESP-IDF guarantee compatibility with previous releases. The sections below explain different aspects and limitations to compatibility. Source-level Compatibility ESP-IDF guarantees source-level compatibility of C functions, structures, enums, type definitions, and preprocessor macros declared in public header files of ESP-IDF components. Source-level compatibility implies that the application source code can be recompiled with the newer version of ESP-IDF without changes.
46
The following changes are allowed between minor versions and do not break source-level compatibility: Lack of Binary Compatibility ESP-IDF does not guarantee binary compatibility between releases. This means that if a precompiled library is built with one ESP-IDF version, it is not guaranteed to work the same way with the next minor or bugfix release. The following are the possible changes that keep source-level compatibility but not binary compatibility: Other Exceptions from Compatibility While we try to make upgrading to a new ESP-IDF version easy, there are parts of ESP-IDF that may change between minor versions in an incompatible way. We appreciate issuing reports about any unintended breaking changes that do not fall into the categories below. .. _designated initializers: https://en.cppreference.com/w/c/language/struct_initialization
46
Networking APIs .. only:: SOC_WIFI_SUPPORTED Wi-Fi .. toctree:: :maxdepth: 1 esp_now :SOC_WIFI_MESH_SUPPORT: esp-wifi-mesh esp_smartconfig esp_wifi esp_dpp :SOC_WIFI_NAN_SUPPORT: esp_nan Code examples for the Wi-Fi API are provided in the :example:`wifi` directory of ESP-IDF examples. .. only:: SOC_WIFI_MESH_SUPPORT Code examples for ESP-WIFI-MESH are provided in the :example:`mesh` directory of ESP-IDF examples. Ethernet .. toctree:: :maxdepth: 1 esp_eth Code examples for the Ethernet API are provided in the :example:`ethernet` directory of ESP-IDF examples. Thread .. toctree:: :maxdepth: 1 esp_openthread Thread is an IPv6-based mesh networking technology for IoT. Code examples for the Thread API are provided in the :example:`openthread` directory of ESP-IDF examples. ESP-NETIF .. toctree:: :maxdepth: 1 esp_netif IP Network Layer .. toctree:: :hidden: esp_netif_driver Code examples for TCP/IP socket APIs are provided in the :example:`protocols/sockets` directory of ESP-IDF examples.
47
Application Layer Documentation for Application layer network protocols (above the IP Network layer) are provided in :doc:`../protocols/index`.
47
Ethernet {IDF_TARGET_SOC_REF_CLK_IN_GPIO:default="", esp32="GPIO0", esp32p4="GPIO32, GPIO44 and GPIO50"} {IDF_TARGET_SOC_REF_CLK_OUT_GPIO:default="", esp32="GPIO0, GPIO16 and GPIO17", esp32p4="GPIO23 and GPIO39"} {IDF_TARGET_SOC_RMII_TX_EN:default="", esp32="GPIO21", esp32p4="GPIO33, GPIO40 and GPIO49"} {IDF_TARGET_SOC_RMII_TXD0:default="", esp32="GPIO19", esp32p4="GPIO34 and GPIO41"} {IDF_TARGET_SOC_RMII_TXD1:default="", esp32="GPIO22", esp32p4="GPIO35 and GPIO42"} {IDF_TARGET_SOC_RMII_CRS_DV:default="", esp32="GPIO27", esp32p4="GPIO28, GPIO45 and GPIO51"} {IDF_TARGET_SOC_RMII_RXD0:default="", esp32="GPIO25", esp32p4="GPIO29, GPIO46 and GPIO52"} {IDF_TARGET_SOC_RMII_RXD1:default="", esp32="GPIO26", esp32p4="GPIO30, GPIO47 and GPIO53"} .. Overview Overview .. only:: SOC_EMAC_SUPPORTED ESP-IDF provides a set of consistent and flexible APIs to support both internal Ethernet MAC (EMAC) controller and external SPI-Ethernet modules. .. only:: not SOC_EMAC_SUPPORTED ESP-IDF provides a set of consistent and flexible APIs to support external SPI-Ethernet modules.
48
This programming guide is split into the following sections: .. Basic Ethernet Concepts .. _basic-ethernet-concepts: Basic Ethernet Concepts Ethernet is an asynchronous Carrier Sense Multiple Access with Collision Detect (CSMA/CD) protocol/interface. It is generally not well suited for low-power applications. However, with ubiquitous deployment, internet connectivity, high data rates, and limitless-range expandability, Ethernet can accommodate nearly all wired communications. Normal IEEE 802.3 compliant Ethernet frames are between 64 and 1518 bytes in length. They are made up of five or six different fields: a destination MAC address (DA), a source MAC address (SA), a type/length field, a data payload, an optional padding field and a Cyclic Redundancy Check (CRC). Additionally, when transmitted on the Ethernet medium, a 7-byte preamble field and Start-of-Frame (SOF) delimiter byte are appended to the beginning of the Ethernet packet. Thus the traffic on the twist-pair cabling appears as shown below: .
48
. rackdiag:: ../../../_static/diagrams/ethernet/data_frame_format.diag :caption: Ethernet Data Frame Format :align: center Preamble and Start-of-Frame Delimiter The preamble contains seven bytes of ``55H``. It allows the receiver to lock onto the stream of data before the actual frame arrives. The Start-of-Frame Delimiter (SFD) is a binary sequence ``10101011`` (as seen on the physical medium). It is sometimes considered to be part of the preamble. When transmitting and receiving data, the preamble and SFD bytes will be automatically generated or stripped from the packets. Destination Address The destination address field contains a 6-byte length MAC address of the device that the packet is directed to. If the Least Significant bit in the first byte of the MAC address is set, the address is a multicast destination. For example, 01-00-00-00-F0-00 and 33-45-67-89-AB-CD are multi-cast addresses, while 00-00-00-00-F0-00 and 32-45-67-89-AB-CD are not. Packets with multi-cast destination addresses are designed to arrive and be important to a selected group of Ethernet nodes.
48
If the destination address field is the reserved multicast address, i.e., FF-FF-FF-FF-FF-FF, the packet is a broadcast packet and it will be directed to everyone sharing the network. If the Least Significant bit in the first byte of the MAC address is clear, the address is a unicast address and will be designed for usage by only the addressed node. Normally the EMAC controller incorporates receive filters which can be used to discard or accept packets with multi-cast, broadcast and/or unicast destination addresses. When transmitting packets, the host controller is responsible for writing the desired destination address into the transmit buffer. Source Address The source address field contains a 6-byte length MAC address of the node which created the Ethernet packet. Users of Ethernet must generate a unique MAC address for each controller used. MAC addresses consist of two portions. The first three bytes are known as the Organizationally Unique Identifier (OUI). OUIs are distributed by the IEEE.
48
The last three bytes are address bytes at the discretion of the company that purchased the OUI. For more information about MAC Address used in ESP-IDF, please see :ref:`MAC Address Allocation `. When transmitting packets, the assigned source MAC address must be written into the transmit buffer by the host controller. Type/Length The type/length field is a 2-byte field. If the value in this field is = 1536, it represents the protocol the following packet data belongs to. The followings are the most common type values: Users implementing proprietary networks may choose to treat this field as a length field, while applications implementing protocols such as the Internet Protocol (IP) or Address Resolution Protocol (ARP), should program this field with the appropriate type defined by the protocol's specification when transmitting packets. Payload The payload field is a variable length field, anywhere from 0 to 1500 bytes. Larger data packets violates Ethernet standards and will be dropped by most Ethernet nodes.
48
This field contains the client data, such as an IP datagram. Padding and FCS The padding field is a variable length field added to meet the IEEE 802.3 specification requirements when small data payloads are used. The DA, SA, type, payload, and padding of an Ethernet packet must be no smaller than 60 bytes in total. If the required 4-byte FCS field is added, packets must be no smaller than 64 bytes. If the payload field is less than 46-byte long, a padding field is required. The FCS field is a 4-byte field that contains an industry-standard 32-bit CRC calculated with the data from the DA, SA, type, payload, and padding fields. Given the complexity of calculating a CRC, the hardware normally automatically generates a valid CRC and transmit it. Otherwise, the host controller must generate the CRC and place it in the transmit buffer. Normally, the host controller does not need to concern itself with padding and the CRC which the hardware EMAC will also be able to automatically generate when transmitting and verify when receiving.
48
However, the padding and CRC fields will be written into the receive buffer when packets arrive, so they may be evaluated by the host controller if needed. .. note:: Besides the basic data frame described above, there are two other common frame types in 10/100 Mbps Ethernet: control frames and VLAN-tagged frames. They are not supported in ESP-IDF. .. Driver Operation .. _driver-configuration-and-installation: Configure MAC and PHY The Ethernet driver is composed of two parts: MAC and PHY. .. only:: SOC_EMAC_SUPPORTED The communication between MAC and PHY can have diverse choices: **MII** (Media Independent Interface), **RMII** (Reduced Media Independent Interface), etc. .. figure:: ../../../_static/rmii-interface.png :scale: 80 % :alt: Ethernet RMII Interface :figclass: align-center Ethernet RMII Interface One of the obvious differences between MII and RMII is signal consumption. MII usually costs up to 18 signals, while the RMII interface can reduce the consumption to 9.
48
.. only:: esp32 .. note:: ESP-IDF only supports the RMII interface. Therefore, always set :cpp:member:`eth_esp32_emac_config_t::interface` to :cpp:enumerator:`eth_data_interface_t::EMAC_DATA_INTERFACE_RMII` or always select ``CONFIG_ETH_PHY_INTERFACE_RMII`` in the Kconfig option :ref:`CONFIG_ETH_PHY_INTERFACE`. .. only:: not esp32 .. note:: ESP-IDF only supports the RMII interface. Therefore, always set :cpp:member:`eth_esp32_emac_config_t::interface` to :cpp:enumerator:`eth_data_interface_t::EMAC_DATA_INTERFACE_RMII`. In RMII mode, both the receiver and transmitter signals are referenced to the ``REF_CLK``. ``REF_CLK`` **must be stable during any access to PHY and MAC**. Generally, there are three ways to generate the ``REF_CLK`` depending on the PHY device in your design: .. only:: esp32 .. note:: The ``REF_CLK`` can be also configured via Project Configuration when :cpp:member:`eth_esp32_emac_config_t::clock_config::mode` of :cpp:member:`eth_esp32_emac_config_t::clock_config` is set to :cpp:enumerator:`emac_rmii_clock_mode_t::EMAC_CLK_DEFAULT`.
48
Choose appropriately ``CONFIG_ETH_RMII_CLK_INPUT`` or ``CONFIG_ETH_RMII_CLK_OUTPUT`` option under :ref:`CONFIG_ETH_RMII_CLK_MODE` configuration based on your design as discussed above. .. warning:: If the RMII clock mode is configured to :cpp:enumerator:`emac_rmii_clock_mode_t::EMAC_CLK_OUT` (or ``CONFIG_ETH_RMII_CLK_OUTPUT`` is selected), then ``GPIO0`` can be used to output the ``REF_CLK`` signal. See :cpp:enumerator:`emac_rmii_clock_gpio_t::EMAC_APPL_CLK_OUT_GPIO` or :ref:`CONFIG_ETH_RMII_CLK_OUTPUT_GPIO0` for more information. What is more, if you are not using PSRAM in your design, GPIO16 and GPIO17 are also available to output the reference clock signal. See :cpp:enumerator:`emac_rmii_clock_gpio_t::EMAC_CLK_OUT_GPIO` and :cpp:enumerator:`emac_rmii_clock_gpio_t::EMAC_CLK_OUT_180_GPIO` or :ref:`CONFIG_ETH_RMII_CLK_OUT_GPIO` for more information. If the RMII clock mode is configured to :cpp:enumerator:`emac_rmii_clock_mode_t::EMAC_CLK_EXT_IN` (or ``CONFIG_ETH_RMII_CLK_INPUT`` is selected), then ``GPIO0`` is the only choice to input the ``REF_CLK`` signal.
48
Please note that ``GPIO0`` is also an important strapping GPIO on ESP32. If GPIO0 samples a low level during power-up, ESP32 will go into download mode. The system will get halted until a manually reset. The workaround for this issue is disabling the ``REF_CLK`` in hardware by default so that the strapping pin is not interfered by other signals in the boot stage. Then, re-enable the ``REF_CLK`` in the Ethernet driver installation stage. The ways to disable the ``REF_CLK`` signal can be: .. only:: not esp32 .. note:: If the RMII clock mode is configured to :cpp:enumerator:`emac_rmii_clock_mode_t::EMAC_CLK_OUT`, {IDF_TARGET_SOC_REF_CLK_OUT_GPIO} can be selected as output pin of the ``REF_CLK`` signal via IO_MUX. If the RMII clock mode is configured to :cpp:enumerator:`emac_rmii_clock_mode_t::EMAC_CLK_EXT_IN`, {IDF_TARGET_SOC_REF_CLK_IN_GPIO} can be selected as input pin for the ``REF_CLK`` signal via IO_MUX. .. only:: not SOC_EMAC_RMII_CLK_OUT_INTERNAL_LOOPBACK .
48
. warning:: If the RMII clock mode is configured to :cpp:enumerator:`emac_rmii_clock_mode_t::EMAC_CLK_OUT`, the ``REF_CLK`` output signal must be looped back to the EMAC externally. You have to configure :cpp:member:`eth_mac_clock_config_t::clock_mode` of :cpp:member:`eth_esp32_emac_config_t::clock_config_out_in` to :cpp:enumerator:`emac_rmii_clock_mode_t::EMAC_CLK_EXT_IN` and select GPIO number associated with ``REF_CLK`` input GPIO's ({IDF_TARGET_SOC_REF_CLK_IN_GPIO}). .. only:: esp32p4 .. figure:: ../../../_static/rmii_ref_clk_esp32p4.png :scale: 95 % :alt: RMII REF_CKL Output Loopback :figclass: align-center RMII REF_CKL Output Loopback **No matter which RMII clock mode you select, you really need to take care of the signal integrity of REF_CLK in your hardware design!** Keep the trace as short as possible. Keep it away from RF devices and inductor elements.
48
.. only:: not SOC_EMAC_USE_IO_MUX .. note:: Signals used in the data plane are fixed to specific GPIOs via IO_MUX, they can not be modified to other GPIOs. Signals used in the control plane can be routed to any free GPIOs via Matrix. Please refer to :doc:`ESP32-Ethernet-Kit ` for hardware design example. .. only:: SOC_EMAC_USE_IO_MUX .. note:: Signals used in the data plane can be configured to predefined set of GPIOs via IO_MUX for the RMII, see below table. The data plane GPIO configuration is performed by the driver based on content of :cpp:member:`eth_esp32_emac_config_t::emac_dataif_gpio`. Signals used in the control plane can be routed to any free GPIOs via GPIO Matrix. .. list-table:: {IDF_TARGET_NAME} RMII Data Plane GPIO :header-rows: 1 :widths: 50 50 :align: center - GPIO Number - {IDF_TARGET_SOC_RMII_TX_EN} - {IDF_TARGET_SOC_RMII_TXD0} - {IDF_TARGET_SOC_RMII_TXD1} - {IDF_TARGET_SOC_RMII_CRS_DV} - {IDF_TARGET_SOC_RMII_RXD0} - {IDF_TARGET_SOC_RMII_RXD1} You need to set up the necessary parameters for MAC and PHY respectively based on your Ethernet board design, and then combine the two together to complete the driver installation.
48
Configuration for MAC is described in :cpp:class:`eth_mac_config_t`, including: .. list:: :SOC_EMAC_SUPPORTED: * :cpp:member:`eth_esp32_emac_config_t::smi_mdc_gpio_num` and :cpp:member:`eth_esp32_emac_config_t::smi_mdio_gpio_num`: the GPIO number used to connect the SMI signals. :SOC_EMAC_SUPPORTED: * :cpp:member:`eth_esp32_emac_config_t::interface`: configuration of MAC Data interface to PHY (MII/RMII). :SOC_EMAC_SUPPORTED: * :cpp:member:`eth_esp32_emac_config_t::clock_config`: configuration of EMAC Interface clock (``REF_CLK`` mode and GPIO number in case of RMII). :SOC_EMAC_USE_IO_MUX: * :cpp:member:`eth_esp32_emac_config_t::emac_dataif_gpio`: configuration of EMAC MII/RMII data plane GPIO numbers. :not SOC_EMAC_RMII_CLK_OUT_INTERNAL_LOOPBACK: * :cpp:member:`eth_esp32_emac_config_t::clock_config_out_in`: configuration of EMAC input interface clock when ``REF_CLK`` signal is generated internally and is looped back to the EMAC externally. The mode must be always configured to :cpp:enumerator:`emac_rmii_clock_mode_t::EMAC_CLK_EXT_IN`.
48
This option is valid only when configuration of :cpp:member:`eth_esp32_emac_config_t::clock_config` is set to :cpp:enumerator:`emac_rmii_clock_mode_t::EMAC_CLK_OUT`. Configuration for PHY is described in :cpp:class:`eth_phy_config_t`, including: .. list:: ESP-IDF provides a default configuration for MAC and PHY in macro :c:macro:`ETH_MAC_DEFAULT_CONFIG` and :c:macro:`ETH_PHY_DEFAULT_CONFIG`. Create MAC and PHY Instance The Ethernet driver is implemented in an Object-Oriented style. Any operation on MAC and PHY should be based on the instance of the two. .. only:: SOC_EMAC_SUPPORTED Internal EMAC + External PHY .. highlight:: c :: eth_mac_config_t mac_config = ETH_MAC_DEFAULT_CONFIG(); // apply default common MAC configuration eth_esp32_emac_config_t esp32_emac_config = ETH_ESP32_EMAC_DEFAULT_CONFIG(); // apply default vendor-specific MAC configuration esp32_emac_config.smi_mdc_gpio_num = CONFIG_EXAMPLE_ETH_MDC_GPIO; // alter the GPIO used for MDC signal esp32_emac_config.
48
smi_mdio_gpio_num = CONFIG_EXAMPLE_ETH_MDIO_GPIO; // alter the GPIO used for MDIO signal esp_eth_mac_t *mac = esp_eth_mac_new_esp32(&esp32_emac_config, &mac_config); // create MAC instance eth_phy_config_t phy_config = ETH_PHY_DEFAULT_CONFIG(); // apply default PHY configuration phy_config.phy_addr = CONFIG_EXAMPLE_ETH_PHY_ADDR; // alter the PHY address according to your board design phy_config.reset_gpio_num = CONFIG_EXAMPLE_ETH_PHY_RST_GPIO; // alter the GPIO used for PHY reset esp_eth_phy_t *phy = esp_eth_phy_new_ip101(&phy_config); // create PHY instance // ESP-IDF officially supports several different Ethernet PHY chip driver // esp_eth_phy_t *phy = esp_eth_phy_new_rtl8201(&phy_config); // esp_eth_phy_t *phy = esp_eth_phy_new_lan8720(&phy_config); // esp_eth_phy_t *phy = esp_eth_phy_new_dp83848(&phy_config); Optional Runtime MAC Clock Configuration EMAC ``REF_CLK`` can be optionally configured from the user application code.
48
.. highlight:: c :: eth_esp32_emac_config_t esp32_emac_config = ETH_ESP32_EMAC_DEFAULT_CONFIG(); // apply default vendor-specific MAC configuration // ... esp32_emac_config.interface = EMAC_DATA_INTERFACE_RMII; // alter EMAC Data Interface esp32_emac_config.clock_config.rmii.clock_mode = EMAC_CLK_OUT; // select EMAC REF_CLK mode esp32_emac_config.clock_config.rmii.clock_gpio = EMAC_CLK_OUT_GPIO; // select GPIO number used to input/output EMAC REF_CLK esp_eth_mac_t *mac = esp_eth_mac_new_esp32(&esp32_emac_config, &mac_config); // create MAC instance SPI-Ethernet Module .. highlight:: c :: eth_mac_config_t mac_config = ETH_MAC_DEFAULT_CONFIG(); // apply default common MAC configuration eth_phy_config_t phy_config = ETH_PHY_DEFAULT_CONFIG(); // apply default PHY configuration phy_config.phy_addr = CONFIG_EXAMPLE_ETH_PHY_ADDR; // alter the PHY address according to your board design phy_config.
48
reset_gpio_num = CONFIG_EXAMPLE_ETH_PHY_RST_GPIO; // alter the GPIO used for PHY reset // Install GPIO interrupt service (as the SPI-Ethernet module is interrupt-driven) gpio_install_isr_service(0); // SPI bus configuration spi_device_handle_t spi_handle = NULL; spi_bus_config_t buscfg = { .miso_io_num = CONFIG_EXAMPLE_ETH_SPI_MISO_GPIO, .mosi_io_num = CONFIG_EXAMPLE_ETH_SPI_MOSI_GPIO, .sclk_io_num = CONFIG_EXAMPLE_ETH_SPI_SCLK_GPIO, .quadwp_io_num = -1, .quadhd_io_num = -1, }; ESP_ERROR_CHECK(spi_bus_initialize(CONFIG_EXAMPLE_ETH_SPI_HOST, &buscfg, 1)); // Configure SPI device spi_device_interface_config_t spi_devcfg = { .mode = 0, .clock_speed_hz = CONFIG_EXAMPLE_ETH_SPI_CLOCK_MHZ * 1000 * 1000, .spics_io_num = CONFIG_EXAMPLE_ETH_SPI_CS_GPIO, .queue_size = 20 }; /* dm9051 ethernet driver is based on spi driver */ eth_dm9051_config_t dm9051_config = ETH_DM9051_DEFAULT_CONFIG(CONFIG_EXAMPLE_ETH_SPI_HOST, &spi_devcfg); dm9051_config.
48
int_gpio_num = CONFIG_EXAMPLE_ETH_SPI_INT_GPIO; esp_eth_mac_t *mac = esp_eth_mac_new_dm9051(&dm9051_config, &mac_config); esp_eth_phy_t *phy = esp_eth_phy_new_dm9051(&phy_config); .. note:: Install Driver To install the Ethernet driver, we need to combine the instance of MAC and PHY and set some additional high-level configurations (i.e., not specific to either MAC or PHY) in :cpp:class:`esp_eth_config_t`: ESP-IDF provides a default configuration for driver installation in macro :c:macro:`ETH_DEFAULT_CONFIG`. .. highlight:: c :: esp_eth_config_t config = ETH_DEFAULT_CONFIG(mac, phy); // apply default driver configuration esp_eth_handle_t eth_handle = NULL; // after the driver is installed, we will get the handle of the driver esp_eth_driver_install(&config, &eth_handle); // install driver The Ethernet driver also includes an event-driven model, which sends useful and important events to user space. We need to initialize the event loop before installing the Ethernet driver.
48
For more information about event-driven programming, please refer to :doc:`ESP Event `. .. highlight:: c :: /** Event handler for Ethernet events */ static void eth_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) { uint8_t mac_addr[6] = {0}; /* we can get the ethernet driver handle from event data */ esp_eth_handle_t eth_handle = *(esp_eth_handle_t *)event_data; switch (event_id) { case ETHERNET_EVENT_CONNECTED: esp_eth_ioctl(eth_handle, ETH_CMD_G_MAC_ADDR, mac_addr); ESP_LOGI(TAG, "Ethernet Link Up"); ESP_LOGI(TAG, "Ethernet HW Addr %02x:%02x:%02x:%02x:%02x:%02x", mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]); break; case ETHERNET_EVENT_DISCONNECTED: ESP_LOGI(TAG, "Ethernet Link Down"); break; case ETHERNET_EVENT_START: ESP_LOGI(TAG, "Ethernet Started"); break; case ETHERNET_EVENT_STOP: ESP_LOGI(TAG, "Ethernet Stopped"); break; default: break; } } esp_event_loop_create_default(); // create a default event loop that runs in the background esp_event_handler_register(ETH_EVENT, ESP_EVENT_ANY_ID, &eth_event_handler, NULL); // register Ethernet event handler (to deal with user-specific stuff when events like link up/down happened) Start Ethernet Driver After driver installation, we can start Ethernet immediately.
48
.. highlight:: c :: esp_eth_start(eth_handle); // start Ethernet driver state machine .. _connect-driver-to-stack: Connect Driver to TCP/IP Stack Up until now, we have installed the Ethernet driver. From the view of OSI (Open System Interconnection), we are still on level 2 (i.e., Data Link Layer). While we can detect link up and down events and gain MAC address in user space, it is infeasible to obtain the IP address, let alone send an HTTP request. The TCP/IP stack used in ESP-IDF is called LwIP. For more information about it, please refer to :doc:`LwIP `. To connect the Ethernet driver to TCP/IP stack, follow these three steps: For more information about the network interface, please refer to :doc:`Network Interface `. .. highlight:: c :: /** Event handler for IP_EVENT_ETH_GOT_IP */ static void got_ip_event_handler(void *arg, esp_event_base_t event_base, int32_t event_id, void *event_data) { ip_event_got_ip_t *event = (ip_event_got_ip_t *) event_data; const esp_netif_ip_info_t *ip_info = &event->ip_info; ESP_LOGI(TAG, "Ethernet Got IP Address"); ESP_LOGI(TAG, "~~~~~~~~~~~"); ESP_LOGI(TAG, "ETHIP:" IPSTR, IP2STR(&ip_info->ip)); ESP_LOGI(TAG, "ETHMASK:" IPSTR, IP2STR(&ip_info->netmask)); ESP_LOGI(TAG, "ETHGW:" IPSTR, IP2STR(&ip_info->gw)); ESP_LOGI(TAG, "~~~~~~~~~~~"); } esp_netif_init()); // Initialize TCP/IP network interface (should be called only once in application) esp_netif_config_t cfg = ESP_NETIF_DEFAULT_ETH(); // apply default network interface configuration for Ethernet esp_netif_t *eth_netif = esp_netif_new(&cfg); // create network interface for Ethernet driver esp_netif_attach(eth_netif, esp_eth_new_netif_glue(eth_handle)); // attach Ethernet driver to TCP/IP stack esp_event_handler_register(IP_EVENT, IP_EVENT_ETH_GOT_IP, &got_ip_event_handler, NULL); // register user defined IP event handlers esp_eth_start(eth_handle); // start Ethernet driver state machine .
48
. warning:: It is recommended to fully initialize the Ethernet driver and network interface before registering the user's Ethernet/IP event handlers, i.e., register the event handlers as the last thing prior to starting the Ethernet driver. Such an approach ensures that Ethernet/IP events get executed first by the Ethernet driver or network interface so the system is in the expected state when executing the user's handlers. .. _misc-operation-of-driver: Misc Control of Ethernet Driver The following functions should only be invoked after the Ethernet driver has been installed. .. highlight:: c :: /* get MAC address */ uint8_t mac_addr[6]; memset(mac_addr, 0, sizeof(mac_addr)); esp_eth_ioctl(eth_handle, ETH_CMD_G_MAC_ADDR, mac_addr); ESP_LOGI(TAG, "Ethernet MAC Address: %02x:%02x:%02x:%02x:%02x:%02x", mac_addr[0], mac_addr[1], mac_addr[2], mac_addr[3], mac_addr[4], mac_addr[5]); /* get PHY address */ int phy_addr = -1; esp_eth_ioctl(eth_handle, ETH_CMD_G_PHY_ADDR, &phy_addr); ESP_LOGI(TAG, "Ethernet PHY Address: %d", phy_addr); .
48
. _flow-control: Flow Control Ethernet on MCU usually has a limitation in the number of frames it can handle during network congestion, because of the limitation in RAM size. A sending station might be transmitting data faster than the peer end can accept it. The ethernet flow control mechanism allows the receiving node to signal the sender requesting the suspension of transmissions until the receiver catches up. The magic behind that is the pause frame, which was defined in IEEE 802.3x. Pause frame is a special Ethernet frame used to carry the pause command, whose EtherType field is ``0x8808``, with the Control opcode set to ``0x0001``. Only stations configured for full-duplex operation may send pause frames. When a station wishes to pause the other end of a link, it sends a pause frame to the 48-bit reserved multicast address of ``01-80-C2-00-00-01``. The pause frame also includes the period of pause time being requested, in the form of a two-byte integer, ranging from ``0`` to ``65535``.
48