Skip to content

Commit

Permalink
[VSC-1213] Enhance flash encryption (#1247)
Browse files Browse the repository at this point in the history
* Enhance flash ecnryption

* fix: display number and boolean values in Explorer

* Add validation for jtag disabled from hardware

* Fix lint

* Revert unwanted changes caused by rebase

* Fix file path

* move encryption functions to new file

* Add no reset flag if realease mode is enabled

* Add translation; Fix after rebase

* Fixes after rebase

* Fix based on PR comments

* Fix: Documentation

* Add progress bar for reading efuse

* Fix lint
  • Loading branch information
radurentea authored Nov 19, 2024
1 parent 5e2f0b9 commit 122f84e
Show file tree
Hide file tree
Showing 16 changed files with 638 additions and 38 deletions.
1 change: 1 addition & 0 deletions docs_espressif/en/additionalfeatures.rst
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ Additional IDE Features
Docker container <additionalfeatures/docker-container>
ESP-IDF Terminal<additionalfeatures/esp-terminal>
EFuse Explorer<additionalfeatures/efuse>
Flash Encryption<additionalfeatures/flash-encryption>
Heap Tracing<additionalfeatures/heap-tracing>
Hints viewer<additionalfeatures/hints-viewer>
Install ESP-IDF Components<additionalfeatures/install-esp-components>
Expand Down
41 changes: 41 additions & 0 deletions docs_espressif/en/additionalfeatures/flash-encryption.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
.. _flash_encryption:

Flash Encryption
========================

Flash Encryption secures the device's flash memory contents. Once enabled, the firmware is uploaded in plaintext but becomes encrypted on the first boot, thus preventing unauthorized flash readouts. For more details, refer to the `ESP-IDF Flash Encryption documentation <https://docs.espressif.com/projects/esp-idf/en/latest/esp32/security/flash-encryption.html>`_.

Let's open an ESP-IDF project. For this tutorial, we will use the ``security/flash_encryption`` example.

1. Navigate to **View** > **Command Palette** and search for the **ESP-IDF: Show Example Projects** command, then choose ``Use Current ESP-IDF (/path/to/esp-idf)``. If you don't see this option, please review the setup in the :ref:`Install ESP-IDF and Tools <installation>`.

2. A window will open with a list of projects. Search for ``flash_encryption``. You will see a **Create project using example flash_encryption** button at the top and a description of the project below. Click the button, and the project will open in a new window.

.. image:: ../../../media/tutorials/flash_encryption/flash-encryption.png
:alt: Flash Encryption example

3. Configure the project by setting up the following:

- Select the Port to Use
- Set the Espressif Device Target
- Set the Flashing Method to UART

.. note::
In case this step is not clear, take a look at the :ref:`Build the project <build the project>`.

4. Use the Command Palette with ``ESP-IDF: SDK Configuration editor (Menuconfig)`` to open the SDK Config Menu. Search for **flash encryption** and enable the following option:

.. image:: ../../../media/tutorials/flash_encryption/flash-encryption2.png
:alt: Flash Encryption configuration

.. important::
Enabling flash encryption limits the options for further updates of the ESP32. Before using this feature, read the document and make sure to understand the implications. `ESP-IDF Flash Encryption documentation <https://docs.espressif.com/projects/esp-idf/en/latest/esp32/security/flash-encryption.html>`_

5. Build the project.

6. Flash the project.

.. note::
The first flash will upload the firmware without using the ``--encrypt`` flag. After flashing is complete, you will need to reset your device by pressing the reset button on the board. (The button may be labeled as "RESET", "RST", or "EN")

7. Flash the firmware once again, this time if all the steps were followed correctly, the ``--encrypt`` flag will be automatically added.
10 changes: 9 additions & 1 deletion l10n/bundle.l10n.es.json
Original file line number Diff line number Diff line change
Expand Up @@ -188,5 +188,13 @@
"Target {0} Set Successfully.": "Objetivo {0} configurado con éxito.",
"Unknown error occurred while setting IDF target.": "Ocurrió un error desconocido al configurar el objetivo IDF.",
"compile_commands.json is missing. This may cause errors with code analysis extensions.": "Falta compile_commands.json. Esto puede causar errores con las extensiones de análisis de código.",
"Generate compile_commands.json": "Generar compile_commands.json"
"Generate compile_commands.json": "Generar compile_commands.json",
"Cannot flash via JTAG method: {0}": "No se puede flashear mediante el método JTAG: {0}",
"{0}\n\nThe JTAG configuration may depend on hardware strapping. Please consult the ESP32 technical documentation for your specific model to ensure proper JTAG configuration before proceeding.": "{0}\n\nLa configuración de JTAG puede depender del acoplamiento del hardware. Por favor, consulte la documentación técnica del ESP32 para su modelo específico para asegurar la configuración correcta de JTAG antes de continuar.",
"JTAG is permanently disabled in hardware ({0} is set).": "JTAG está deshabilitado permanentemente en hardware (se ha establecido {0}).",
"USB-to-JTAG functionality is disabled ({0} is set).": "La funcionalidad USB a JTAG está deshabilitada (se ha establecido {0}).",
"JTAG is soft-disabled ({0} is set to an odd value: {1}).": "JTAG está deshabilitado por software ({0} se ha establecido con un valor impar: {1}).",
"JTAG selection may be affected by strapping configuration ({0} is set).": "La selección de JTAG puede verse afectada por la configuración de strapping (se ha establecido {0}).",
"JTAG is not disabled.": "JTAG no está deshabilitado.",
"IDF Version >= 4.3.x required to have e-fuse view": "Se requiere IDF Versión >= 4.3.x para tener vista de e-fuse"
}
10 changes: 9 additions & 1 deletion l10n/bundle.l10n.pt.json
Original file line number Diff line number Diff line change
Expand Up @@ -188,5 +188,13 @@
"Target {0} Set Successfully.": "Alvo {0} definido com sucesso.",
"Unknown error occurred while setting IDF target.": "Ocorreu um erro desconhecido ao definir o alvo IDF.",
"compile_commands.json is missing. This may cause errors with code analysis extensions.": "O arquivo compile_commands.json está faltando. Isso pode causar erros com extensões de análise de código.",
"Generate compile_commands.json": "Gerar compile_commands.json"
"Generate compile_commands.json": "Gerar compile_commands.json",
"Cannot flash via JTAG method: {0}": "Não é possível flashear pelo método JTAG: {0}",
"{0}\n\nThe JTAG configuration may depend on hardware strapping. Please consult the ESP32 technical documentation for your specific model to ensure proper JTAG configuration before proceeding.": "{0}\n\nA configuração JTAG pode depender da configuração do hardware. Por favor, consulte a documentação técnica do ESP32 para o seu modelo específico para garantir a configuração adequada do JTAG antes de prosseguir.",
"JTAG is permanently disabled in hardware ({0} is set).": "JTAG está permanentemente desativado no hardware ({0} está definido).",
"USB-to-JTAG functionality is disabled ({0} is set).": "A funcionalidade USB para JTAG está desativada ({0} está definido).",
"JTAG is soft-disabled ({0} is set to an odd value: {1}).": "JTAG está desativado por software ({0} está definido com um valor ímpar: {1}).",
"JTAG selection may be affected by strapping configuration ({0} is set).": "A seleção JTAG pode ser afetada pela configuração de strapping ({0} está definido).",
"JTAG is not disabled.": "JTAG não está desativado.",
"IDF Version >= 4.3.x required to have e-fuse view": "IDF Versão >= 4.3.x necessária para ter visualização de e-fuse"
}
10 changes: 9 additions & 1 deletion l10n/bundle.l10n.ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -188,5 +188,13 @@
"Target {0} Set Successfully.": "Цель {0} успешно установлена.",
"Unknown error occurred while setting IDF target.": "Произошла неизвестная ошибка при установке цели IDF.",
"compile_commands.json is missing. This may cause errors with code analysis extensions.": "Отсутствует файл compile_commands.json. Это может вызвать ошибки в работе расширений для анализа кода.",
"Generate compile_commands.json": "Создать compile_commands.json"
"Generate compile_commands.json": "Создать compile_commands.json",
"Cannot flash via JTAG method: {0}": "Невозможно прошить методом JTAG: {0}",
"{0}\n\nThe JTAG configuration may depend on hardware strapping. Please consult the ESP32 technical documentation for your specific model to ensure proper JTAG configuration before proceeding.": "{0}\n\nКонфигурация JTAG может зависеть от аппаратной конфигурации. Пожалуйста, обратитесь к технической документации ESP32 для вашей конкретной модели, чтобы обеспечить правильную конфигурацию JTAG перед продолжением.",
"JTAG is permanently disabled in hardware ({0} is set).": "JTAG постоянно отключен на аппаратном уровне (установлен {0}).",
"USB-to-JTAG functionality is disabled ({0} is set).": "Функциональность USB-to-JTAG отключена (установлен {0}).",
"JTAG is soft-disabled ({0} is set to an odd value: {1}).": "JTAG программно отключен ({0} установлен на нечетное значение: {1}).",
"JTAG selection may be affected by strapping configuration ({0} is set).": "Выбор JTAG может зависеть от конфигурации стрэппинга (установлен {0}).",
"JTAG is not disabled.": "JTAG не отключен.",
"IDF Version >= 4.3.x required to have e-fuse view": "Требуется IDF версии >= 4.3.x для просмотра e-fuse"
}
10 changes: 9 additions & 1 deletion l10n/bundle.l10n.zh-CN.json
Original file line number Diff line number Diff line change
Expand Up @@ -188,5 +188,13 @@
"Target {0} Set Successfully.": "目标 {0} 设置成功",
"Unknown error occurred while setting IDF target.": "设置 IDF 目标时发生未知错误",
"compile_commands.json is missing. This may cause errors with code analysis extensions.": "缺少 compile_commands.json 文件。这可能会导致代码分析扩展出错。",
"Generate compile_commands.json": "生成 compile_commands.json"
"Generate compile_commands.json": "生成 compile_commands.json",
"Cannot flash via JTAG method: {0}": "无法通过JTAG方法刷写:{0}",
"{0}\n\nThe JTAG configuration may depend on hardware strapping. Please consult the ESP32 technical documentation for your specific model to ensure proper JTAG configuration before proceeding.": "{0}\n\nJTAG配置可能取决于硬件配置。请在继续之前查阅您特定型号的ESP32技术文档,以确保正确的JTAG配置。",
"JTAG is permanently disabled in hardware ({0} is set).": "JTAG在硬件上被永久禁用(已设置{0})。",
"USB-to-JTAG functionality is disabled ({0} is set).": "USB-to-JTAG功能已禁用(已设置{0})。",
"JTAG is soft-disabled ({0} is set to an odd value: {1}).": "JTAG已软禁用({0}设置为奇数值:{1})。",
"JTAG selection may be affected by strapping configuration ({0} is set).": "JTAG选择可能受到硬件配置的影响(已设置{0})。",
"JTAG is not disabled.": "JTAG未被禁用。",
"IDF Version >= 4.3.x required to have e-fuse view": "需要 IDF 版本 >= 4.3.x 才能查看 e-fuse"
}
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
1 change: 1 addition & 0 deletions src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ export namespace ESP {
export const IDF_VERSIONS =
"https://dl.espressif.com/dl/esp-idf/idf_versions.js";
export const README = ESP.URL.GithubRepository + "/blob/master/README.md";
export const FLASH_ENCRYPTION = "/security/flash-encryption.html";
}
}

