diff --git a/.cyignore b/.cyignore new file mode 100644 index 0000000..e712b49 --- /dev/null +++ b/.cyignore @@ -0,0 +1,62 @@ +# Documentation +documents + +# Exports, Project settings +.mtbLaunchConfigs +.settings +.vscode + +# Not required PALs +$(SEARCH_optiga-trust-m)/pal/NEW_PAL_TEMPLATE +$(SEARCH_optiga-trust-m)/pal/esp32_freertos +$(SEARCH_optiga-trust-m)/pal/libusb +$(SEARCH_optiga-trust-m)/pal/linux +$(SEARCH_optiga-trust-m)/pal/xmc4800 +$(SEARCH_optiga-trust-m)/pal/xmc4800_freertos + +# Not required Crypto midlayers +$(SEARCH_optiga-trust-m)/pal/pal_crypt_openssl.c +$(SEARCH_optiga-trust-m)/pal/pal_crypt_wolfssl.c + +# Not required mbedtls wrapers +$(SEARCH_optiga-trust-m)/examples/mbedtls_port + +# Exclude tools and utilities from the build +$(SEARCH_optiga-trust-m)/examples/tools + +# Not required executeable for tools +$(SEARCH_optiga-trust-m)/examples/utilities/authenticate_chip +$(SEARCH_optiga-trust-m)/examples/utilities/pkcs11_trustm.c +$(SEARCH_optiga-trust-m)/examples/utilities/trustm_chipinfo.c +$(SEARCH_optiga-trust-m)/examples/utilities/optiga_trust.c +$(SEARCH_optiga-trust-m)/examples/optiga_shell.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_init_deinit.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_util_protected_update.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_util_read_data.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_util_update_count.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_util_write_data.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_util_hibernate_restore.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_read_coprocessor_id.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_crypt_clear_auto_state.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_crypt_ecc_generate_keypair.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_crypt_ecdh.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_crypt_ecdsa_sign.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_crypt_ecdsa_verify.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_crypt_hash.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_crypt_hkdf.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_crypt_hmac.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_crypt_random.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_crypt_rsa_decrypt.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_crypt_rsa_encrypt_message.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_crypt_rsa_encrypt_session.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_crypt_rsa_generate_keypair.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_crypt_rsa_sign.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_crypt_rsa_verify.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_crypt_symmetric_encrypt_decrypt.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_crypt_symmetric_encrypt_decrypt_ecb.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_crypt_symmetric_generate_key.c +$(SEARCH_optiga-trust-m)/examples/optiga/example_optiga_crypt_tls_prf_sha256.c +$(SEARCH_optiga-trust-m)/examples/optiga/usecases/example_optiga_hmac_verify_with_authorization_reference.c +$(SEARCH_optiga-trust-m)/examples/optiga/usecases/example_pair_host_and_optiga_using_pre_shared_secret.c +$(SEARCH_optiga-trust-m)/examples/optiga/usecases/example_optiga_hibernate_restore.c +$(SEARCH_optiga-trust-m)/examples/optiga/usecases/example_read_coprocessor_id.c \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..a053ead --- /dev/null +++ b/.gitignore @@ -0,0 +1,148 @@ +# This list of files to ignore includes common, tool- or user-specific files that +# are typically not checked into a version control system (VCS). It is a superset +# of such files. You may want to add others, especially if you use a tool not listed +# here. You can remove those that do not apply to you. +# +# The .gitignore file is intended for the git VCS. For another VCS you would specify +# which files to ignore in whatever form your VCS requires. If you do not check your +# code into a VCS, you can ignore the .gitignore file. + +# ModusToolbox library repos or information about library dependencies +libs/ + +# Eclipse IDE for ModusToolbox files +.metadata/ +# .cyignore +# .settings/ +# .cproject +# .project +# .mtbLaunchConfigs/ + +# ModusToolbox Configurator generated code +GeneratedSource/ + +# ModusToolbox build system output +build/ +Debug/ +Release/ +*_build/ + +# Visual Studio Code +openocd.tcl +.vscode/ +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json + +# IAR Embedded Workbench files + +# IAR Project file. +# *.ewp + +# IAR Settings +/settings/ + +# Uncomment this if not using project connections +# *.ipcf + +# Comment this out if using custom argument variables +*.custom_argvars + +# IAR Debugger Settings +# *.ewd + +# Comment this out if you use C-Stat or C-Run to compile/analyze your project +*.ewt + +# IAR Workspace files +# *.eww + +# IAR Debug Exe +/Debug/Exe/ + +# IAR Debug List +/Debug/List + +# IAR Debug Obj +/Obj/*.pbd +/Obj/*.pbd.* +/Obj/*.pbi +/Obj/*.pbi.* + +# Log files +*.log + +# IAR backup files +Backup* + +# IAR dependency files +*.dep + +# Compiled Binaries +*.bin +*.elf +*.hex +*.map + +# Trash files +*.bak + + +# Keil uVision files + +# Project and package description files +*.cpdsc +*.gpdsc + +# uVision Project file (generated by uVision). Uncomment this if do not want to track the Keil uVision project file +# *.uvprojx (is used to build the project from scratch) + +# Project options file (contains information about the debugger and trace configuration) +# *.uvoptx + +# Project file for multi-project workspaces +# *.uvmpw + +# Project screen layout file +*.uvguix.* + +# Configuration files for the run-time environment +# RTE/ + +# Generated output files +*.lst +*.map + +# Eclipse workspace/user-specific files/settings/caches +.metadata/ +# .settings/ + +# Vi and Emacs backup files +*~ +\#*\# +[._]*.s[a-v][a-z] +[._]*.sw[a-p] +[._]s[a-rt-v][a-z] +[._]ss[a-gi-z] +[._]sw[a-p] + +# Created by git when using merge tools for conflicts +*.BACKUP.* +*.BASE.* +*.LOCAL.* +*.REMOTE.* +*_BACKUP_*.txt +*_BASE_*.txt +*_LOCAL_*.txt +*_REMOTE_*.txt + +# macOS Finder incidental files +.DS_Store + +# Windows Explorer incidental files +Thumbs.db +Thumbs.db:encryptable +ehthumbs.db +ehthumbs_vista.db +[Dd]esktop.ini diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..2ca04a2 --- /dev/null +++ b/Makefile @@ -0,0 +1,193 @@ +################################################################################ +# \file Makefile +# \version 1.0 +# +# \brief +# Top-level application make file. +# +################################################################################ +# \copyright +# Copyright 2018-2020 Cypress Semiconductor Corporation +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +################################################################################ + + +################################################################################ +# Basic Configuration +################################################################################ + +# Target board/hardware (BSP). +# To change the target, it is recommended to use the Library manager +# ('make modlibs' from command line), which will also update Eclipse IDE launch +# configurations. If TARGET is manually edited, ensure TARGET_.mtb with a +# valid URL exists in the application, run 'make getlibs' to fetch BSP contents +# and update or regenerate launch configurations for your IDE. +TARGET=CY8CEVAL-062S2 + +# Name of application (used to derive name of final linked file). +# +# If APPNAME is edited, ensure to update or regenerate launch +# configurations for your IDE. +APPNAME=mtb-example-optiga-power-management + +# Name of toolchain to use. Options include: +# +# GCC_ARM -- GCC provided with ModusToolbox IDE +# ARM -- ARM Compiler (must be installed separately) +# IAR -- IAR Compiler (must be installed separately) +# +# See also: CY_COMPILER_PATH below +TOOLCHAIN=GCC_ARM + +# Default build configuration. Options include: +# +# Debug -- build with minimal optimizations, focus on debugging. +# Release -- build with full optimizations +# Custom -- build with custom configuration, set the optimization flag in CFLAGS +# +# If CONFIG is manually edited, ensure to update or regenerate launch configurations +# for your IDE. +CONFIG=Debug + +# If set to "true" or "1", display full command-lines when building. +VERBOSE= + +# Define a different core if required +# CORE=CM0P + +################################################################################ +# Advanced Configuration +################################################################################ + +# Enable optional code that is ordinarily disabled by default. +# +# Available components depend on the specific targeted hardware and firmware +# in use. In general, if you have +# +# COMPONENTS=foo bar +# +# ... then code in directories named COMPONENT_foo and COMPONENT_bar will be +# added to the build +# +COMPONENTS=PSOC6_BAREMETAL + +# Like COMPONENTS, but disable optional code that was enabled by default. +DISABLE_COMPONENTS= + +# By default the build system automatically looks in the Makefile's directory +# tree for source code and builds it. The SOURCES variable can be used to +# manually add source code to the build process from a location not searched +# by default, or otherwise not found by the build system. +SOURCES= + +# Like SOURCES, but for include directories. Value should be paths to +# directories (without a leading -I). +INCLUDES= + +# Add additional defines to the build process (without a leading -D). +DEFINES=\ + OPTIGA_LIB_EXTERNAL='"optiga_lib_config_mtb.h"' \ + MODE=$(MODE) + +# Select softfp or hardfp floating point. Default is softfp. +VFP_SELECT= + +# Additional / custom C compiler flags. +# +# NOTE: Includes and defines should use the INCLUDES and DEFINES variable +# above. +CFLAGS= + +# Additional / custom C++ compiler flags. +# +# NOTE: Includes and defines should use the INCLUDES and DEFINES variable +# above. +CXXFLAGS= + +# Additional / custom assembler flags. +# +# NOTE: Includes and defines should use the INCLUDES and DEFINES variable +# above. +ASFLAGS= + +# Additional / custom linker flags. +LDFLAGS= + +# Additional / custom libraries to link in to the application. +LDLIBS= + +# Path to the linker script to use (if empty, use the default linker script). +LINKER_SCRIPT= + +# Custom pre-build commands to run. +PREBUILD= + +# Custom post-build commands to run. +POSTBUILD= + + +################################################################################ +# Paths +################################################################################ + +# Relative path to the project directory (default is the Makefile's directory). +# +# This controls where automatic source code discovery looks for code. +CY_APP_PATH= + +# Relative path to the shared repo location. +# +# All .mtb files have the format, ##. If the field +# begins with $$ASSET_REPO$$, then the repo is deposited in the path specified by +# the CY_GETLIBS_SHARED_PATH variable. The default location is one directory level +# above the current app directory. +# This is used with CY_GETLIBS_SHARED_NAME variable, which specifies the directory name. +CY_GETLIBS_SHARED_PATH=../ + +# Directory name of the shared repo location. +# +CY_GETLIBS_SHARED_NAME=mtb_shared + +# Absolute path to the compiler's "bin" directory. +# +# The default depends on the selected TOOLCHAIN (GCC_ARM uses the ModusToolbox +# IDE provided compiler by default). +CY_COMPILER_PATH= + + +# Locate ModusToolbox IDE helper tools folders in default installation +# locations for Windows, Linux, and macOS. +CY_WIN_HOME=$(subst \,/,$(USERPROFILE)) +CY_TOOLS_PATHS ?= $(wildcard \ + $(CY_WIN_HOME)/ModusToolbox/tools_* \ + $(HOME)/ModusToolbox/tools_* \ + /Applications/ModusToolbox/tools_*) + +# If you install ModusToolbox IDE in a custom location, add the path to its +# "tools_X.Y" folder (where X and Y are the version number of the tools +# folder). Make sure you use forward slashes. +CY_TOOLS_PATHS+= + +# Default to the newest installed tools folder, or the users override (if it's +# found). +CY_TOOLS_DIR=$(lastword $(sort $(wildcard $(CY_TOOLS_PATHS)))) + +ifeq ($(CY_TOOLS_DIR),) +$(error Unable to find any of the available CY_TOOLS_PATHS -- $(CY_TOOLS_PATHS). On Windows, use forward slashes.) +endif + +$(info Tools Directory: $(CY_TOOLS_DIR)) + +include $(CY_TOOLS_DIR)/make/start.mk diff --git a/README.md b/README.md new file mode 100644 index 0000000..6d9ea28 --- /dev/null +++ b/README.md @@ -0,0 +1,286 @@ +# OPTIGA™ Trust M: Power management + +This example uses an OPTIGA™ Trust M V3 security solution along with a PSoC™ 6 MCU to execute example code to demonstrate the power management routines of the secure element. This example outputs the result and the time taken to perform the operations in a UART terminal. + +In a nutshell, the hibernation feature on the OPTIGA™ Trust M means that a host MCU can power down the security solution by removing the power from it, but under certain conditions, the latter can hold all internal temporarily allocated information despite being disconnected from the power line. + +The interconnection setup looks like the following: + +**Figure 1. Connection between PSoC™ 6 host MCU and OPTIGA™ Trust M** + +![](images/power_management_setup.png) + +[View this README on GitHub.](https://github.com/Infineon/mtb-example-optiga-power-management) + +[Provide feedback on this code example.](https://cypress.co1.qualtrics.com/jfe/form/SV_1NTns53sK2yiljn?Q_EED=eyJVbmlxdWUgRG9jIElkIjoiQ0UyMzM3MzQiLCJTcGVjIE51bWJlciI6IjAwMi0zMzczNCIsIkRvYyBUaXRsZSI6Ik9QVElHQeKEoiBUcnVzdCBNOiBQb3dlciBtYW5hZ2VtZW50IiwicmlkIjoieXVzaGV2IiwiRG9jIHZlcnNpb24iOiIxLjAuMCIsIkRvYyBMYW5ndWFnZSI6IkVuZ2xpc2giLCJEb2MgRGl2aXNpb24iOiJOL0EiLCJEb2MgQlUiOiJOL0EiLCJEb2MgRmFtaWx5IjoiTi9BIn0=) + + +## Requirements + +- [ModusToolbox™ software](https://www.cypress.com/products/modustoolbox) v2.4 +- Board support package (BSP) minimum required version: 2.0.0 +- Programming language: C +- Associated parts: + - All [PSoC™ 6 MCU](http://www.cypress.com/PSoC6) parts + - [OPTIGA™ Trust M V3](http://www.infineon.com/optiga-trust-m) + + +## Supported toolchains (make variable 'TOOLCHAIN') + +- GNU Arm® embedded compiler v9.3.1 (`GCC_ARM`) - Default value of `TOOLCHAIN` +- Arm® compiler v6.11 (`ARM`) +- IAR C/C++ compiler v8.42.2 (`IAR`) + + +## Supported kits (make variable 'TARGET') + +- [PSoC™ 62S2 evaluation kit](https://www.infineon.com/CY8CEVAL-062S2) (`CY8CEVAL-062S2`) +- [PSoC™ 62S2 evaluation kit with the Sterling-LWB5+ M.2 radio module](https://www.infineon.com/cms/en/product/evaluation-boards/cy8ceval-062s2/) (`CY8CEVAL-062S2-LAI-4373M2`) +- [PSoC™ 62S2 evaluation kit with the CYW943439M2IPA1 radio module](https://www.infineon.com/cms/en/product/evaluation-boards/cy8ceval-062s2/) (`CY8CEVAL-062S2-CYW943439M2IPA1`) + + +## Hardware setup + +This example uses the board's default configuration. See the kit user guide to ensure that the board is configured correctly. + + +## Software setup + +Install a terminal emulator if you don't have one. Instructions in this document use [Tera Term](https://ttssh2.osdn.jp/index.html.en). + +## Using the code example + +Create the project and open it using one of the following: + +
In Eclipse IDE for ModusToolbox™ software + +1. Click the **New application** link in the **quick panel** (or, use **File** > **New** > **ModusToolbox™ Application**). This launches the [Project Creator](https://www.cypress.com/ModusToolboxProjectCreator) tool. + +2. Pick a kit supported by the code example from the list shown in the **Project creator - Choose board support package (BSP)** dialog. + + When you select a supported kit, the example is reconfigured automatically to work with the kit. To work with a different supported kit later, use the [Library Manager](https://www.cypress.com/ModusToolboxLibraryManager) to choose the BSP for the supported kit. You can use the library manager to select or update the BSP and firmware libraries used in this application. To access the library manager, click the link from the **Quick Panel**. + + You can also just start the application creation process again and select a different kit. + + If you want to use the application for a kit not listed here, you may need to update the source files. If the kit does not have the required resources, the application may not work. + +3. In the **Project Creator - Select Application** dialog, choose the example by enabling the checkbox. + +4. (Optional) Change the suggested **New Application Name**. + +5. The **Application(s) Root Path** defaults to the Eclipse workspace which is usually the desired location for the application. If you want to store the application in a different location, you can change the *Application(s) root path* value. Applications that share libraries should be in the same root path. + +6. Click **Create** to complete the application creation process. + +For more details, see the [Eclipse IDE for ModusToolbox™ software user guide](https://www.cypress.com/MTBEclipseIDEUserGuide) (locally available at *{ModusToolbox™ software install directory}/ide_{version}/docs/mt_ide_user_guide.pdf*). + +
+ +
In command-line interface (CLI) + +ModusToolbox™ software provides the project creator as both a GUI tool and the command line tool, "project-creator-cli". The CLI tool can be used to create applications from a CLI terminal or from within batch files or shell scripts. This tool is available in the *{ModusToolbox™ software install directory}/tools_{version}/project-creator/* directory. + +Use a CLI terminal to invoke the "project-creator-cli" tool. On Windows, use the command line "modus-shell" program provided in the ModusToolbox™ software installation instead of a standard Windows command-line application. This shell provides access to all ModusToolbox™ software tools. You can access it by typing `modus-shell` in the search box in the Windows menu. In Linux and macOS, you can use any terminal application. + +This tool has the following arguments: + +Argument | Description | Required/optional +---------|-------------|----------- +`--board-id` | Defined in the `` field of the [BSP](https://github.com/Infineon?q=bsp-manifest&type=&language=&sort=) manifest | Required +`--app-id` | Defined in the `` field of the [CE](https://github.com/Infineon?q=ce-manifest&type=&language=&sort=) manifest | Required +`--target-dir`| Specify the directory in which the application is to be created if you prefer not to use the default current working directory | Optional +`--user-app-name`| Specify the name of the application if you prefer to have a name other than the example's default name | Optional + +
+ +The following example will clone the "[OPTIGA™ Trust M: Power management](https://github.com/Infineon/mtb-example-optiga-power-management)" application with the desired name "MyOPTIGAPowerManagement" configured for the *CY8CEVAL-062S2* BSP into the specified working directory, *C:/mtb_projects*: + + ``` + project-creator-cli --board-id CY8CEVAL-062S2 --app-id mtb-example-optiga-power-management --user-app-name MyOPTIGAPowerManagement --target-dir "C:/mtb_projects" + ``` + +**Note:** The project-creator-cli tool uses the `git clone` and `make getlibs` commands to fetch the repository and import the required libraries. For details, see the "Project creator tools" section of the [ModusToolbox™ software user guide](https://www.cypress.com/ModusToolboxUserGuide) (locally available at *{ModusToolbox™ software install directory}/docs_{version}/mtb_user_guide.pdf*). + +
+ +
In third-party IDEs + +Use one of the following options: + +- **Use the standalone [Project Creator](https://www.cypress.com/ModusToolboxProjectCreator) tool:** + + 1. Launch the project creator from the Windows Start menu or from *{ModusToolbox™ software install directory}/tools_{version}/project-creator/project-creator.exe*. + + 2. In the initial **Choose board support package** screen, select the BSP, and click **Next**. + + 3. In the **Select application** screen, select the appropriate IDE from the **Target IDE** drop-down menu. + + 4. Click **Create** and follow the instructions printed in the bottom pane to import or open the exported project in the respective IDE. + +
+ +- **Use command-line interface (CLI):** + + 1. Follow the instructions from the **In command-line interface (CLI)** section to create the application, and then import the libraries using the `make getlibs` command. + + 2. Export the application to a supported IDE using the `make ` command. + + 3. Follow the instructions displayed in the terminal to create or import the application as an IDE project. + +For a list of supported IDEs and more details, see the "Exporting to IDEs" section of the [ModusToolbox™ software user guide](https://www.cypress.com/ModusToolboxUserGuide) (locally available at *{ModusToolbox™ software install directory}/docs_{version}/mtb_user_guide.pdf*). + +
+ + +## Operation + +1. Connect the board to your PC using the provided USB cable through the KitProg3 USB connector. + +2. Open a terminal program and select the KitProg3 COM port. Set the serial port parameters to 8N1 and 115200 baud. + +3. Program the board using one of the following: + +
Using Eclipse IDE for ModusToolbox™ software + + 1. Select the application project in the project explorer. + + 2. In the **quick panel**, scroll down, and click **\ Program (KitProg3_MiniProg4)**. +
+ +
Using CLI + + From the terminal, execute the `make program` command to build and program the application using the default toolchain to the default target. The default toolchain and target are specified in the application's Makefile but you can override those values manually: + ``` + make program TARGET= TOOLCHAIN= + ``` + + Example: + ``` + make program TARGET=CY8CEVAL-062S2 TOOLCHAIN=GCC_ARM + ``` + +4. After programming, the application starts automatically. Confirm that the following text is displayed on the UART terminal. + + **Figure 2. Terminal output on program startup** + + ![](images/terminal-power-management.png) + + +## Debugging + +You can debug the example to step through the code. In the IDE, use the **\ Debug (KitProg3_MiniProg4)** configuration in the **Quick Panel**. For more details, see the "Program and debug" section in the [Eclipse IDE for ModusToolbox™ software user guide](https://www.cypress.com/MTBEclipseIDEUserGuide). + +**Note:** **(Only while debugging)** On the CM4 CPU, some code in `main()` may execute before the debugger halts at the beginning of `main()`. This means that some code executes twice - once before the debugger stops execution, and again after the debugger resets the program counter to the beginning of `main()`. See [KBA231071](https://community.cypress.com/docs/DOC-21143) to learn about this and for the workaround. + + +## Design and implementation + +The code example demonstrates one of scenarios to prepare and make use of the hibernation feature of the OPTIGA™ Trust M security solution. In a nutshell, the host MCU can control the enablement of the hibernation feature on the OPTIGA™ device by sending a corresponding command to the chip over the I2C channel. + +**Important:** To use all features provided by this example, your board should be able to control the power switch of the OPTIGA™ Trust M device. See [Resources and settings](#resources-and-settings). + +Do the following: + +1. Open the application on the security solution as usual. + +2. Generate an ECC key pair and store the result in a session object. + + The session object is located in a volatile memory and thus is erased each time the chip is powered off. + +3. To enter hibernate mode, the security monitor counter should be 0. Note that the previous step performed a crypto operation that caused the security monitor counter to increment to 1. + + **Note:** To learn more about the security monitor and its operation, see [this Wiki page](https://github.com/Infineon/optiga-trust-m/wiki/Security-Monitor). + +4. Enter hibernate mode and save the communication context on both sides (host MCU and security solution) by closing the application with the hibernate flag set to '1'. + +5. Open the application once again with the hibernate flag set to '1'. This restores the old communication context and all temporally stored data on the security solution. + +6. Generate an ECDSA signature using the private key from the session object. In normal conditions with no hibernate option used, that would be not possible, because the session object would be empty. + +7. Verify the signature using the public key saved in Step 2. + +8. Close the application without transitioning to hibernate mode. + +Hibernate mode plays a very important role if a shielded communication is used (protected I2C connection). Both the host MCU and the security solution maintain a session context that contains several aspects of the communication. This information is temporally stored on the security solution (the host side can theoretically store it) and is by default erased after every power cycle. + +If the hibernate feature is not used, that session context must be established every single time. This leads to a platform-binding secret usage, thus triggering a SEC counter (security monitor counter). If this is triggered too often, eventually every system power-up routine will take a lot of time. The latter would be required because to use the OPTIGA™ Trust M device, the host MCU must wait until the SEC counter reaches a value when a new security relevant operation can be performed. + + +### Power states of OPTIGA™ Trust M + +OPTIGA™ Trust M automatically enters a low-power mode after a configurable delay. This isn't hibernation mode, which can be entered only on demand by sending a corresponding command from the host MCU to the security solution. Once it has entered sleep mode, the OPTIGA™ solution resumes the normal operation as soon as its address is detected on the I2C bus. If no command is sent to the chip, it behaves as show in Figure 3. + +1. As soon as the OPTIGA™ device is idle, it starts to count down a "delay to sleep" time (tsdy). + +2. When this time elapses, the device enters a "go to sleep" procedure. + +3. The "go to sleep" procedure waits until all idle tasks are completed (e.g., counting down the SEC counter). If all idle tasks are completed and no command is pending, the OPTIGA™ device enters sleep mode. + +**Figure 3. Go-to-sleep diagram** + +![](images/go_to_sleep_diagram.png) + + + +### Resources and settings + +OPTIGA™ Trust M pins | Assigned GPIOs by default | Notes +--------------------- | ------------------------- | ------ +I2C SDA (I/O) | CYBSP_TRUSTM_I2C_SDA | Any GPIO connected to the I2C SDA line can be used. +I2C SCL (Clock) | CYBSP_TRUSTM_I2C_SCL | Any GPIO connected to the I2C SDA line can be used. +RST (Reset) | CYBSP_TRUSTM_RST | An optional control pin if defined in [*optiga_lib_config_mtb.h*](source/optiga_lib_config_mtb.h) +VDD (Power control) | (Optional) CYBSP_TRUSTM_VDD | An optional control pin if defined in [*optiga_lib_config_mtb.h*](source/optiga_lib_config_mtb.h) + +
+ +[*optiga_lib_config_mtb.h*](source/optiga_lib_config_mtb.h) macros | Meaning | Default value + ---------------- | ------------- | --------- +`OPTIGA_CRYPT_XXXX` | Controls whether to enable/disable selected crypto support on the host library side | All enabled +`OPTIGA_COMMS_SHIELDED_CONNECTION` and `OPTIGA_COMMS_DEFAULT_PROTECTION_LEVEL` | Together define whether to use and the extent of use of the shielded connection (encrypted and integrity-protected I2C communication) | Defined `OPTIGA_COMMS_SHIELDED_CONNECTION` | If this and the `OPTIGA_COMMS_DEFAULT_PROTECTION_LEVEL` macro are set to `OPTIGA_COMMS_NO_PROTECTION`, you must decide the API to protect and the extent of protection right before that API is called by calling `OPTIGA_CRYPT_SET_COMMS_PROTECTION_LEVEL()` and `OPTIGA_CRYPT_SET_COMMS_PROTOCOL_VERSION()` | `OPTIGA_COMMS_SHIELDED_CONNECTION`: Defined `OPTIGA_COMMS_DEFAULT_PROTECTION_LEVEL`: Set to `OPTIGA_COMMS_NO_PROTECTION` +`OPTIGA_COMMS_DEFAULT_RESET_TYPE` | The reset type if VDD or RST pin is defined. Choose 1 or 2 depending on the combination used. VDD can be used in certain cases as a reset line, but it is recommended to use them separately. | 2 +`OPTIGA_CMD_MAX_REGISTRATIONS` | Controls the number of `crypt`/`util` registrations allowed. In a very basic scenario, this can be reduced to 2 (one registration each for `crypt` and `util`). | 6 +`OPTIGA_MAX_COMMS_BUFFER_SIZE` | Maximum buffer size that the command layer should be able to store intermediately | 0x615 +`OPTIGA_LIB_ENABLE_LOGGING` | Controls whether logging can be enabled in general | Defined +`OPTIGA_LIB_ENABLE_UTIL_LOGGING` | If defined together with `OPTIGA_LIB_ENABLE_LOGGING`, outputs messages relevant to the `util` API | Undefined +`OPTIGA_LIB_ENABLE_CRYPT_LOGGING` | If defined together with `OPTIGA_LIB_ENABLE_LOGGING`, outputs messages relevant to the `crypt` API | Undefined +`OPTIGA_LIB_ENABLE_CMD_LOGGING` | If defined together with `OPTIGA_LIB_ENABLE_LOGGING`, outputs the application protocol data unit (APDU) sent to the OPTIGA™ Trust M external interface (See the solution reference manual) | Undefined +`OPTIGA_LIB_ENABLE_COMMS_LOGGING` | If defined together with `OPTIGA_LIB_ENABLE_LOGGING`, prints out I2C frames | Undefined + +
+ +## Related resources + +Resources | Links +----------|------ +Application notes |[AN228571](https://www.cypress.com/AN228571) – Getting started with PSoC™ 6 MCU on ModusToolbox™ software
[AN215656](https://www.cypress.com/AN215656) – PSoC™ 6 MCU: Dual-CPU system design +Code examples on GitHub| [Using ModusToolbox™ software](https://github.com/infineon/Code-Examples-for-ModusToolbox-Software) +Device documentation | [PSoC™ 6 MCU datasheets](https://www.cypress.com/search/all?f[0]=meta_type%3Atechnical_documents&f[1]=resource_meta_type%3A575&f[2]=field_related_products%3A114026)
[PSoC™ 6 technical reference manuals](https://www.cypress.com/search/all/PSoC%206%20Technical%20Reference%20Manual?f[0]=meta_type%3Atechnical_documents&f[1]=resource_meta_type%3A583)
[OPTIGA™ Trust M datasheet](https://www.infineon.com/cms/en/product/security-smart-card-solutions/optiga-embedded-security-solutions/optiga-trust/optiga-trust-m-sls32aia/#!?fileId=5546d4626c1f3dc3016c853c271a7e4a) +Development kits | Select your kits from the [Evaluation Board Finder](https://www.infineon.com/cms/en/design-support/finder-selection-tools/product-finder/evaluation-board) page. +Libraries on GitHub | [mtb-pdl-cat1](https://github.com/infineon/mtb-pdl-cat1) – PSoC™ 6 peripheral driver library (PDL)
[mtb-hal-cat1](https://github.com/infineon/mtb-hal-cat1) – Hardware abstraction layer (HAL) library
[retarget-io](https://github.com/infineon/retarget-io) – Utility library to retarget STDIO messages to a UART port +Middleware on GitHub | [optiga-trust-m](https://github.com/infineon/optiga-trust-m) – OPTIGA™ Trust M library and documents
[capsense](https://github.com/infineon/capsense) – CAPSENSE™ library and documents
[psoc6-middleware](https://github.com/Infineon/modustoolbox-software#psoc-6-middleware-libraries) – Links to all PSoC™ 6 MCU middleware +Tools | [Eclipse IDE for ModusToolbox™ software](https://www.cypress.com/modustoolbox) – ModusToolbox™ software is a collection of easy-to-use software and tools enabling rapid development with Infineon MCUs, covering applications from embedded sense and control to wireless and cloud-connected systems using AIROC™ Wi-Fi and Bluetooth® connectivity devices. + + +## Other resources + +Infineon provides a wealth of data at www.infineon.com to help you select the right device, and quickly and effectively integrate it into your design. + +For PSoC™ 6 MCU devices, see [How to design with PSoC™ 6 MCU - KBA223067](https://community.infineon.com/t5/Knowledge-Base-Articles/How-to-Design-with-PSoC-6-MCU-KBA223067/ta-p/248857) in the Infineon community. + + +## Document history + +Document title: *CE233734* – *OPTIGA™ Trust M: Power management* + +| Version | Description of change | +| ------- | --------------------- | +| 1.0.0 | New code example | +------ + +All other trademarks or registered trademarks referenced herein are the property of their respective owners. + +------------ + +© Cypress Semiconductor Corporation, 2022. This document is the property of Cypress Semiconductor Corporation, an Infineon Technologies company, and its affiliates ("Cypress"). This document, including any software or firmware included or referenced in this document ("Software"), is owned by Cypress under the intellectual property laws and treaties of the United States and other countries worldwide. Cypress reserves all rights under such laws and treaties and does not, except as specifically stated in this paragraph, grant any license under its patents, copyrights, trademarks, or other intellectual property rights. If the Software is not accompanied by a license agreement and you do not otherwise have a written agreement with Cypress governing the use of the Software, then Cypress hereby grants you a personal, non-exclusive, nontransferable license (without the right to sublicense) (1) under its copyright rights in the Software (a) for Software provided in source code form, to modify and reproduce the Software solely for use with Cypress hardware products, only internally within your organization, and (b) to distribute the Software in binary code form externally to end users (either directly or indirectly through resellers and distributors), solely for use on Cypress hardware product units, and (2) under those claims of Cypress’s patents that are infringed by the Software (as provided by Cypress, unmodified) to make, use, distribute, and import the Software solely for use with Cypress hardware products. Any other use, reproduction, modification, translation, or compilation of the Software is prohibited.
+TO THE EXTENT PERMITTED BY APPLICABLE LAW, CYPRESS MAKES NO WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, WITH REGARD TO THIS DOCUMENT OR ANY SOFTWARE OR ACCOMPANYING HARDWARE, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. No computing device can be absolutely secure. Therefore, despite security measures implemented in Cypress hardware or software products, Cypress shall have no liability arising out of any security breach, such as unauthorized access to or use of a Cypress product. CYPRESS DOES NOT REPRESENT, WARRANT, OR GUARANTEE THAT CYPRESS PRODUCTS, OR SYSTEMS CREATED USING CYPRESS PRODUCTS, WILL BE FREE FROM CORRUPTION, ATTACK, VIRUSES, INTERFERENCE, HACKING, DATA LOSS OR THEFT, OR OTHER SECURITY INTRUSION (collectively, "Security Breach"). Cypress disclaims any liability relating to any Security Breach, and you shall and hereby do release Cypress from any claim, damage, or other liability arising from any Security Breach. In addition, the products described in these materials may contain design defects or errors known as errata which may cause the product to deviate from published specifications. To the extent permitted by applicable law, Cypress reserves the right to make changes to this document without further notice. Cypress does not assume any liability arising out of the application or use of any product or circuit described in this document. Any information provided in this document, including any sample design information or programming code, is provided only for reference purposes. It is the responsibility of the user of this document to properly design, program, and test the functionality and safety of any application made of this information and any resulting product. "High-Risk Device" means any device or system whose failure could cause personal injury, death, or property damage. Examples of High-Risk Devices are weapons, nuclear installations, surgical implants, and other medical devices. "Critical Component" means any component of a High-Risk Device whose failure to perform can be reasonably expected to cause, directly or indirectly, the failure of the High-Risk Device, or to affect its safety or effectiveness. Cypress is not liable, in whole or in part, and you shall and hereby do release Cypress from any claim, damage, or other liability arising from any use of a Cypress product as a Critical Component in a High-Risk Device. You shall indemnify and hold Cypress, its directors, officers, employees, agents, affiliates, distributors, and assigns harmless from and against all claims, costs, damages, and expenses, arising out of any claim, including claims for product liability, personal injury or death, or property damage arising from any use of a Cypress product as a Critical Component in a High-Risk Device. Cypress products are not intended or authorized for use as a Critical Component in any High-Risk Device except to the limited extent that (i) Cypress's published data sheet for the product explicitly states Cypress has qualified the product for use in a specific High-Risk Device, or (ii) Cypress has given you advance written authorization to use the product as a Critical Component in the specific High-Risk Device and you have signed a separate indemnification agreement.
+Cypress, the Cypress logo, Spansion, the Spansion logo, and combinations thereof, WICED, PSoC, CapSense, EZ-USB, F-RAM, and Traveo are trademarks or registered trademarks of Cypress in the United States and other countries. For a more complete list of Cypress trademarks, visit cypress.com. Other names and brands may be claimed as property of their respective owners. diff --git a/deps/TARGET_CY8CEVAL-062S2.mtb b/deps/TARGET_CY8CEVAL-062S2.mtb new file mode 100644 index 0000000..4cfd91d --- /dev/null +++ b/deps/TARGET_CY8CEVAL-062S2.mtb @@ -0,0 +1 @@ +https://github.com/Infineon/TARGET_CY8CEVAL-062S2#release-v2.3.0#$$LOCAL$$/TARGET_CY8CEVAL-062S2 diff --git a/deps/optiga-trust-m.mtb b/deps/optiga-trust-m.mtb new file mode 100644 index 0000000..c08cdbd --- /dev/null +++ b/deps/optiga-trust-m.mtb @@ -0,0 +1 @@ +https://github.com/Infineon/optiga-trust-m#latest-v3.X#$$ASSET_REPO$$/optiga-trust-m/latest-v3.X \ No newline at end of file diff --git a/deps/retarget-io.mtb b/deps/retarget-io.mtb new file mode 100644 index 0000000..5f86d6c --- /dev/null +++ b/deps/retarget-io.mtb @@ -0,0 +1 @@ +https://github.com/cypresssemiconductorco/retarget-io#latest-v1.X#$$ASSET_REPO$$/retarget-io/latest-v1.X diff --git a/images/go_to_sleep_diagram.png b/images/go_to_sleep_diagram.png new file mode 100644 index 0000000..53383ec Binary files /dev/null and b/images/go_to_sleep_diagram.png differ diff --git a/images/power_management_setup.png b/images/power_management_setup.png new file mode 100644 index 0000000..5454848 Binary files /dev/null and b/images/power_management_setup.png differ diff --git a/images/terminal-power-management.png b/images/terminal-power-management.png new file mode 100644 index 0000000..933f186 Binary files /dev/null and b/images/terminal-power-management.png differ diff --git a/main.c b/main.c new file mode 100644 index 0000000..bee465c --- /dev/null +++ b/main.c @@ -0,0 +1,328 @@ +/****************************************************************************** +* File Name: main.c +* +* Description: This is the source code for the PSoC 6 MCU and OPTIGA Trust M +* for ModusToolbox. +* +* Related Document: See README.md +* +* +* The MIT License +* +* Copyright (c) 2021 Infineon Technologies AG +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE +*******************************************************************************/ + +#include "cy_pdl.h" +#include "cyhal.h" +#include "cybsp.h" +#include "cy_retarget_io.h" + +#include "optiga/optiga_util.h" +#include "optiga/optiga_crypt.h" +#include "optiga/pal/pal_os_timer.h" +#include "optiga/pal/pal_logger.h" +#include "optiga/pal/pal.h" +#include "optiga_example.h" + +/******************************************************************************* +* Function Prototypes +*******************************************************************************/ +static void optiga_lib_callback(void * context, optiga_lib_status_t return_status); +static void example_optiga_util_hibernate_restore(void); + +/******************************************************************************* +* Global Variables +*******************************************************************************/ +/** + * Callback when optiga_util_xxxx operation is completed asynchronously + */ +static volatile optiga_lib_status_t optiga_lib_status; + +//SHA-256 Digest to be signed +static const uint8_t digest [] = +{ + 0x61, 0xC7, 0xDE, 0xF9, 0x0F, 0xD5, 0xCD, 0x7A,0x8B, 0x7A, 0x36, 0x41, 0x04, 0xE0, 0x0D, 0x82, + 0x38, 0x46, 0xBF, 0xB7, 0x70, 0xEE, 0xBF, 0x8F,0x40, 0x25, 0x2E, 0x0A, 0x21, 0x42, 0xAF, 0x9C, +}; + + +//lint --e{818} suppress "argument "context" is not used in the sample provided" +static void optiga_lib_callback(void * context, optiga_lib_status_t return_status) +{ + optiga_lib_status = return_status; + if (NULL != context) + { + // callback to upper layer here + } +} + +/** + * The below example demonstrates hibernate and restore functionalities + * + * Example for #optiga_util_open_application and #optiga_util_close_application + * + */ +static void example_optiga_util_hibernate_restore(void) +{ + optiga_util_t * me_util = NULL; + optiga_crypt_t * me_crypt = NULL; + // To store the public key generated + uint8_t public_key [100]; + //To store the signature generated + uint8_t signature [80]; + uint16_t signature_length = sizeof(signature); + uint16_t bytes_to_read = 1; + optiga_key_id_t optiga_key_id; + optiga_lib_status_t return_status = !OPTIGA_LIB_SUCCESS; + uint8_t security_event_counter = 0; + public_key_from_host_t public_key_details; + //To store the generated public key as part of Generate key pair + uint16_t public_key_length = sizeof(public_key); + uint32_t time_taken = 0; + + OPTIGA_EXAMPLE_LOG_MESSAGE("Begin demonstrating hibernate feature...\n"); + OPTIGA_EXAMPLE_LOG_MESSAGE(__FUNCTION__); + + do + { + OPTIGA_EXAMPLE_LOG_MESSAGE("Create both crypt and util instances\n") + //Create an instance of optiga_util and optiga_crypt + me_util = optiga_util_create(0, optiga_lib_callback, NULL); + if (NULL == me_util) + { + break; + } + + me_crypt = optiga_crypt_create(0, optiga_lib_callback, NULL); + if (NULL == me_crypt) + { + break; + } + + /** + * 1. Open the application on OPTIGA which is a pre-condition to perform any other operations + * using optiga_util_open_application + */ + OPTIGA_EXAMPLE_LOG_MESSAGE("1. Open the application on OPTIGA which is a pre-condition to perform any other operations\n") + optiga_lib_status = OPTIGA_LIB_BUSY; + + START_PERFORMANCE_MEASUREMENT(time_taken); + + return_status = optiga_util_open_application(me_util, 0); + + WAIT_AND_CHECK_STATUS(return_status, optiga_lib_status); + + /** + * 2. Generate ECC Key pair + * - Use ECC NIST P 256 Curve + * - Specify the Key Usage (Key Agreement or Sign based on requirement) + * - Store the Private key generated in a Session OID + * - Export Public Key + */ + OPTIGA_EXAMPLE_LOG_MESSAGE("2. Generate ECC Key pair\n") + optiga_lib_status = OPTIGA_LIB_BUSY; + optiga_key_id = OPTIGA_KEY_ID_SESSION_BASED; + return_status = optiga_crypt_ecc_generate_keypair(me_crypt, + OPTIGA_ECC_CURVE_NIST_P_256, + (uint8_t)OPTIGA_KEY_USAGE_SIGN, + FALSE, + &optiga_key_id, + public_key, + &public_key_length); + WAIT_AND_CHECK_STATUS(return_status, optiga_lib_status); + + /** + * - The subsequent steps will hibernate OPTIGA and save the session and optiga comms related information in OPTIGA . + * - The session and optiga comms related information are then restored back and crypto operation are performed using these information. + */ + + /** + * 3. To perform the hibernate, Security Event Counter(SEC) must be 0. + * Read SEC data object (0xE0C5) and wait until SEC = 0 + */ + OPTIGA_EXAMPLE_LOG_MESSAGE("Note: The subsequent steps will hibernate OPTIGA and save the session and optiga comms related information in OPTIGA\n") + OPTIGA_EXAMPLE_LOG_MESSAGE("The session and optiga comms related information are then restored back and crypto operation are performed using these information.\n") + OPTIGA_EXAMPLE_LOG_MESSAGE("3. To perform the hibernate, Security Event Counter(SEC) must be 0.\n") + OPTIGA_EXAMPLE_LOG_MESSAGE("Read SEC data object (0xE0C5) and wait until SEC = 0.\n") + do + { + optiga_lib_status = OPTIGA_LIB_BUSY; + return_status = optiga_util_read_data(me_util, + 0xE0C5, + 0x0000, + &security_event_counter, + &bytes_to_read); + + WAIT_AND_CHECK_STATUS(return_status, optiga_lib_status); + pal_os_timer_delay_in_milliseconds(1000); + } while (0 != security_event_counter); + + /** + * 4. Hibernate the application on OPTIGA + * using optiga_util_close_application with perform_hibernate parameter as true + */ + OPTIGA_EXAMPLE_LOG_MESSAGE("4. Hibernate the application on OPTIGA.\n") + optiga_lib_status = OPTIGA_LIB_BUSY; + return_status = optiga_util_close_application(me_util, 1); + + WAIT_AND_CHECK_STATUS(return_status, optiga_lib_status); + + /** + * 5. Restore the application on OPTIGA + * using optiga_util_open_application with perform_restore parameter as true + */ + OPTIGA_EXAMPLE_LOG_MESSAGE("5. Restore the application on OPTIGA.\n") + optiga_lib_status = OPTIGA_LIB_BUSY; + return_status = optiga_util_open_application(me_util, 1); + + WAIT_AND_CHECK_STATUS(return_status, optiga_lib_status); + + /** + * 6. Sign the digest using the session key from Step 3 + */ + OPTIGA_EXAMPLE_LOG_MESSAGE("6. Sign the digest using the session key from Step 3.\n") + optiga_lib_status = OPTIGA_LIB_BUSY; + return_status = optiga_crypt_ecdsa_sign(me_crypt, + digest, + sizeof(digest), + OPTIGA_KEY_ID_SESSION_BASED, + signature, + &signature_length); + + WAIT_AND_CHECK_STATUS(return_status, optiga_lib_status); + + /** + * 7. Verify ECDSA signature using public key from step 2 + */ + OPTIGA_EXAMPLE_LOG_MESSAGE("7. Verify ECDSA signature using public key from step 2.\n") + optiga_lib_status = OPTIGA_LIB_BUSY; + public_key_details.public_key = public_key; + public_key_details.length = public_key_length; + public_key_details.key_type = (uint8_t)OPTIGA_ECC_CURVE_NIST_P_256; + return_status = optiga_crypt_ecdsa_verify (me_crypt, + digest, + sizeof(digest), + signature, + signature_length, + OPTIGA_CRYPT_HOST_DATA, + &public_key_details); + + WAIT_AND_CHECK_STATUS(return_status, optiga_lib_status); + + /** + * 8. Close the application on OPTIGA without hibernating + * using optiga_util_close_application + */ + OPTIGA_EXAMPLE_LOG_MESSAGE("8. Close the application on OPTIGA without hibernating.\n") + optiga_lib_status = OPTIGA_LIB_BUSY; + return_status = optiga_util_close_application(me_util, 0); + WAIT_AND_CHECK_STATUS(return_status, optiga_lib_status); + + READ_PERFORMANCE_MEASUREMENT(time_taken); + + return_status = OPTIGA_LIB_SUCCESS; + OPTIGA_EXAMPLE_LOG_MESSAGE("Hibernate feature demonstration completed...\n"); + } while (FALSE); + OPTIGA_EXAMPLE_LOG_STATUS(return_status); + + OPTIGA_EXAMPLE_LOG_MESSAGE("Destroy both crypt and util instances.\n") + + if (me_util) + { + //Destroy the instance after the completion of usecase if not required. + return_status = optiga_util_destroy(me_util); + if(OPTIGA_LIB_SUCCESS != return_status) + { + //lint --e{774} suppress This is a generic macro + OPTIGA_EXAMPLE_LOG_STATUS(return_status); + } + } + + if (me_crypt) + { + //Destroy the instance after the completion of usecase if not required. + return_status = optiga_crypt_destroy(me_crypt); + if(OPTIGA_LIB_SUCCESS != return_status) + { + //lint --e{774} suppress This is a generic macro + OPTIGA_EXAMPLE_LOG_STATUS(return_status); + } + } +} + +extern void example_optiga_crypt_hash(void); +/******************************************************************************* +* Function Name: main +******************************************************************************** +* Summary: +* This is the main function for CM4 CPU. It sets up a timer to trigger a +* periodic interrupt. The main while loop checks for the status of a flag set +* by the interrupt and toggles an LED at 1Hz to create an LED blinky. The +* while loop also checks whether the 'Enter' key was pressed and +* stops/restarts LED blinking. +* +* Parameters: +* none +* +* Return: +* int +* +*******************************************************************************/ +int main(void) +{ + cy_rslt_t result; + + /* Initialize the device and board peripherals */ + result = cybsp_init(); + + /* Board init failed. Stop program execution */ + if (result != CY_RSLT_SUCCESS) + { + CY_ASSERT(0); + } + + /* Enable global interrupts */ + __enable_irq(); + + /* Initialize retarget-io to use the debug UART port */ + cy_retarget_io_init(CYBSP_DEBUG_UART_TX, CYBSP_DEBUG_UART_RX, CY_RETARGET_IO_BAUDRATE); + + /* \x1b[2J\x1b[;H - ANSI ESC sequence for clear screen */ + printf("\x1b[2J\x1b[;H"); + + printf("****************** OPTIGA™ Trust M: Power management Example ****************** \r\n\n"); + + /* + PAL stands for Pltaform Abstraction Layer in OPTIGA Host library + Here all the target system relevant function started + */ + pal_init(); + +#ifdef CYBSP_TRUSTM_VDD + example_optiga_util_hibernate_restore(); +#else + OPTIGA_EXAMPLE_LOG_MESSAGE("If you see this message, it means that your board doesn't implement the OPTIGA VCC Control circuit.\n"); + OPTIGA_EXAMPLE_LOG_MESSAGE("If you have a custom board please define the CYBSP_TRUSTM_VDD macro with the corresponding GPIO in your build.\n"); +#endif + +} + +/* [] END OF FILE */ diff --git a/mtb-example-optiga-power-management.code-workspace b/mtb-example-optiga-power-management.code-workspace new file mode 100644 index 0000000..d42ae35 --- /dev/null +++ b/mtb-example-optiga-power-management.code-workspace @@ -0,0 +1,24 @@ +{ + "folders": [ + { + "path": "." + }, + { + "path": "../mtb_shared" + } + ], + "settings": { + //mtb// If this project will be shared with multiple users, the + //mtb// modustoolbox.toolsPath property must be placed in user settings + //mtb// file instead of this file. The user settings file location for + //mtb// VSCode depends on your OS: + //mtb// + //mtb// Windows: %APPDATA%\Code\User\settings.json + //mtb// macOS : $HOME/Library/Application Support/Code/User/settings.json + //mtb// Linux : $HOME/.config/Code/User/settings.json + //mtb// + "modustoolbox.toolsPath": "C:/Users/yushev/ModusToolbox/tools_2.3", + "cortex-debug.armToolchainPath": "${config:modustoolbox.toolsPath}/gcc/bin", + "cortex-debug.openocdPath": "${config:modustoolbox.toolsPath}/openocd/bin/openocd" + } +} \ No newline at end of file diff --git a/optiga_lib_config_mtb.h b/optiga_lib_config_mtb.h new file mode 100644 index 0000000..3404aad --- /dev/null +++ b/optiga_lib_config_mtb.h @@ -0,0 +1,181 @@ +/** +* \copyright +* MIT License +* +* Copyright (c) 2020 Infineon Technologies AG +* +* Permission is hereby granted, free of charge, to any person obtaining a copy +* of this software and associated documentation files (the "Software"), to deal +* in the Software without restriction, including without limitation the rights +* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +* copies of the Software, and to permit persons to whom the Software is +* furnished to do so, subject to the following conditions: +* +* The above copyright notice and this permission notice shall be included in all +* copies or substantial portions of the Software. +* +* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +* SOFTWARE +* +* \endcopyright +* +* \author Infineon Technologies AG +* +* \file optiga_lib_config_m_v3.h +* +* \brief This file is defines the compilation switches to build code with required features. +* +* \ingroup grOptigaLibCommon +* +* @{ +*/ + + +#ifndef _OPTIGA_LIB_CONFIG_M_V3_H_ +#define _OPTIGA_LIB_CONFIG_M_V3_H_ + +#include "cybsp.h" + +#ifdef __cplusplus +extern "C" { +#endif + + /** @brief OPTIGA CRYPT random number generation feature enable/disable macro */ + #define OPTIGA_CRYPT_RANDOM_ENABLED + /** @brief OPTIGA CRYPT hash feature enable/disable macro */ + #define OPTIGA_CRYPT_HASH_ENABLED + /** @brief OPTIGA CRYPT ECC generate keypair feature enable/disable macro */ + #define OPTIGA_CRYPT_ECC_GENERATE_KEYPAIR_ENABLED + /** @brief OPTIGA CRYPT ECDSA signature feature enable/disable macro */ + #define OPTIGA_CRYPT_ECDSA_SIGN_ENABLED + /** @brief OPTIGA CRYPT verify ECDSA signature feature enable/disable macro */ + #define OPTIGA_CRYPT_ECDSA_VERIFY_ENABLED + /** @brief OPTIGA CRYPT ECDH feature enable/disable macro */ + #define OPTIGA_CRYPT_ECDH_ENABLED + /** @brief OPTIGA CRYPT ECC 521 feature enable/disable macro */ + #define OPTIGA_CRYPT_ECC_NIST_P_521_ENABLED + /** @brief OPTIGA CRYPT ECC Brainpool feature enable/disable macro */ + #define OPTIGA_CRYPT_ECC_BRAINPOOL_P_R1_ENABLED + /** @brief OPTIGA CRYPT TLS PRF sha256 feature enable/disable macro */ + #define OPTIGA_CRYPT_TLS_PRF_SHA256_ENABLED + /** @brief OPTIGA CRYPT TLS PRF sha384 feature enable/disable macro */ + #define OPTIGA_CRYPT_TLS_PRF_SHA384_ENABLED + /** @brief OPTIGA CRYPT TLS PRF sha512 feature enable/disable macro */ + #define OPTIGA_CRYPT_TLS_PRF_SHA512_ENABLED + /** @brief OPTIGA CRYPT RSA generate keypair feature enable/disable macro */ + #define OPTIGA_CRYPT_RSA_GENERATE_KEYPAIR_ENABLED + /** @brief OPTIGA CRYPT RSA sign feature enable/disable macro */ + #define OPTIGA_CRYPT_RSA_SIGN_ENABLED + /** @brief OPTIGA CRYPT RSA verify sign feature enable/disable macro */ + #define OPTIGA_CRYPT_RSA_VERIFY_ENABLED + /** @brief OPTIGA CRYPT RSA Encrypt feature enable/disable macro */ + #define OPTIGA_CRYPT_RSA_ENCRYPT_ENABLED + /** @brief OPTIGA CRYPT RSA Decrypt feature enable/disable macro */ + #define OPTIGA_CRYPT_RSA_DECRYPT_ENABLED + /** @brief OPTIGA CRYPT RSA pre-master feature enable/disable macro */ + #define OPTIGA_CRYPT_RSA_PRE_MASTER_SECRET_ENABLED + /** @brief OPTIGA CRYPT RSA SSA with SHA512 as digest feature enable/disable macro */ + #define OPTIGA_CRYPT_RSA_SSA_SHA512_ENABLED + /** @brief OPTIGA CRYPT symmetric encrypt feature enable/disable macro */ + #define OPTIGA_CRYPT_SYM_ENCRYPT_ENABLED + /** @brief OPTIGA CRYPT symmetric decrypt feature enable/disable macro */ + #define OPTIGA_CRYPT_SYM_DECRYPT_ENABLED + /** @brief OPTIGA CRYPT HMAC feature enable/disable macro */ + #define OPTIGA_CRYPT_HMAC_ENABLED + /** @brief OPTIGA CRYPT HKDF feature enable/disable macro */ + #define OPTIGA_CRYPT_HKDF_ENABLED + /** @brief OPTIGA CRYPT symmetric generate key feature enable/disable macro */ + #define OPTIGA_CRYPT_SYM_GENERATE_KEY_ENABLED + /** @brief OPTIGA CRYPT generate auth code feature enable/disable macro */ + #define OPTIGA_CRYPT_GENERATE_AUTH_CODE_ENABLED + /** @brief OPTIGA CRYPT HMAC verify feature enable/disable macro */ + #define OPTIGA_CRYPT_HMAC_VERIFY_ENABLED + /** @brief OPTIGA CRYPT clear AUTO state feature enable/disable macro */ + #define OPTIGA_CRYPT_CLEAR_AUTO_STATE_ENABLED + + /** @brief OPTIGA COMMS shielded connection feature. + * To disable the feature, undefine the macro + */ + #define OPTIGA_COMMS_SHIELDED_CONNECTION + + /** @brief Default reset protection level for OPTIGA CRYPT and UTIL APIs */ + #define OPTIGA_COMMS_DEFAULT_PROTECTION_LEVEL OPTIGA_COMMS_NO_PROTECTION + + /** @brief Default reset type in optiga_comms_open. \n + * Cold Reset - (0) : This is applicable if the host platform has GPIO option for RST and VDD. \n + * Soft Reset - (1) : This is applicable if the host platform doesn't have GPIO options for VDD and RST. \n + * Warm Reset - (2) : This is applicable if the host platform doesn't have GPIO option for VDD. \n + * Any other value will lead to error + */ + #ifndef OPTIGA_COMMS_DEFAULT_RESET_TYPE + #define OPTIGA_COMMS_DEFAULT_RESET_TYPE (0U) + #endif + + /** @brief NULL parameter check. + * To disable the check, undefine the macro + */ + #define OPTIGA_LIB_DEBUG_NULL_CHECK + /** @brief Maximum number of instance registration */ + #define OPTIGA_CMD_MAX_REGISTRATIONS (0x06) + /** @brief Maximum buffer size required to communicate with OPTIGA */ + #define OPTIGA_MAX_COMMS_BUFFER_SIZE (0x615) //1557 in decimal + + /** @brief Macro to enable logger \n + * Enable macro OPTIGA_LIB_ENABLE_UTIL_LOGGING for Util Service layer logging \n + * Enable macro OPTIGA_LIB_ENABLE_CRYPT_LOGGING for Crypt Service layer logging \n + * Enable macro OPTIGA_LIB_ENABLE_CMD_LOGGING for Command layer logging \n + * Enable macro OPTIGA_LIB_ENABLE_COMMS_LOGGING for Communication layer logging */ + #define OPTIGA_LIB_ENABLE_LOGGING + /** @brief Enable macro OPTIGA_PAL_INIT_ENABLED for calling pal_init functionality */ + #define OPTIGA_PAL_INIT_ENABLED +/// @cond +#ifdef OPTIGA_LIB_ENABLE_LOGGING + /** @brief Macro to enable logger for Util service */ + //#define OPTIGA_LIB_ENABLE_UTIL_LOGGING + /** @brief Macro to enable logger for Crypt service */ + //#define OPTIGA_LIB_ENABLE_CRYPT_LOGGING + /** @brief Macro to enable logger for Command layer */ + //#define OPTIGA_LIB_ENABLE_CMD_LOGGING + /** @brief Macro to enable logger for Communication layer */ + //#define OPTIGA_LIB_ENABLE_COMMS_LOGGING +#endif +/// @endcond + + /* Below are the example macros for protected update not for any feature */ + /** @brief OPTIGA UTIL confidentiality protected update feature enable/disable macro */ + #define EXAMPLE_OPTIGA_UTIL_PROTECTED_UPDATE_CONFIDENTIALITY_ENABLED + /** @brief OPTIGA UTIL key object protected update feature enable/disable macro */ + #define EXAMPLE_OPTIGA_UTIL_PROTECTED_UPDATE_OBJECT_KEY_ENABLED + /** @brief OPTIGA UTIL metadata object protected update feature enable/disable macro */ + #define EXAMPLE_OPTIGA_UTIL_PROTECTED_UPDATE_OBJECT_METADATA_ENABLED + + + /* The following GPIO settings are only ModusToolbox and specific PSoC6 family board relevant + * If you don't have both the Reset and the VCC Power Control connected, please define + * OPTIGA_COMMS_DEFAULT_RESET_TYPE to be 1 + * in case you have both VDD and Reset lines connected use the value 0 + * */ + #define OPTIGA_TRUSTM_SCL CYBSP_TRUSTM_I2C_SCL + #define OPTIGA_TRUSTM_SDA CYBSP_TRUSTM_I2C_SDA +#ifdef CYBSP_TRUSTM_RST + #define OPTIGA_TRUSTM_RST CYBSP_TRUSTM_RST +#endif +#ifdef CYBSP_TRUSTM_VDD + #define OPTIGA_TRUSTM_VDD CYBSP_TRUSTM_VDD +#endif + + +#ifdef __cplusplus +} +#endif + +#endif /* _OPTIGA_LIB_CONFIG_M_V3_H_*/ + +/** +* @} +*/