Expand Down
53 changes: 36 additions & 17 deletions src/efuse/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import { readParameter } from "../idfConfiguration";
import { tmpdir } from "os";
import { readJson, unlink } from "fs-extra";
import { Logger } from "../logger/logger";
import { Uri } from "vscode";
import { Uri, l10n } from "vscode";
import { getVirtualEnvPythonPath } from "../pythonManager";

export type ESPEFuseSummary = {
Expand Down Expand Up @@ -55,8 +55,30 @@ export class ESPEFuseManager {
}

async summary(): Promise<ESPEFuseSummary> {
const eFuseFields = await this.readSummary();

const resp = {};
for (const name in eFuseFields) {
const fields = eFuseFields[name];
if (!fields.category) {
const error = new Error(
l10n.t("IDF Version >= 4.3.x required to have e-fuse view")
);
error.name = "IDF_VERSION_MIN_REQUIREMENT_ERROR";
throw error;
}
if (!resp[fields.category]) {
resp[fields.category] = [];
}
resp[fields.category].push(fields);
}
return resp;
}

async readSummary() {
const tempFile = join(tmpdir(), "espefusejsondump.tmp");
const pythonPath = await getVirtualEnvPythonPath(this.workspace);

await spawn(
pythonPath,
[
Expand All @@ -71,26 +93,23 @@ export class ESPEFuseManager {
],
{}
);

const eFuseFields = await readJson(tempFile);

unlink(tempFile, (err) => {
Logger.error("Failed to delete the tmp espfuse json file", err, "ESPEFuseManager summary");
});
const resp = {};
for (const name in eFuseFields) {
const fields = eFuseFields[name];
if (!fields.category) {
const error = new Error(
"IDF Version >= 4.3.x required to have e-fuse view"
if (err) {
Logger.error(
"Failed to delete the tmp espefuse json file",
err,
"readSummary",
{
tag: "ESPeFuse",
}
);
error.name = "IDF_VERSION_MIN_REQUIREMENT_ERROR";
throw error;
}
if (!resp[fields.category]) {
resp[fields.category] = [];
}
resp[fields.category].push(fields);
}
return resp;
});

return eFuseFields;
}

private get toolPath(): string {
Expand Down
5 changes: 4 additions & 1 deletion src/efuse/view/item_generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,10 @@ export function FieldsForCategory(
return fields.map((v) => {
const item = new ESPEFuseTreeDataItem(v.name);
item.tooltip = v.writeable ? "writable" : "read only";
item.description = v.value;
item.description =
typeof v.value === "boolean" || typeof v.value === "number"
? JSON.stringify(v.value)
: v.value;
item.iconPath = v.writeable
? ThemeIconFor("edit", "merge.currentHeaderBackground")
: ThemeIconFor("book", "button.background");
Expand Down
42 changes: 40 additions & 2 deletions src/espIdf/documentation/getDocsVersion.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,10 @@ import { basename, join } from "path";
import { DownloadManager } from "../../downloadManager";
import jsonic from "jsonic";
import { Logger } from "../../logger/logger";
import { extensionContext } from "../../utils";
import { extensionContext, getEspIdfFromCMake } from "../../utils";
import * as vscode from "vscode";
import * as idfConf from "../../idfConfiguration";
import { getIdfTargetFromSdkconfig } from "../../workspaceConfig";

export interface IEspIdfDocVersion {
name: string;
Expand Down Expand Up @@ -66,7 +69,11 @@ export function getDocsLocaleLang() {
const localeConf = JSON.parse(process.env.VSCODE_NLS_CONFIG);
localeLang = localeConf.locale === "zh-CN" ? "zh_CN" : "en";
} catch (error) {
Logger.error("Error getting current vscode language", error, "getDocsVersion getDocsLocaleLang");
Logger.error(
"Error getting current vscode language",
error,
"getDocsVersion getDocsLocaleLang"
);
}
return localeLang;
}
Expand Down Expand Up @@ -112,3 +119,34 @@ export async function readObjectFromUrlFile(objectUrl: string) {
return jsonic(objectMatches[0]);
}
}

/**
* Retrieves the URL for the specified documentation part based on the ESP-IDF version and workspace.
* @param documentationPart - The documentation part to retrieve the URL for.
* @param workspace - The workspace URI.
* @returns The URL for the ESP-IDF specified documentation part.
*/
export async function getDocsUrl(
documentationPart: string,
workspace: vscode.Uri
) {
const espIdfPath = idfConf.readParameter(
"idf.espIdfPath",
workspace
) as string;

const adapterTargetName = await getIdfTargetFromSdkconfig(workspace);
const idfVersion = await getEspIdfFromCMake(espIdfPath);
const docVersions = await getDocsVersion();
let docVersion = docVersions.find((docVer) => docVer.name === idfVersion);
if (!docVersion) {
docVersion = docVersions.find((docVer) => docVer.name === "latest");
}
if (!docVersion) {
return;
}
const baseUrl = getDocsBaseUrl(docVersion.name, adapterTargetName);
const url = `${baseUrl}/${documentationPart}`;

return url;
}
Loading

0 comments on commit 122f84e

Please sign in to comment.