diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index ae0095d5..b7a9a022 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -40,15 +40,15 @@ jobs: - name: Run firmware coverage script run: | - ledger/coverage/gen-coverage - COVPCT=$(cat ledger/coverage/output/total) + firmware/coverage/gen-coverage + COVPCT=$(cat firmware/coverage/output/total) COVCOL=$(utils/coverage-color.sh $COVPCT) - echo "{ \"schemaVersion\": 1, \"label\": \"Firmware coverage\", \"message\": \"$COVPCT%\", \"color\": \"$COVCOL\" }" > ledger/coverage/output/badge.json + echo "{ \"schemaVersion\": 1, \"label\": \"Firmware coverage\", \"message\": \"$COVPCT%\", \"color\": \"$COVCOL\" }" > firmware/coverage/output/badge.json - name: "Upload firmware coverage report" run: | aws s3 sync \ - ledger/coverage/output/ \ + firmware/coverage/output/ \ s3://${{ secrets.CODECOVERAGE_S3_BUCKET }}/powhsm_5.0.x/firmware_coverage_report \ --sse aws:kms --sse-kms-key-id ${{ secrets.CODECOVERAGE_KMS_KEY_ID }} \ --no-progress --follow-symlinks --delete --only-show-errors diff --git a/.github/workflows/run-tests.yml b/.github/workflows/run-tests.yml index 3906d9a0..9171fd6f 100644 --- a/.github/workflows/run-tests.yml +++ b/.github/workflows/run-tests.yml @@ -20,28 +20,20 @@ jobs: - name: Middleware tests run: middleware/test-all - - name: Ledger tests for TCPSigner - run: ledger/test/test-all + - name: Firmware tests using TCPSigner + run: firmware/test/test-all - - name: Ledger Signer's tests - run: ledger/src/signer/test/run-all.sh + - name: Firmware HAL's unit tests + run: firmware/src/hal/test/run-all.sh - - name: Ledger UI's tests - run: ledger/src/ui/test/run-all.sh + - name: Firmware common lib unit tests + run: firmware/src/common/test/run-all.sh - - name: Ledger common lib tests - working-directory: ledger/src/common/test/ - run: | - for d in memutil ints; do - (cd "$d" && make clean test) - done + - name: Firmware PowHSM's unit tests + run: firmware/src/powhsm/test/run-all.sh - - name: Ledger TCPSigner's tests - working-directory: ledger/src/tcpsigner/test/ - run: | - for d in hmac_sha256; do - (cd "$d" && make clean test) - done + - name: Ledger UI's unit tests + run: firmware/src/ledger/ui/test/run-all.sh run-integration-tests: name: Integration tests @@ -59,7 +51,7 @@ jobs: docker/mware/build docker/packer/build middleware/build/manager-tcp - ledger/build/build-tcpsigner + firmware/build/build-tcpsigner - name: Checkout hsm-integration-test repo uses: actions/checkout@v3 @@ -74,7 +66,7 @@ jobs: mkdir hsm-integration-test/docker/manager/manager-tcp tar -xzf rsk-powhsm/middleware/bin/manager-tcp.tgz \ -C hsm-integration-test/docker/manager/manager-tcp - cp rsk-powhsm/ledger/src/tcpsigner/tcpsigner \ + cp rsk-powhsm/firmware/src/tcpsigner/tcpsigner \ hsm-integration-test/docker/tcpsigner/ - name: Run HSM integration tests diff --git a/.github/workflows/static-analysis.yml b/.github/workflows/static-analysis.yml index a4620ad2..c8ecd73f 100644 --- a/.github/workflows/static-analysis.yml +++ b/.github/workflows/static-analysis.yml @@ -20,13 +20,13 @@ jobs: id: static-analysis continue-on-error: true run: | - ledger/static-analysis/gen-static-analysis + firmware/static-analysis/gen-static-analysis - name: Upload static analysis reports uses: actions/upload-artifact@v3 with: name: static-analysis-reports - path: ledger/static-analysis/output + path: firmware/static-analysis/output - name: Report static analysis findings if: steps.static-analysis.outcome != 'success' diff --git a/.gitignore b/.gitignore index d4e2c370..1d02b745 100644 --- a/.gitignore +++ b/.gitignore @@ -20,5 +20,5 @@ .vscode/ # Ignore fuzz artifacts -ledger/fuzz/.coverage-build -ledger/fuzz/output +firmware/fuzz/.coverage-build +firmware/fuzz/output diff --git a/QUICKSTART.md b/QUICKSTART.md index e62019b8..41c5a3cd 100644 --- a/QUICKSTART.md +++ b/QUICKSTART.md @@ -17,21 +17,22 @@ Whether new to the project or just wanting to quickly get an environment up and Unless otherwise stated, only x86 platforms are supported for building this project and running the tools provided. The only exception is the [TCPSigner bundle](./utils/tcpsigner-bundle/README.md), which can be built and ran in x86 and arm64 platforms. - ## Common tasks - Run tests: ``` ~/repo> middleware/test-all # Middleware unit tests -~/repo> ledger/test/test-all # Ledger signer application tests -~/repo/ledger/src/signer/test/*> make test # Run ledger signer application unit tests -~/repo/ledger/src/common/test/*> make test # Run ledger common libraries unit tests +~/repo> firmware/test/test-all # Firmware tests +~/repo> firmware/src/ledger/ui/test/run-all.sh # Ledger UI application unit tests +~/repo> firmware/src/common/test/run-all.sh # Common code unit tests +~/repo> firmware/src/powhsm/test/run-all.sh # powHSM logic unit tests +~/repo> firmware/src/hal/test/run-all.sh # HAL unit tests ``` -- Build firmware binaries: +- Build Ledger Nano S application binaries: ``` -~/repo> ledger/build/build-signer # Build signer -~/repo> ledger/build/build-ui # Build UI +~/repo> firmware/build/build-signer # Build signer +~/repo> firmware/build/build-ui # Build UI ``` - Build middleware binaries: @@ -43,3 +44,8 @@ Unless otherwise stated, only x86 platforms are supported for building this proj ``` ~/repo> ./build-dist ``` + +- Build the TCPSigner: +``` +~/repo> firmware/build/build-tcpsigner +``` diff --git a/README.md b/README.md index 39596598..1870a016 100644 --- a/README.md +++ b/README.md @@ -28,7 +28,7 @@ Unless otherwise stated, only x86 platforms are supported for building this proj ## Concepts overview -powHSM is a solution designed specifically for the [RSK network](https://www.rsk.co/) powPeg. Its main role is to safekeep and prevent the unauthorized usage of each of the powPeg's members' private keys. powHSM is implemented as a pair of applications for the [Ledger Nano S](https://shop.ledger.com/products/ledger-nano-s), namely a UI and a Signer, and it strongly depends on the device's security features to implement the aforementioned safekeeping. +powHSM is a solution designed specifically for the [RSK network](https://www.rsk.co/) powPeg. Its main role is to safekeep and prevent the unauthorized usage of each of the powPeg's members' private keys. powHSM is currently implemented as a pair of applications for the [Ledger Nano S](https://shop.ledger.com/products/ledger-nano-s), namely a UI and a Signer, and it strongly depends on the device's security features to implement the aforementioned safekeeping. Each powPeg member runs an individual physical device on which a transparent installation and onboarding process is carried. Amongst other things, this process safely generates the root key, that never leaves the device. There is an [attestation process](./docs/attestation.md) that serves the purpose of testifying and guaranteeing this key generation process, and ultimately the fact that the key is only ever known to the device. @@ -48,7 +48,7 @@ Refer to the following documents for details on specifics: - [Blockchain bookkeeping documentation](./docs/blockchain-bookkeeping.md) - [Attestation documentation](./docs/attestation.md) - [Heartbeat documentation](./docs/heartbeat.md) -- [Ledger apps](./ledger/README.md) +- [Firmware](./firmware/README.md) - [Middleware](./middleware/README.md) - [Distribution](./dist/README.md) diff --git a/build-dist b/build-dist index dad4bf60..995eecad 100755 --- a/build-dist +++ b/build-dist @@ -65,32 +65,32 @@ computeHash() { } echo -e "\e[33mBuilding signer...\e[0m" -$ROOT_DIR/ledger/build/build-signer $CHECKPOINT $DIFFICULTY $NETWORK > /dev/null -cp $ROOT_DIR/ledger/src/signer/bin/app.hex $FIRMWARE_DIR/signer.hex -cp $ROOT_DIR/ledger/src/signer/icon.hex $FIRMWARE_DIR/signer.icon.hex +$ROOT_DIR/firmware/build/build-ledger-signer $CHECKPOINT $DIFFICULTY $NETWORK > /dev/null +cp $ROOT_DIR/firmware/src/ledger/signer/bin/app.hex $FIRMWARE_DIR/signer.hex +cp $ROOT_DIR/firmware/src/ledger/signer/icon.hex $FIRMWARE_DIR/signer.icon.hex HEX_NAME="Signer" -HEX_PATH="ledger/src/signer/bin/app.hex" +HEX_PATH="firmware/src/ledger/signer/bin/app.hex" computeHash SIGNER_HASH=$APP_HASH echo -e "\e[33mBuilding UI...\e[0m" -$ROOT_DIR/ledger/build/build-ui $SIGNER_HASH $UI_ITERATION $UI_AUTHORIZERS > /dev/null -cp $ROOT_DIR/ledger/src/ui/bin/token.hex $FIRMWARE_DIR/ui.hex -cp $ROOT_DIR/ledger/src/ui/icon.hex $FIRMWARE_DIR/ui.icon.hex +$ROOT_DIR/firmware/build/build-ledger-ui $SIGNER_HASH $UI_ITERATION $UI_AUTHORIZERS > /dev/null +cp $ROOT_DIR/firmware/src/ledger/ui/bin/token.hex $FIRMWARE_DIR/ui.hex +cp $ROOT_DIR/firmware/src/ledger/ui/icon.hex $FIRMWARE_DIR/ui.icon.hex HEX_NAME="UI" -HEX_PATH="ledger/src/ui/bin/token.hex" +HEX_PATH="firmware/src/ledger/ui/bin/token.hex" CA_FILE="rsk-ca.txt" computeHash echo -e "\e[33mSigning apps...\e[0m" -$ROOT_DIR/docker/mware/do-notty-nousb /hsm2 "python middleware/signonetime.py -a ledger/src/ui/bin/token.hex,ledger/src/signer/bin/app.hex -p $CA_FILE" > /dev/null -mv -f $ROOT_DIR/ledger/src/ui/bin/token.hex.sig $FIRMWARE_DIR/ui.hex.sig -mv -f $ROOT_DIR/ledger/src/signer/bin/app.hex.sig $FIRMWARE_DIR/signer.hex.sig +$ROOT_DIR/docker/mware/do-notty-nousb /hsm2 "python middleware/signonetime.py -a firmware/src/ledger/ui/bin/token.hex,firmware/src/ledger/signer/bin/app.hex -p $CA_FILE" > /dev/null +mv -f $ROOT_DIR/firmware/src/ledger/ui/bin/token.hex.sig $FIRMWARE_DIR/ui.hex.sig +mv -f $ROOT_DIR/firmware/src/ledger/signer/bin/app.hex.sig $FIRMWARE_DIR/signer.hex.sig mv -f $ROOT_DIR/$CA_FILE $SCRIPTS_DIR/$CA_FILE SIGNER_AUTH_FILE="signer_auth.json" echo -e "\e[33mCreating empty signer authorization for upgrades...\e[0m" -$ROOT_DIR/docker/mware/do-notty-nousb /hsm2 "python middleware/signapp.py message -a ledger/src/signer/bin/app.hex -i $UI_ITERATION -o $SIGNER_AUTH_FILE" > /dev/null +$ROOT_DIR/docker/mware/do-notty-nousb /hsm2 "python middleware/signapp.py message -a firmware/src/ledger/signer/bin/app.hex -i $UI_ITERATION -o $SIGNER_AUTH_FILE" > /dev/null mv -f $ROOT_DIR/$SIGNER_AUTH_FILE $FIRMWARE_DIR/$SIGNER_AUTH_FILE echo diff --git a/dist/README.md b/dist/README.md index c52dfb52..f970ceea 100644 --- a/dist/README.md +++ b/dist/README.md @@ -1,6 +1,6 @@ # powHSM distribution -This document describes the artifacts provided to build a distributable version of the powHSM software. This distributable version includes both ledger apps and middleware binaries, as well as scripts for both setting up and onboarding a brand new Ledger Nano S; and also for upgrading an existing Ledger Nano S with powHSM to a newer Signer version. +This document describes the artifacts provided to build a distributable version of the powHSM software for Ledger Nano S. This distributable version includes both Ledger apps and middleware binaries, as well as scripts for both setting up and onboarding a brand new Ledger Nano S; and also for upgrading an existing Ledger Nano S with powHSM to a newer Signer version. ## Prerequisites @@ -14,7 +14,7 @@ To generate a full distribution into a fresh directory, issue: ~/repo> ./build-dist ``` -where `` is the target directory (which must not exist); ``, `` and `` are the build parameters for the signer app; `` is the signer version iteration with which the UI must be built; and `` is the basename of the authorizers header file. The script will build the ledger apps (signer and UI) as well as the required middleware. Then it will output all of the necessary distribution artifacts, including the aforementioned builds, to the destination path given. +where `` is the target directory (which must not exist); ``, `` and `` are the build parameters for the signer app; `` is the signer version iteration with which the UI must be built; and `` is the basename of the authorizers header file. The script will build the Ledger apps (signer and UI) as well as the required middleware. Then it will output all of the necessary distribution artifacts, including the aforementioned builds, to the destination path given. For example, to build a distribution with checkpoint `0x00f06dcff26ec8b4d373fbd53ee770e9348d9bd6a247ad4c86e82ceb3c2130ac`, minimum cumulative difficulty of `0x7c50933098`, `testnet` network, signer iteration `43` and authorizers header file `testing`, issue: diff --git a/docs/blockchain-bookkeeping.md b/docs/blockchain-bookkeeping.md index 0c41588e..22147087 100644 --- a/docs/blockchain-bookkeeping.md +++ b/docs/blockchain-bookkeeping.md @@ -63,7 +63,7 @@ In order to update the `blockchain_state` of an *initialized* powHSM device, we #### Context and preliminaries -The following constants are assumed to be predefined (and hardcoded into the physical device's firmware): +The following constants are assumed to be predefined (and hardcoded into the device's firmware): - `MINIMUM_CUMULATIVE_DIFFICULTY`: The minimum cumulative block difficulty to consider a block sufficiently confirmed. - `MAXIMUM_BLOCK_DIFFICULTY`: The maximum allowed difficulty for any given block. diff --git a/docs/heartbeat.md b/docs/heartbeat.md index 43755c6c..8688a1d2 100644 --- a/docs/heartbeat.md +++ b/docs/heartbeat.md @@ -7,11 +7,11 @@ acknowledge the state of a running powHSM installation. ## Heartbeat and attestation -Just like the attestation process, the heartbeat feature makes use of the Ledger Nano S -endorsement mechanism to prove to the end user a given state of the device and its running -applications. Nevertheless, and as opposed to the attestation process, the heartbeat -feature itself does not include the chain of certification all the way up to the -manufacturer (Ledger itself), but rather leverages the previously generated attestation +Just like the attestation process, the heartbeat feature makes use of the Hardware +Abstraction Layer's endorsement mechanism to prove to the end user a given state of the +device and its running applications. Nevertheless, and as opposed to the attestation +process, the heartbeat feature itself does not include the chain of certification all the +way up to the manufacturer, but rather leverages the previously generated attestation process artifacts for this purpose. For more details about this and the attestation process, see [the attestation documentation](./attestation.md). diff --git a/docs/signer-authorization.md b/docs/signer-authorization.md index dc695462..8ac1e796 100644 --- a/docs/signer-authorization.md +++ b/docs/signer-authorization.md @@ -2,23 +2,23 @@ ## Abstract -This document describes the mechanisms by which the UI component authorizes versions of -the Signer component to run on a device. It is an improvement to the authorization scheme -present up to version 2.3 in that it introduces an "N of M" signatures requirement for the -authorization of any given Signer version, enhancing security and decentralization of the -powHSM solution as a whole. It is also an improvement over the "downgrade prevention" -mechanism (also present up to version 2.3), in that it removes the limit present in the -feature up to then. +This document describes the mechanisms by which the Ledger Nano S UI application +authorizes versions of the Signer application to run on an onboarded device. It is an +improvement to the authorization scheme present up to version 2.3 in that it introduces an +"N of M" signatures requirement for the authorization of any given Signer version, +enhancing security and decentralization of the powHSM solution as a whole. It is also an +improvement over the "downgrade prevention" mechanism (also present up to version 2.3), in +that it removes the limit present in the feature up to then. ## Motivation Up to version 2.3 of the UI, each new version of the Signer component is authorized using the Ledger Nano S's custom certificate authority (CCA for short), represented by a unique ECDSA pair. If lost or stolen, there would be a need to generate a new pair, reset the -existing devices and update the RSK federation in order to issue new Signer versions. +existing devices and update the RSK PowPeg in order to issue new Signer versions. Moreover, the downgrade prevention mechanism, which is based on a finite blacklist of previous signer versions, rolls over after 100 versions, which also implies the need to -reset existing devices, the CCA and update the RSK federation in order to clear said list +reset existing devices, the CCA and update the RSK PowPeg in order to clear said list and move past the 100 signer version mark. Even though at the time of writing the 100 signer version mark is very far away, it would eventually become an issue. @@ -36,7 +36,7 @@ has no real use beyond the device setup, a scenario where the user tampers with process and uses a CCA of his choosing would have no real impact on the device's security. The UI and Signer are still protected from counterfeiting by the [attestation process](./attestation.md), which is the ultimate source of truth when it comes to -determining RSK's federation members. +determining RSK's PowPeg members. ## Implementation @@ -92,7 +92,7 @@ of: ### Considerations -It is important to mention that, when distributing UI and Signer for a new federation +It is important to mention that, when distributing UI and Signer for a new PowPeg member, the UI should be built with the `authorized_signer_iteration` corresponding to the current Signer version, preventing the installation of older Signers using old authorization witnesses. diff --git a/ledger/README.md b/firmware/README.md similarity index 54% rename from ledger/README.md rename to firmware/README.md index f161382c..fbb391dc 100644 --- a/ledger/README.md +++ b/firmware/README.md @@ -1,15 +1,26 @@ -# powHSM Ledger Nano S apps +# powHSM Firmware -There are two ledger apps, both of them targeted for running on a Ledger Nano S with a 1.3.1 firmware. +## Overview and source code + +By firmware, we collectively refer to the group of applications that comprise the main powHSM logic and its different implementations (currently and namely, powHSM for Ledger Nano S and powHSM for x86 -- codenamed TCPSigner). The source code under this document's directory is located within the `src` directory, and is organised as follows: + +- `hal`: contains header and source files for the Hardware Abstraction Layer, on top of which the powHSM logic is built. Currently implemented for Ledger Nano S and x86. +- `powhsm`: contains the powHSM logic. +- `ledger`: contains the Ledger Nano S apps. +- `tcpsigner`: contains the x86 implementation of powHSM. +- `common`: contains some common headers used both in powHSM and the Ledger Nano S apps (note that the Ledger UI app does not use the HAL layer). + +## powHSM for Ledger Nano S -- UI: this is the modified 1.3.1 UI with a nonblocking behavior to allow the device to run uninterruptedly without human interaction. It is essentially the RSK version of the Ledger Nano S User Interface which can be loaded as a specific application - it can be used to personalize most generic parts of the user experience. This version also modifies the onboarding process to reflect RSK needs. Modified UIs display a warning at boot time to let you know whether you're running a certified version. This application shall be installed in Recovery mode. Find the source code under `ledger/src/ui`. +### Apps -- Signer: this is the main app that implements the signing and authorization logic for powHSM. It is intended to be used alongside the UI. Find the source code under `ledger/src/signer`. +There are two ledger apps, both of them targeted for running on a Ledger Nano S with a 1.3.1 firmware. +- UI: this is the modified 1.3.1 UI with a nonblocking behavior to allow the device to run uninterruptedly without human interaction. It is essentially the RSK version of the Ledger Nano S User Interface which can be loaded as a specific application - it can be used to personalize most generic parts of the user experience. This version also modifies the onboarding process to reflect RSK needs. Modified UIs display a warning at boot time to let you know whether you're running a certified version. This application shall be installed in Recovery mode. Find the source code under `firmware/src/ledger/ui`. -There exists also an x86 implementation of the _Signer_ component, which we call TCPSigner, that we use to smoke test, fuzz (see [the fuzzing documentation](./fuzz/README.md) for details) and debug & test new features on before we jump onto testing on a physical device. With the exception of fuzzing, this component creates a TCP/IP server that serves the purpose of enabling the otherwise USB-based interactions with a given client. +- Signer: this is the main app that implements the signing and authorization logic for powHSM. It is intended to be used alongside the UI. Find the source code under `firmware/src/powhsm`. -## Prerequisites +### Prerequisites Before starting, you must have the following installed on your system: @@ -29,24 +40,29 @@ and that should build (or rebuild in case any of the `Dockerfile`s have changed) the corresponding docker images. -## Common tasks and documentation +### Common tasks and documentation -Refer to [ledger/build/README.md](./build/README.md) for instructions on building and to [ledger/deploy/README.md](./deploy/README.md) for instructions on deploying. +Refer to [firmware/build/README.md](./build/README.md) for instructions on building and to [firmware/deploy/README.md](./deploy/README.md) for instructions on deploying. See [Ledger's documentation](http://ledger.readthedocs.io) to get a reference on developing for the platform. + +## powHSM for x86 + +Besides the Ledger implementation, there is also an x86 based implementation of the powHSM, which we call _TCPSigner_. This is used to smoke test, fuzz (see [the fuzzing documentation](./fuzz/README.md) for details) and debug & test new features on before we jump onto testing on a physical Ledger Nano S device. With the exception of fuzzing, this component creates a TCP/IP server that serves the purpose of enabling the otherwise USB-based interactions with a given client. + ## Tests There are some tests written in Python that serve the purpose of smoke testing the powHSM signer when either installed and running on a Ledger Nano S or via a fresh TCPSigner build. To run them against a TCPSigner, issue: ``` -~/repo/ledger/test> ./test-all +~/repo/firmware/test> ./test-all ``` To run them against a Ledger Nano S, issue: ``` -~/repo/ledger/test> ./test-all dongle +~/repo/firmware/test> ./test-all dongle ``` Make sure that the Ledger is unlocked and with the signer app running for the tests to run correctly. diff --git a/ledger/build/README.md b/firmware/build/README.md similarity index 51% rename from ledger/build/README.md rename to firmware/build/README.md index 11b0e38f..ed50833c 100644 --- a/ledger/build/README.md +++ b/firmware/build/README.md @@ -1,27 +1,32 @@ -# Ledger app building +# powHSM building -The Docker image for ledger builds (see [the ledger readme](../README.md)) provides a environment suitable to build Ledger Nano S applications on 1.3.1 firmware. This way new developers don't have to struggle setting up the build toolchain, and all of them will have exactly the same toolchain (no different compiler versions and related nuisances). Overall, we have an infrastructure enabling repeatable and bytewise reproducible builds. +## Building the Ledger Nano S apps -### Building signer and UI +The following instructions indicate how to build both the Signer and UI applications for +Ledger Nano S. The Docker image for ledger builds (see [the ledger readme](../README.md)) provides an environment suitable to build Ledger Nano S applications on 1.3.1 firmware. This way new developers don't have to struggle setting up the build toolchain, and all of them will have exactly the same toolchain (no different compiler versions and related nuisances). Overall, we have an infrastructure enabling repeatable and bytewise reproducible builds. This image must be built beforehand. + +### Building the UI To build the UI, just issue: ```bash -~/repo> ledger/build/build-ui +~/repo> firmware/build/build-ledger-ui ``` -where `` is the hash of the authorized signer version (only this signer can be opened in the UI once running), `` is the iteration of the authorized signer version (used for downgrade prevention) and `` is the basename of the signer authorizers header file (the file to be included for the build process should be at `~/ledger/src/ui/src/signer_authorization_signers/.h`). +where `` is the hash of the authorized signer version (only this signer can be opened in the UI once running), `` is the iteration of the authorized signer version (used for downgrade prevention) and `` is the basename of the signer authorizers header file (the file to be included for the build process should be at `~/firmware/src/ledger/ui/src/signer_authorization_signers/.h`). There is also a *debug* version of the UI, which disables disallowing PINs with no alpha characters, therefore allowing for testing UI (and Signer) builds granting access to recovery mode without the need for wiping the device each time. This debug version is intended for development purposes only, and to build it, just issue: ```bash -~/repo> ledger/build/build-ui-debug +~/repo> firmware/build/build-ledger-ui-debug ``` +### Building the Signer + To build the signer, just issue: ```bash -~/repo> ledger/build/build-signer +~/repo> firmware/build/build-ledger-signer ``` where `` is the desired blockchain checkpoint hash, `` is the minimum required difficulty (can be specified as a decimal number or as a hexadecimal - prefixed with `0x`), and `` is the desired network the build is to target (one of `mainnet`, `testnet` or `regtest`). @@ -29,19 +34,21 @@ where `` is the desired blockchain checkpoint hash, ` ledger/build/build-signer 0x00f06dcff26ec8b4d373fbd53ee770e9348d9bd6a247ad4c86e82ceb3c2130ac 0x7c50933098 testnet +~/repo> firmware/build/build-ledger-signer 0x00f06dcff26ec8b4d373fbd53ee770e9348d9bd6a247ad4c86e82ceb3c2130ac 0x7c50933098 testnet ``` -Once the build is complete, you will get the hash of the build as output, and the actual build output will be in `/ledger/src/signer/bin/app.hex` (for the signer) and `/ledger/src/ui/bin/token.hex` (for the UI). +Once the build is complete, you will get the hash of the build as output, and the actual build output will be in `/firmware/src/ledger/signer/bin/app.hex` (for the signer) and `/firmware/src/ledger/ui/bin/token.hex` (for the UI). -#### Reproducible builds +### Reproducible builds It is *very important* to mention that both the Signer and the UI builds are bitwise reproducible. That is, two independent builds of the same code will yield the exact same hex files (and thus, the same app hashes). This is of remarkable importance for the [attestation process](../../docs/attestation.md). -### Building the TCPSigner +## Building the TCPSigner + +The Docker image for the middleware (see [the middleware readme](../../middleware/README.md)) provides a suitable environment to build, run and test the TCPSigner. This image must be built beforehand. To then build the TCPSigner, just issue: ```bash -~/repo> ledger/build/build-tcpsigner +~/repo> firmware/build/build-tcpsigner ``` Happy building! diff --git a/ledger/build/build-signer b/firmware/build/build-ledger-signer similarity index 80% rename from ledger/build/build-signer rename to firmware/build/build-ledger-signer index 3097f8e8..4dc58c92 100755 --- a/ledger/build/build-signer +++ b/firmware/build/build-ledger-signer @@ -25,10 +25,10 @@ HSM_ROOT=$(realpath $BUILD_ROOT/../../) DOCKER_IMAGE=hsm:ledger source $BUILD_ROOT/../../docker/check-image -HEX_PATH="/hsm2/ledger/src/signer/bin/app.hex" +HEX_PATH="/hsm2/firmware/src/ledger/signer/bin/app.hex" HASH_CMD="cd /opt && echo '*******************' && echo 'Build successful. Signer hash:' && python -m hashapp.hashApp --hex $HEX_PATH && echo '*******************'" BUILD_CMD="make clean && make CHECKPOINT=$1 TARGET_DIFFICULTY=$2 NETWORK=$NETWORK && $HASH_CMD" DOCKER_USER="$(id -u):$(id -g)" -docker run -t --rm --user $DOCKER_USER -w /hsm2/ledger/src/signer -v ${HSM_ROOT}:/hsm2 ${DOCKER_IMAGE} /bin/bash -c "$BUILD_CMD" +docker run -t --rm --user $DOCKER_USER -w /hsm2/firmware/src/ledger/signer -v ${HSM_ROOT}:/hsm2 ${DOCKER_IMAGE} /bin/bash -c "$BUILD_CMD" diff --git a/ledger/build/build-ui b/firmware/build/build-ledger-ui similarity index 76% rename from ledger/build/build-ui rename to firmware/build/build-ledger-ui index 5783c3c9..64c5e23a 100755 --- a/ledger/build/build-ui +++ b/firmware/build/build-ledger-ui @@ -14,10 +14,10 @@ HSM_ROOT=$(realpath $BUILD_ROOT/../../) DOCKER_IMAGE=hsm:ledger source $BUILD_ROOT/../../docker/check-image -HEX_PATH="/hsm2/ledger/src/ui/bin/token.hex" +HEX_PATH="/hsm2/firmware/src/ledger/ui/bin/token.hex" HASH_CMD="cd /opt && echo '*******************' && echo 'Build successful. UI hash:' && python -m hashapp.hashApp --hex $HEX_PATH && echo '*******************'" BUILD_CMD="make clean && make SIGNER_HASH=$1 SIGNER_ITERATION=$2 SIGNERS_FILE=$3 && $HASH_CMD" DOCKER_USER="$(id -u):$(id -g)" -docker run -t --rm --user $DOCKER_USER -w /hsm2/ledger/src/ui -v ${HSM_ROOT}:/hsm2 ${DOCKER_IMAGE} /bin/bash -c "$BUILD_CMD" +docker run -t --rm --user $DOCKER_USER -w /hsm2/firmware/src/ledger/ui -v ${HSM_ROOT}:/hsm2 ${DOCKER_IMAGE} /bin/bash -c "$BUILD_CMD" diff --git a/ledger/build/build-ui-debug b/firmware/build/build-ledger-ui-debug similarity index 76% rename from ledger/build/build-ui-debug rename to firmware/build/build-ledger-ui-debug index a653c165..ec1047dc 100755 --- a/ledger/build/build-ui-debug +++ b/firmware/build/build-ledger-ui-debug @@ -14,10 +14,10 @@ HSM_ROOT=$(realpath $BUILD_ROOT/../../) DOCKER_IMAGE=hsm:ledger source $BUILD_ROOT/../../docker/check-image -HEX_PATH="/hsm2/ledger/src/ui/bin/token.hex" +HEX_PATH="/hsm2/firmware/src/ledger/ui/bin/token.hex" HASH_CMD="cd /opt && echo '*******************' && echo 'Build successful. UI hash:' && python -m hashapp.hashApp --hex $HEX_PATH && echo '*******************'" BUILD_CMD="make clean && make SIGNER_HASH=$1 SIGNER_ITERATION=$2 SIGNERS_FILE=$3 DEBUG_BUILD=1 && $HASH_CMD" DOCKER_USER="$(id -u):$(id -g)" -docker run -t --rm --user $DOCKER_USER -w /hsm2/ledger/src/ui -v ${HSM_ROOT}:/hsm2 ${DOCKER_IMAGE} /bin/bash -c "$BUILD_CMD" +docker run -t --rm --user $DOCKER_USER -w /hsm2/firmware/src/ledger/ui -v ${HSM_ROOT}:/hsm2 ${DOCKER_IMAGE} /bin/bash -c "$BUILD_CMD" diff --git a/ledger/build/build-tcpsigner b/firmware/build/build-tcpsigner similarity index 70% rename from ledger/build/build-tcpsigner rename to firmware/build/build-tcpsigner index e6538844..7efb1f91 100755 --- a/ledger/build/build-tcpsigner +++ b/firmware/build/build-tcpsigner @@ -18,4 +18,4 @@ BUILD_CMD="make clean all" DOCKER_USER="$(id -u):$(id -g)" -docker run -t --rm --user $DOCKER_USER -w /hsm2/ledger/src/tcpsigner -v ${HSM_ROOT}:/hsm2 ${DOCKER_IMAGE} /bin/bash -c "$BUILD_CMD" +docker run -t --rm --user $DOCKER_USER -w /hsm2/firmware/src/tcpsigner -v ${HSM_ROOT}:/hsm2 ${DOCKER_IMAGE} /bin/bash -c "$BUILD_CMD" diff --git a/ledger/build/build-tcpsigner-afl b/firmware/build/build-tcpsigner-afl similarity index 56% rename from ledger/build/build-tcpsigner-afl rename to firmware/build/build-tcpsigner-afl index 38e190a0..5972602d 100755 --- a/ledger/build/build-tcpsigner-afl +++ b/firmware/build/build-tcpsigner-afl @@ -13,7 +13,7 @@ HSM_ROOT=$(realpath $BUILD_ROOT/../../) COVERAGE_DIR="$1" if [[ -z "$COVERAGE_DIR" ]]; then - COVERAGE_DIR="$HSM_ROOT/ledger/fuzz/.coverage-build" + COVERAGE_DIR="$HSM_ROOT/firmware/fuzz/.coverage-build" fi if [[ -z "$2" || "$2" != "--force" ]]; then @@ -29,10 +29,13 @@ fi if [[ $REPLY =~ ^[Yy]$ ]]; then rm -rf $COVERAGE_DIR - mkdir -p $COVERAGE_DIR - cp -rf $HSM_ROOT/ledger/src/tcpsigner $COVERAGE_DIR/tcpsigner - cp -rf $HSM_ROOT/ledger/src/signer $COVERAGE_DIR/signer - cp -rf $HSM_ROOT/ledger/src/common $COVERAGE_DIR/common + mkdir -p $COVERAGE_DIR/ledger + cp -rf $HSM_ROOT/firmware/src/hal $COVERAGE_DIR/hal + cp -rf $HSM_ROOT/firmware/src/common $COVERAGE_DIR/common + cp -rf $HSM_ROOT/firmware/src/powhsm $COVERAGE_DIR/powhsm + cp -rf $HSM_ROOT/firmware/src/tcpsigner $COVERAGE_DIR/tcpsigner + # Some UI dependencies needed (symlinks within tcpsigner/src) + cp -rf $HSM_ROOT/firmware/src/ledger/ui $COVERAGE_DIR/ledger/ui else exit 1 fi @@ -42,9 +45,9 @@ source $BUILD_ROOT/../../docker/check-image DOCKER_USER="$(id -u):$(id -g)" -COVERAGE_CMD="CC=\"gcc-7 --coverage\" CXX=g++-7 make clean all" +COVERAGE_CMD="HSM_AFL=1 CC=\"gcc-7 --coverage\" CXX=g++-7 make clean all" docker run -ti --rm --user $DOCKER_USER -w /hsm2-cov/tcpsigner -v ${COVERAGE_DIR}:/hsm2-cov ${DOCKER_IMAGE} /bin/bash -c "$COVERAGE_CMD" # Good luck modifying this line. I don't recommend it. -BUILD_CMD="AFL_CC=gcc-7 AFL_CXX=g++-7 CC=afl-gcc-fast CXX=afl-g++-fast make clean all" -docker run -ti --rm --user $DOCKER_USER -w /hsm2/ledger/src/tcpsigner -v ${HSM_ROOT}:/hsm2 ${DOCKER_IMAGE} /bin/bash -c "$BUILD_CMD" +BUILD_CMD="HSM_AFL=1 AFL_CC=gcc-7 AFL_CXX=g++-7 CC=afl-gcc-fast CXX=afl-g++-fast make clean all" +docker run -ti --rm --user $DOCKER_USER -w /hsm2/firmware/src/tcpsigner -v ${HSM_ROOT}:/hsm2 ${DOCKER_IMAGE} /bin/bash -c "$BUILD_CMD" diff --git a/ledger/build/builder-term b/firmware/build/builder-term similarity index 100% rename from ledger/build/builder-term rename to firmware/build/builder-term diff --git a/ledger/build/builder-tcpsigner-afl b/firmware/build/builder-term-afl similarity index 100% rename from ledger/build/builder-tcpsigner-afl rename to firmware/build/builder-term-afl diff --git a/ledger/coverage/.gitignore b/firmware/coverage/.gitignore similarity index 100% rename from ledger/coverage/.gitignore rename to firmware/coverage/.gitignore diff --git a/ledger/coverage/coverage.mk b/firmware/coverage/coverage.mk similarity index 100% rename from ledger/coverage/coverage.mk rename to firmware/coverage/coverage.mk diff --git a/ledger/coverage/gen-coverage b/firmware/coverage/gen-coverage similarity index 54% rename from ledger/coverage/gen-coverage rename to firmware/coverage/gen-coverage index db4d2f63..c0cc2072 100755 --- a/ledger/coverage/gen-coverage +++ b/firmware/coverage/gen-coverage @@ -7,24 +7,35 @@ if [[ $1 == "exec" ]]; then # Remove any existing coverage data rm -rf $BASEDIR/coverage.info $BASEDIR/output - find $REPOROOT/ledger -name "*.gcno" -o -name "*.gcda" | xargs rm -f + find $REPOROOT/firmware -name "*.gcno" -o -name "*.gcda" | xargs rm -f - # Run firmware unit tests with coverage generation - COVERAGE=y $REPOROOT/ledger/src/signer/test/run-all.sh - COVERAGE=y $REPOROOT/ledger/src/ui/test/run-all.sh + # Run unit tests with coverage generation + COVERAGE=y $REPOROOT/firmware/src/common/test/run-all.sh + COVERAGE=y $REPOROOT/firmware/src/powhsm/test/run-all.sh + COVERAGE=y $REPOROOT/firmware/src/ledger/ui/test/run-all.sh + COVERAGE=y $REPOROOT/firmware/src/tcpsigner/test/run-all.sh # Run tcpsigner test suite - pushd $REPOROOT/ledger/src/tcpsigner > /dev/null + pushd $REPOROOT/firmware/src/tcpsigner > /dev/null COVERAGE=y make clean all ./tcpsigner --checkpoint 0xbdcb3c17c7aee714cec8ad900341bfd987b452280220dcbd6e7191f67ea4209b --difficulty 0x32 --network regtest > /dev/null & + TCPSIGNER_PID=$! popd > /dev/null - pushd $REPOROOT/ledger/test > /dev/null + pushd $REPOROOT/firmware/test > /dev/null python run.py err_code=$? popd > /dev/null + kill $TCPSIGNER_PID + + # Capture coverage data lcov --capture --directory $SRCDIR --list-full-path --output-file $BASEDIR/coverage.info + # Remove unwanted coverage info (test files, tcpsigner, x86 HAL implementation) + lcov --remove $BASEDIR/coverage.info "*/test_*.c" --output-file $BASEDIR/coverage.info + lcov --remove $BASEDIR/coverage.info "*/tcpsigner/src/*" --output-file $BASEDIR/coverage.info + lcov --remove $BASEDIR/coverage.info "*/hal/src/x86/*" --output-file $BASEDIR/coverage.info + # Generate report and summary genhtml $BASEDIR/coverage.info --output $BASEDIR/output -p $SRCDIR -t "powHSM firmware" lcov --summary $BASEDIR/coverage.info | grep lines | sed -e "s/.\+lines.\+: \([[:digit:].]\+\).\+/\1/g" > $BASEDIR/output/total mv $BASEDIR/coverage.info $BASEDIR/output diff --git a/ledger/deploy/Makefile.defines b/firmware/deploy/Makefile.defines similarity index 100% rename from ledger/deploy/Makefile.defines rename to firmware/deploy/Makefile.defines diff --git a/ledger/deploy/Makefile.rules b/firmware/deploy/Makefile.rules similarity index 100% rename from ledger/deploy/Makefile.rules rename to firmware/deploy/Makefile.rules diff --git a/ledger/deploy/README.md b/firmware/deploy/README.md similarity index 87% rename from ledger/deploy/README.md rename to firmware/deploy/README.md index c4a5456b..72386763 100644 --- a/ledger/deploy/README.md +++ b/firmware/deploy/README.md @@ -1,4 +1,4 @@ -# Ledger app deployment +# powHSM Ledger Nano S app deployment The Docker image for middleware (see [the middleware readme](../../middleware/README.md)) provides an environment suitable to deploy Ledger Nano S applications on a Ledger Nano S device. This way new developers don't have to struggle setting up the deployment toolchain. @@ -11,7 +11,7 @@ Before deploying the Signer or UI, you first have to build them. Refer to [the b Once the UI is built, you must have your device plugged in and in recovery mode. Issue: ```bash -~/repo> ledger/deploy/deploy-ui +~/repo> firmware/deploy/deploy-ledger-ui ``` and follow the prompts on the device. @@ -21,7 +21,7 @@ and follow the prompts on the device. Once the Signer is built, you must have your device plugged in and unlocked (or alternatively in recovery mode). Issue: ```bash -~/repo> ledger/deploy/deploy-signer +~/repo> firmware/deploy/deploy-ledger-signer ``` and follow the prompts on the device (only if in recovery mode or using the factory UI). diff --git a/ledger/deploy/deploy-ui b/firmware/deploy/deploy-ledger-signer similarity index 62% rename from ledger/deploy/deploy-ui rename to firmware/deploy/deploy-ledger-signer index 80aec3af..e54ba955 100755 --- a/ledger/deploy/deploy-ui +++ b/firmware/deploy/deploy-ledger-signer @@ -5,4 +5,4 @@ pushd $(dirname $0) > /dev/null DEPLOY_DIR=$(pwd) popd > /dev/null -$DEPLOY_DIR/../../docker/mware/do /hsm2/ledger/deploy ./dui +$DEPLOY_DIR/../../docker/mware/do /hsm2/firmware/deploy ./dledsig diff --git a/ledger/deploy/deploy-signer b/firmware/deploy/deploy-ledger-ui similarity index 62% rename from ledger/deploy/deploy-signer rename to firmware/deploy/deploy-ledger-ui index 70cd4325..fc5ca76e 100755 --- a/ledger/deploy/deploy-signer +++ b/firmware/deploy/deploy-ledger-ui @@ -5,4 +5,4 @@ pushd $(dirname $0) > /dev/null DEPLOY_DIR=$(pwd) popd > /dev/null -$DEPLOY_DIR/../../docker/mware/do /hsm2/ledger/deploy ./dsig +$DEPLOY_DIR/../../docker/mware/do /hsm2/firmware/deploy ./dledui diff --git a/ledger/deploy/dsig b/firmware/deploy/dledsig similarity index 85% rename from ledger/deploy/dsig rename to firmware/deploy/dledsig index 44bb371d..d0ac56b5 100755 --- a/ledger/deploy/dsig +++ b/firmware/deploy/dledsig @@ -8,7 +8,7 @@ export BOLOS_SDK=$CURDIR export TARGET_ID=`cat $CURDIR/target.id` TOPDIR=$CURDIR/../ -BUILDDIR=$TOPDIR/src/signer/ +BUILDDIR=$TOPDIR/src/ledger/signer/ pushd $BUILDDIR > /dev/null make load diff --git a/ledger/deploy/dui b/firmware/deploy/dledui similarity index 88% rename from ledger/deploy/dui rename to firmware/deploy/dledui index 33ea0c28..b766e066 100755 --- a/ledger/deploy/dui +++ b/firmware/deploy/dledui @@ -9,7 +9,7 @@ export TARGET_ID=`cat $CURDIR/target.id` export ONLY_LOAD=YES TOPDIR=$CURDIR/../ -BUILDDIR=$TOPDIR/src/ui/ +BUILDDIR=$TOPDIR/src/ledger/ui/ pushd $BUILDDIR > /dev/null make load diff --git a/ledger/deploy/target.id b/firmware/deploy/target.id similarity index 100% rename from ledger/deploy/target.id rename to firmware/deploy/target.id diff --git a/ledger/fuzz/README.md b/firmware/fuzz/README.md similarity index 74% rename from ledger/fuzz/README.md rename to firmware/fuzz/README.md index 40fcf749..788977fe 100644 --- a/ledger/fuzz/README.md +++ b/firmware/fuzz/README.md @@ -6,32 +6,33 @@ is geared towards (AFL++)[https://github.com/aflplusplus]. Most of the scripts here require a working `hsm:afl` Docker image which you can build using the `~/repo/docker/afl/build` script. -# Building a fuzzable TCPSinger +## Building a fuzzable TCPSigner You can build the TCPSigner with the AFL++ compilers with the -`~/repo/ledger/build/build-tcpsigner-afl` script, which uses the +`~/repo/firmware/build/build-tcpsigner-afl` script, which uses the `~/repo/docker/afl/Dockerfile` instructions to build a `tcpsigner` binary which you can then fuzz using the `fuzz` script in this folder. The `fuzz` script takes three optional parameters: - number of cores, defaults to the number of cores on your machine (as per reported by `nproc`) -- path to testcases, defaults to `~/repo/ledger/fuzz/testcases` -- path to output, defaults to `~/repo/ledger/fuzz/output` -- path to dictionary, defaults to `~/repo/ledger/fuzz/dict` -- path to coverage build, defaults to `~/repo/ledger/fuzz/.coverage-build` +- path to testcases, defaults to `~/repo/firmware/fuzz/testcases` +- path to output, defaults to `~/repo/firmware/fuzz/output` +- path to dictionary, defaults to `~/repo/firmware/fuzz/dict` +- path to coverage build, defaults to `~/repo/firmware/fuzz/.coverage-build` And runs a primary fuzzer, coverage and `cores - 1` secondary fuzzers. -The script uses the `env` file to read some `tcpsinger` arguments. See the +The script uses the `env` file to read some `tcpsigner` arguments. See the `Modifying run parameters` title on this doc. -# Coverage build +## Coverage build + The `coverage-build` parameter is an unfortunate technicality. Coverage needs a copy of the source files, and we must put it somewhere. The default is `./.coverage-build`. You can mostly ignore this folder. But whatever you specify as the coverage build folder **will get deleted** by the script, so be careful. -# Generating testcases +## Generating testcases You can run `./generate-testcases` to generate the testcases, make them unique and minimize them. This is recommended but takes @@ -45,7 +46,7 @@ If you want to run only some steps of the process, you can run the helper scripts `extract-inputs-from-tests`, `unique-testcases` and `min-testcases` one by one. -# Creating new entries in the dictionary +## Creating new entries in the dictionary The `./fuzz` script will read from the dictionary at `./dict/`. To easily add entries to the dictionary, you can use the helper python script `hex_to_dict.py` like this: @@ -54,6 +55,7 @@ entries to the dictionary, you can use the helper python script `hex_to_dict.py` python3 hex_to_dict.py ``` -# Modifying run parameters -The `~/repo/ledger/fuzz/env` file specifies the difficulty, network and checkpoint to be +## Modifying run parameters + +The `~/repo/firmware/fuzz/env` file specifies the difficulty, network and checkpoint to be used both by the fuzzer and the coverage script. diff --git a/ledger/fuzz/add-new-testcases b/firmware/fuzz/add-new-testcases similarity index 91% rename from ledger/fuzz/add-new-testcases rename to firmware/fuzz/add-new-testcases index 16994b4e..a32efe6f 100755 --- a/ledger/fuzz/add-new-testcases +++ b/firmware/fuzz/add-new-testcases @@ -34,12 +34,12 @@ CMD="./tcpsigner --checkpoint $CHECKPOINT --difficulty $DIFFICULTY --network $NE TESTCASES="$1" OUTPUT="$2" if [[ -z "$OUTPUT" ]]; then - OUTPUT="$HSM_ROOT/ledger/fuzz/output" + OUTPUT="$HSM_ROOT/firmware/fuzz/output" fi NEW_SEEDS_CMD="afl-fuzz -S newseeds -i /testcases -o /output $CMD" # no tmux needed as this should not take a long time... docker run -ti --rm --env AFL_BENCH_JUST_ONE=1 --env AFL_FAST_CAL=1 \ - --user $DOCKER_USER -w /hsm2/ledger/src/tcpsigner \ + --user $DOCKER_USER -w /hsm2/firmware/src/tcpsigner \ -v "$TESTCASES":/testcases -v "$OUTPUT":/output \ -v "$HSM_ROOT":/hsm2 ${DOCKER_IMAGE} /bin/bash -c "$NEW_SEEDS_CMD" diff --git a/ledger/fuzz/dict/btc_trans b/firmware/fuzz/dict/btc_trans similarity index 100% rename from ledger/fuzz/dict/btc_trans rename to firmware/fuzz/dict/btc_trans diff --git a/ledger/fuzz/dict/header b/firmware/fuzz/dict/header similarity index 100% rename from ledger/fuzz/dict/header rename to firmware/fuzz/dict/header diff --git a/ledger/fuzz/dict/receipt b/firmware/fuzz/dict/receipt similarity index 100% rename from ledger/fuzz/dict/receipt rename to firmware/fuzz/dict/receipt diff --git a/ledger/fuzz/env b/firmware/fuzz/env similarity index 100% rename from ledger/fuzz/env rename to firmware/fuzz/env diff --git a/ledger/fuzz/extract-inputs-from-tests b/firmware/fuzz/extract-inputs-from-tests similarity index 55% rename from ledger/fuzz/extract-inputs-from-tests rename to firmware/fuzz/extract-inputs-from-tests index a9ce276a..dec37c4b 100755 --- a/ledger/fuzz/extract-inputs-from-tests +++ b/firmware/fuzz/extract-inputs-from-tests @@ -24,19 +24,19 @@ for ((N=1; N<=$RES_AMOUNT; N++)); do echo "Running loop $N / $RES_AMOUNT" REPLICA="replica-$N.out" - rm ../../ledger/src/tcpsigner/replica-$N.out 2> /dev/null || true + rm $FUZZ_ROOT/../src/tcpsigner/replica-$N.out 2> /dev/null || true - $TEST_ROOT/../../docker/mware/do-notty-nousb /hsm2/ledger/src/tcpsigner ./tcpsigner -r "$REPLICA" --checkpoint 0xbdcb3c17c7aee714cec8ad900341bfd987b452280220dcbd6e7191f67ea4209b --difficulty 0x32 --network regtest > /dev/null & + $FUZZ_ROOT/../../docker/mware/do-notty-nousb /hsm2/firmware/src/tcpsigner ./tcpsigner -r "$REPLICA" --checkpoint 0xbdcb3c17c7aee714cec8ad900341bfd987b452280220dcbd6e7191f67ea4209b --difficulty 0x32 --network regtest > /dev/null & sleep 1 - CMD="docker exec -t -w /hsm2/ledger/test hsm-mware-notty python run.py --filter" + CMD="docker exec -t -w /hsm2/firmware/test hsm-mware-notty python run.py --filter" echo "$RESOURCES" | head -n "$N" | xargs -n 1 $CMD - docker cp hsm-mware-notty:/hsm2/ledger/src/tcpsigner/replica-$N.out $TESTCASES - rm ../../ledger/src/tcpsigner/replica-$N.out 2> /dev/null || true + docker cp hsm-mware-notty:/hsm2/firmware/src/tcpsigner/replica-$N.out $TESTCASES + rm $FUZZ_ROOT/../src/tcpsigner/replica-$N.out 2> /dev/null || true # Kill (and remove) container docker kill hsm-mware-notty > /dev/null - echo "Input replica in /hsm2/ledger/src/tcpsinger/$REPLICA" + echo "Input replica in /hsm2/firmware/src/tcpsigner/$REPLICA" done diff --git a/ledger/fuzz/fuzz b/firmware/fuzz/fuzz similarity index 92% rename from ledger/fuzz/fuzz rename to firmware/fuzz/fuzz index f61fcff1..7029e113 100755 --- a/ledger/fuzz/fuzz +++ b/firmware/fuzz/fuzz @@ -53,22 +53,22 @@ fi TESTCASES="$2" if [[ -z "$TESTCASES" ]]; then - TESTCASES="$HSM_ROOT/ledger/fuzz/testcases" + TESTCASES="$HSM_ROOT/firmware/fuzz/testcases" fi OUTPUT="$3" if [[ -z "$OUTPUT" ]]; then - OUTPUT="$HSM_ROOT/ledger/fuzz/output" + OUTPUT="$HSM_ROOT/firmware/fuzz/output" fi DICT="$4" if [[ -z "$DICT" ]]; then - DICT="$HSM_ROOT/ledger/fuzz/dict" + DICT="$HSM_ROOT/firmware/fuzz/dict" fi COVERAGE_DIR="$5" if [[ -z "$COVERAGE_DIR" ]]; then - COVERAGE_DIR="$HSM_ROOT/ledger/fuzz/.coverage-build" + COVERAGE_DIR="$HSM_ROOT/firmware/fuzz/.coverage-build" fi if [[ -d "$OUTPUT/cov" ]]; then @@ -92,7 +92,7 @@ sleep 0.5 # give some time to coverage to start... MAIN_FUZZ_CMD="afl-fuzz -x /dict -D -M main -i /testcases -o /output $CMD" tmux new -d -s main \ docker run -ti --rm --env AFL_AUTORESUME=1 --env AFL_TESTCACHE_SIZE=500 \ - --user $DOCKER_USER -w /hsm2/ledger/src/tcpsigner \ + --user $DOCKER_USER -w /hsm2/firmware/src/tcpsigner \ -v "$DICT":/dict -v "$TESTCASES":/testcases -v "$OUTPUT":/output \ -v "$HSM_ROOT":/hsm2 ${DOCKER_IMAGE} /bin/bash -c "$MAIN_FUZZ_CMD" sleep 0.1 # starting too many instances of AFL too quickly seems to mess things up @@ -122,7 +122,7 @@ while [[ $CORE -lt $CORES ]]; do tmux new -d -s secondary-$CORE \ docker run -ti --rm \ --env AFL_AUTORESUME=1 --env AFL_TESTCACHE_SIZE=500 \ - --user $DOCKER_USER -w /hsm2/ledger/src/tcpsigner \ + --user $DOCKER_USER -w /hsm2/firmware/src/tcpsigner \ -v "$DICT":/dict -v "$TESTCASES":/testcases -v "$OUTPUT":/output \ -v "$HSM_ROOT":/hsm2 ${DOCKER_IMAGE} /bin/bash -c "$SECONDARY_FUZZ_CMD" CORE=$(( CORE+1 )) diff --git a/ledger/fuzz/generate-testcases b/firmware/fuzz/generate-testcases similarity index 100% rename from ledger/fuzz/generate-testcases rename to firmware/fuzz/generate-testcases diff --git a/ledger/fuzz/hex_to_dict.py b/firmware/fuzz/hex_to_dict.py similarity index 100% rename from ledger/fuzz/hex_to_dict.py rename to firmware/fuzz/hex_to_dict.py diff --git a/ledger/fuzz/min-testcases b/firmware/fuzz/min-testcases similarity index 67% rename from ledger/fuzz/min-testcases rename to firmware/fuzz/min-testcases index e04bbef1..a74b37cd 100755 --- a/ledger/fuzz/min-testcases +++ b/firmware/fuzz/min-testcases @@ -18,16 +18,16 @@ DOCKER_USER="$(id -u):$(id -g)" TESTCASESUNIQUE="$1" if [[ -z "$TESTCASESUNIQUE" ]]; then - TESTCASESUNIQUE="$HSM_ROOT/ledger/fuzz/testcases-unique" + TESTCASESUNIQUE="$HSM_ROOT/firmware/fuzz/testcases-unique" fi TESTCASES="$2" if [[ -z "$TESTCASES" ]]; then - TESTCASES="$HSM_ROOT/ledger/fuzz/testcases" + TESTCASES="$HSM_ROOT/firmware/fuzz/testcases" fi cd $TESTCASESUNIQUE; for i in *; do CMD="afl-tmin -i /testcases-unique/$i -o /testcases/$i -- ./tcpsigner -i @@" - docker run -t --rm --user $DOCKER_USER -w /hsm2/ledger/src/tcpsigner -v "$HSM_ROOT":/hsm2 -v "$TESTCASESUNIQUE":/testcases-unique -v "$TESTCASES":/testcases ${DOCKER_IMAGE} /bin/bash -c "$CMD" + docker run -t --rm --user $DOCKER_USER -w /hsm2/firmware/src/tcpsigner -v "$HSM_ROOT":/hsm2 -v "$TESTCASESUNIQUE":/testcases-unique -v "$TESTCASES":/testcases ${DOCKER_IMAGE} /bin/bash -c "$CMD" done diff --git a/ledger/fuzz/testcases-raw/replica-1.out b/firmware/fuzz/testcases-raw/replica-1.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-1.out rename to firmware/fuzz/testcases-raw/replica-1.out diff --git a/ledger/fuzz/testcases-raw/replica-10.out b/firmware/fuzz/testcases-raw/replica-10.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-10.out rename to firmware/fuzz/testcases-raw/replica-10.out diff --git a/ledger/fuzz/testcases-raw/replica-11.out b/firmware/fuzz/testcases-raw/replica-11.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-11.out rename to firmware/fuzz/testcases-raw/replica-11.out diff --git a/ledger/fuzz/testcases-raw/replica-12.out b/firmware/fuzz/testcases-raw/replica-12.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-12.out rename to firmware/fuzz/testcases-raw/replica-12.out diff --git a/ledger/fuzz/testcases-raw/replica-13.out b/firmware/fuzz/testcases-raw/replica-13.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-13.out rename to firmware/fuzz/testcases-raw/replica-13.out diff --git a/ledger/fuzz/testcases-raw/replica-14.out b/firmware/fuzz/testcases-raw/replica-14.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-14.out rename to firmware/fuzz/testcases-raw/replica-14.out diff --git a/ledger/fuzz/testcases-raw/replica-15.out b/firmware/fuzz/testcases-raw/replica-15.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-15.out rename to firmware/fuzz/testcases-raw/replica-15.out diff --git a/ledger/fuzz/testcases-raw/replica-16.out b/firmware/fuzz/testcases-raw/replica-16.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-16.out rename to firmware/fuzz/testcases-raw/replica-16.out diff --git a/ledger/fuzz/testcases-raw/replica-17.out b/firmware/fuzz/testcases-raw/replica-17.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-17.out rename to firmware/fuzz/testcases-raw/replica-17.out diff --git a/ledger/fuzz/testcases-raw/replica-18.out b/firmware/fuzz/testcases-raw/replica-18.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-18.out rename to firmware/fuzz/testcases-raw/replica-18.out diff --git a/ledger/fuzz/testcases-raw/replica-19.out b/firmware/fuzz/testcases-raw/replica-19.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-19.out rename to firmware/fuzz/testcases-raw/replica-19.out diff --git a/ledger/fuzz/testcases-raw/replica-2.out b/firmware/fuzz/testcases-raw/replica-2.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-2.out rename to firmware/fuzz/testcases-raw/replica-2.out diff --git a/ledger/fuzz/testcases-raw/replica-20.out b/firmware/fuzz/testcases-raw/replica-20.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-20.out rename to firmware/fuzz/testcases-raw/replica-20.out diff --git a/ledger/fuzz/testcases-raw/replica-21.out b/firmware/fuzz/testcases-raw/replica-21.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-21.out rename to firmware/fuzz/testcases-raw/replica-21.out diff --git a/ledger/fuzz/testcases-raw/replica-22.out b/firmware/fuzz/testcases-raw/replica-22.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-22.out rename to firmware/fuzz/testcases-raw/replica-22.out diff --git a/ledger/fuzz/testcases-raw/replica-23.out b/firmware/fuzz/testcases-raw/replica-23.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-23.out rename to firmware/fuzz/testcases-raw/replica-23.out diff --git a/ledger/fuzz/testcases-raw/replica-24.out b/firmware/fuzz/testcases-raw/replica-24.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-24.out rename to firmware/fuzz/testcases-raw/replica-24.out diff --git a/ledger/fuzz/testcases-raw/replica-25.out b/firmware/fuzz/testcases-raw/replica-25.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-25.out rename to firmware/fuzz/testcases-raw/replica-25.out diff --git a/ledger/fuzz/testcases-raw/replica-26.out b/firmware/fuzz/testcases-raw/replica-26.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-26.out rename to firmware/fuzz/testcases-raw/replica-26.out diff --git a/ledger/fuzz/testcases-raw/replica-27.out b/firmware/fuzz/testcases-raw/replica-27.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-27.out rename to firmware/fuzz/testcases-raw/replica-27.out diff --git a/ledger/fuzz/testcases-raw/replica-28.out b/firmware/fuzz/testcases-raw/replica-28.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-28.out rename to firmware/fuzz/testcases-raw/replica-28.out diff --git a/ledger/fuzz/testcases-raw/replica-29.out b/firmware/fuzz/testcases-raw/replica-29.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-29.out rename to firmware/fuzz/testcases-raw/replica-29.out diff --git a/ledger/fuzz/testcases-raw/replica-3.out b/firmware/fuzz/testcases-raw/replica-3.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-3.out rename to firmware/fuzz/testcases-raw/replica-3.out diff --git a/ledger/fuzz/testcases-raw/replica-30.out b/firmware/fuzz/testcases-raw/replica-30.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-30.out rename to firmware/fuzz/testcases-raw/replica-30.out diff --git a/ledger/fuzz/testcases-raw/replica-31.out b/firmware/fuzz/testcases-raw/replica-31.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-31.out rename to firmware/fuzz/testcases-raw/replica-31.out diff --git a/ledger/fuzz/testcases-raw/replica-32.out b/firmware/fuzz/testcases-raw/replica-32.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-32.out rename to firmware/fuzz/testcases-raw/replica-32.out diff --git a/ledger/fuzz/testcases-raw/replica-33.out b/firmware/fuzz/testcases-raw/replica-33.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-33.out rename to firmware/fuzz/testcases-raw/replica-33.out diff --git a/ledger/fuzz/testcases-raw/replica-34.out b/firmware/fuzz/testcases-raw/replica-34.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-34.out rename to firmware/fuzz/testcases-raw/replica-34.out diff --git a/ledger/fuzz/testcases-raw/replica-35.out b/firmware/fuzz/testcases-raw/replica-35.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-35.out rename to firmware/fuzz/testcases-raw/replica-35.out diff --git a/ledger/fuzz/testcases-raw/replica-36.out b/firmware/fuzz/testcases-raw/replica-36.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-36.out rename to firmware/fuzz/testcases-raw/replica-36.out diff --git a/ledger/fuzz/testcases-raw/replica-4.out b/firmware/fuzz/testcases-raw/replica-4.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-4.out rename to firmware/fuzz/testcases-raw/replica-4.out diff --git a/ledger/fuzz/testcases-raw/replica-5.out b/firmware/fuzz/testcases-raw/replica-5.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-5.out rename to firmware/fuzz/testcases-raw/replica-5.out diff --git a/ledger/fuzz/testcases-raw/replica-6.out b/firmware/fuzz/testcases-raw/replica-6.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-6.out rename to firmware/fuzz/testcases-raw/replica-6.out diff --git a/ledger/fuzz/testcases-raw/replica-7.out b/firmware/fuzz/testcases-raw/replica-7.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-7.out rename to firmware/fuzz/testcases-raw/replica-7.out diff --git a/ledger/fuzz/testcases-raw/replica-8.out b/firmware/fuzz/testcases-raw/replica-8.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-8.out rename to firmware/fuzz/testcases-raw/replica-8.out diff --git a/ledger/fuzz/testcases-raw/replica-9.out b/firmware/fuzz/testcases-raw/replica-9.out similarity index 100% rename from ledger/fuzz/testcases-raw/replica-9.out rename to firmware/fuzz/testcases-raw/replica-9.out diff --git a/ledger/fuzz/testcases-unique/replica-1.out b/firmware/fuzz/testcases-unique/replica-1.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-1.out rename to firmware/fuzz/testcases-unique/replica-1.out diff --git a/ledger/fuzz/testcases-unique/replica-11.out b/firmware/fuzz/testcases-unique/replica-11.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-11.out rename to firmware/fuzz/testcases-unique/replica-11.out diff --git a/ledger/fuzz/testcases-unique/replica-12.out b/firmware/fuzz/testcases-unique/replica-12.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-12.out rename to firmware/fuzz/testcases-unique/replica-12.out diff --git a/ledger/fuzz/testcases-unique/replica-13.out b/firmware/fuzz/testcases-unique/replica-13.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-13.out rename to firmware/fuzz/testcases-unique/replica-13.out diff --git a/ledger/fuzz/testcases-unique/replica-14.out b/firmware/fuzz/testcases-unique/replica-14.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-14.out rename to firmware/fuzz/testcases-unique/replica-14.out diff --git a/ledger/fuzz/testcases-unique/replica-15.out b/firmware/fuzz/testcases-unique/replica-15.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-15.out rename to firmware/fuzz/testcases-unique/replica-15.out diff --git a/ledger/fuzz/testcases-unique/replica-16.out b/firmware/fuzz/testcases-unique/replica-16.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-16.out rename to firmware/fuzz/testcases-unique/replica-16.out diff --git a/ledger/fuzz/testcases-unique/replica-17.out b/firmware/fuzz/testcases-unique/replica-17.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-17.out rename to firmware/fuzz/testcases-unique/replica-17.out diff --git a/ledger/fuzz/testcases-unique/replica-18.out b/firmware/fuzz/testcases-unique/replica-18.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-18.out rename to firmware/fuzz/testcases-unique/replica-18.out diff --git a/ledger/fuzz/testcases-unique/replica-19.out b/firmware/fuzz/testcases-unique/replica-19.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-19.out rename to firmware/fuzz/testcases-unique/replica-19.out diff --git a/ledger/fuzz/testcases-unique/replica-2.out b/firmware/fuzz/testcases-unique/replica-2.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-2.out rename to firmware/fuzz/testcases-unique/replica-2.out diff --git a/ledger/fuzz/testcases-unique/replica-20.out b/firmware/fuzz/testcases-unique/replica-20.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-20.out rename to firmware/fuzz/testcases-unique/replica-20.out diff --git a/ledger/fuzz/testcases-unique/replica-21.out b/firmware/fuzz/testcases-unique/replica-21.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-21.out rename to firmware/fuzz/testcases-unique/replica-21.out diff --git a/ledger/fuzz/testcases-unique/replica-22.out b/firmware/fuzz/testcases-unique/replica-22.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-22.out rename to firmware/fuzz/testcases-unique/replica-22.out diff --git a/ledger/fuzz/testcases-unique/replica-23.out b/firmware/fuzz/testcases-unique/replica-23.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-23.out rename to firmware/fuzz/testcases-unique/replica-23.out diff --git a/ledger/fuzz/testcases-unique/replica-25.out b/firmware/fuzz/testcases-unique/replica-25.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-25.out rename to firmware/fuzz/testcases-unique/replica-25.out diff --git a/ledger/fuzz/testcases-unique/replica-28.out b/firmware/fuzz/testcases-unique/replica-28.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-28.out rename to firmware/fuzz/testcases-unique/replica-28.out diff --git a/ledger/fuzz/testcases-unique/replica-29.out b/firmware/fuzz/testcases-unique/replica-29.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-29.out rename to firmware/fuzz/testcases-unique/replica-29.out diff --git a/ledger/fuzz/testcases-unique/replica-3.out b/firmware/fuzz/testcases-unique/replica-3.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-3.out rename to firmware/fuzz/testcases-unique/replica-3.out diff --git a/ledger/fuzz/testcases-unique/replica-30.out b/firmware/fuzz/testcases-unique/replica-30.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-30.out rename to firmware/fuzz/testcases-unique/replica-30.out diff --git a/ledger/fuzz/testcases-unique/replica-31.out b/firmware/fuzz/testcases-unique/replica-31.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-31.out rename to firmware/fuzz/testcases-unique/replica-31.out diff --git a/ledger/fuzz/testcases-unique/replica-32.out b/firmware/fuzz/testcases-unique/replica-32.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-32.out rename to firmware/fuzz/testcases-unique/replica-32.out diff --git a/ledger/fuzz/testcases-unique/replica-33.out b/firmware/fuzz/testcases-unique/replica-33.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-33.out rename to firmware/fuzz/testcases-unique/replica-33.out diff --git a/ledger/fuzz/testcases-unique/replica-34.out b/firmware/fuzz/testcases-unique/replica-34.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-34.out rename to firmware/fuzz/testcases-unique/replica-34.out diff --git a/ledger/fuzz/testcases-unique/replica-35.out b/firmware/fuzz/testcases-unique/replica-35.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-35.out rename to firmware/fuzz/testcases-unique/replica-35.out diff --git a/ledger/fuzz/testcases-unique/replica-4.out b/firmware/fuzz/testcases-unique/replica-4.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-4.out rename to firmware/fuzz/testcases-unique/replica-4.out diff --git a/ledger/fuzz/testcases-unique/replica-5.out b/firmware/fuzz/testcases-unique/replica-5.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-5.out rename to firmware/fuzz/testcases-unique/replica-5.out diff --git a/ledger/fuzz/testcases-unique/replica-6.out b/firmware/fuzz/testcases-unique/replica-6.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-6.out rename to firmware/fuzz/testcases-unique/replica-6.out diff --git a/ledger/fuzz/testcases-unique/replica-7.out b/firmware/fuzz/testcases-unique/replica-7.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-7.out rename to firmware/fuzz/testcases-unique/replica-7.out diff --git a/ledger/fuzz/testcases-unique/replica-8.out b/firmware/fuzz/testcases-unique/replica-8.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-8.out rename to firmware/fuzz/testcases-unique/replica-8.out diff --git a/ledger/fuzz/testcases-unique/replica-9.out b/firmware/fuzz/testcases-unique/replica-9.out similarity index 100% rename from ledger/fuzz/testcases-unique/replica-9.out rename to firmware/fuzz/testcases-unique/replica-9.out diff --git a/ledger/fuzz/testcases/replica-1.out b/firmware/fuzz/testcases/replica-1.out similarity index 100% rename from ledger/fuzz/testcases/replica-1.out rename to firmware/fuzz/testcases/replica-1.out diff --git a/ledger/fuzz/testcases/replica-2.out b/firmware/fuzz/testcases/replica-2.out similarity index 100% rename from ledger/fuzz/testcases/replica-2.out rename to firmware/fuzz/testcases/replica-2.out diff --git a/ledger/fuzz/testcases/replica-3.out b/firmware/fuzz/testcases/replica-3.out similarity index 100% rename from ledger/fuzz/testcases/replica-3.out rename to firmware/fuzz/testcases/replica-3.out diff --git a/ledger/fuzz/unique-testcases b/firmware/fuzz/unique-testcases similarity index 65% rename from ledger/fuzz/unique-testcases rename to firmware/fuzz/unique-testcases index 7ae17fbe..6a673228 100755 --- a/ledger/fuzz/unique-testcases +++ b/firmware/fuzz/unique-testcases @@ -19,13 +19,13 @@ CMD="afl-cmin -i /testcases-raw -o /testcases-unique ./tcpsigner -i @@" TESTCASES="$1" if [[ -z "$TESTCASES" ]]; then - TESTCASES="$HSM_ROOT/ledger/fuzz/testcases-raw" + TESTCASES="$HSM_ROOT/firmware/fuzz/testcases-raw" fi TESTCASESUNIQ="$2" if [[ -z "$TESTCASESUNIQ" ]]; then - TESTCASESUNIQ="$HSM_ROOT/ledger/fuzz/testcases-unique" + TESTCASESUNIQ="$HSM_ROOT/firmware/fuzz/testcases-unique" fi -docker run -ti --rm --user $DOCKER_USER -w /hsm2/ledger/src/tcpsigner -v ${HSM_ROOT}:/hsm2 -v "$TESTCASES":/testcases-raw -v "$TESTCASESUNIQ":/testcases-unique ${DOCKER_IMAGE} /bin/bash -c "$CMD" +docker run -ti --rm --user $DOCKER_USER -w /hsm2/firmware/src/tcpsigner -v ${HSM_ROOT}:/hsm2 -v "$TESTCASES":/testcases-raw -v "$TESTCASESUNIQ":/testcases-unique ${DOCKER_IMAGE} /bin/bash -c "$CMD" diff --git a/firmware/src/.gitignore b/firmware/src/.gitignore new file mode 100644 index 00000000..51faf1b8 --- /dev/null +++ b/firmware/src/.gitignore @@ -0,0 +1,25 @@ +# Build artifacts +**/bin +**/debug +**/dep +**/obj +**/objs +**/static-analysis +**/test/**/*.o +**/test/**/*.out + +# UI glyphs +ledger/ui/src/glyphs.c +ledger/ui/src/glyphs.h + +# Icons hex +ledger/signer/icon.hex +ledger/ui/icon.hex + +# TCPSigner +tcpsigner/tcpsigner +tcpsigner/**/*.json + +# Code coverage artifacts +**/*.gcda +**/*.gcno diff --git a/ledger/src/common/src/apdu.h b/firmware/src/common/src/apdu.h similarity index 70% rename from ledger/src/common/src/apdu.h rename to firmware/src/common/src/apdu.h index 80c7e15b..b2b42040 100644 --- a/ledger/src/common/src/apdu.h +++ b/firmware/src/common/src/apdu.h @@ -29,6 +29,8 @@ #ifndef __APDU_H #define __APDU_H +#include "common_requirements.h" + // CLA for the entire protocol #define CLA 0x80 @@ -40,25 +42,29 @@ #define CLAPOS 0 // APDU buffer getters -#define APDU_CLA() (G_io_apdu_buffer[CLAPOS]) -#define APDU_CMD() (G_io_apdu_buffer[CMDPOS]) -#define APDU_OP() (G_io_apdu_buffer[OP]) -#define APDU_TXLEN() (G_io_apdu_buffer[TXLEN]) -#define APDU_AT(pos) (G_io_apdu_buffer[pos]) +#define APDU_CLA() (communication_get_msg_buffer()[CLAPOS]) +#define APDU_CMD() (communication_get_msg_buffer()[CMDPOS]) +#define APDU_OP() (communication_get_msg_buffer()[OP]) +#define APDU_TXLEN() (communication_get_msg_buffer()[TXLEN]) +#define APDU_AT(pos) (communication_get_msg_buffer()[pos]) // APDU buffer setters -#define SET_APDU_CLA() (G_io_apdu_buffer[CLAPOS] = CLA) -#define SET_APDU_CMD(cmd) (G_io_apdu_buffer[CMDPOS] = (cmd)) -#define SET_APDU_OP(op) (G_io_apdu_buffer[OP] = (op)) -#define SET_APDU_TXLEN(len) (G_io_apdu_buffer[TXLEN] = (len)) -#define SET_APDU_AT(pos, value) (G_io_apdu_buffer[pos] = (value)) +#define SET_APDU_CLA() (communication_get_msg_buffer()[CLAPOS] = CLA) +#define SET_APDU_CMD(cmd) (communication_get_msg_buffer()[CMDPOS] = (cmd)) +#define SET_APDU_OP(op) (communication_get_msg_buffer()[OP] = (op)) +#define SET_APDU_TXLEN(len) (communication_get_msg_buffer()[TXLEN] = (len)) +#define SET_APDU_AT(pos, value) (communication_get_msg_buffer()[pos] = (value)) // Get pointer to payload within APDU buffer. // No args, so it can be treated like an array pointer. -#define APDU_DATA_PTR (G_io_apdu_buffer + DATA) +#define APDU_DATA_PTR (communication_get_msg_buffer() + DATA) +// Total size of APDU +#define APDU_TOTAL_SIZE (communication_get_msg_buffer_size()) +// Size of APDU elements +#define APDU_ELEMENT_SIZE (sizeof(communication_get_msg_buffer()[0])) // Total size of APDU data part -#define APDU_TOTAL_DATA_SIZE (sizeof(G_io_apdu_buffer) - DATA) +#define APDU_TOTAL_DATA_SIZE (communication_get_msg_buffer_size() - DATA) // Total size of APDU data part for outputting // (need to leave space for result code) #define APDU_RESULT_CODE_SIZE 2 diff --git a/ledger/src/common/src/compiletime.h b/firmware/src/common/src/compiletime.h similarity index 100% rename from ledger/src/common/src/compiletime.h rename to firmware/src/common/src/compiletime.h diff --git a/ledger/src/common/src/ints.h b/firmware/src/common/src/ints.h similarity index 100% rename from ledger/src/common/src/ints.h rename to firmware/src/common/src/ints.h diff --git a/ledger/src/common/src/memutil.h b/firmware/src/common/src/memutil.h similarity index 97% rename from ledger/src/common/src/memutil.h rename to firmware/src/common/src/memutil.h index e480d730..890ff97c 100644 --- a/ledger/src/common/src/memutil.h +++ b/firmware/src/common/src/memutil.h @@ -26,9 +26,8 @@ #define __MEMUTIL_H #include -#include -#include "os.h" +#include "common_requirements.h" #define MEMMOVE_ZERO_OFFSET 0 @@ -54,7 +53,7 @@ __attribute__((always_inline)) static inline int safe_memmove( return false; } else { - os_memmove( + platform_memmove( (unsigned char *)dst + dst_off, (unsigned char *)src + src_off, n); return true; } diff --git a/ledger/src/common/src/modes.h b/firmware/src/common/src/modes.h similarity index 100% rename from ledger/src/common/src/modes.h rename to firmware/src/common/src/modes.h diff --git a/ledger/src/common/src/runtime.h b/firmware/src/common/src/runtime.h similarity index 80% rename from ledger/src/common/src/runtime.h rename to firmware/src/common/src/runtime.h index 45f6eeb6..0746bfba 100644 --- a/ledger/src/common/src/runtime.h +++ b/firmware/src/common/src/runtime.h @@ -25,10 +25,27 @@ #ifndef __RUNTIME_H #define __RUNTIME_H -#ifdef HSM_SIMULATOR +#if defined(HSM_PLATFORM_LEDGER) + +// We can't include any HAL headers here because +// the Ledger UI does not know anything about it +#include "os.h" + +#define NON_VOLATILE const + +#elif defined(HSM_PLATFORM_X86) + +#include "hal/platform.h" +#include "hal/exceptions.h" + +#include "ui_deps.h" + +#define PIC(x) (x) + #define NON_VOLATILE + #else -#define NON_VOLATILE const +#error "HSM Platform undefined" #endif #endif // __RUNTIME_H \ No newline at end of file diff --git a/firmware/src/common/test/common.mk b/firmware/src/common/test/common.mk new file mode 100644 index 00000000..3a69b0e5 --- /dev/null +++ b/firmware/src/common/test/common.mk @@ -0,0 +1,28 @@ +# The MIT License (MIT) +# +# Copyright (c) 2021 RSK Labs Ltd +# +# 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. + +SRCDIR = ../../src +CFLAGS = -iquote $(SRCDIR) -iquote . + +include ../../../../coverage/coverage.mk + +CFLAGS += $(COVFLAGS) diff --git a/ledger/src/common/test/ints/Makefile b/firmware/src/common/test/ints/Makefile similarity index 93% rename from ledger/src/common/test/ints/Makefile rename to firmware/src/common/test/ints/Makefile index 0a1f031b..b5deed2f 100644 --- a/ledger/src/common/test/ints/Makefile +++ b/firmware/src/common/test/ints/Makefile @@ -20,8 +20,7 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -SRCDIR = ../../src -CFLAGS = -I $(SRCDIR) -I ./ +include ../common.mk PROG = test.out OBJS = test_ints.o @@ -29,14 +28,14 @@ OBJS = test_ints.o all: $(PROG) $(PROG): $(OBJS) - $(CC) -o $@ $^ + $(CC) $(COVFLAGS) -o $@ $^ test_ints.o: test_ints.c $(SRCDIR)/ints.h .PHONY: clean test clean: - rm -f $(PROG) ./*.o + rm -f $(PROG) ./*.o $(COVFILES) test: all ./$(PROG) diff --git a/ledger/src/common/test/ints/test_ints.c b/firmware/src/common/test/ints/test_ints.c similarity index 100% rename from ledger/src/common/test/ints/test_ints.c rename to firmware/src/common/test/ints/test_ints.c diff --git a/ledger/src/common/test/memutil/Makefile b/firmware/src/common/test/memutil/Makefile similarity index 89% rename from ledger/src/common/test/memutil/Makefile rename to firmware/src/common/test/memutil/Makefile index ae413179..dce34187 100644 --- a/ledger/src/common/test/memutil/Makefile +++ b/firmware/src/common/test/memutil/Makefile @@ -20,8 +20,7 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -SRCDIR = ../../src -CFLAGS = -I $(SRCDIR) -I ./ +include ../common.mk PROG = test.out OBJS = test_memutil.o @@ -29,14 +28,14 @@ OBJS = test_memutil.o all: $(PROG) $(PROG): $(OBJS) - $(CC) -o $@ $^ + $(CC) $(COVFLAGS) -o $@ $^ -test_memutil.o: test_memutil.c $(SRCDIR)/memutil.h os.h +test_memutil.o: test_memutil.c $(SRCDIR)/memutil.h .PHONY: clean test clean: - rm -f $(PROG) ./*.o + rm -f $(PROG) ./*.o $(COVFILES) test: all ./$(PROG) diff --git a/ledger/src/tcpsigner/os_io_seproxyhal.h b/firmware/src/common/test/memutil/common_requirements.h similarity index 87% rename from ledger/src/tcpsigner/os_io_seproxyhal.h rename to firmware/src/common/test/memutil/common_requirements.h index cd6b53fc..f3a69730 100644 --- a/ledger/src/tcpsigner/os_io_seproxyhal.h +++ b/firmware/src/common/test/memutil/common_requirements.h @@ -22,9 +22,9 @@ * IN THE SOFTWARE. */ -#ifndef __SIMULATOR_OS_IO_SEPROXYHAL_H -#define __SIMULATOR_OS_IO_SEPROXYHAL_H +#ifndef __COMMON_REQUIREMENTS_H +#define __COMMON_REQUIREMENTS_H -void os_sched_exit(unsigned int exit_code); +void platform_memmove(void *dst, const void *src, unsigned int length); -#endif // __SIMULATOR_OS_IO_SEPROXYHAL_H +#endif // __COMMON_REQUIREMENTS_H diff --git a/ledger/src/common/test/memutil/test_memutil.c b/firmware/src/common/test/memutil/test_memutil.c similarity index 94% rename from ledger/src/common/test/memutil/test_memutil.c rename to firmware/src/common/test/memutil/test_memutil.c index 5c0212fa..1ef3bdad 100644 --- a/ledger/src/common/test/memutil/test_memutil.c +++ b/firmware/src/common/test/memutil/test_memutil.c @@ -46,11 +46,11 @@ unsigned char* expected_src; unsigned int expected_length; int copied; -void os_memmove_reset_mock() { +void platform_memmove_reset_mock() { copied = 0; } -void os_memmove(void* dst, const void* src, unsigned int length) { +void platform_memmove(void* dst, const void* src, unsigned int length) { assert(expected_dst == dst); assert(expected_src == src); assert(expected_length == length); @@ -62,7 +62,7 @@ void test_ok() { char src[15]; char dst[10]; - os_memmove_reset_mock(); + platform_memmove_reset_mock(); TEST_MEMMOVE( dst, sizeof(dst), 0, src, sizeof(src), 0, 10, { assert(false); }); TEST_MEMMOVE( @@ -82,7 +82,7 @@ void test_negatives() { char dst[10]; int failed = 0; - os_memmove_reset_mock(); + platform_memmove_reset_mock(); TEST_MEMMOVE(dst, sizeof(dst), 0, src, sizeof(src), 0, -1, { failed++; }); TEST_MEMMOVE(dst, sizeof(dst), 0, src, sizeof(src), 0, -5, { failed++; }); TEST_MEMMOVE(dst, sizeof(dst), -1, src, sizeof(src), 0, 2, { failed++; }); @@ -97,7 +97,7 @@ void test_src_outofbounds() { char dst[10]; int failed = 0; - os_memmove_reset_mock(); + platform_memmove_reset_mock(); TEST_MEMMOVE(dst, sizeof(dst), 0, src, sizeof(src), 0, 6, { failed++; }); TEST_MEMMOVE(dst, sizeof(dst), 0, src, sizeof(src), 0, 7, { failed++; }); assert(failed == 2); @@ -110,7 +110,7 @@ void test_src_outofbounds_offset() { char dst[10]; int failed = 0; - os_memmove_reset_mock(); + platform_memmove_reset_mock(); TEST_MEMMOVE(dst, sizeof(dst), 0, src, sizeof(src), 6, 10, { failed++; }); TEST_MEMMOVE(dst, sizeof(dst), 0, src, sizeof(src), 15, 4, { failed++; }); assert(failed == 2); @@ -123,7 +123,7 @@ void test_dst_outofbounds() { char dst[10]; int failed = 0; - os_memmove_reset_mock(); + platform_memmove_reset_mock(); TEST_MEMMOVE(dst, sizeof(dst), 0, src, sizeof(src), 0, 11, { failed++; }); TEST_MEMMOVE(dst, sizeof(dst), 0, src, sizeof(src), 0, 13, { failed++; }); assert(failed == 2); @@ -136,7 +136,7 @@ void test_dst_outofbounds_offset() { char dst[10]; int failed = 0; - os_memmove_reset_mock(); + platform_memmove_reset_mock(); TEST_MEMMOVE(dst, sizeof(dst), 8, src, sizeof(src), 0, 3, { failed++; }); TEST_MEMMOVE(dst, sizeof(dst), 10, src, sizeof(src), 0, 1, { failed++; }); assert(failed == 2); @@ -149,7 +149,7 @@ void test_overflow() { char dst[10]; int failed = 0; - os_memmove_reset_mock(); + platform_memmove_reset_mock(); TEST_MEMMOVE( dst, sizeof(dst), 10, src, sizeof(src), 0, UINT_MAX - 5, { failed++; }); TEST_MEMMOVE( diff --git a/ledger/src/common/test/run-all.sh b/firmware/src/common/test/run-all.sh similarity index 100% rename from ledger/src/common/test/run-all.sh rename to firmware/src/common/test/run-all.sh diff --git a/firmware/src/hal/include/hal/communication.h b/firmware/src/hal/include/hal/communication.h new file mode 100644 index 00000000..71da6fe1 --- /dev/null +++ b/firmware/src/hal/include/hal/communication.h @@ -0,0 +1,123 @@ +/** + * The MIT License (MIT) + * + * Copyright (c) 2021 RSK Labs Ltd + * + * 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. + */ + +#ifndef __HAL_COMMUNICATION_H +#define __HAL_COMMUNICATION_H + +#include +#include +#include + +/** + * @brief Initializes the communication module + * + * @param msg_buffer The buffer to use for communication + * @param msg_buffer_size The size of the message buffer in bytes + * + * @returns whether the initialisation succeeded + */ +bool communication_init(unsigned char *msg_buffer, size_t msg_buffer_size); + +/** + * @brief Get a pointer to the message buffer + * + * @returns a pointer to the message buffer + */ +unsigned char *communication_get_msg_buffer(); + +/** + * @brief Get the message buffer size + * + * @returns the message buffer size + */ +size_t communication_get_msg_buffer_size(); + +/** + * @brief Exchanges bytes with the host. This function blocks until the host + * sends a message. + * + * The message exchanges data with the host using the msg_buffer. If there are + * any bytes to transmit, they are transmitted first. After that the function + * blocks until a new message is received from the host. + * + * @param tx The number of bytes sent to the host + * + * @returns the number of bytes received from the host + */ +unsigned short communication_io_exchange(unsigned short tx); + +// BEGINNING of platform-dependent code +#if defined(HSM_PLATFORM_X86) + +#include + +/** + * @brief For an external module processing + * APDU messages + * + * @param cb the external module processing callback + */ +typedef unsigned short (*communication_external_module_process_t)( + unsigned short tx); +void communication_set_external_module_process( + communication_external_module_process_t cb); + +/** + * @brief Starts a TCP server at the given host and port and sets it as the + * channel on which communication_io_exchange will perform the IO operations + * Either this or communication_set_input_file must be called before + * using communication_io_exchange. + * + * @param port the port on which to listen for connections + * @param host the interface to bind to + */ +void communication_set_and_start_server(int port, const char *host); + +/** + * @brief Sets the input file from which communication_io_exchange + * will read the input. + * Either this or communication_set_server must be called before + * using communication_io_exchange. + * + * @param _input_file the input file that is used for I/O + */ +void communication_set_input_file(FILE *_input_file); + +/** + * @brief Sets the replica file to which communication_io_exchange will + * write the input. Setting this is optional. + * + * @param _replica_file the file to which to replicate the inputs + */ +void communication_set_replica_file(FILE *_replica_file); + +/** + * @brief Perform an empty message write on the IO channel + */ +void communication_reply(); + +#endif +// END of platform-dependent code + +#endif // __HAL_COMMUNICATION_H diff --git a/ledger/src/common/src/constants.h b/firmware/src/hal/include/hal/constants.h similarity index 90% rename from ledger/src/common/src/constants.h rename to firmware/src/hal/include/hal/constants.h index b8deb134..7ba79c11 100644 --- a/ledger/src/common/src/constants.h +++ b/firmware/src/hal/include/hal/constants.h @@ -22,16 +22,16 @@ * IN THE SOFTWARE. */ -#ifndef __CONSTANTS_H -#define __CONSTANTS_H +#ifndef __HAL_CONSTANTS_H +#define __HAL_CONSTANTS_H -// Sizes +// ECDSA related sizes #define HASH_LENGTH 32 #define SEED_LENGTH 32 #define PRIVATE_KEY_LENGTH 32 -#define DERIVATION_PATH_PARTS 5 #define PUBKEY_UNCMP_LENGTH 65 #define PUBKEY_CMP_LENGTH 33 #define MAX_SIGNATURE_LENGTH 72 +#define BIP32_PATH_NUMPARTS 5 -#endif // __CONSTANTS_H +#endif // __HAL_CONSTANTS_H diff --git a/firmware/src/hal/include/hal/endorsement.h b/firmware/src/hal/include/hal/endorsement.h new file mode 100644 index 00000000..489a8bf7 --- /dev/null +++ b/firmware/src/hal/include/hal/endorsement.h @@ -0,0 +1,105 @@ +/** + * The MIT License (MIT) + * + * Copyright (c) 2021 RSK Labs Ltd + * + * 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. + */ + +#ifndef __HAL_ENDORSEMENT_H +#define __HAL_ENDORSEMENT_H + +#include +#include +#include + +/** + * @brief Endorses the given message + * + * @param msg The message to attest + * @param msg_size The size of the message to attest + * @param signature_out Where the signature should be output + * @param signature_out_length [in/out] the length of the output buffer / + * length of the produced signature + * + * @returns whether endorsement succeeded + */ +bool endorsement_sign(uint8_t* msg, + size_t msg_size, + uint8_t* signature_out, + uint8_t* signature_out_length); + +/** + * @brief Grabs the hash of the currently running code + * + * @param code_hash_out Where the code hash should be output + * @param code_hash_out_length [in/out] the length of the output buffer / + * length of the produced code hash + * + * @returns whether code hash gathering succeeded + */ +bool endorsement_get_code_hash(uint8_t* code_hash_out, + uint8_t* code_hash_out_length); + +/** + * @brief Grabs the endorsement public key + * + * @param public_key_out Where the public key should be output + * @param public_key_out_length [in/out] the length of the output buffer / + * length of the produced public key + * + * @returns whether public key gathering succeeded + */ +bool endorsement_get_public_key(uint8_t* public_key_out, + uint8_t* public_key_out_length); + +// BEGINNING of platform-dependent code +#if defined(HSM_PLATFORM_X86) + +#include "hal/constants.h" + +// An attestation ID (in lack of a better name) +// is simply a pair consisting of a secp256k1 private key +// representing the device attestation private key and +// a code hash representing the hash of the running +// application that is attestating. Together, they can +// be used to construct another secp256k1 private key +// which is the attestation private key used to sign the +// attestation messages. +typedef struct { + unsigned char key[PRIVATE_KEY_LENGTH]; + unsigned char code_hash[HASH_LENGTH]; +} attestation_id_t; + +extern attestation_id_t attestation_id; + +/** + * @brief Initializes the endorsement module + * + * @param att_file_path the path to the file that + * contains the attestation id + * + * @returns whether the initialisation succeeded + */ +bool endorsement_init(char* att_file_path); + +#endif +// END of platform-dependent code + +#endif // __HAL_ENDORSEMENT_H \ No newline at end of file diff --git a/ledger/src/tcpsigner/os_exceptions.h b/firmware/src/hal/include/hal/exceptions.h similarity index 96% rename from ledger/src/tcpsigner/os_exceptions.h rename to firmware/src/hal/include/hal/exceptions.h index 1397e5f6..d5f374e2 100644 --- a/ledger/src/tcpsigner/os_exceptions.h +++ b/firmware/src/hal/include/hal/exceptions.h @@ -39,14 +39,20 @@ * limitations under the License. *****************************************************************************/ +#ifndef __HAL_EXCEPTIONS_H +#define __HAL_EXCEPTIONS_H + +#if defined(HSM_PLATFORM_LEDGER) + +#include "os.h" // This includes the exception engine + +#elif defined(HSM_PLATFORM_X86) + /** * Modified try...catch exception implementation (taken from nanos-secure-sdk) * (https://github.com/LedgerHQ/nanos-secure-sdk/blob/nanos-1314/include/os.h) */ -#ifndef __SIMULATOR_OS_EXCEPTIONS_H -#define __SIMULATOR_OS_EXCEPTIONS_H - #include #include @@ -187,7 +193,7 @@ void os_longjmp(jmp_buf b, unsigned int exception); #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION -#include +#include "bc_err.h" #define IGNORE_WHEN_FUZZING(e) \ (e == MERKLE_PROOF_MISMATCH || e == CB_TXN_HASH_MISMATCH || \ @@ -208,4 +214,6 @@ void os_longjmp(jmp_buf b, unsigned int exception); #endif -#endif // __SIMULATOR_OS_EXCEPTIONS_H +#endif // HSM_PLATFORM_X86 + +#endif // __HAL_EXCEPTIONS_H diff --git a/firmware/src/hal/include/hal/hash.h b/firmware/src/hal/include/hal/hash.h new file mode 100644 index 00000000..0514324a --- /dev/null +++ b/firmware/src/hal/include/hal/hash.h @@ -0,0 +1,177 @@ +/** + * The MIT License (MIT) + * + * Copyright (c) 2021 RSK Labs Ltd + * + * 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. + */ + +#ifndef __HAL_HASH_H +#define __HAL_HASH_H + +#include +#include +#include + +#include "hal/constants.h" + +// BEGINNING of platform-dependent code +#if defined(HSM_PLATFORM_LEDGER) + +#include "os.h" +#include "sha256.h" + +typedef cx_sha256_t hash_sha256_ctx_t; +typedef cx_sha3_t hash_keccak256_ctx_t; +typedef SHA256_CTX hash_sha256_ms_ctx_t; + +#elif defined(HSM_PLATFORM_X86) + +#include "sha256.h" +#include "keccak256.h" + +typedef SHA256_CTX hash_sha256_ctx_t; +typedef SHA3_CTX hash_keccak256_ctx_t; +typedef SHA256_CTX hash_sha256_ms_ctx_t; + +#else +#error "HSM Platform undefined" +#endif +// END of platform-dependent code + +// *** sha256 *** + +/** + * @brief Initialize a sha256 hash context + * + * @param[inout] ctx the context to initialize + * + * @returns whether the initialisation succeeded + */ +bool hash_sha256_init(hash_sha256_ctx_t* ctx); + +/** + * @brief Update a sha256 hash context with given data + * + * @param[inout] ctx the context to update + * @param[in] data pointer to message to hash + * @param[in] len length of message in bytes + * + * @returns whether the update succeeded + */ +bool hash_sha256_update(hash_sha256_ctx_t* ctx, + const uint8_t* data, + size_t len); + +/** + * @brief Compute the final sha256 hash for the given context + * + * @param[inout] ctx the context to finalise + * @param[out] out_hash The final hash obtained from the incremental hash + * + * @returns whether the finalisation succeeded + */ +bool hash_sha256_final(hash_sha256_ctx_t* ctx, uint8_t* out_hash); + +// *** sha256 with midstate support *** + +/** + * @brief Initialize a sha256 ms hash context + * + * @param[inout] ctx the context to initialize + * + * @returns whether the initialisation succeeded + */ +bool hash_sha256_ms_init(hash_sha256_ms_ctx_t* ctx); + +/** + * @brief Set sha256 ms hash context to the given mid state + * + * @details + * Mid state must be 52 bytes long: + * - midstate[0:8]: ignore + * - midstate[8:16]: counter, as a big-endian uint64_t + * - midstate[16:48]: current hash, as 8 big-endian uint32_t integers + * - midstate[48:52]: ignore + * + * @param[inout] ctx the context to set + * @param[in] midstate pointer to midstate buffer + * + * @returns whether the midstate succeeded + */ +bool hash_sha256_ms_midstate(hash_sha256_ms_ctx_t* ctx, uint8_t* midstate); + +/** + * @brief Update a sha256 ms hash context with given data + * + * @param[inout] ctx the context to update + * @param[in] data pointer to message to hash + * @param[in] len length of message in bytes + * + * @returns whether the update succeeded + */ +bool hash_sha256_ms_update(hash_sha256_ms_ctx_t* ctx, + const uint8_t* data, + size_t len); + +/** + * @brief Compute the final sha256 ms hash for the given context + * + * @param[inout] ctx the context to finalise + * @param[out] out_hash The final hash obtained from the incremental hash + * + * @returns whether the finalisation succeeded + */ +bool hash_sha256_ms_final(hash_sha256_ms_ctx_t* ctx, uint8_t* out_hash); + +// *** keccak256 *** + +/** + * @brief Initialize a keccak256 hash context + * + * @param[inout] ctx the context to initialize + * + * @returns whether the initialisation succeeded + */ +bool hash_keccak256_init(hash_keccak256_ctx_t* ctx); + +/** + * @brief Update a keccak256 hash context with given data + * + * @param[inout] ctx the context to update + * @param[in] data pointer to message to hash + * @param[in] len length of message in bytes + * + * @returns whether the update succeeded + */ +bool hash_keccak256_update(hash_keccak256_ctx_t* ctx, + const uint8_t* data, + size_t len); + +/** + * @brief Compute the final keccak256 hash for the given context + * + * @param[inout] ctx the context to finalise + * @param[out] out_hash The final hash obtained from the incremental hash + * + * @returns whether the finalisation succeeded + */ +bool hash_keccak256_final(hash_keccak256_ctx_t* ctx, uint8_t* out_hash); + +#endif // __HAL_HASH_H diff --git a/ledger/src/signer/src/dbg.h b/firmware/src/hal/include/hal/log.h similarity index 65% rename from ledger/src/signer/src/dbg.h rename to firmware/src/hal/include/hal/log.h index 4e73f45d..88549759 100644 --- a/ledger/src/signer/src/dbg.h +++ b/firmware/src/hal/include/hal/log.h @@ -22,42 +22,35 @@ * IN THE SOFTWARE. */ -#ifndef __DBG_H -#define __DBG_H +#ifndef __LOG_H +#define __LOG_H -#ifdef HSM_SIMULATOR +#if defined(HSM_PLATFORM_X86) #include #include -#include "bigdigits.h" -#include "srlp.h" - -#define LOG(...) printf(__VA_ARGS__); +/** + * @brief Works just like printf + */ +void LOG(const char *format, ...); -/** Print buffer in hex format with prefix */ +/** + * @brief Print buffer in hex format with prefix + * + * @param prefix the log prefix (the general log prefix will be prepended too) + * @param buffer the buffer containing the bytes to output as hex chars + * @param size the size of buffer in bytes + */ void LOG_HEX(const char *prefix, void *buffer, size_t size); -/** Print big integer in hex format with optional prefix and suffix strings */ -void LOG_BIGD_HEX(const char *prefix, - const DIGIT_T *a, - size_t len, - const char *suffix); - -/** Print N copies of a given char */ -void LOG_N_CHARS(const char c, unsigned int times); - -/** Print the given SRLP context (see srlp.h) */ -void LOG_SRLP_CTX(uint8_t v, rlp_ctx_t ctx[], uint8_t ptr); - -#else +#elif defined(HSM_PLATFORM_LEDGER) #define LOG(...) #define LOG_HEX(...) -#define LOG_BIGD_HEX(...) -#define LOG_N_CHARS(...) -#define LOG_SRLP_CTX(...) +#else +#error "HSM Platform undefined" #endif -#endif // __DBG_H +#endif // __LOG_H diff --git a/ledger/src/tcpsigner/log.c b/firmware/src/hal/include/hal/nvmem.h similarity index 58% rename from ledger/src/tcpsigner/log.c rename to firmware/src/hal/include/hal/nvmem.h index f34f90b1..f7c89701 100644 --- a/ledger/src/tcpsigner/log.c +++ b/firmware/src/hal/include/hal/nvmem.h @@ -22,36 +22,44 @@ * IN THE SOFTWARE. */ -/******************************************************************************* - * powHSM - * - * Generic logging to screen functions for TCPSigner - ********************************************************************************/ +#ifndef __HAL_NVMEM_H +#define __HAL_NVMEM_H #include -#include +#include +#include -#include "log.h" -#include "dbg.h" +/** + * @brief Write to non volatile memory + * + * @param dst The destination address in non volatile memory + * @param src The source address to write from + * @param length The amount of bytes to write + * + * @returns whether the write succeeded + */ +bool nvmem_write(void *dst, void *src, unsigned int length); -#define PREFIX "[TCPSIGNER] " +// BEGINNING of platform-dependent code +#if defined(HSM_PLATFORM_X86) -void info(const char *format, ...) { - va_list args; - va_start(args, format); +typedef struct nvmmem_stats_s { + unsigned int write_count; +} nvmmem_stats_t; - LOG(PREFIX); - vprintf(format, args); +/** + * @brief Resets the non volatile memory statistics + */ +void nvmem_stats_reset(); - va_end(args); -} +/** + * @brief Returns the current non volatile memory statistics + * + * @returns the statistics + */ +nvmmem_stats_t nvmem_get_stats(); -void info_hex(const char *prefix, void *buffer, size_t size) { - LOG(PREFIX); - LOG_HEX(prefix, buffer, size); -} +#endif +// END of platform-dependent code -void info_bigd_hex(const char *prefix, const DIGIT_T *a, size_t len) { - LOG(PREFIX); - LOG_BIGD_HEX(prefix, a, len, "\n"); -} +#endif // __HAL_NVMEM_H \ No newline at end of file diff --git a/ledger/src/tcpsigner/hsmsim_exceptions.h b/firmware/src/hal/include/hal/platform.h similarity index 67% rename from ledger/src/tcpsigner/hsmsim_exceptions.h rename to firmware/src/hal/include/hal/platform.h index 25795453..3b0af3ae 100644 --- a/ledger/src/tcpsigner/hsmsim_exceptions.h +++ b/firmware/src/hal/include/hal/platform.h @@ -22,17 +22,33 @@ * IN THE SOFTWARE. */ -#ifndef __SIMULATOR_HSMSIM_EXCEPTIONS_H -#define __SIMULATOR_HSMSIM_EXCEPTIONS_H +#ifndef __HAL_PLATFORM_H +#define __HAL_PLATFORM_H +#include #include -#include "os_exceptions.h" -/* ----------------------------------------------------------------------- */ -/* - HSM SIMULATOR SPECIFIC EXCEPTIONS - */ -/* ----------------------------------------------------------------------- */ -#define HSMSIM_EXC_INVALID_PATH 0xbb01 -#define HSMSIM_EXC_SECP_ERROR 0xbb02 -#define HSMSIM_EXC_HMAC_ERROR 0xbb03 +/** + * @brief Perform the platform-specific version of memmove + * + * @param dst destination buffer + * @param src source buffer + * @param length number of bytes to copy + */ +void platform_memmove(void *dst, const void *src, unsigned int length); + +/** + * @brief Request exiting/closing to the underlying platform + */ +void platform_request_exit(); + +/** + * X86 specific headers + */ +#if defined(HSM_PLATFORM_X86) + +#include "explicit_bzero.h" + +#endif // HSM_PLATFORM_X86 -#endif // __SIMULATOR_HSMSIM_EXCEPTIONS_H +#endif // __HAL_PLATFORM_H diff --git a/firmware/src/hal/include/hal/seed.h b/firmware/src/hal/include/hal/seed.h new file mode 100644 index 00000000..022d79a4 --- /dev/null +++ b/firmware/src/hal/include/hal/seed.h @@ -0,0 +1,122 @@ +/** + * The MIT License (MIT) + * + * Copyright (c) 2021 RSK Labs Ltd + * + * 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. + */ + +#ifndef __HAL_SEED_H +#define __HAL_SEED_H + +#include +#include +#include + +/** + * @brief Returns whether there's a generated seed + * + * @returns whether there's a generated seed + */ +bool seed_available(); + +/** + * @brief Derives the main node using the given derivation path and + * computes and outputs its public key in uncompressed format + * + * @param path the BIP32 path to use for derivation + * @param path_length the BIP32 path length in parts (not bytes) + * @param pubkey_out where the public key should be output + * @param pubkey_out_length [in/out] the length of the output buffer / + * length of the produced public key + * + * @returns whether the derivation succeeded + */ +bool seed_derive_pubkey(uint32_t* path, + uint8_t path_length, + uint8_t* pubkey_out, + uint8_t* pubkey_out_length); + +/** + * @brief Signs the given hash with the private key obtained + * by deriving the main node using the given derivation path, and + * outputs the signature in DER format. + * + * @param path the BIP32 path to use for derivation + * @param hash32 the 32 byte hash to sign + * @param sig_out where the public key should be output + * @param sig_out_length [in/out] the length of the output buffer / + * length of the produced signature + * + * @returns whether the signing succeeded + */ +bool seed_sign(uint32_t* path, + uint8_t path_length, + uint8_t* hash32, + uint8_t* sig_out, + uint8_t* sig_out_length); + +// BEGINNING of platform-dependent code +#if defined(HSM_PLATFORM_X86) + +typedef struct seed_data_s { + bool is_onboarded; + +} seed_data_t; + +/** + * @brief Derive the public key corresponding to the given + * private key and output it in either compressed + * or uncompressed format + * + * @param key the private key + * @param dest the destination buffer for the derived public key + * @param compressed whether to output in compressed or uncompressed format + * + * @returns the size of the output public key in bytes + */ +uint8_t seed_derive_pubkey_format(const unsigned char* key, + unsigned char* dest, + bool compressed); + +/** + * @brief Mock the return value of the seed_available() function + * + * @param is_onboarded the mock value + */ +void seed_set_is_onboarded(bool is_onboarded); + +/** + * @brief Initializes the seed module + * + * @param key_file_path the path to the file that + * contains the private keys + * @param bip32_paths an array containing the bip32 path strings + * @param bip32_paths_count the number of bip32 paths + * + * @returns whether the initialisation succeeded + */ +bool seed_init(const char* key_file_path, + const char* bip32_paths[], + const size_t bip32_paths_count); + +#endif +// END of platform-dependent code + +#endif // __HAL_SEED_H diff --git a/ledger/src/signer/src/sha256.c b/firmware/src/hal/src/common/sha256.c similarity index 100% rename from ledger/src/signer/src/sha256.c rename to firmware/src/hal/src/common/sha256.c diff --git a/ledger/src/signer/src/sha256.h b/firmware/src/hal/src/common/sha256.h similarity index 100% rename from ledger/src/signer/src/sha256.h rename to firmware/src/hal/src/common/sha256.h diff --git a/firmware/src/hal/src/ledger/communication.c b/firmware/src/hal/src/ledger/communication.c new file mode 100644 index 00000000..2f12023a --- /dev/null +++ b/firmware/src/hal/src/ledger/communication.c @@ -0,0 +1,49 @@ +/** + * The MIT License (MIT) + * + * Copyright (c) 2021 RSK Labs Ltd + * + * 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 "os.h" +#include "hal/communication.h" + +static unsigned char* msg_buffer; +static size_t msg_buffer_size; + +// HAL implementation +bool communication_init(unsigned char* _msg_buffer, size_t _msg_buffer_size) { + // Setup the exchange buffer + msg_buffer = _msg_buffer; + msg_buffer_size = _msg_buffer_size; + return true; +} + +unsigned char* communication_get_msg_buffer() { + return msg_buffer; +} + +size_t communication_get_msg_buffer_size() { + return msg_buffer_size; +} + +unsigned short communication_io_exchange(unsigned short tx) { + return io_exchange(CHANNEL_APDU, tx); +} diff --git a/ledger/src/signer/src/hsm-ledger.c b/firmware/src/hal/src/ledger/endorsement.c similarity index 50% rename from ledger/src/signer/src/hsm-ledger.c rename to firmware/src/hal/src/ledger/endorsement.c index 376052e4..dd6708e3 100644 --- a/ledger/src/signer/src/hsm-ledger.c +++ b/firmware/src/hal/src/ledger/endorsement.c @@ -23,37 +23,45 @@ */ #include "os.h" -#include "hsm.h" -#include "err.h" - -void hsm_ledger_main_loop() { - volatile unsigned int rx = 0; - volatile unsigned int tx = 0; - - // DESIGN NOTE: the bootloader ignores the way APDU are fetched. The only - // goal is to retrieve APDU. - // When APDU are to be fetched from multiple IOs, like NFC+USB+BLE, make - // sure the io_event is called with a - // switch event, before the apdu is replied to the bootloader. This avoid - // APDU injection faults. - while (!hsm_exit_requested()) { - BEGIN_TRY { - TRY { - // ensure no race in catch_other if io_exchange throws - // an error - rx = tx; - tx = 0; - rx = io_exchange(CHANNEL_APDU, rx); - - tx = hsm_process_apdu(rx); - THROW(0x9000); - } - CATCH_OTHER(e) { - tx = hsm_process_exception(e, tx); - } - FINALLY { - } - } - END_TRY; +#include "hal/constants.h" +#include "hal/endorsement.h" + +// Index of the ledger endorsement scheme +#define ENDORSEMENT_SCHEME_INDEX 2 + +bool endorsement_sign(uint8_t* msg, + size_t msg_size, + uint8_t* signature_out, + uint8_t* signature_out_length) { + + if (*signature_out_length < MAX_SIGNATURE_LENGTH) { + return false; } + + *signature_out_length = + os_endorsement_key2_derive_sign_data(msg, msg_size, signature_out); + + return true; } + +bool endorsement_get_code_hash(uint8_t* code_hash_out, + uint8_t* code_hash_out_length) { + + if (*code_hash_out_length < HASH_LENGTH) { + return false; + } + + *code_hash_out_length = os_endorsement_get_code_hash(code_hash_out); + return true; +} + +bool endorsement_get_public_key(uint8_t* public_key_out, + uint8_t* public_key_out_length) { + if (*public_key_out_length < PUBKEY_UNCMP_LENGTH) { + return false; + } + + *public_key_out_length = + os_endorsement_get_public_key(ENDORSEMENT_SCHEME_INDEX, public_key_out); + return true; +} \ No newline at end of file diff --git a/firmware/src/hal/src/ledger/hash.c b/firmware/src/hal/src/ledger/hash.c new file mode 100644 index 00000000..0169015c --- /dev/null +++ b/firmware/src/hal/src/ledger/hash.c @@ -0,0 +1,86 @@ +/** + * The MIT License (MIT) + * + * Copyright (c) 2021 RSK Labs Ltd + * + * 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 "hal/hash.h" +#include "sha256.h" +#include "os.h" + +// *** sha256 *** +bool hash_sha256_init(hash_sha256_ctx_t* ctx) { + cx_sha256_init(ctx); + return true; +} + +bool hash_sha256_update(hash_sha256_ctx_t* ctx, + const uint8_t* data, + size_t len) { + cx_hash((cx_hash_t*)(ctx), 0, (unsigned char*)data, len, NULL); + return true; +} + +bool hash_sha256_final(hash_sha256_ctx_t* ctx, uint8_t* out_hash) { + cx_hash((cx_hash_t*)(ctx), CX_LAST, NULL, 0, out_hash); + return true; +} + +// *** sha256 with midstate support *** +bool hash_sha256_ms_init(hash_sha256_ms_ctx_t* ctx) { + sha256_init(ctx); + return true; +} + +bool hash_sha256_ms_midstate(hash_sha256_ms_ctx_t* ctx, uint8_t* midstate) { + sha256_midstate(ctx, midstate); + return true; +} + +bool hash_sha256_ms_update(hash_sha256_ms_ctx_t* ctx, + const uint8_t* data, + size_t len) { + sha256_update(ctx, data, len); + return true; +} + +bool hash_sha256_ms_final(hash_sha256_ms_ctx_t* ctx, uint8_t* out_hash) { + sha256_final(ctx, out_hash); + return true; +} + +// *** keccak256 *** +bool hash_keccak256_init(hash_keccak256_ctx_t* ctx) { + cx_keccak_init(ctx, 256); + return true; +} + +bool hash_keccak256_update(hash_keccak256_ctx_t* ctx, + const uint8_t* data, + size_t len) { + cx_hash((cx_hash_t*)(ctx), 0, (unsigned char*)data, len, NULL); + return true; +} + +bool hash_keccak256_final(hash_keccak256_ctx_t* ctx, uint8_t* out_hash) { + cx_hash((cx_hash_t*)(ctx), CX_LAST, NULL, 0, out_hash); + return true; +} \ No newline at end of file diff --git a/ledger/src/signer/src/hsm-ledger.h b/firmware/src/hal/src/ledger/nvmem.c similarity index 88% rename from ledger/src/signer/src/hsm-ledger.h rename to firmware/src/hal/src/ledger/nvmem.c index 2079a4a7..f0c68904 100644 --- a/ledger/src/signer/src/hsm-ledger.h +++ b/firmware/src/hal/src/ledger/nvmem.c @@ -22,9 +22,10 @@ * IN THE SOFTWARE. */ -#ifndef __HSM_LEDGER_H -#define __HSM_LEDGER_H +#include "os.h" +#include "hal/nvmem.h" -void hsm_ledger_main_loop(); - -#endif // __HSM_LEDGER_H +bool nvmem_write(void *dst, void *src, unsigned int length) { + nvm_write(dst, src, length); + return true; +} diff --git a/firmware/src/hal/src/ledger/platform.c b/firmware/src/hal/src/ledger/platform.c new file mode 100644 index 00000000..ecea2a79 --- /dev/null +++ b/firmware/src/hal/src/ledger/platform.c @@ -0,0 +1,41 @@ +/** + * The MIT License (MIT) + * + * Copyright (c) 2021 RSK Labs Ltd + * + * 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 "hal/platform.h" +#include "hal/exceptions.h" + +void platform_memmove(void *dst, const void *src, unsigned int length) { + os_memmove(dst, src, length); +} + +void platform_request_exit() { + BEGIN_TRY_L(exit) { + TRY_L(exit) { + os_sched_exit(-1); + } + FINALLY_L(exit) { + } + } + END_TRY_L(exit); +} \ No newline at end of file diff --git a/ledger/src/signer/src/sign.c b/firmware/src/hal/src/ledger/seed.c similarity index 64% rename from ledger/src/signer/src/sign.c rename to firmware/src/hal/src/ledger/seed.c index ea7cc82e..392457a1 100644 --- a/ledger/src/signer/src/sign.c +++ b/firmware/src/hal/src/ledger/seed.c @@ -26,33 +26,22 @@ #include "os.h" #include "cx.h" +#include "hal/constants.h" +#include "hal/seed.h" -#include "sign.h" -#include "defs.h" -#include "memutil.h" +bool seed_available() { + return os_perso_isonboarded() == 1; +} -/* - * Derive the public key for a given path. - * Store the public key into the given destination buffer. - * - * @arg[in] path derivation path - * @arg[in] path_length length of the derivation path - * @arg[in] dest destination buffer - * @arg[in] dest destination buffer size - * @ret size of the public key derived, - * or DO_PUBKEY_ERROR in case of error - */ -int do_pubkey(unsigned int* path, - unsigned char path_length, - unsigned char* dest, - size_t dest_size) { +bool seed_derive_pubkey(uint32_t* path, + uint8_t path_length, + uint8_t* pubkey_out, + uint8_t* pubkey_out_length) { volatile unsigned char private_key_data[PRIVATE_KEY_LENGTH]; volatile cx_ecfp_private_key_t private_key; volatile cx_ecfp_public_key_t public_key; - volatile int pubkey_size; - BEGIN_TRY { TRY { // Derive and init private key @@ -74,16 +63,13 @@ int do_pubkey(unsigned int* path, 1); // Cleanup private key explicit_bzero((void*)&private_key, sizeof(private_key)); + if (*pubkey_out_length < public_key.W_len) { + THROW(1); + } // Output the public key - pubkey_size = public_key.W_len; - SAFE_MEMMOVE(dest, - dest_size, - MEMMOVE_ZERO_OFFSET, - (void*)public_key.W, - public_key.W_len, - MEMMOVE_ZERO_OFFSET, - public_key.W_len, - { pubkey_size = DO_PUBKEY_ERROR; }) + *pubkey_out_length = public_key.W_len; + os_memmove( + (void*)pubkey_out, (const void*)public_key.W, public_key.W_len); // Cleanup public key explicit_bzero((void*)&public_key, sizeof(public_key)); } @@ -92,45 +78,28 @@ int do_pubkey(unsigned int* path, explicit_bzero((void*)private_key_data, sizeof(private_key_data)); explicit_bzero((void*)&private_key, sizeof(private_key)); explicit_bzero((void*)&public_key, sizeof(public_key)); - // Signal error deriving public key - pubkey_size = DO_PUBKEY_ERROR; + return false; } FINALLY { } } END_TRY; - // Return public key size - return pubkey_size; + + return true; } -/* - * Sign a message with a given path. - * Store the signature into the given destination buffer. - * - * @arg[in] path derivation path - * @arg[in] path_length length of the derivation path - * @arg[in] message message buffer - * @arg[in] message_size message size - * @arg[in] dest destination buffer - * @arg[in] dest destination buffer size - * @ret size of the signature produced, - * or DO_SIGN_ERROR in case of error - */ -int do_sign(unsigned int* path, - unsigned char path_length, - unsigned char* message, - size_t message_size, - unsigned char* dest, - size_t dest_size) { +bool seed_sign(uint32_t* path, + uint8_t path_length, + uint8_t* hash32, + uint8_t* sig_out, + uint8_t* sig_out_length) { volatile unsigned char private_key_data[PRIVATE_KEY_LENGTH]; volatile cx_ecfp_private_key_t private_key; - volatile int sig_size; - // Check the destination buffer won't be overflowed by the signature - if (dest_size < MAX_SIGNATURE_LENGTH) { - return DO_SIGN_ERROR; + if (*sig_out_length < MAX_SIGNATURE_LENGTH) { + return false; } BEGIN_TRY { @@ -147,12 +116,12 @@ int do_sign(unsigned int* path, (cx_ecfp_private_key_t*)&private_key); // Cleanup private key data explicit_bzero((void*)private_key_data, sizeof(private_key_data)); - sig_size = cx_ecdsa_sign((void*)&private_key, - CX_RND_RFC6979 | CX_LAST, - CX_SHA256, - message, - message_size, - dest); + *sig_out_length = (uint8_t)cx_ecdsa_sign((void*)&private_key, + CX_RND_RFC6979 | CX_LAST, + CX_SHA256, + hash32, + HASH_LENGTH, + sig_out); // Cleanup private key explicit_bzero((void*)&private_key, sizeof(private_key)); } @@ -160,13 +129,12 @@ int do_sign(unsigned int* path, // Cleanup key data and fail explicit_bzero((void*)private_key_data, sizeof(private_key_data)); explicit_bzero((void*)&private_key, sizeof(private_key)); - // Signal error signing - sig_size = DO_SIGN_ERROR; + return false; } FINALLY { } } END_TRY; - // Return signature size - return sig_size; -} \ No newline at end of file + + return true; +} diff --git a/firmware/src/hal/src/ledger/sha256.c b/firmware/src/hal/src/ledger/sha256.c new file mode 120000 index 00000000..a21d1a59 --- /dev/null +++ b/firmware/src/hal/src/ledger/sha256.c @@ -0,0 +1 @@ +../common/sha256.c \ No newline at end of file diff --git a/firmware/src/hal/src/ledger/sha256.h b/firmware/src/hal/src/ledger/sha256.h new file mode 120000 index 00000000..65492ab2 --- /dev/null +++ b/firmware/src/hal/src/ledger/sha256.h @@ -0,0 +1 @@ +../common/sha256.h \ No newline at end of file diff --git a/firmware/src/hal/src/x86/bip32.c b/firmware/src/hal/src/x86/bip32.c new file mode 100644 index 00000000..7ccd8460 --- /dev/null +++ b/firmware/src/hal/src/x86/bip32.c @@ -0,0 +1,98 @@ +#include "bip32.h" +#include "hal/constants.h" +#include "hal/log.h" + +#include +#include +#include +#include + +#define BIP32_PREFIX "m/" +#define MIN_PATH_LENGTH (strlen("m/0/0/0/0/0")) +#define MAX_PART_DECIMAL_DIGITS 10 +#define EXPECTED_PARTS BIP32_PATH_NUMPARTS + +#ifdef DEBUG_BIP32 +#define DEBUG_LOG(...) LOG(__VA_ARGS__) +#else +#define DEBUG_LOG(...) +#endif + +size_t bip32_parse_path(const char* path, uint8_t* out) { + size_t pos, start, pathlen; + int parts; + int index; + bool number; + char indexstr[MAX_PART_DECIMAL_DIGITS + 1]; + uint32_t indexint; + + if (strlen(path) < MIN_PATH_LENGTH) { + DEBUG_LOG("BIP32 path too short: %s\n", path); + return 0; + } + + if (strncmp(path, BIP32_PREFIX, strlen(BIP32_PREFIX))) { + DEBUG_LOG("Bad prefix for path: %s\n", path); + return 0; + } + + parts = 0; + pathlen = strlen(path); + pos = strlen(BIP32_PREFIX); + start = pos; + index = 0; + number = true; + while (pos < pathlen) { + if (number && path[pos] >= '0' && path[pos] <= '9') { + pos++; + if (pos - start > MAX_PART_DECIMAL_DIGITS) { + DEBUG_LOG("Path part %d too long for path: %s\n", parts, path); + return 0; + } + } else if (number && path[pos] == '\'') { + number = false; + index = 0x80000000; + pos++; + } else if (path[pos] != '/') { + DEBUG_LOG( + "Unexpected path character: %c for path %s\n", path[pos], path); + return 0; + } + + if (pos == pathlen || path[pos] == '/') { + // Compute the index + memcpy(indexstr, path + start, pos - start); + indexstr[pos - start] = '\0'; + indexint = (uint32_t)atol(indexstr); + if (indexint >= 0x80000000) { + DEBUG_LOG("Path part %d needs to be between 0 and 2^31-1 for " + "path: %s\n", + parts, + path); + return 0; + } + index += indexint; + // Output the index in LE + for (int i = 0; i < sizeof(uint32_t); i++) { + out[1 + (parts * sizeof(uint32_t)) + i] = + (index >> (8 * i)) & 0xFF; + } + // Next! + parts++; + index = 0; + number = true; + start = ++pos; + if (parts == EXPECTED_PARTS) { + if (pos < pathlen) { + DEBUG_LOG("Path has too many parts: %s\n", path); + return 0; + } + out[0] = (char)parts; + return 1 + parts * sizeof(uint32_t); + } + } + } + + DEBUG_LOG("Unexpected code path reached for path: %s\n", path); + return 0; +} diff --git a/ledger/src/tcpsigner/log.h b/firmware/src/hal/src/x86/bip32.h similarity index 65% rename from ledger/src/tcpsigner/log.h rename to firmware/src/hal/src/x86/bip32.h index b0f66e6e..29af0251 100644 --- a/ledger/src/tcpsigner/log.h +++ b/firmware/src/hal/src/x86/bip32.h @@ -22,19 +22,26 @@ * IN THE SOFTWARE. */ -/******************************************************************************* - * powHSM - * - * Generic logging to screen functions for TCPSigner - ********************************************************************************/ +#ifndef __HAL_BIP32_H +#define __HAL_BIP32_H + +#include +#include -#ifndef __SIMULATOR_LOG_H -#define __SIMULATOR_LOG_H +#include "hal/constants.h" -#include "bigdigits.h" +#define BIP32_PATH_PART_LENGTH (sizeof(uint32_t)) +#define BIP32_PATH_LENGTH (1 + BIP32_PATH_NUMPARTS * BIP32_PATH_PART_LENGTH) -void info(const char *format, ...); -void info_hex(const char *prefix, void *buffer, size_t size); -void info_bigd_hex(const char *prefix, const DIGIT_T *a, size_t len); +/** + * @brief Parse the given string representation of a bip32 path + * into binary format + * + * @param path the bip32 path as string + * @param out the destination buffer for the parsed path + * + * @returns the size of the parsed path in bytes, or zero in case of error + */ +size_t bip32_parse_path(const char* path, uint8_t* out); -#endif // __SIMULATOR_LOG_H +#endif // __HAL_BIP32_H diff --git a/ledger/src/tcpsigner/cJSON.c b/firmware/src/hal/src/x86/cJSON.c similarity index 100% rename from ledger/src/tcpsigner/cJSON.c rename to firmware/src/hal/src/x86/cJSON.c diff --git a/ledger/src/tcpsigner/cJSON.h b/firmware/src/hal/src/x86/cJSON.h similarity index 100% rename from ledger/src/tcpsigner/cJSON.h rename to firmware/src/hal/src/x86/cJSON.h diff --git a/ledger/src/tcpsigner/os_io.c b/firmware/src/hal/src/x86/communication.c similarity index 50% rename from ledger/src/tcpsigner/os_io.c rename to firmware/src/hal/src/x86/communication.c index aded6661..a477b4f9 100644 --- a/ledger/src/tcpsigner/os_io.c +++ b/firmware/src/hal/src/x86/communication.c @@ -22,26 +22,26 @@ * IN THE SOFTWARE. */ -#include #include -#include -#include -#include +#include +#include #include -#include #include +#include +#include +#include +#include +#include -#include "os_io.h" -#include "tcp.h" -#include "log.h" -#include "defs.h" -#include "hsmsim_admin.h" +#include "hal/communication.h" +#include "hal/log.h" #include "apdu.h" /** * APDU buffer */ -unsigned char G_io_apdu_buffer[IO_APDU_BUFFER_SIZE]; +#define IO_APDU_BUFFER_SIZE 85 +static unsigned char apdu_buffer[IO_APDU_BUFFER_SIZE]; #define MAX_FUZZ_TRANSFER IO_APDU_BUFFER_SIZE @@ -53,109 +53,151 @@ enum io_mode_e io_mode; */ int server; int socketfd; +struct sockaddr_in servaddr, cli; /** * For the file input mode */ -FILE *input_file; +static FILE *input_file; /** * Copy all input to this file, if set. */ -FILE *replica_file; +static FILE *replica_file; /** * For flushing in between mains */ static bool io_exchange_write_only; -/* - * Sets the server on which io_exchange will perform - * the IO operations - * (This *MUST* be set before using io_exchange) +/** + * For an external module processing + * APDU messages */ -void os_io_set_server(int svr) { - server = svr; - socketfd = 0; - io_mode = IO_MODE_SERVER; - io_exchange_write_only = false; -} +typedef unsigned short (*communication_external_module_process_t)( + unsigned short tx); +communication_external_module_process_t external_module_process_cb = NULL; -void os_io_set_input_file(FILE *_input_file) { - input_file = _input_file; - io_mode = IO_MODE_INPUT_FILE; +void communication_set_external_module_process( + communication_external_module_process_t cb) { + external_module_process_cb = cb; } -void os_io_set_replica_file(FILE *_replica_file) { - replica_file = _replica_file; -} +/** + * @brief Start server, return a socket on connection + * + * @arg[in] PORT tcp port + * @arg[in] HOST HOST string + * + * @returns socket file descriptor + */ +static int start_server(int port, const char *host) { + int sockfd; + struct hostent *hostinfo; + hostinfo = gethostbyname(host); -unsigned short io_exchange(unsigned char channel_and_flags, unsigned short tx) { - unsigned short rx; - switch (io_mode) { - case IO_MODE_SERVER: - rx = io_exchange_server(channel_and_flags, tx); - break; - case IO_MODE_INPUT_FILE: - rx = io_exchange_file(channel_and_flags, tx, input_file); - break; - default: - info("[TCPSigner] No IO Mode set! This is a bug."); + if (hostinfo == NULL) { + LOG("Host not found.\n"); exit(1); - break; } - if (replica_file != NULL) { - int written = replicate_to_file(replica_file, rx); - if (written != rx + 1) { - info("Error writting to output file %s\n", replica_file); - exit(-1); - } + // socket create and verification + sockfd = socket(AF_INET, SOCK_STREAM, 0); + if (sockfd == -1) { + LOG("Socket creation failed...\n"); + exit(1); } - // Process one APDU message using the admin module - // if need be (there shouldn't normally - // be many of these in a row, so the stack shouldn't overflow) - if (hsmsim_admin_need_process(rx)) { - tx = hsmsim_admin_process_apdu(rx); - return io_exchange(channel_and_flags, tx); + bzero(&servaddr, sizeof(servaddr)); + + if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)) < + 0) { + LOG("Socket option setting failed failed\n"); + exit(1); } - return rx; + if (setsockopt(sockfd, SOL_TCP, TCP_NODELAY, &(int){1}, sizeof(int)) < 0) { + LOG("Socket option setting failed failed\n"); + exit(1); + } + + // Set address and port + servaddr.sin_family = AF_INET; + memcpy(&servaddr.sin_addr, hostinfo->h_addr_list[0], hostinfo->h_length); + servaddr.sin_port = htons(port); + + // Binding newly created socket to given IP and verification + if ((bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr))) != 0) { + LOG("Socket bind failed...\n"); + exit(1); + } + + // Now server is ready to listen and verification + if ((listen(sockfd, 5)) != 0) { + LOG("Listen failed...\n"); + exit(1); + } + + LOG("Server listening...\n"); + return sockfd; +} + +/** + * @brief Accept the data packet from client and verification + * + * @arg[in] sockfd server socket + * + * @returns connection file descriptor + */ +static int accept_connection(int sockfd) { + int len = sizeof(cli); + int connfd = accept(sockfd, (struct sockaddr *)&cli, &len); + if (connfd < 0) { + LOG("Client connection failed...\n"); + exit(1); + } + + LOG("Client connected...\n"); + return connfd; +} + +void communication_set_and_start_server(int port, const char *host) { + server = start_server(port, host); + socketfd = 0; + io_mode = IO_MODE_SERVER; + io_exchange_write_only = false; +} + +void communication_set_input_file(FILE *_input_file) { + input_file = _input_file; + io_mode = IO_MODE_INPUT_FILE; +} + +void communication_set_replica_file(FILE *_replica_file) { + replica_file = _replica_file; } /** * Perform an empty message * write on the IO channel */ -void io_exchange_reply() { +void communication_reply() { io_exchange_write_only = true; - G_io_apdu_buffer[0] = (APDU_OK & 0xff00) >> 8; - G_io_apdu_buffer[1] = APDU_OK & 0xff; - io_exchange(0, 2); + apdu_buffer[0] = (APDU_OK & 0xff00) >> 8; + apdu_buffer[1] = APDU_OK & 0xff; + communication_io_exchange(2); } /* * This function emulates USB device, writing bytes to tcpsocket instead - * @arg[in] channel_and_flags must be CHANNEL_APDU * @arg[in] tx amount of bytes to transmit to the client * @ret amount of bytes received from the client */ -unsigned short io_exchange_server(unsigned char channel_and_flags, - unsigned short tx) { +static unsigned short io_exchange_server(unsigned short tx) { uint32_t tx_net, rx_net; unsigned int rx; int readlen; - // "Test" correct value on channel and flags in every call - if (channel_and_flags != CHANNEL_APDU) { - info("Invalid channel and flags specified for io_exchange: %d " - "(expected %d). Terminating TCPSigner.\n", - channel_and_flags, - CHANNEL_APDU); - exit(1); - } - while (true) { if (!socketfd) { socketfd = accept_connection(server); @@ -171,17 +213,17 @@ unsigned short io_exchange_server(unsigned char channel_and_flags, tx_net = htonl(tx_net); size_t written; if (send(socketfd, &tx_net, sizeof(tx_net), MSG_NOSIGNAL) == -1) { - info("Connection closed by the client\n"); + LOG("Connection closed by the client\n"); socketfd = 0; continue; } // Write APDU - if (send(socketfd, G_io_apdu_buffer, tx, MSG_NOSIGNAL) == -1) { - info("Connection closed by the client\n"); + if (send(socketfd, apdu_buffer, tx, MSG_NOSIGNAL) == -1) { + LOG("Connection closed by the client\n"); socketfd = 0; continue; } - info_hex("Dongle =>", G_io_apdu_buffer, tx); + LOG_HEX("Dongle =>", apdu_buffer, tx); } // Only write? We're done @@ -198,52 +240,48 @@ unsigned short io_exchange_server(unsigned char channel_and_flags, rx = ntohl(rx_net); if (rx > 0) { // Read APDU from socket - readlen = - read(socketfd, G_io_apdu_buffer, sizeof(G_io_apdu_buffer)); + readlen = read(socketfd, apdu_buffer, sizeof(apdu_buffer)); if (readlen != rx) { - info("Error reading APDU (got %d bytes != %d bytes). " - "Disconnected\n", - readlen, - rx); + LOG("Error reading APDU (got %d bytes != %d bytes). " + "Disconnected\n", + readlen, + rx); socketfd = 0; continue; } - info_hex("Dongle <=", G_io_apdu_buffer, rx); + LOG_HEX("Dongle <=", apdu_buffer, rx); } else { // Empty packet - info("Dongle <= \n"); + LOG("Dongle <= \n"); } return rx; } else if (readlen == 0) { // EOF => socket closed - info("Connection closed by the client\n"); + LOG("Connection closed by the client\n"); } else if (readlen == -1) { // Error reading - info("Error reading from socket. Disconnected\n"); + LOG("Error reading from socket. Disconnected\n"); } else { // Invalid packet header - info("Error reading APDU length (got %d bytes != %ld bytes). " - "Disconnected\n", - readlen, - sizeof(rx_net)); + LOG("Error reading APDU length (got %d bytes != %ld bytes). " + "Disconnected\n", + readlen, + sizeof(rx_net)); } socketfd = 0; } } /* This function emulates the HOST device, reading bytes from a file instead - * @arg[in] channel_and_flags must be CHANNEL_APDU * @arg[in] tx_len amount of bytes to transmit to the client * @arg[in] inputfd the input file * @ret amount of bytes received from the client */ -unsigned short io_exchange_file(unsigned char channel_and_flags, - unsigned char tx, - FILE *input_file) { +static unsigned short io_exchange_file(unsigned char tx, FILE *input_file) { // File input format: |1 byte length| |len bytes data| static unsigned long file_index = 0; - info_hex("Dongle => ", G_io_apdu_buffer, tx); + LOG_HEX("Dongle => ", apdu_buffer, tx); // Only write? We're done if (io_exchange_write_only) { @@ -254,10 +292,10 @@ unsigned short io_exchange_file(unsigned char channel_and_flags, unsigned char announced_rx; if (fread(&announced_rx, sizeof(char), 1, input_file) != 1) { if (feof(input_file)) { - info("Server: EOF\n"); + LOG("Server: EOF\n"); exit(0); } - info("Server: could not read rx size\n"); + LOG("Server: could not read rx size\n"); exit(1); } @@ -269,26 +307,25 @@ unsigned short io_exchange_file(unsigned char channel_and_flags, capped_rx = MAX_FUZZ_TRANSFER; } - info("Server: reading %d (announced: %d) bytes at index: %d\n", - capped_rx, - announced_rx, - file_index); - unsigned short rx = - fread(G_io_apdu_buffer, sizeof(char), capped_rx, input_file); + LOG("Server: reading %d (announced: %d) bytes at index: %d\n", + capped_rx, + announced_rx, + file_index); + unsigned short rx = fread(apdu_buffer, sizeof(char), capped_rx, input_file); if (rx != capped_rx) { // if we reach EOF while reading the data portion it means // the announced size did not match the file if (feof(input_file)) { - info("Server: malformed input, tried reading %d bytes but reached " - "EOF after %d\n", - capped_rx, - rx); + LOG("Server: malformed input, tried reading %d bytes but reached " + "EOF after %d\n", + capped_rx, + rx); exit(1); } - info("Server: Could not read %d bytes (only: %d) from input file\n", - capped_rx, - rx); + LOG("Server: Could not read %d bytes (only: %d) from input file\n", + capped_rx, + rx); exit(1); } @@ -298,12 +335,12 @@ unsigned short io_exchange_file(unsigned char channel_and_flags, // interpreting data as the length. unsigned long index_offset = announced_rx + 1; if (file_index > (ULONG_MAX - index_offset)) { - info("Server: input file too big, can't store offset."); + LOG("Server: input file too big, can't store offset."); exit(1); } file_index += index_offset; - info_hex("Dongle <= ", G_io_apdu_buffer, rx); + LOG_HEX("Dongle <= ", apdu_buffer, rx); return capped_rx; } @@ -312,11 +349,11 @@ unsigned short io_exchange_file(unsigned char channel_and_flags, * @arg[in] rx Lenght of the command * @ret number of bytes written */ -unsigned int replicate_to_file(FILE *replica_file, unsigned short rx) { +static unsigned int replicate_to_file(FILE *replica_file, unsigned short rx) { unsigned char rx_byte = rx; - info_hex("Replica =>", G_io_apdu_buffer, rx_byte); + LOG_HEX("Replica =>", apdu_buffer, rx_byte); unsigned int written = fwrite(&rx_byte, sizeof(char), 1, replica_file); - written += fwrite(G_io_apdu_buffer, sizeof(char), rx_byte, replica_file); + written += fwrite(apdu_buffer, sizeof(char), rx_byte, replica_file); // XXX: This should not be necessary. We are correctly closing the file // at the end of the process. But for whatever reason, this does not seem @@ -325,3 +362,64 @@ unsigned int replicate_to_file(FILE *replica_file, unsigned short rx) { fflush(replica_file); return written; } + +/***** BEGIN HAL Communication module implementation *****/ + +/** + * @brief Initializes the communication module + * + * @param msg_buffer The buffer to use for communication + * @param msg_buffer_size The size of the message buffer in bytes + * + * @returns whether the initialisation succeeded + */ +bool communication_init(unsigned char *msg_buffer, size_t msg_buffer_size) { + // Nothing to do here +} + +unsigned char *communication_get_msg_buffer() { + return apdu_buffer; +} + +size_t communication_get_msg_buffer_size() { + return sizeof(apdu_buffer); +} + +unsigned short communication_io_exchange(unsigned short tx) { + unsigned short rx, tx_ex; + + switch (io_mode) { + case IO_MODE_SERVER: + rx = io_exchange_server(tx); + break; + case IO_MODE_INPUT_FILE: + rx = io_exchange_file(tx, input_file); + break; + default: + LOG("[TCPSigner] No IO Mode set! This is a bug."); + exit(1); + break; + } + + if (replica_file != NULL) { + int written = replicate_to_file(replica_file, rx); + if (written != rx + 1) { + LOG("Error writting to output file %s\n", replica_file); + exit(-1); + } + } + + // Process one APDU message using an external module callback + // (there should generally speaking be at most one of these in a row, + // so the stack shouldn't overflow) + if (external_module_process_cb) { + tx_ex = external_module_process_cb(rx); + if (tx_ex) { + return communication_io_exchange(tx_ex); + } + } + + return rx; +} + +/***** END HAL Communication module implementation *****/ diff --git a/firmware/src/hal/src/x86/endorsement.c b/firmware/src/hal/src/x86/endorsement.c new file mode 100644 index 00000000..a449e950 --- /dev/null +++ b/firmware/src/hal/src/x86/endorsement.c @@ -0,0 +1,249 @@ +/** + * The MIT License (MIT) + * + * Copyright (c) 2021 RSK Labs Ltd + * + * 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 +#include +#include +#include + +#include "hal/constants.h" +#include "hal/endorsement.h" +#include "hal/seed.h" +#include "hal/exceptions.h" +#include "hal/log.h" + +#include "random.h" +#include "hmac_sha256.h" +#include "cJSON.h" +#include "json.h" +#include "hex_reader.h" + +#define ATTESTATION_KEY_KEY "attestationKey" +#define CODE_HASH_KEY "codeHash" + +static secp256k1_context* sp_ctx = NULL; +attestation_id_t attestation_id; + +static size_t tweak_sign(const unsigned char* key, + const unsigned char* tweak, + const unsigned char* hash, + unsigned char* sig) { + unsigned char tweaked_key[PRIVATE_KEY_LENGTH]; + secp256k1_ecdsa_signature sp_sig; + size_t sig_serialized_size = MAX_SIGNATURE_LENGTH; + + // Tweak private key + memmove(tweaked_key, key, sizeof(tweaked_key)); + if (!secp256k1_ec_privkey_tweak_add(sp_ctx, tweaked_key, tweak)) + return 0; + + // Sign and serialize as DER + secp256k1_ecdsa_sign(sp_ctx, &sp_sig, hash, tweaked_key, NULL, NULL); + secp256k1_ecdsa_signature_serialize_der( + sp_ctx, sig, &sig_serialized_size, &sp_sig); + + return (int)sig_serialized_size; +} + +/** + * Write current attestation id in JSON-format to the given path + */ +static bool write_attestation_id_file(char* attid_file_path) { + cJSON* json = cJSON_CreateObject(); + + unsigned long max_size = + sizeof(attestation_id.key) > sizeof(attestation_id.code_hash) + ? sizeof(attestation_id.key) + : sizeof(attestation_id.code_hash); + + char hex_str[max_size * 2 + 1]; + + // Write attestation key + for (int i = 0; i < sizeof(attestation_id.key); i++) + sprintf(hex_str + i * 2, "%02x", attestation_id.key[i]); + hex_str[sizeof(attestation_id.key) * 2] = '\0'; + cJSON_AddStringToObject(json, ATTESTATION_KEY_KEY, hex_str); + + // Write code hash + for (int i = 0; i < sizeof(attestation_id.code_hash); i++) + sprintf(hex_str + i * 2, "%02x", attestation_id.code_hash[i]); + hex_str[sizeof(attestation_id.code_hash) * 2] = '\0'; + cJSON_AddStringToObject(json, CODE_HASH_KEY, hex_str); + + return write_json_file(attid_file_path, json); +} + +static inline bool read_hex_value_into(cJSON* json, + char* key, + unsigned char* dest) { + cJSON* entry = cJSON_GetObjectItemCaseSensitive(json, key); + if (entry == NULL || !cJSON_IsString(entry)) + return false; + char* hex_value = cJSON_GetStringValue(entry); + read_hex(hex_value, strlen(hex_value), dest); + return true; +} + +bool endorsement_init(char* att_file_path) { + // Init the secp256k1 context + if (!sp_ctx) + sp_ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); + + LOG("Loading endorsement file '%s'\n", att_file_path); + cJSON* json = read_json_file(att_file_path); + + if (json == NULL) { + LOG("Endorsement file not found or file format incorrect. Creating a " + "random endorsement id (key and code hash pair)\n"); + + // Init new random key and code hash + random_getrandom(attestation_id.key, sizeof(attestation_id.key), 0); + random_getrandom( + attestation_id.code_hash, sizeof(attestation_id.code_hash), 0); + + // Write attestation id to the file + if (!write_attestation_id_file(att_file_path)) { + LOG("Error writing attestation id to %s\n", att_file_path); + return false; + } + LOG("Attestation id created and saved to %s\n", att_file_path); + } else { + // Load attestation id into memory + if (!cJSON_IsObject(json)) { + LOG("Expected an object as top level element of %s\n", + att_file_path); + return false; + } + + // Read attestation key + if (!read_hex_value_into( + json, ATTESTATION_KEY_KEY, attestation_id.key)) { + LOG("'%s' not found in '%s'\n", ATTESTATION_KEY_KEY, att_file_path); + return false; + } + + // Read code hash + if (!read_hex_value_into( + json, CODE_HASH_KEY, attestation_id.code_hash)) { + LOG("'%s' not found in '%s'\n", CODE_HASH_KEY, att_file_path); + return false; + } + } + + // Grab attestation id public key + unsigned char pubkey[PUBKEY_CMP_LENGTH]; + if (seed_derive_pubkey_format(attestation_id.key, pubkey, true) != + PUBKEY_CMP_LENGTH) { + LOG("Error getting compressed public key for attestation id key\n"); + return false; + } + LOG("Loaded attestation id:\n"); + LOG("\tPublic key: "); + for (int i = 0; i < sizeof(pubkey); i++) + LOG("%02x", pubkey[i]); + LOG("\n"); + LOG("\tCode hash: "); + for (int i = 0; i < sizeof(attestation_id.code_hash); i++) + LOG("%02x", attestation_id.code_hash[i]); + LOG("\n"); + + return true; +} + +bool endorsement_sign(uint8_t* msg, + size_t msg_size, + uint8_t* signature_out, + uint8_t* signature_out_length) { + + uint8_t pubkey[PUBKEY_UNCMP_LENGTH]; + uint8_t tweak[HMAC_SHA256_SIZE]; + uint8_t hash[HASH_LENGTH]; + + if (*signature_out_length < MAX_SIGNATURE_LENGTH) { + return false; + } + + sha256(msg, msg_size, hash, sizeof(hash)); + + if (seed_derive_pubkey_format(attestation_id.key, pubkey, false) != + sizeof(pubkey)) { + LOG("Error deriving public key for endorsement\n"); + return false; + } + + if (hmac_sha256(attestation_id.code_hash, + sizeof(attestation_id.code_hash), + pubkey, + sizeof(pubkey), + tweak, + sizeof(tweak)) != sizeof(tweak)) { + LOG("Error computing tweak for endorsement\n"); + return false; + } + + if (*signature_out_length < MAX_SIGNATURE_LENGTH) { + LOG("Output buffer for signature too small: %u bytes\n", + *signature_out_length); + return false; + } + + *signature_out_length = + tweak_sign(attestation_id.key, tweak, hash, signature_out); + + return true; +} + +bool endorsement_get_code_hash(uint8_t* code_hash_out, + uint8_t* code_hash_out_length) { + + if (*code_hash_out_length < HASH_LENGTH) { + LOG("Output buffer for code hash too small: %u bytes\n", + *code_hash_out_length); + return false; + } + + memmove(code_hash_out, + attestation_id.code_hash, + sizeof(attestation_id.code_hash)); + *code_hash_out_length = sizeof(attestation_id.code_hash); + + return true; +} + +bool endorsement_get_public_key(uint8_t* public_key_out, + uint8_t* public_key_out_length) { + uint8_t tempbuf[PUBKEY_UNCMP_LENGTH]; + + if (*public_key_out_length < PUBKEY_UNCMP_LENGTH) { + LOG("Output buffer for public key too small: %u bytes\n", + *public_key_out_length); + return false; + } + + *public_key_out_length = + seed_derive_pubkey_format(attestation_id.key, tempbuf, false); + memcpy(public_key_out, tempbuf, *public_key_out_length); + + return true; +} \ No newline at end of file diff --git a/ledger/src/tcpsigner/os_exceptions.c b/firmware/src/hal/src/x86/exceptions.c similarity index 96% rename from ledger/src/tcpsigner/os_exceptions.c rename to firmware/src/hal/src/x86/exceptions.c index a4533a93..64269f06 100644 --- a/ledger/src/tcpsigner/os_exceptions.c +++ b/firmware/src/hal/src/x86/exceptions.c @@ -44,7 +44,11 @@ * (https://github.com/LedgerHQ/nanos-secure-sdk/blob/nanos-1314/include/os.h) */ -#include "os_exceptions.h" +#ifndef HSM_PLATFORM_X86 +#define HSM_PLATFORM_X86 +#endif + +#include "hal/exceptions.h" static try_context_t G_try_last_open_context_var; diff --git a/ledger/src/tcpsigner/hsmsim_explicit_bzero.c b/firmware/src/hal/src/x86/explicit_bzero.c similarity index 95% rename from ledger/src/tcpsigner/hsmsim_explicit_bzero.c rename to firmware/src/hal/src/x86/explicit_bzero.c index 29905058..8ccec7a4 100644 --- a/ledger/src/tcpsigner/hsmsim_explicit_bzero.c +++ b/firmware/src/hal/src/x86/explicit_bzero.c @@ -42,9 +42,9 @@ Architecture-specific implementations also need to define __explicit_bzero_chk. */ -#include "hsmsim_explicit_bzero.h" +#include "explicit_bzero.h" -#ifdef __HSMSIM_EXPLICIT_BZERO_H +#ifdef __HSM_CUSTOM_EXPLICIT_BZERO_H /* Set LEN bytes of S to 0. The compiler will not delete a call to this function, even if S is dead after the call. */ @@ -54,4 +54,4 @@ void explicit_bzero(void *s, size_t len) { asm volatile("" ::: "memory"); } -#endif // __HSMSIM_EXPLICIT_BZERO_H +#endif // __HSM_CUSTOM_EXPLICIT_BZERO_H diff --git a/ledger/src/tcpsigner/hsmsim_explicit_bzero.h b/firmware/src/hal/src/x86/explicit_bzero.h similarity index 95% rename from ledger/src/tcpsigner/hsmsim_explicit_bzero.h rename to firmware/src/hal/src/x86/explicit_bzero.h index 49779507..62a6731d 100644 --- a/ledger/src/tcpsigner/hsmsim_explicit_bzero.h +++ b/firmware/src/hal/src/x86/explicit_bzero.h @@ -49,12 +49,12 @@ #pragma message "Using ad-hoc explicit_bzero" -#ifndef __HSMSIM_EXPLICIT_BZERO_H -#define __HSMSIM_EXPLICIT_BZERO_H +#ifndef __HSM_CUSTOM_EXPLICIT_BZERO_H +#define __HSM_CUSTOM_EXPLICIT_BZERO_H #include void explicit_bzero(void *s, size_t len); -#endif // __HSMSIM_EXPLICIT_BZERO_H +#endif // __HSM_CUSTOM_EXPLICIT_BZERO_H #endif diff --git a/firmware/src/hal/src/x86/hash.c b/firmware/src/hal/src/x86/hash.c new file mode 100644 index 00000000..39b43f93 --- /dev/null +++ b/firmware/src/hal/src/x86/hash.c @@ -0,0 +1,86 @@ +/** + * The MIT License (MIT) + * + * Copyright (c) 2021 RSK Labs Ltd + * + * 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 "hal/hash.h" +#include "sha256.h" +#include "keccak256.h" + +// *** sha256 *** +bool hash_sha256_init(hash_sha256_ctx_t* ctx) { + sha256_init(ctx); + return true; +} + +bool hash_sha256_update(hash_sha256_ctx_t* ctx, + const uint8_t* data, + size_t len) { + sha256_update(ctx, data, len); + return true; +} + +bool hash_sha256_final(hash_sha256_ctx_t* ctx, uint8_t* out_hash) { + sha256_final(ctx, out_hash); + return true; +} + +// *** sha256 with midstate support *** +bool hash_sha256_ms_init(hash_sha256_ms_ctx_t* ctx) { + sha256_init(ctx); + return true; +} + +bool hash_sha256_ms_midstate(hash_sha256_ms_ctx_t* ctx, uint8_t* midstate) { + sha256_midstate(ctx, midstate); + return true; +} + +bool hash_sha256_ms_update(hash_sha256_ms_ctx_t* ctx, + const uint8_t* data, + size_t len) { + sha256_update(ctx, data, len); + return true; +} + +bool hash_sha256_ms_final(hash_sha256_ms_ctx_t* ctx, uint8_t* out_hash) { + sha256_final(ctx, out_hash); + return true; +} + +// *** keccak256 *** +bool hash_keccak256_init(hash_keccak256_ctx_t* ctx) { + keccak_init(ctx); + return true; +} + +bool hash_keccak256_update(hash_keccak256_ctx_t* ctx, + const uint8_t* data, + size_t len) { + keccak_update(ctx, data, len); + return true; +} + +bool hash_keccak256_final(hash_keccak256_ctx_t* ctx, uint8_t* out_hash) { + keccak_final(ctx, out_hash); + return true; +} \ No newline at end of file diff --git a/ledger/src/tcpsigner/hex_reader.c b/firmware/src/hal/src/x86/hex_reader.c similarity index 100% rename from ledger/src/tcpsigner/hex_reader.c rename to firmware/src/hal/src/x86/hex_reader.c diff --git a/ledger/src/tcpsigner/hex_reader.h b/firmware/src/hal/src/x86/hex_reader.h similarity index 100% rename from ledger/src/tcpsigner/hex_reader.h rename to firmware/src/hal/src/x86/hex_reader.h diff --git a/ledger/src/tcpsigner/hmac_sha256.c b/firmware/src/hal/src/x86/hmac_sha256.c similarity index 100% rename from ledger/src/tcpsigner/hmac_sha256.c rename to firmware/src/hal/src/x86/hmac_sha256.c diff --git a/ledger/src/tcpsigner/hmac_sha256.h b/firmware/src/hal/src/x86/hmac_sha256.h similarity index 100% rename from ledger/src/tcpsigner/hmac_sha256.h rename to firmware/src/hal/src/x86/hmac_sha256.h diff --git a/ledger/src/tcpsigner/json.c b/firmware/src/hal/src/x86/json.c similarity index 95% rename from ledger/src/tcpsigner/json.c rename to firmware/src/hal/src/x86/json.c index cee86d94..dac51319 100644 --- a/ledger/src/tcpsigner/json.c +++ b/firmware/src/hal/src/x86/json.c @@ -28,7 +28,7 @@ #include // Read a JSON file into memory -cJSON* read_json_file(char* file_path) { +cJSON* read_json_file(const char* file_path) { FILE* key_file; char* buffer; long file_size; @@ -63,7 +63,7 @@ cJSON* read_json_file(char* file_path) { } // Write JSON from memory to disk -bool write_json_file(char* file_path, cJSON* json) { +bool write_json_file(const char* file_path, cJSON* json) { FILE* key_file = fopen(file_path, "w"); if (key_file == NULL) return false; diff --git a/ledger/src/tcpsigner/json.h b/firmware/src/hal/src/x86/json.h similarity index 92% rename from ledger/src/tcpsigner/json.h rename to firmware/src/hal/src/x86/json.h index 079c47b6..e0d146b0 100644 --- a/ledger/src/tcpsigner/json.h +++ b/firmware/src/hal/src/x86/json.h @@ -29,8 +29,8 @@ #include #include "cJSON.h" -cJSON* read_json_file(char* file_path); +cJSON* read_json_file(const char* file_path); -bool write_json_file(char* file_path, cJSON* json); +bool write_json_file(const char* file_path, cJSON* json); #endif // __SIMULATOR_JSON_H diff --git a/ledger/src/signer/src/keccak256.c b/firmware/src/hal/src/x86/keccak256.c similarity index 100% rename from ledger/src/signer/src/keccak256.c rename to firmware/src/hal/src/x86/keccak256.c diff --git a/ledger/src/signer/src/keccak256.h b/firmware/src/hal/src/x86/keccak256.h similarity index 100% rename from ledger/src/signer/src/keccak256.h rename to firmware/src/hal/src/x86/keccak256.h diff --git a/ledger/src/tcpsigner/os.h b/firmware/src/hal/src/x86/log.c similarity index 68% rename from ledger/src/tcpsigner/os.h rename to firmware/src/hal/src/x86/log.c index 4aaba444..3eb673cd 100644 --- a/ledger/src/tcpsigner/os.h +++ b/firmware/src/hal/src/x86/log.c @@ -22,28 +22,32 @@ * IN THE SOFTWARE. */ -#ifndef __SIMULATOR_OS_H -#define __SIMULATOR_OS_H - -#include "os_hash.h" -#include "os_attestation.h" -#include "os_ecdsa.h" -#include "os_exceptions.h" -#include "os_io.h" - -#include "hsmsim_explicit_bzero.h" - -/** - * Miscellaneous - */ -#define PIC(x) (x) - -void os_memmove(void *dst, const void *src, unsigned int length); - -unsigned int os_perso_isonboarded(); - -unsigned int os_global_pin_retries(); - -void nvm_write(void *dst_adr, void *src_adr, unsigned int src_len); - -#endif // __SIMULATOR_OS_H +#ifdef HSM_PLATFORM_X86 + +#include +#include +#include + +void LOG(const char *format, ...) { + va_list args; + va_start(args, format); + + vprintf(format, args); + + va_end(args); +} + +void LOG_HEX(const char *prefix, void *buffer, size_t size) { + printf("%s ", prefix); + if (size > 0) { + printf("0x"); + for (unsigned int i = 0; i < size; i++) { + printf("%02x", ((unsigned char *)buffer)[i]); + } + } else { + printf("EMPTY"); + } + printf("\n"); +} + +#endif \ No newline at end of file diff --git a/ledger/src/tcpsigner/os.c b/firmware/src/hal/src/x86/nvmem.c similarity index 71% rename from ledger/src/tcpsigner/os.c rename to firmware/src/hal/src/x86/nvmem.c index 6e6da8c9..8d41edec 100644 --- a/ledger/src/tcpsigner/os.c +++ b/firmware/src/hal/src/x86/nvmem.c @@ -22,31 +22,31 @@ * IN THE SOFTWARE. */ -#include +#include "hal/nvmem.h" +#include "hal/log.h" -#include "os.h" -#include "hsmsim_admin.h" +#include +#include -void os_memmove(void *dst, const void *src, unsigned int length) { - memmove(dst, src, length); -} +static nvmmem_stats_t nvmmem_stats; -unsigned int os_perso_isonboarded() { - return hsmsim_admin_get_is_onboarded(); +void nvmem_stats_reset() { + memset(&nvmmem_stats, 0, sizeof(nvmmem_stats)); + LOG("NVM stats reset OK.\n"); } -unsigned int os_global_pin_retries(void) { - return HSMSIM_RETRIES; +nvmmem_stats_t nvmem_get_stats() { + return nvmmem_stats; } -void nvm_write(void *dst_adr, void *src_adr, unsigned int src_len) { - if (src_adr == NULL) { +bool nvmem_write(void *dst, void *src, unsigned int length) { + if (src == NULL) { // Treat as memory reset - memset(dst_adr, 0, src_len); + memset(dst, 0, length); } else { // Treat as normal copy - memmove(dst_adr, src_adr, src_len); + memmove(dst, src, length); } // Log the write - hsmsim_admin_nvm_record_write(); -} + nvmmem_stats.write_count++; +} \ No newline at end of file diff --git a/ledger/src/tcpsigner/os_io_seproxyhal.c b/firmware/src/hal/src/x86/platform.c similarity index 82% rename from ledger/src/tcpsigner/os_io_seproxyhal.c rename to firmware/src/hal/src/x86/platform.c index c6e43702..5cf96a53 100644 --- a/ledger/src/tcpsigner/os_io_seproxyhal.c +++ b/firmware/src/hal/src/x86/platform.c @@ -22,11 +22,16 @@ * IN THE SOFTWARE. */ -#include "os_io_seproxyhal.h" -#include "os_io.h" -#include "log.h" +#include "hal/platform.h" +#include "hal/log.h" -void os_sched_exit(unsigned int exit_code) { +#include + +void platform_memmove(void *dst, const void *src, unsigned int length) { + memmove(dst, src, length); +} + +void platform_request_exit() { // Currently unsupported, just log the call - info("os_sched_exit called with argument %u\n"); + LOG("platform_request_exit called\n"); } \ No newline at end of file diff --git a/ledger/src/tcpsigner/hsmsim_random.c b/firmware/src/hal/src/x86/random.c similarity index 91% rename from ledger/src/tcpsigner/hsmsim_random.c rename to firmware/src/hal/src/x86/random.c index 6b5aff83..c01c6554 100644 --- a/ledger/src/tcpsigner/hsmsim_random.c +++ b/firmware/src/hal/src/x86/random.c @@ -22,12 +22,11 @@ * IN THE SOFTWARE. */ -#include "hsmsim_random.h" +#include "random.h" -#include #include #include -void getrandom(void *buffer, size_t length, unsigned int flags) { +void random_getrandom(void *buffer, size_t length, unsigned int flags) { syscall(SYS_getrandom, buffer, length, 0); -} +} \ No newline at end of file diff --git a/ledger/src/tcpsigner/hsmsim_random.h b/firmware/src/hal/src/x86/random.h similarity index 89% rename from ledger/src/tcpsigner/hsmsim_random.h rename to firmware/src/hal/src/x86/random.h index f5f5a970..f20fa992 100644 --- a/ledger/src/tcpsigner/hsmsim_random.h +++ b/firmware/src/hal/src/x86/random.h @@ -22,6 +22,11 @@ * IN THE SOFTWARE. */ +#ifndef __HAL_RANDOM_H +#define __HAL_RANDOM_H + #include -void getrandom(void *buffer, size_t length, unsigned int flags); +void random_getrandom(void *buffer, size_t length, unsigned int flags); + +#endif // __HAL_RANDOM_H \ No newline at end of file diff --git a/firmware/src/hal/src/x86/seed.c b/firmware/src/hal/src/x86/seed.c new file mode 100644 index 00000000..7d291b29 --- /dev/null +++ b/firmware/src/hal/src/x86/seed.c @@ -0,0 +1,267 @@ +/** + * The MIT License (MIT) + * + * Copyright (c) 2021 RSK Labs Ltd + * + * 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 +#include +#include +#include +#include + +#include "hal/constants.h" +#include "hal/seed.h" +#include "hal/log.h" +#include "random.h" + +#include "json.h" +#include "bip32.h" +#include "cJSON.h" +#include "hex_reader.h" + +#define SEED_DEFAULT_IS_ONBOARDED (true) + +typedef struct private_key_mapping_s { + const char* bip32_path; + uint8_t binary_path[BIP32_PATH_LENGTH]; + uint8_t key[PRIVATE_KEY_LENGTH]; +} private_key_mapping_t; + +static seed_data_t seed_data; +static secp256k1_context* sp_ctx = NULL; + +#define MAX_PRIVATE_KEYS 10 +static private_key_mapping_t private_keys[MAX_PRIVATE_KEYS]; +static unsigned int total_private_keys = 0; + +/** + * Write current private keys in JSON-format to the given path + */ +static bool write_key_file(const char* key_file_path) { + cJSON* json = cJSON_CreateObject(); + char hex_key[sizeof(private_keys[0].key) * 2 + 1]; + + for (int i = 0; i < total_private_keys; i++) { + for (int j = 0; j < sizeof(private_keys[0].key); j++) + sprintf(hex_key + j * 2, "%02x", private_keys[i].key[j]); + hex_key[sizeof(hex_key) - 1] = '\0'; + cJSON* json_hex_key = cJSON_CreateString(hex_key); + cJSON_AddStringToObject(json, private_keys[i].bip32_path, hex_key); + } + + return write_json_file(key_file_path, json); +} + +/** + * Get the key corresponding to the given path + */ +static bool get_key(uint32_t* path, uint8_t path_length, unsigned char* dest) { + // TODO: validate path length + bool found = false; + for (int i = 0; i < total_private_keys; i++) { + // Compare paths, skip first byte of stored path (length, not included + // in the path parameter) + if (!memcmp( + path, private_keys[i].binary_path + 1, BIP32_PATH_LENGTH - 1)) { + found = true; + memmove(dest, private_keys[i].key, sizeof(private_keys[i].key)); + break; + } + } + return found; +} + +uint8_t seed_derive_pubkey_format(const unsigned char* key, + unsigned char* dest, + bool compressed) { + secp256k1_pubkey pubkey; + size_t dest_size = compressed ? PUBKEY_CMP_LENGTH : PUBKEY_UNCMP_LENGTH; + + // Calculate the public key and serialize it according to + // the compressed argument + if (!secp256k1_ec_pubkey_create(sp_ctx, &pubkey, key)) { + return 0; + } + + secp256k1_ec_pubkey_serialize(sp_ctx, + dest, + &dest_size, + &pubkey, + compressed ? SECP256K1_EC_COMPRESSED + : SECP256K1_EC_UNCOMPRESSED); + + return (uint8_t)dest_size; +} + +static bool add_bip32_path(const char* bip32_path) { + private_keys[total_private_keys].bip32_path = bip32_path; + uint8_t* bpath = private_keys[total_private_keys].binary_path; + if (bip32_parse_path(bip32_path, bpath) != BIP32_PATH_LENGTH) { + LOG("Invalid BIP32 path given: %s\n", bip32_path); + return false; + } + total_private_keys++; + return true; +} + +bool seed_init(const char* key_file_path, + const char* bip32_paths[], + const size_t bip32_paths_count) { + // Init the secp256k1 context + if (!sp_ctx) + sp_ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); + + // Initialize the onboarded value + seed_data.is_onboarded = SEED_DEFAULT_IS_ONBOARDED; + + // Configure BIP32 paths + for (int i = 0; i < bip32_paths_count; i++) { + if (!add_bip32_path((const char*)(bip32_paths[i]))) { + LOG("Error during seed initialization when trying to add path: " + "%s\n", + bip32_paths[i]); + return false; + } + } + + // Load keys + LOG("Loading key file '%s'\n", key_file_path); + cJSON* json = read_json_file(key_file_path); + + if (json == NULL) { + LOG("Keyfile not found or file format incorrect. Creating a new " + "random set of keys\n"); + // Init new random keys + for (int i = 0; i < total_private_keys; i++) { + random_getrandom( + private_keys[i].key, sizeof(private_keys[i].key), 0); + } + + // Write keys to the file + if (!write_key_file(key_file_path)) { + LOG("Error writing keys to %s\n", key_file_path); + return false; + } + LOG("Keys created and saved to %s\n", key_file_path); + } else { + // Load keys into memory + if (!cJSON_IsObject(json)) { + LOG("Expected an object as top level element of %s\n", + key_file_path); + return false; + } + + for (int i = 0; i < total_private_keys; i++) { + cJSON* key_entry = cJSON_GetObjectItemCaseSensitive( + json, private_keys[i].bip32_path); + if (key_entry == NULL || !cJSON_IsString(key_entry)) { + LOG("Path \"%s\" not found in \"%s\"\n", + bip32_paths[i], + key_file_path); + return false; + } + char* hex_key = cJSON_GetStringValue(key_entry); + read_hex(hex_key, strlen(hex_key), private_keys[i].key); + } + } + + unsigned char pubkey[PUBKEY_CMP_LENGTH]; + LOG("Loaded keys:\n"); + for (int i = 0; i < total_private_keys; i++) { + if (seed_derive_pubkey_format(private_keys[i].key, pubkey, true) != + PUBKEY_CMP_LENGTH) { + LOG("Error getting public key for path \"%s\"\n", + private_keys[i].bip32_path); + return false; + } + LOG("\t%s: ", private_keys[i].bip32_path); + for (int j = 0; j < sizeof(pubkey); j++) + LOG("%02x", pubkey[j]); + LOG("\n"); + } + + return true; +} + +void seed_set_is_onboarded(bool is_onboarded) { + seed_data.is_onboarded = is_onboarded; +} + +bool seed_available() { + return seed_data.is_onboarded; +} + +bool seed_derive_pubkey(uint32_t* path, + uint8_t path_length, + uint8_t* pubkey_out, + uint8_t* pubkey_out_length) { + + uint8_t key[PRIVATE_KEY_LENGTH]; + if (!get_key(path, path_length, key)) { + LOG("Invalid path given: %s\n", (unsigned char*)path); + return false; + } + + if (*pubkey_out_length < PUBKEY_CMP_LENGTH) { + LOG("Output buffer for public key too small: %u bytes\n", + *pubkey_out_length); + return false; + } + + *pubkey_out_length = seed_derive_pubkey_format(key, pubkey_out, false); + if (!(*pubkey_out_length)) { + LOG("Error deriving public key for path: %s\n", (unsigned char*)path); + return false; + } + + return true; +} + +bool seed_sign(uint32_t* path, + uint8_t path_length, + uint8_t* hash32, + uint8_t* sig_out, + uint8_t* sig_out_length) { + + secp256k1_ecdsa_signature sp_sig; + size_t sig_serialized_size = MAX_SIGNATURE_LENGTH; + + uint8_t key[PRIVATE_KEY_LENGTH]; + if (!get_key(path, path_length, key)) { + LOG("Invalid path given: %s\n", (unsigned char*)path); + return false; + } + + if (*sig_out_length < MAX_SIGNATURE_LENGTH) { + LOG("Output buffer for signature too small: %u bytes\n", + *sig_out_length); + return false; + } + + // Sign and serialize as DER + secp256k1_ecdsa_sign(sp_ctx, &sp_sig, hash32, key, NULL, NULL); + secp256k1_ecdsa_signature_serialize_der( + sp_ctx, sig_out, &sig_serialized_size, &sp_sig); + *sig_out_length = (uint8_t)sig_serialized_size; + + return true; +} diff --git a/firmware/src/hal/src/x86/sha256.c b/firmware/src/hal/src/x86/sha256.c new file mode 120000 index 00000000..a21d1a59 --- /dev/null +++ b/firmware/src/hal/src/x86/sha256.c @@ -0,0 +1 @@ +../common/sha256.c \ No newline at end of file diff --git a/firmware/src/hal/src/x86/sha256.h b/firmware/src/hal/src/x86/sha256.h new file mode 120000 index 00000000..65492ab2 --- /dev/null +++ b/firmware/src/hal/src/x86/sha256.h @@ -0,0 +1 @@ +../common/sha256.h \ No newline at end of file diff --git a/firmware/src/hal/test/bip32/Makefile b/firmware/src/hal/test/bip32/Makefile new file mode 100644 index 00000000..d6b661c3 --- /dev/null +++ b/firmware/src/hal/test/bip32/Makefile @@ -0,0 +1,42 @@ +# The MIT License (MIT) +# +# Copyright (c) 2021 RSK Labs Ltd +# +# 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 ../common.mk + +ifneq ($(DEBUG),) + CFLAGS += -DDEBUG_BIP32 +endif + +PROG = test.out +OBJS = bip32.o test_bip32.o log.o + +all: $(PROG) + +$(PROG): $(OBJS) + $(CC) $(COVFLAGS) -o $@ $^ + +.PHONY: clean test +clean: + rm -f $(PROG) ./*.o $(COVFILES) + +test: all + ./$(PROG) diff --git a/firmware/src/hal/test/bip32/test_bip32.c b/firmware/src/hal/test/bip32/test_bip32.c new file mode 100644 index 00000000..cae7a116 --- /dev/null +++ b/firmware/src/hal/test/bip32/test_bip32.c @@ -0,0 +1,120 @@ +/** + * The MIT License (MIT) + * + * Copyright (c) 2021 RSK Labs Ltd + * + * 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 +#include +#include + +#include "bip32.h" + +void test_parses_correctly(const char* path, + const uint32_t expected_parts[], + const size_t expected_parts_count) { + + printf("Testing path \"%s\" is parsed correctly... ", path); + fflush(stdout); + + uint8_t binpath[5 * sizeof(uint32_t) + 1]; + size_t binpathlen = bip32_parse_path(path, binpath); + + // Return value + assert(binpathlen == expected_parts_count * sizeof(uint32_t) + 1); + + // First byte should be the number of parts + assert(binpath[0] == (uint8_t)expected_parts_count); + + uint32_t* parts = (uint32_t*)(&binpath[1]); + + // Validate parts + for (int i = 0; i < expected_parts_count; i++) { + assert(parts[i] == expected_parts[i]); + } + + printf("OK!\n"); +} + +void test_parsing_fails(const char* path) { + uint8_t binpath[5 * sizeof(uint32_t) + 1]; + + printf("Testing path \"%s\" parsing fails... ", path); + fflush(stdout); + + assert(!bip32_parse_path(path, binpath)); + + printf("OK!\n"); +} + +int main() { + test_parses_correctly("m/0/0/0/0/0", (const uint32_t[]){0, 0, 0, 0, 0}, 5); + test_parses_correctly( + "m/10/20/30/40/50", (const uint32_t[]){10, 20, 30, 40, 50}, 5); + + // PowHSM authorized paths + test_parses_correctly( + "m/44'/0'/0'/0/0", + (const uint32_t[]){0x8000002c, 0x80000000, 0x80000000, 0, 0}, + 5); + + test_parses_correctly( + "m/44'/1'/0'/0/0", + (const uint32_t[]){0x8000002c, 0x80000001, 0x80000000, 0, 0}, + 5); + + test_parses_correctly( + "m/44'/1'/1'/0/0", + (const uint32_t[]){0x8000002c, 0x80000001, 0x80000001, 0, 0}, + 5); + + test_parses_correctly( + "m/44'/1'/2'/0/0", + (const uint32_t[]){0x8000002c, 0x80000001, 0x80000002, 0, 0}, + 5); + + test_parses_correctly( + "m/44'/137'/0'/0/0", + (const uint32_t[]){0x8000002c, 0x80000089, 0x80000000, 0, 0}, + 5); + + test_parses_correctly( + "m/44'/137'/1'/0/0", + (const uint32_t[]){0x8000002c, 0x80000089, 0x80000001, 0, 0}, + 5); + + // Some failure cases + test_parsing_fails("somethingelse"); + test_parsing_fails("f/0/0/0/0/0"); + test_parsing_fails("m/0/0/0/0/0/0"); + test_parsing_fails("m/0/0/0/0/1suffix"); + test_parsing_fails("m/123/notanumber/0/0/0"); + + // Part limits + test_parses_correctly("m/2147483647/0/0/0/2147483647'", + (const uint32_t[]){0x7fffffff, 0, 0, 0, 0xffffffff}, + 5); + test_parsing_fails("m/2147483648/0/0/0/0"); + test_parsing_fails("m/2147483648'/0/0/0/0"); + test_parsing_fails("m/01234567890/0/0/0/0"); + + return 0; +} \ No newline at end of file diff --git a/firmware/src/hal/test/common.mk b/firmware/src/hal/test/common.mk new file mode 100644 index 00000000..4d2a8ea3 --- /dev/null +++ b/firmware/src/hal/test/common.mk @@ -0,0 +1,32 @@ +# The MIT License (MIT) +# +# Copyright (c) 2021 RSK Labs Ltd +# +# 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. + +INCDIR = ../../include +SRCDIR = ../../src/x86 +CFLAGS = -iquote $(INCDIR) -iquote $(SRCDIR) +CFLAGS += -DHSM_PLATFORM_X86 + +include ../../../../coverage/coverage.mk + +CFLAGS += $(COVFLAGS) + +VPATH += $(SRCDIR):$(INCDIR) diff --git a/ledger/src/tcpsigner/test/hmac_sha256/Makefile b/firmware/src/hal/test/hmac_sha256/Makefile similarity index 75% rename from ledger/src/tcpsigner/test/hmac_sha256/Makefile rename to firmware/src/hal/test/hmac_sha256/Makefile index c8b76dcb..08c87864 100644 --- a/ledger/src/tcpsigner/test/hmac_sha256/Makefile +++ b/firmware/src/hal/test/hmac_sha256/Makefile @@ -20,9 +20,7 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -SRCDIR = ../.. -SIGNERSRCDIR = ../../../signer/src -CFLAGS = -I $(SRCDIR) -I $(SIGNERSRCDIR) +include ../common.mk PROG = test.out OBJS = sha256.o hmac_sha256.o test_hmac_sha256.o @@ -30,22 +28,11 @@ OBJS = sha256.o hmac_sha256.o test_hmac_sha256.o all: $(PROG) $(PROG): $(OBJS) - $(CC) -o $@ $^ - -sha256.o: $(SIGNERSRCDIR)/sha256.c - $(CC) $(CFLAGS) -c -o $@ $^ - -hmac_sha256.o: $(SRCDIR)/hmac_sha256.c - $(CC) $(CFLAGS) -c -o $@ $^ - -test_sha256.o: test_sha256.c hmac_sha256.o sha256.o - -$(SRCDIR)/hmac_sha256.c: $(SRCDIR)/hmac_sha256.h -$(SIGNERSRCDIR)/sha256.c: $(SIGNERSRCDIR)/sha256.h + $(CC) $(COVFLAGS) -o $@ $^ .PHONY: clean test clean: - rm -f $(PROG) ./*.o + rm -f $(PROG) ./*.o $(COVFILES) test: all ./$(PROG) diff --git a/ledger/src/tcpsigner/test/hmac_sha256/test_hmac_sha256.c b/firmware/src/hal/test/hmac_sha256/test_hmac_sha256.c similarity index 100% rename from ledger/src/tcpsigner/test/hmac_sha256/test_hmac_sha256.c rename to firmware/src/hal/test/hmac_sha256/test_hmac_sha256.c diff --git a/ledger/src/ui/test/run-all.sh b/firmware/src/hal/test/run-all.sh similarity index 70% rename from ledger/src/ui/test/run-all.sh rename to firmware/src/hal/test/run-all.sh index b13403c3..48b5e871 100755 --- a/ledger/src/ui/test/run-all.sh +++ b/firmware/src/hal/test/run-all.sh @@ -1,6 +1,6 @@ #!/bin/bash BASEDIR=$(dirname $0) -TESTDIRS="attestation signer_authorization communication onboard pin unlock bootloader ux_handlers ui_heartbeat" +TESTDIRS="bip32 hmac_sha256" TESTDIRS=${1:-"$TESTDIRS"} for d in $TESTDIRS; do diff --git a/ledger/src/signer/Makefile b/firmware/src/ledger/signer/Makefile similarity index 93% rename from ledger/src/signer/Makefile rename to firmware/src/ledger/signer/Makefile index aff44a18..1a7150b9 100755 --- a/ledger/src/signer/Makefile +++ b/firmware/src/ledger/signer/Makefile @@ -44,13 +44,13 @@ include $(BOLOS_SDK)/Makefile.defines # Main app configuration APPNAME = "RSK Sign" -APPVERSION = 4 +APPVERSION = 5 # No flags APPFLAGS = 0x00 PROG = "app" # Build configuration -APP_SOURCE_PATH += src ../common/src +APP_SOURCE_PATH += src ../../powhsm/src ../../common/src ../../hal/src/ledger SDK_SOURCE_PATH += lib_stusb lib_stusb_impl DEFINES += APPVERSION=\"$(APPVERSION)\" @@ -65,6 +65,7 @@ DEFINES += HAVE_IO_USB HAVE_L4_USBLIB IO_USB_MAX_ENDPOINTS=3 IO_HID_EP_LENGTH=64 CC := $(CLANGPATH)clang CFLAGS += -O0 -I$(GCC_INCLUDE) CFLAGS += -Werror +CFLAGS += -DHSM_PLATFORM_LEDGER # Convert min required difficulty to what the compiler expects ifneq ($(TARGET_DIFFICULTY),) @@ -128,3 +129,7 @@ delete: # Import generic rules from the SDK include $(BOLOS_SDK)/Makefile.rules + +# This is to prevent individual subdirectory inclusion by using the +# SDK provided APP_SOURCE_PATH variable +INCLUDES_PATH += ../../hal/include diff --git a/ledger/src/signer/icon.gif b/firmware/src/ledger/signer/icon.gif similarity index 100% rename from ledger/src/signer/icon.gif rename to firmware/src/ledger/signer/icon.gif diff --git a/firmware/src/ledger/signer/icon.hex b/firmware/src/ledger/signer/icon.hex new file mode 100644 index 00000000..ba691e7e --- /dev/null +++ b/firmware/src/ledger/signer/icon.hex @@ -0,0 +1 @@ +0100000000ffffff000000c0014001c001ae3a9a2cae3ac4114411c411ae3a9a2cae3ac0014001c001 \ No newline at end of file diff --git a/ledger/src/signer/make-difficulty.py b/firmware/src/ledger/signer/make-difficulty.py similarity index 100% rename from ledger/src/signer/make-difficulty.py rename to firmware/src/ledger/signer/make-difficulty.py diff --git a/ledger/src/signer/make-initial-block-hash.py b/firmware/src/ledger/signer/make-initial-block-hash.py similarity index 100% rename from ledger/src/signer/make-initial-block-hash.py rename to firmware/src/ledger/signer/make-initial-block-hash.py diff --git a/ledger/src/signer/src/main.c b/firmware/src/ledger/signer/src/main.c similarity index 96% rename from ledger/src/signer/src/main.c rename to firmware/src/ledger/signer/src/main.c index 4599f973..7bdaebe8 100644 --- a/ledger/src/signer/src/main.c +++ b/firmware/src/ledger/signer/src/main.c @@ -43,7 +43,9 @@ #include "os_io_seproxyhal.h" #include "hsm.h" -#include "hsm-ledger.h" + +// HAL includes +#include "hal/communication.h" unsigned char G_io_seproxyhal_spi_buffer[IO_SEPROXYHAL_BUFFER_SIZE_B]; @@ -240,11 +242,17 @@ __attribute__((section(".boot"))) int main(int argc, char **argv) { // APDU buffer initialization os_memset(G_io_apdu_buffer, 0, sizeof(G_io_apdu_buffer)); + // HAL modules initialization + communication_init(G_io_apdu_buffer, sizeof(G_io_apdu_buffer)); + // HSM context initialization hsm_init(); // HSM main loop - hsm_ledger_main_loop(); + hsm_main_loop(); + + // HAL modules finalisation + // Nothing for now } CATCH_OTHER(e) { } diff --git a/ledger/src/ui/LICENSE b/firmware/src/ledger/ui/LICENSE similarity index 100% rename from ledger/src/ui/LICENSE rename to firmware/src/ledger/ui/LICENSE diff --git a/ledger/src/ui/Makefile b/firmware/src/ledger/ui/Makefile similarity index 98% rename from ledger/src/ui/Makefile rename to firmware/src/ledger/ui/Makefile index e0da592a..a5d361e5 100755 --- a/ledger/src/ui/Makefile +++ b/firmware/src/ledger/ui/Makefile @@ -42,7 +42,7 @@ ifeq ($(TARGET_ID),) TARGET_ID := $(shell cat $(BOLOS_SDK)/include/bolos_target.h | grep 0x | cut -f3 -d' ') endif APPNAME = UX -APPVERSION = 4 +APPVERSION = 5 VERSION = ux$(APPVERSION) # APPLICATION_FLAG_BOLOS_UX | APPLICATION_FLAG_GLOBAL_PIN | APPLICATION_FLAG_BOLOS_SETTINGS APPFLAGS = 0x248 @@ -84,7 +84,7 @@ CONFIG_PRODUCTIONS := bin/$(PROG) # Nano S ifeq ($(TARGET_ID)$(ONLY_LOAD),0x31100002) DEFINES += BOLOS_APP_ICON_SIZE_B=\(9+32\) -SOURCE_PATH := src src_common $(BOLOS_SDK)/src ../common/src +SOURCE_PATH := src src_common $(BOLOS_SDK)/src ../../common/src SOURCE_PATH += $(BOLOS_SDK)/lib_stusb $(BOLOS_SDK)/lib_stusb_impl SOURCE_PATH += $(BOLOS_SDK)/lib_stusb/STM32_USB_Device_Library/Class/HID/Src else ifeq ($(TARGET_ID),0x31000002) @@ -136,6 +136,7 @@ CFLAGS += -fdata-sections -ffunction-sections -funsigned-char -fshort-enums CFLAGS += -mno-unaligned-access CFLAGS += -Wno-unused-parameter -Wno-duplicate-decl-specifier CFLAGS += -Werror +CFLAGS += -DHSM_PLATFORM_LEDGER ifeq ($(DEBUG_BUILD),1) CFLAGS += -DDEBUG_BUILD=${DEBUG_BUILD} endif diff --git a/ledger/src/ui/glyphs/badge_back.gif b/firmware/src/ledger/ui/glyphs/badge_back.gif similarity index 100% rename from ledger/src/ui/glyphs/badge_back.gif rename to firmware/src/ledger/ui/glyphs/badge_back.gif diff --git a/ledger/src/ui/glyphs/badge_loading_v2.gif b/firmware/src/ledger/ui/glyphs/badge_loading_v2.gif similarity index 100% rename from ledger/src/ui/glyphs/badge_loading_v2.gif rename to firmware/src/ledger/ui/glyphs/badge_loading_v2.gif diff --git a/ledger/src/ui/glyphs/digit_0.gif b/firmware/src/ledger/ui/glyphs/digit_0.gif similarity index 100% rename from ledger/src/ui/glyphs/digit_0.gif rename to firmware/src/ledger/ui/glyphs/digit_0.gif diff --git a/ledger/src/ui/glyphs/digit_1.gif b/firmware/src/ledger/ui/glyphs/digit_1.gif similarity index 100% rename from ledger/src/ui/glyphs/digit_1.gif rename to firmware/src/ledger/ui/glyphs/digit_1.gif diff --git a/ledger/src/ui/glyphs/digit_2.gif b/firmware/src/ledger/ui/glyphs/digit_2.gif similarity index 100% rename from ledger/src/ui/glyphs/digit_2.gif rename to firmware/src/ledger/ui/glyphs/digit_2.gif diff --git a/ledger/src/ui/glyphs/digit_3.gif b/firmware/src/ledger/ui/glyphs/digit_3.gif similarity index 100% rename from ledger/src/ui/glyphs/digit_3.gif rename to firmware/src/ledger/ui/glyphs/digit_3.gif diff --git a/ledger/src/ui/glyphs/digit_4.gif b/firmware/src/ledger/ui/glyphs/digit_4.gif similarity index 100% rename from ledger/src/ui/glyphs/digit_4.gif rename to firmware/src/ledger/ui/glyphs/digit_4.gif diff --git a/ledger/src/ui/glyphs/digit_5.gif b/firmware/src/ledger/ui/glyphs/digit_5.gif similarity index 100% rename from ledger/src/ui/glyphs/digit_5.gif rename to firmware/src/ledger/ui/glyphs/digit_5.gif diff --git a/ledger/src/ui/glyphs/digit_6.gif b/firmware/src/ledger/ui/glyphs/digit_6.gif similarity index 100% rename from ledger/src/ui/glyphs/digit_6.gif rename to firmware/src/ledger/ui/glyphs/digit_6.gif diff --git a/ledger/src/ui/glyphs/digit_7.gif b/firmware/src/ledger/ui/glyphs/digit_7.gif similarity index 100% rename from ledger/src/ui/glyphs/digit_7.gif rename to firmware/src/ledger/ui/glyphs/digit_7.gif diff --git a/ledger/src/ui/glyphs/digit_8.gif b/firmware/src/ledger/ui/glyphs/digit_8.gif similarity index 100% rename from ledger/src/ui/glyphs/digit_8.gif rename to firmware/src/ledger/ui/glyphs/digit_8.gif diff --git a/ledger/src/ui/glyphs/digit_9.gif b/firmware/src/ledger/ui/glyphs/digit_9.gif similarity index 100% rename from ledger/src/ui/glyphs/digit_9.gif rename to firmware/src/ledger/ui/glyphs/digit_9.gif diff --git a/ledger/src/ui/glyphs/digit_dot.gif b/firmware/src/ledger/ui/glyphs/digit_dot.gif similarity index 100% rename from ledger/src/ui/glyphs/digit_dot.gif rename to firmware/src/ledger/ui/glyphs/digit_dot.gif diff --git a/ledger/src/ui/glyphs/digit_underscore.gif b/firmware/src/ledger/ui/glyphs/digit_underscore.gif similarity index 100% rename from ledger/src/ui/glyphs/digit_underscore.gif rename to firmware/src/ledger/ui/glyphs/digit_underscore.gif diff --git a/ledger/src/ui/glyphs/fish_left.gif b/firmware/src/ledger/ui/glyphs/fish_left.gif similarity index 100% rename from ledger/src/ui/glyphs/fish_left.gif rename to firmware/src/ledger/ui/glyphs/fish_left.gif diff --git a/ledger/src/ui/glyphs/fish_right.gif b/firmware/src/ledger/ui/glyphs/fish_right.gif similarity index 100% rename from ledger/src/ui/glyphs/fish_right.gif rename to firmware/src/ledger/ui/glyphs/fish_right.gif diff --git a/ledger/src/ui/glyphs/icon_backspace.gif b/firmware/src/ledger/ui/glyphs/icon_backspace.gif similarity index 100% rename from ledger/src/ui/glyphs/icon_backspace.gif rename to firmware/src/ledger/ui/glyphs/icon_backspace.gif diff --git a/ledger/src/ui/glyphs/icon_classes.gif b/firmware/src/ledger/ui/glyphs/icon_classes.gif similarity index 100% rename from ledger/src/ui/glyphs/icon_classes.gif rename to firmware/src/ledger/ui/glyphs/icon_classes.gif diff --git a/ledger/src/ui/glyphs/icon_dashboard.gif b/firmware/src/ledger/ui/glyphs/icon_dashboard.gif similarity index 100% rename from ledger/src/ui/glyphs/icon_dashboard.gif rename to firmware/src/ledger/ui/glyphs/icon_dashboard.gif diff --git a/ledger/src/ui/glyphs/icon_digits.gif b/firmware/src/ledger/ui/glyphs/icon_digits.gif similarity index 100% rename from ledger/src/ui/glyphs/icon_digits.gif rename to firmware/src/ledger/ui/glyphs/icon_digits.gif diff --git a/ledger/src/ui/glyphs/icon_lowercase.gif b/firmware/src/ledger/ui/glyphs/icon_lowercase.gif similarity index 100% rename from ledger/src/ui/glyphs/icon_lowercase.gif rename to firmware/src/ledger/ui/glyphs/icon_lowercase.gif diff --git a/ledger/src/ui/glyphs/icon_uppercase.gif b/firmware/src/ledger/ui/glyphs/icon_uppercase.gif similarity index 100% rename from ledger/src/ui/glyphs/icon_uppercase.gif rename to firmware/src/ledger/ui/glyphs/icon_uppercase.gif diff --git a/ledger/src/ui/glyphs/icon_validate.gif b/firmware/src/ledger/ui/glyphs/icon_validate.gif similarity index 100% rename from ledger/src/ui/glyphs/icon_validate.gif rename to firmware/src/ledger/ui/glyphs/icon_validate.gif diff --git a/ledger/src/ui/glyphs/icon_validate_bold.gif b/firmware/src/ledger/ui/glyphs/icon_validate_bold.gif similarity index 100% rename from ledger/src/ui/glyphs/icon_validate_bold.gif rename to firmware/src/ledger/ui/glyphs/icon_validate_bold.gif diff --git a/ledger/src/ui/icon.gif b/firmware/src/ledger/ui/icon.gif similarity index 100% rename from ledger/src/ui/icon.gif rename to firmware/src/ledger/ui/icon.gif diff --git a/firmware/src/ledger/ui/icon.hex b/firmware/src/ledger/ui/icon.hex new file mode 100644 index 00000000..228d1154 --- /dev/null +++ b/firmware/src/ledger/ui/icon.hex @@ -0,0 +1 @@ +0100000000ffffff0000002004100808100420fe7f02402248725c224992433a4112400240fe7f0000 \ No newline at end of file diff --git a/ledger/src/ui/make-initial-signer-hash.py b/firmware/src/ledger/ui/make-initial-signer-hash.py similarity index 100% rename from ledger/src/ui/make-initial-signer-hash.py rename to firmware/src/ledger/ui/make-initial-signer-hash.py diff --git a/ledger/src/ui/make-initial-signer-iteration.py b/firmware/src/ledger/ui/make-initial-signer-iteration.py similarity index 100% rename from ledger/src/ui/make-initial-signer-iteration.py rename to firmware/src/ledger/ui/make-initial-signer-iteration.py diff --git a/ledger/src/ui/script.ux.ld b/firmware/src/ledger/ui/script.ux.ld similarity index 100% rename from ledger/src/ui/script.ux.ld rename to firmware/src/ledger/ui/script.ux.ld diff --git a/ledger/src/ui/src/attestation.c b/firmware/src/ledger/ui/src/attestation.c similarity index 100% rename from ledger/src/ui/src/attestation.c rename to firmware/src/ledger/ui/src/attestation.c diff --git a/ledger/src/ui/src/attestation.h b/firmware/src/ledger/ui/src/attestation.h similarity index 98% rename from ledger/src/ui/src/attestation.h rename to firmware/src/ledger/ui/src/attestation.h index 9d2fb260..54a2e499 100644 --- a/ledger/src/ui/src/attestation.h +++ b/firmware/src/ledger/ui/src/attestation.h @@ -81,7 +81,7 @@ typedef struct { unsigned int msg_offset; unsigned char path[PUBKEY_PATH_LENGTH]; - unsigned char priv_key_data[SEED_LENGTH]; + unsigned char priv_key_data[PRIVATE_KEY_LENGTH]; cx_ecfp_private_key_t priv_key; cx_ecfp_public_key_t pub_key; } att_t; diff --git a/ledger/src/ui/src/bolos_ux.c b/firmware/src/ledger/ui/src/bolos_ux.c similarity index 100% rename from ledger/src/ui/src/bolos_ux.c rename to firmware/src/ledger/ui/src/bolos_ux.c diff --git a/ledger/src/ui/src/bolos_ux.h b/firmware/src/ledger/ui/src/bolos_ux.h similarity index 100% rename from ledger/src/ui/src/bolos_ux.h rename to firmware/src/ledger/ui/src/bolos_ux.h diff --git a/ledger/src/ui/src/bolos_ux_dashboard.c b/firmware/src/ledger/ui/src/bolos_ux_dashboard.c similarity index 100% rename from ledger/src/ui/src/bolos_ux_dashboard.c rename to firmware/src/ledger/ui/src/bolos_ux_dashboard.c diff --git a/ledger/src/ui/src/bolos_ux_not_personalized.c b/firmware/src/ledger/ui/src/bolos_ux_not_personalized.c similarity index 100% rename from ledger/src/ui/src/bolos_ux_not_personalized.c rename to firmware/src/ledger/ui/src/bolos_ux_not_personalized.c diff --git a/ledger/src/ui/src/bolos_ux_processing.c b/firmware/src/ledger/ui/src/bolos_ux_processing.c similarity index 100% rename from ledger/src/ui/src/bolos_ux_processing.c rename to firmware/src/ledger/ui/src/bolos_ux_processing.c diff --git a/ledger/src/ui/src/bolos_ux_settings.c b/firmware/src/ledger/ui/src/bolos_ux_settings.c similarity index 100% rename from ledger/src/ui/src/bolos_ux_settings.c rename to firmware/src/ledger/ui/src/bolos_ux_settings.c diff --git a/ledger/src/ui/src/bootloader.c b/firmware/src/ledger/ui/src/bootloader.c similarity index 98% rename from ledger/src/ui/src/bootloader.c rename to firmware/src/ledger/ui/src/bootloader.c index 22666126..8beedf37 100644 --- a/ledger/src/ui/src/bootloader.c +++ b/firmware/src/ledger/ui/src/bootloader.c @@ -22,7 +22,7 @@ * IN THE SOFTWARE. */ -#include +#include "bolos_ux_common.h" #include "apdu.h" #include "ux_handlers.h" @@ -30,7 +30,7 @@ #include "ui_instructions.h" #include "defs.h" #include "ui_err.h" -#include "communication.h" +#include "ui_comm.h" #include "unlock.h" // Attestation context shorthand @@ -206,7 +206,7 @@ void bootloader_main(bootloader_mode_t mode) { break; } CATCH_OTHER(e) { - tx = comm_process_exception(e, tx, &reset_state); + tx = ui_process_exception(e, tx, &reset_state); } FINALLY { } diff --git a/ledger/src/ui/src/bootloader.h b/firmware/src/ledger/ui/src/bootloader.h similarity index 100% rename from ledger/src/ui/src/bootloader.h rename to firmware/src/ledger/ui/src/bootloader.h diff --git a/ledger/src/tcpsigner/hsmsim_ecdsa.h b/firmware/src/ledger/ui/src/common_requirements.h similarity index 78% rename from ledger/src/tcpsigner/hsmsim_ecdsa.h rename to firmware/src/ledger/ui/src/common_requirements.h index c93ad616..e0763cbf 100644 --- a/ledger/src/tcpsigner/hsmsim_ecdsa.h +++ b/firmware/src/ledger/ui/src/common_requirements.h @@ -22,13 +22,15 @@ * IN THE SOFTWARE. */ -#ifndef __SIMULATOR_HSMSIM_ECDSA_H -#define __SIMULATOR_HSMSIM_ECDSA_H +#ifndef __COMMON_REQUIREMENTS_H +#define __COMMON_REQUIREMENTS_H -#include +#include -bool hsmsim_ecdsa_initialize(char* key_file_path); +#include "os.h" -bool hsmsim_ecdsa_get_key(unsigned char* path, unsigned char* dst_key); +#define communication_get_msg_buffer() (G_io_apdu_buffer) +#define communication_get_msg_buffer_size() (sizeof(G_io_apdu_buffer)) +#define platform_memmove(...) os_memmove(__VA_ARGS__) -#endif // __SIMULATOR_HSMSIM_ECDSA_H +#endif // __COMMON_REQUIREMENTS_H diff --git a/firmware/src/ledger/ui/src/constants.h b/firmware/src/ledger/ui/src/constants.h new file mode 120000 index 00000000..7a27783a --- /dev/null +++ b/firmware/src/ledger/ui/src/constants.h @@ -0,0 +1 @@ +../../../hal/include/hal/constants.h \ No newline at end of file diff --git a/ledger/src/ui/src/defs.h b/firmware/src/ledger/ui/src/defs.h similarity index 100% rename from ledger/src/ui/src/defs.h rename to firmware/src/ledger/ui/src/defs.h index 16d823f9..cb1a01c3 100644 --- a/ledger/src/ui/src/defs.h +++ b/firmware/src/ledger/ui/src/defs.h @@ -25,8 +25,8 @@ #ifndef __DEFS_H #define __DEFS_H -#include "apdu.h" #include "constants.h" +#include "apdu.h" // Version and patchlevel #define VERSION_MAJOR 0x05 diff --git a/ledger/src/ui/src/main.c b/firmware/src/ledger/ui/src/main.c similarity index 100% rename from ledger/src/ui/src/main.c rename to firmware/src/ledger/ui/src/main.c diff --git a/ledger/src/ui/src/onboard.c b/firmware/src/ledger/ui/src/onboard.c similarity index 100% rename from ledger/src/ui/src/onboard.c rename to firmware/src/ledger/ui/src/onboard.c diff --git a/ledger/src/ui/src/onboard.h b/firmware/src/ledger/ui/src/onboard.h similarity index 100% rename from ledger/src/ui/src/onboard.h rename to firmware/src/ledger/ui/src/onboard.h diff --git a/ledger/src/ui/src/pin.c b/firmware/src/ledger/ui/src/pin.c similarity index 100% rename from ledger/src/ui/src/pin.c rename to firmware/src/ledger/ui/src/pin.c diff --git a/ledger/src/ui/src/pin.h b/firmware/src/ledger/ui/src/pin.h similarity index 100% rename from ledger/src/ui/src/pin.h rename to firmware/src/ledger/ui/src/pin.h diff --git a/ledger/src/ui/src/signer_authorization.c b/firmware/src/ledger/ui/src/signer_authorization.c similarity index 100% rename from ledger/src/ui/src/signer_authorization.c rename to firmware/src/ledger/ui/src/signer_authorization.c diff --git a/ledger/src/ui/src/signer_authorization.h b/firmware/src/ledger/ui/src/signer_authorization.h similarity index 100% rename from ledger/src/ui/src/signer_authorization.h rename to firmware/src/ledger/ui/src/signer_authorization.h diff --git a/ledger/src/ui/src/signer_authorization_signers/aleph.h b/firmware/src/ledger/ui/src/signer_authorization_signers/aleph.h similarity index 100% rename from ledger/src/ui/src/signer_authorization_signers/aleph.h rename to firmware/src/ledger/ui/src/signer_authorization_signers/aleph.h diff --git a/ledger/src/ui/src/signer_authorization_signers/testing.h b/firmware/src/ledger/ui/src/signer_authorization_signers/testing.h similarity index 100% rename from ledger/src/ui/src/signer_authorization_signers/testing.h rename to firmware/src/ledger/ui/src/signer_authorization_signers/testing.h diff --git a/ledger/src/ui/src/signer_authorization_status.c b/firmware/src/ledger/ui/src/signer_authorization_status.c similarity index 98% rename from ledger/src/ui/src/signer_authorization_status.c rename to firmware/src/ledger/ui/src/signer_authorization_status.c index 8c9a9823..f7ce2b81 100644 --- a/ledger/src/ui/src/signer_authorization_status.c +++ b/firmware/src/ledger/ui/src/signer_authorization_status.c @@ -22,7 +22,6 @@ * IN THE SOFTWARE. */ -#include "os.h" #include "signer_authorization_status.h" #include "runtime.h" diff --git a/ledger/src/ui/src/signer_authorization_status.h b/firmware/src/ledger/ui/src/signer_authorization_status.h similarity index 100% rename from ledger/src/ui/src/signer_authorization_status.h rename to firmware/src/ledger/ui/src/signer_authorization_status.h diff --git a/ledger/src/ui/src/communication.c b/firmware/src/ledger/ui/src/ui_comm.c similarity index 90% rename from ledger/src/ui/src/communication.c rename to firmware/src/ledger/ui/src/ui_comm.c index f385fa46..bb869a4e 100644 --- a/ledger/src/ui/src/communication.c +++ b/firmware/src/ledger/ui/src/ui_comm.c @@ -22,9 +22,9 @@ * IN THE SOFTWARE. */ -#include "os.h" +#include "runtime.h" #include "apdu.h" -#include "communication.h" +#include "ui_comm.h" #include "modes.h" /** @@ -88,13 +88,13 @@ unsigned int get_retries() { * @arg[in] comm_reset_cb callback to reset the state * @returns the resulting APDU buffer size */ -unsigned int comm_process_exception(unsigned short ex, - unsigned int tx, - comm_reset_cb_t comm_reset_cb) { +unsigned int ui_process_exception(unsigned short ex, + unsigned int tx, + comm_reset_cb_t comm_reset_cb) { unsigned short sw = 0; // Reset the state in case of an error - if (ex != APDU_OK || tx + 2 > sizeof(G_io_apdu_buffer)) { + if (ex != APDU_OK || tx + 2 > APDU_TOTAL_SIZE) { comm_reset_cb(); } @@ -110,7 +110,7 @@ unsigned int comm_process_exception(unsigned short ex, // Unexpected exception => report // (check for a potential overflow first) - if (tx + 2 > sizeof(G_io_apdu_buffer)) { + if (tx + 2 > APDU_TOTAL_SIZE) { tx = 0; sw = 0x6983; } diff --git a/ledger/src/ui/src/communication.h b/firmware/src/ledger/ui/src/ui_comm.h similarity index 90% rename from ledger/src/ui/src/communication.h rename to firmware/src/ledger/ui/src/ui_comm.h index 96d970e7..449044d8 100644 --- a/ledger/src/ui/src/communication.h +++ b/firmware/src/ledger/ui/src/ui_comm.h @@ -22,8 +22,8 @@ * IN THE SOFTWARE. */ -#ifndef __COMMUNICATION_H -#define __COMMUNICATION_H +#ifndef __UI_COMM_H +#define __UI_COMM_H #include @@ -79,8 +79,8 @@ unsigned int get_retries(); * @arg[in] comm_reset_cb callback to reset the state * @returns the resulting APDU buffer size */ -unsigned int comm_process_exception(unsigned short ex, - unsigned int tx, - comm_reset_cb_t comm_reset_cb); +unsigned int ui_process_exception(unsigned short ex, + unsigned int tx, + comm_reset_cb_t comm_reset_cb); -#endif // __COMMUNICATION_H +#endif // __UI_COMM_H diff --git a/ledger/src/ui/src/ui_err.h b/firmware/src/ledger/ui/src/ui_err.h similarity index 100% rename from ledger/src/ui/src/ui_err.h rename to firmware/src/ledger/ui/src/ui_err.h diff --git a/ledger/src/ui/src/ui_heartbeat.c b/firmware/src/ledger/ui/src/ui_heartbeat.c similarity index 98% rename from ledger/src/ui/src/ui_heartbeat.c rename to firmware/src/ledger/ui/src/ui_heartbeat.c index e9f7e7d8..28761e91 100644 --- a/ledger/src/ui/src/ui_heartbeat.c +++ b/firmware/src/ledger/ui/src/ui_heartbeat.c @@ -24,12 +24,13 @@ #include +#include "runtime.h" #include "ui_heartbeat.h" #include "apdu.h" #include "ui_instructions.h" #include "ints.h" #include "ui_err.h" -#include "communication.h" +#include "ui_comm.h" #include "memutil.h" #include "compiletime.h" #include "signer_authorization_status.h" @@ -253,7 +254,7 @@ void ui_heartbeat_main(ui_heartbeat_t *ui_heartbeat_ctx) { } CATCH_OTHER(e) { current_context = ui_heartbeat_ctx; - tx = comm_process_exception(e, tx, &reset_state); + tx = ui_process_exception(e, tx, &reset_state); } FINALLY { } diff --git a/ledger/src/ui/src/ui_heartbeat.h b/firmware/src/ledger/ui/src/ui_heartbeat.h similarity index 100% rename from ledger/src/ui/src/ui_heartbeat.h rename to firmware/src/ledger/ui/src/ui_heartbeat.h diff --git a/ledger/src/ui/src/ui_instructions.h b/firmware/src/ledger/ui/src/ui_instructions.h similarity index 100% rename from ledger/src/ui/src/ui_instructions.h rename to firmware/src/ledger/ui/src/ui_instructions.h diff --git a/ledger/src/ui/src/unlock.c b/firmware/src/ledger/ui/src/unlock.c similarity index 100% rename from ledger/src/ui/src/unlock.c rename to firmware/src/ledger/ui/src/unlock.c diff --git a/ledger/src/ui/src/unlock.h b/firmware/src/ledger/ui/src/unlock.h similarity index 100% rename from ledger/src/ui/src/unlock.h rename to firmware/src/ledger/ui/src/unlock.h diff --git a/ledger/src/ui/src/ux_handlers.c b/firmware/src/ledger/ui/src/ux_handlers.c similarity index 99% rename from ledger/src/ui/src/ux_handlers.c rename to firmware/src/ledger/ui/src/ux_handlers.c index 70ef8419..2985fe03 100644 --- a/ledger/src/ui/src/ux_handlers.c +++ b/firmware/src/ledger/ui/src/ux_handlers.c @@ -21,7 +21,7 @@ * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ -#include +#include "bolos_ux_common.h" #include "ux_handlers.h" #include "bootloader.h" #include "ui_heartbeat.h" diff --git a/ledger/src/ui/src/ux_handlers.h b/firmware/src/ledger/ui/src/ux_handlers.h similarity index 100% rename from ledger/src/ui/src/ux_handlers.h rename to firmware/src/ledger/ui/src/ux_handlers.h diff --git a/ledger/src/ui/src/bolos_ux_common.h b/firmware/src/ledger/ui/src_common/bolos_ux_common.h similarity index 100% rename from ledger/src/ui/src/bolos_ux_common.h rename to firmware/src/ledger/ui/src_common/bolos_ux_common.h diff --git a/ledger/src/ui/src_common/bolos_ux_onboarding_seed_bip39.c b/firmware/src/ledger/ui/src_common/bolos_ux_onboarding_seed_bip39.c similarity index 100% rename from ledger/src/ui/src_common/bolos_ux_onboarding_seed_bip39.c rename to firmware/src/ledger/ui/src_common/bolos_ux_onboarding_seed_bip39.c diff --git a/ledger/src/ui/src_common/bolos_ux_onboarding_seed_bip39.h b/firmware/src/ledger/ui/src_common/bolos_ux_onboarding_seed_bip39.h similarity index 100% rename from ledger/src/ui/src_common/bolos_ux_onboarding_seed_bip39.h rename to firmware/src/ledger/ui/src_common/bolos_ux_onboarding_seed_bip39.h diff --git a/ledger/src/ui/src_common/bolos_ux_onboarding_seed_pbkdf2.c b/firmware/src/ledger/ui/src_common/bolos_ux_onboarding_seed_pbkdf2.c similarity index 100% rename from ledger/src/ui/src_common/bolos_ux_onboarding_seed_pbkdf2.c rename to firmware/src/ledger/ui/src_common/bolos_ux_onboarding_seed_pbkdf2.c diff --git a/ledger/src/ui/src_common/bolos_ux_onboarding_seed_rom_variables.c b/firmware/src/ledger/ui/src_common/bolos_ux_onboarding_seed_rom_variables.c similarity index 100% rename from ledger/src/ui/src_common/bolos_ux_onboarding_seed_rom_variables.c rename to firmware/src/ledger/ui/src_common/bolos_ux_onboarding_seed_rom_variables.c diff --git a/ledger/src/ui/src_common/bolos_ux_onboarding_seed_rom_variables.h b/firmware/src/ledger/ui/src_common/bolos_ux_onboarding_seed_rom_variables.h similarity index 100% rename from ledger/src/ui/src_common/bolos_ux_onboarding_seed_rom_variables.h rename to firmware/src/ledger/ui/src_common/bolos_ux_onboarding_seed_rom_variables.h diff --git a/ledger/src/ui/test/attestation/Makefile b/firmware/src/ledger/ui/test/attestation/Makefile similarity index 89% rename from ledger/src/ui/test/attestation/Makefile rename to firmware/src/ledger/ui/test/attestation/Makefile index 0d48df55..1e37ec92 100644 --- a/ledger/src/ui/test/attestation/Makefile +++ b/firmware/src/ledger/ui/test/attestation/Makefile @@ -20,13 +20,7 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -SRCDIR = ../../src -COMMONDIR = ../../../common/src -MOCKDIR = ../mock -CFLAGS = -I$(COMMONDIR) -I$(MOCKDIR) -I$(SRCDIR) -CFLAGS += -DHSM_SIMULATOR - -include ../../../../coverage/coverage.mk +include ../mock/common.mk PROG = test.out OBJS = mock.o attestation.o test_attestation.o diff --git a/ledger/src/ui/test/attestation/test_attestation.c b/firmware/src/ledger/ui/test/attestation/test_attestation.c similarity index 100% rename from ledger/src/ui/test/attestation/test_attestation.c rename to firmware/src/ledger/ui/test/attestation/test_attestation.c diff --git a/ledger/src/ui/test/bootloader/Makefile b/firmware/src/ledger/ui/test/bootloader/Makefile similarity index 90% rename from ledger/src/ui/test/bootloader/Makefile rename to firmware/src/ledger/ui/test/bootloader/Makefile index 2a77271f..a666ec38 100644 --- a/ledger/src/ui/test/bootloader/Makefile +++ b/firmware/src/ledger/ui/test/bootloader/Makefile @@ -20,12 +20,7 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -SRCDIR = ../../src -COMMONDIR = ../../../common/src -MOCKDIR = ../mock -CFLAGS = -I./mock -I$(COMMONDIR) -I$(MOCKDIR) -I$(SRCDIR) - -include ../../../../coverage/coverage.mk +include ../mock/common.mk PROG = test.out OBJS = mock.o bootloader.o test_bootloader.o diff --git a/ledger/src/ui/test/bootloader/mock/bolos_ux_common.h b/firmware/src/ledger/ui/test/bootloader/mock/bolos_ux_common.h similarity index 100% rename from ledger/src/ui/test/bootloader/mock/bolos_ux_common.h rename to firmware/src/ledger/ui/test/bootloader/mock/bolos_ux_common.h diff --git a/ledger/src/ui/test/bootloader/mock/bootloader_mock.h b/firmware/src/ledger/ui/test/bootloader/mock/bootloader_mock.h similarity index 98% rename from ledger/src/ui/test/bootloader/mock/bootloader_mock.h rename to firmware/src/ledger/ui/test/bootloader/mock/bootloader_mock.h index bc5e72c8..06224a34 100644 --- a/ledger/src/ui/test/bootloader/mock/bootloader_mock.h +++ b/firmware/src/ledger/ui/test/bootloader/mock/bootloader_mock.h @@ -31,7 +31,7 @@ #include #include #include "attestation.h" -#include "os_exceptions.h" +#include "hal/exceptions.h" #include "apdu_utils.h" #include "mock.h" diff --git a/ledger/src/ui/test/bootloader/test_bootloader.c b/firmware/src/ledger/ui/test/bootloader/test_bootloader.c similarity index 98% rename from ledger/src/ui/test/bootloader/test_bootloader.c rename to firmware/src/ledger/ui/test/bootloader/test_bootloader.c index d8c99c9e..573eab9b 100644 --- a/ledger/src/ui/test/bootloader/test_bootloader.c +++ b/firmware/src/ledger/ui/test/bootloader/test_bootloader.c @@ -34,7 +34,7 @@ #include "modes.h" #include "ui_err.h" #include "bootloader_mock.h" -#include "communication.h" +#include "ui_comm.h" // Mock variables needed for bootloader module bolos_ux_context_t G_bolos_ux_context; @@ -176,9 +176,9 @@ unsigned short io_exchange(unsigned char channel, unsigned short tx_len) { return 0; } -unsigned int comm_process_exception(unsigned short ex, - unsigned int tx, - comm_reset_cb_t comm_reset_cb) { +unsigned int ui_process_exception(unsigned short ex, + unsigned int tx, + comm_reset_cb_t comm_reset_cb) { return 0; } diff --git a/ledger/src/ui/test/mock/apdu_utils.h b/firmware/src/ledger/ui/test/mock/apdu_utils.h similarity index 100% rename from ledger/src/ui/test/mock/apdu_utils.h rename to firmware/src/ledger/ui/test/mock/apdu_utils.h diff --git a/ledger/src/ui/test/mock/assert_utils.h b/firmware/src/ledger/ui/test/mock/assert_utils.h similarity index 100% rename from ledger/src/ui/test/mock/assert_utils.h rename to firmware/src/ledger/ui/test/mock/assert_utils.h diff --git a/ledger/src/ui/test/mock/bolos_ux_onboarding_seed_bip39.h b/firmware/src/ledger/ui/test/mock/bolos_ux_onboarding_seed_bip39.h similarity index 100% rename from ledger/src/ui/test/mock/bolos_ux_onboarding_seed_bip39.h rename to firmware/src/ledger/ui/test/mock/bolos_ux_onboarding_seed_bip39.h diff --git a/firmware/src/ledger/ui/test/mock/common.mk b/firmware/src/ledger/ui/test/mock/common.mk new file mode 100644 index 00000000..6e7f396c --- /dev/null +++ b/firmware/src/ledger/ui/test/mock/common.mk @@ -0,0 +1,33 @@ +# The MIT License (MIT) +# +# Copyright (c) 2021 RSK Labs Ltd +# +# 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. + +SRCDIR = ../../src +COMMONDIR = ../../../../common/src +MOCKDIR = ../mock +THISMOCKDIR = ./mock +HALINCDIR = ../../../../hal/include +HALSRCDIR = ../../../../hal/src/x86 +CFLAGS = -iquote $(THISMOCKDIR) -iquote $(COMMONDIR) -iquote $(MOCKDIR) +CFLAGS += -iquote $(SRCDIR) -iquote $(HALINCDIR) -iquote $(HALSRCDIR) +CFLAGS += -DHSM_PLATFORM_X86 + +include ../../../../../coverage/coverage.mk \ No newline at end of file diff --git a/ledger/src/ui/test/mock/cx.h b/firmware/src/ledger/ui/test/mock/cx.h similarity index 100% rename from ledger/src/ui/test/mock/cx.h rename to firmware/src/ledger/ui/test/mock/cx.h diff --git a/ledger/src/ui/test/mock/mock.c b/firmware/src/ledger/ui/test/mock/mock.c similarity index 100% rename from ledger/src/ui/test/mock/mock.c rename to firmware/src/ledger/ui/test/mock/mock.c diff --git a/ledger/src/ui/test/mock/mock.h b/firmware/src/ledger/ui/test/mock/mock.h similarity index 99% rename from ledger/src/ui/test/mock/mock.h rename to firmware/src/ledger/ui/test/mock/mock.h index c2869ca3..07a90c35 100644 --- a/ledger/src/ui/test/mock/mock.h +++ b/firmware/src/ledger/ui/test/mock/mock.h @@ -29,7 +29,7 @@ #include #include -#include "os_exceptions.h" +#include "hal/exceptions.h" #include "apdu_utils.h" #include "defs.h" diff --git a/ledger/src/ui/test/mock/os.h b/firmware/src/ledger/ui/test/mock/os.h similarity index 100% rename from ledger/src/ui/test/mock/os.h rename to firmware/src/ledger/ui/test/mock/os.h diff --git a/ledger/src/ui/test/mock/os_io_seproxyhal.h b/firmware/src/ledger/ui/test/mock/os_io_seproxyhal.h similarity index 100% rename from ledger/src/ui/test/mock/os_io_seproxyhal.h rename to firmware/src/ledger/ui/test/mock/os_io_seproxyhal.h diff --git a/firmware/src/ledger/ui/test/mock/ui_deps.h b/firmware/src/ledger/ui/test/mock/ui_deps.h new file mode 100644 index 00000000..e69de29b diff --git a/ledger/src/ui/test/onboard/Makefile b/firmware/src/ledger/ui/test/onboard/Makefile similarity index 88% rename from ledger/src/ui/test/onboard/Makefile rename to firmware/src/ledger/ui/test/onboard/Makefile index 137dff66..39bedced 100644 --- a/ledger/src/ui/test/onboard/Makefile +++ b/firmware/src/ledger/ui/test/onboard/Makefile @@ -20,13 +20,7 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -SRCDIR = ../../src -COMMONDIR = ../../../common/src -MOCKDIR = ../mock -CFLAGS = -I$(SRCDIR) -I$(MOCKDIR) -I./ -I$(COMMONDIR) -CFLAGS += -DHSM_SIMULATOR - -include ../../../../coverage/coverage.mk +include ../mock/common.mk PROG = test.out OBJS = mock.o onboard.o test_onboard.o diff --git a/ledger/src/ui/test/onboard/test_onboard.c b/firmware/src/ledger/ui/test/onboard/test_onboard.c similarity index 100% rename from ledger/src/ui/test/onboard/test_onboard.c rename to firmware/src/ledger/ui/test/onboard/test_onboard.c diff --git a/ledger/src/ui/test/pin/Makefile b/firmware/src/ledger/ui/test/pin/Makefile similarity index 89% rename from ledger/src/ui/test/pin/Makefile rename to firmware/src/ledger/ui/test/pin/Makefile index d02979d2..f8f1d26f 100644 --- a/ledger/src/ui/test/pin/Makefile +++ b/firmware/src/ledger/ui/test/pin/Makefile @@ -20,12 +20,7 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -SRCDIR = ../../src -COMMONDIR = ../../../common/src -MOCKDIR = ../mock -CFLAGS = -I $(SRCDIR) -I $(MOCKDIR) -I ./ -I$(COMMONDIR) - -include ../../../../coverage/coverage.mk +include ../mock/common.mk PROG = test.out OBJS = mock.o pin.o test_pin.o diff --git a/ledger/src/ui/test/pin/test_pin.c b/firmware/src/ledger/ui/test/pin/test_pin.c similarity index 100% rename from ledger/src/ui/test/pin/test_pin.c rename to firmware/src/ledger/ui/test/pin/test_pin.c diff --git a/firmware/src/ledger/ui/test/run-all.sh b/firmware/src/ledger/ui/test/run-all.sh new file mode 100755 index 00000000..2be0d676 --- /dev/null +++ b/firmware/src/ledger/ui/test/run-all.sh @@ -0,0 +1,13 @@ +#!/bin/bash +BASEDIR=$(dirname $0) +TESTDIRS="attestation bootloader onboard pin signer_authorization ui_comm ui_heartbeat unlock ux_handlers" +TESTDIRS=${1:-"$TESTDIRS"} + +for d in $TESTDIRS; do + echo "******************************" + echo "Testing $d..." + echo "******************************" + cd "$BASEDIR/$d" + make clean test || exit $? + cd - > /dev/null +done diff --git a/ledger/src/ui/test/signer_authorization/Makefile b/firmware/src/ledger/ui/test/signer_authorization/Makefile similarity index 91% rename from ledger/src/ui/test/signer_authorization/Makefile rename to firmware/src/ledger/ui/test/signer_authorization/Makefile index 93f996ea..b9ab69cf 100644 --- a/ledger/src/ui/test/signer_authorization/Makefile +++ b/firmware/src/ledger/ui/test/signer_authorization/Makefile @@ -20,14 +20,10 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -SRCDIR = ../../src -SIGNERDIRS=$(SRCDIR)/signer_authorization_signers -COMMONDIR = ../../../common/src -MOCKDIR = ../mock -CFLAGS = -I$(MOCKDIR) -I$(COMMONDIR) -I$(SRCDIR) -I$(SIGNERDIRS) -CFLAGS += -DHSM_SIMULATOR +include ../mock/common.mk -include ../../../../coverage/coverage.mk +SIGNERDIRS=$(SRCDIR)/signer_authorization_signers +CFLAGS += -iquote $(SIGNERDIRS) PARAM_INITIAL_SIGNER_HASH="\x09\x09\x66\x04\x52\xeb\x7a\x3a\x44\xb6\xca\x07$\ \xed\x0b\x9c\xcf\xdd\xb9\xa6\x99\x9e\xb4\xad\xc3\x99\x50\x91\x71\xd2\x68\xe7$\ diff --git a/ledger/src/ui/test/signer_authorization/test_signer_authorization.c b/firmware/src/ledger/ui/test/signer_authorization/test_signer_authorization.c similarity index 100% rename from ledger/src/ui/test/signer_authorization/test_signer_authorization.c rename to firmware/src/ledger/ui/test/signer_authorization/test_signer_authorization.c diff --git a/firmware/src/ledger/ui/test/ui_comm/Makefile b/firmware/src/ledger/ui/test/ui_comm/Makefile new file mode 100644 index 00000000..c20869d1 --- /dev/null +++ b/firmware/src/ledger/ui/test/ui_comm/Makefile @@ -0,0 +1,48 @@ +# The MIT License (MIT) +# +# Copyright (c) 2021 RSK Labs Ltd +# +# 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 ../mock/common.mk + +PROG = test.out +OBJS = mock.o ui_comm.o test_ui_comm.o + +all: $(PROG) + +$(PROG): $(OBJS) + $(CC) $(COVFLAGS) -o $@ $^ + +test_ui_comm.o: test_ui_comm.c + $(CC) $(CFLAGS) -c -o $@ $^ + +ui_comm.o: $(SRCDIR)/ui_comm.c + $(CC) $(CFLAGS) $(COVFLAGS) -c -o $@ $^ + +mock.o: $(MOCKDIR)/mock.c + $(CC) $(CFLAGS) -c -o $@ $^ + +.PHONY: clean test + +clean: + rm -f $(PROG) *.o $(COVFILES) + +test: all + ./$(PROG) diff --git a/ledger/src/ui/test/communication/test_communication.c b/firmware/src/ledger/ui/test/ui_comm/test_ui_comm.c similarity index 91% rename from ledger/src/ui/test/communication/test_communication.c rename to firmware/src/ledger/ui/test/ui_comm/test_ui_comm.c index 663a6308..72f0232e 100644 --- a/ledger/src/ui/test/communication/test_communication.c +++ b/firmware/src/ledger/ui/test/ui_comm/test_ui_comm.c @@ -30,7 +30,7 @@ #include "assert_utils.h" #include "defs.h" #include "mock.h" -#include "communication.h" +#include "ui_comm.h" static unsigned int G_retries; @@ -88,7 +88,7 @@ void test_process_exception_ok() { SET_APDU("\xaa\xbb\xcc", tx); assert(tx + 2 == - comm_process_exception(APDU_OK, tx, process_exception_callback)); + ui_process_exception(APDU_OK, tx, process_exception_callback)); ASSERT_APDU("\xaa\xbb\xcc\x90\x00"); assert(!M_process_exception_callback_called); @@ -105,8 +105,8 @@ void test_process_exception_start_6_or_9() { unsigned int tx; SET_APDU("\xaa\xbb\xcc", tx); - assert(tx + 2 == comm_process_exception( - error[i], tx, process_exception_callback)); + assert(tx + 2 == + ui_process_exception(error[i], tx, process_exception_callback)); ASSERT_APDU(expected[i]); assert(M_process_exception_callback_called); @@ -121,7 +121,7 @@ void test_process_exception_start_somethingelse() { SET_APDU("\xaa\xbb\xcc", tx); assert(tx + 2 == - comm_process_exception(0x1234, tx, process_exception_callback)); + ui_process_exception(0x1234, tx, process_exception_callback)); ASSERT_APDU("\xaa\xbb\xcc\x6a\x34"); assert(M_process_exception_callback_called); @@ -138,7 +138,7 @@ void test_process_exception_apdu_too_large() { unsigned int tx; SET_APDU(apdu, tx); - assert(2 == comm_process_exception(0x9000, tx, process_exception_callback)); + assert(2 == ui_process_exception(0x9000, tx, process_exception_callback)); ASSERT_APDU("\x69\x83"); assert(M_process_exception_callback_called); diff --git a/ledger/src/ui/test/ui_heartbeat/Makefile b/firmware/src/ledger/ui/test/ui_heartbeat/Makefile similarity index 90% rename from ledger/src/ui/test/ui_heartbeat/Makefile rename to firmware/src/ledger/ui/test/ui_heartbeat/Makefile index 731aa350..68d5688e 100644 --- a/ledger/src/ui/test/ui_heartbeat/Makefile +++ b/firmware/src/ledger/ui/test/ui_heartbeat/Makefile @@ -20,12 +20,7 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -SRCDIR = ../../src -COMMONDIR = ../../../common/src -MOCKDIR = ../mock -CFLAGS = -I$(COMMONDIR) -I$(MOCKDIR) -I$(SRCDIR) - -include ../../../../coverage/coverage.mk +include ../mock/common.mk PROG = test.out OBJS = mock.o ui_heartbeat.o test_ui_heartbeat.o diff --git a/ledger/src/ui/test/ui_heartbeat/test_ui_heartbeat.c b/firmware/src/ledger/ui/test/ui_heartbeat/test_ui_heartbeat.c similarity index 98% rename from ledger/src/ui/test/ui_heartbeat/test_ui_heartbeat.c rename to firmware/src/ledger/ui/test/ui_heartbeat/test_ui_heartbeat.c index 04256818..28a873a5 100644 --- a/ledger/src/ui/test/ui_heartbeat/test_ui_heartbeat.c +++ b/firmware/src/ledger/ui/test/ui_heartbeat/test_ui_heartbeat.c @@ -27,7 +27,7 @@ #include "bolos_ux.h" #include "ui_heartbeat.h" #include "signer_authorization.h" -#include "communication.h" +#include "ui_comm.h" #include "apdu_utils.h" #include "assert_utils.h" #include "ui_err.h" @@ -151,9 +151,9 @@ unsigned short io_exchange(unsigned char channel_and_flags, return M_apdu_size; } -unsigned int comm_process_exception(unsigned short ex, - unsigned int tx, - comm_reset_cb_t comm_reset_cb) { +unsigned int ui_process_exception(unsigned short ex, + unsigned int tx, + comm_reset_cb_t comm_reset_cb) { M_last_exception = ex; return tx; } diff --git a/ledger/src/ui/test/unlock/Makefile b/firmware/src/ledger/ui/test/unlock/Makefile similarity index 90% rename from ledger/src/ui/test/unlock/Makefile rename to firmware/src/ledger/ui/test/unlock/Makefile index ec85f6e6..8668ca01 100644 --- a/ledger/src/ui/test/unlock/Makefile +++ b/firmware/src/ledger/ui/test/unlock/Makefile @@ -20,12 +20,7 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -SRCDIR = ../../src -COMMONDIR = ../../../common/src -MOCKDIR = ../mock -CFLAGS = -I $(SRCDIR) -I $(MOCKDIR) -I $(COMMONDIR) - -include ../../../../coverage/coverage.mk +include ../mock/common.mk PROG = test.out OBJS = mock.o unlock.o test_unlock.o diff --git a/ledger/src/ui/test/unlock/test_unlock.c b/firmware/src/ledger/ui/test/unlock/test_unlock.c similarity index 100% rename from ledger/src/ui/test/unlock/test_unlock.c rename to firmware/src/ledger/ui/test/unlock/test_unlock.c diff --git a/ledger/src/ui/test/ux_handlers/Makefile b/firmware/src/ledger/ui/test/ux_handlers/Makefile similarity index 89% rename from ledger/src/ui/test/ux_handlers/Makefile rename to firmware/src/ledger/ui/test/ux_handlers/Makefile index f89e8491..a940a1f2 100644 --- a/ledger/src/ui/test/ux_handlers/Makefile +++ b/firmware/src/ledger/ui/test/ux_handlers/Makefile @@ -20,12 +20,7 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -SRCDIR = ../../src -COMMONDIR = ../../../common/src -MOCKDIR = ../mock -CFLAGS = -I./mock -I$(MOCKDIR) -I$(SRCDIR) -I$(COMMONDIR) -g - -include ../../../../coverage/coverage.mk +include ../mock/common.mk PROG = test.out OBJS = ux_handlers.o test_ux_handlers.o diff --git a/ledger/src/ui/test/ux_handlers/mock/bolos_ux_common.h b/firmware/src/ledger/ui/test/ux_handlers/mock/bolos_ux_common.h similarity index 100% rename from ledger/src/ui/test/ux_handlers/mock/bolos_ux_common.h rename to firmware/src/ledger/ui/test/ux_handlers/mock/bolos_ux_common.h diff --git a/ledger/src/ui/test/ux_handlers/mock/bolos_ux_onboarding_seed_rom_variables.h b/firmware/src/ledger/ui/test/ux_handlers/mock/bolos_ux_onboarding_seed_rom_variables.h similarity index 100% rename from ledger/src/ui/test/ux_handlers/mock/bolos_ux_onboarding_seed_rom_variables.h rename to firmware/src/ledger/ui/test/ux_handlers/mock/bolos_ux_onboarding_seed_rom_variables.h diff --git a/ledger/src/ui/test/ux_handlers/mock/test_ux_handlers.h b/firmware/src/ledger/ui/test/ux_handlers/mock/test_ux_handlers.h similarity index 100% rename from ledger/src/ui/test/ux_handlers/mock/test_ux_handlers.h rename to firmware/src/ledger/ui/test/ux_handlers/mock/test_ux_handlers.h diff --git a/ledger/src/ui/test/ux_handlers/test_ux_handlers.c b/firmware/src/ledger/ui/test/ux_handlers/test_ux_handlers.c similarity index 100% rename from ledger/src/ui/test/ux_handlers/test_ux_handlers.c rename to firmware/src/ledger/ui/test/ux_handlers/test_ux_handlers.c diff --git a/ledger/src/signer/src/attestation.c b/firmware/src/powhsm/src/attestation.c similarity index 62% rename from ledger/src/signer/src/attestation.c rename to firmware/src/powhsm/src/attestation.c index b91dbf41..9c9130c4 100644 --- a/ledger/src/signer/src/attestation.c +++ b/firmware/src/powhsm/src/attestation.c @@ -24,7 +24,11 @@ #include -#include "os.h" +#include "hal/seed.h" +#include "hal/endorsement.h" +#include "hal/platform.h" +#include "hal/exceptions.h" + #include "attestation.h" #include "apdu.h" #include "defs.h" @@ -43,58 +47,40 @@ const char att_msg_prefix[ATT_MSG_PREFIX_LENGTH] = ATT_MSG_PREFIX; static void hash_public_key(const char* path, size_t path_size, att_t* att_ctx) { - BEGIN_TRY { - TRY { - // Derive public key - - // Skip first byte of path when copying (path size byte) - SAFE_MEMMOVE(att_ctx->path, - sizeof(att_ctx->path), - MEMMOVE_ZERO_OFFSET, - (unsigned int*)path, - path_size, - 1, - sizeof(att_ctx->path), - THROW(ERR_ATT_INTERNAL)); - - // Derive and init private key - os_perso_derive_node_bip32(CX_CURVE_256K1, - att_ctx->path, - DERIVATION_PATH_PARTS, - att_ctx->priv_key_data, - NULL); - cx_ecdsa_init_private_key(CX_CURVE_256K1, - att_ctx->priv_key_data, - PRIVATE_KEY_LENGTH, - &att_ctx->priv_key); - // Cleanup private key data - explicit_bzero(att_ctx->priv_key_data, - sizeof(att_ctx->priv_key_data)); - // Derive public key - cx_ecfp_generate_pair( - CX_CURVE_256K1, &att_ctx->pub_key, &att_ctx->priv_key, 1); - // Cleanup private key - explicit_bzero(&att_ctx->priv_key, sizeof(att_ctx->priv_key)); - - // Hash - SHA256_UPDATE( - &att_ctx->hash_ctx, att_ctx->pub_key.W, att_ctx->pub_key.W_len); - - // Cleanup public key - explicit_bzero(&att_ctx->pub_key, sizeof(att_ctx->pub_key)); - } - CATCH_OTHER(e) { - // Cleanup key data and fail - explicit_bzero(att_ctx->priv_key_data, - sizeof(att_ctx->priv_key_data)); - explicit_bzero(&att_ctx->priv_key, sizeof(att_ctx->priv_key)); - explicit_bzero(&att_ctx->pub_key, sizeof(att_ctx->pub_key)); - THROW(ERR_ATT_INTERNAL); - } - FINALLY { - } + // Derive public key + + // Skip first byte of path when copying (path size byte) + SAFE_MEMMOVE(att_ctx->path, + sizeof(att_ctx->path), + MEMMOVE_ZERO_OFFSET, + (unsigned int*)path, + path_size, + 1, + sizeof(att_ctx->path), + { goto hash_public_key_error; }); + + att_ctx->pubkey_length = sizeof(att_ctx->pubkey); + if (!seed_derive_pubkey(att_ctx->path, + sizeof(att_ctx->path) / sizeof(att_ctx->path[0]), + att_ctx->pubkey, + &att_ctx->pubkey_length)) { + goto hash_public_key_error; } - END_TRY; + + // Hash + SHA256_UPDATE(&att_ctx->hash_ctx, att_ctx->pubkey, att_ctx->pubkey_length); + + // Cleanup public key + explicit_bzero(&att_ctx->pubkey, sizeof(att_ctx->pubkey)); + att_ctx->pubkey_length = 0; + + return; + +hash_public_key_error: + // Cleanup public key + explicit_bzero(&att_ctx->pubkey, sizeof(att_ctx->pubkey)); + att_ctx->pubkey_length = 0; + THROW(ERR_ATT_INTERNAL); } /* @@ -139,15 +125,19 @@ static unsigned int generate_message_to_sign(att_t* att_ctx) { */ unsigned int get_attestation(volatile unsigned int rx, att_t* att_ctx) { unsigned int message_size; + uint8_t code_hash_size; switch (APDU_OP()) { case OP_ATT_GET: - // Generate the message to sign + // Generate the message to attest message_size = generate_message_to_sign(att_ctx); - // Sign message - int endorsement_size = os_endorsement_key2_derive_sign_data( - att_ctx->msg, message_size, APDU_DATA_PTR); + // Attest message + uint8_t endorsement_size = APDU_TOTAL_DATA_SIZE_OUT; + if (!endorsement_sign( + att_ctx->msg, message_size, APDU_DATA_PTR, &endorsement_size)) { + THROW(ERR_ATT_INTERNAL); + } return TX_FOR_DATA_SIZE(endorsement_size); case OP_ATT_GET_MESSAGE: @@ -165,9 +155,14 @@ unsigned int get_attestation(volatile unsigned int rx, att_t* att_ctx) { return TX_FOR_DATA_SIZE(message_size); case OP_ATT_APP_HASH: - return TX_FOR_DATA_SIZE(os_endorsement_get_code_hash(APDU_DATA_PTR)); + code_hash_size = APDU_TOTAL_DATA_SIZE_OUT; + if (!endorsement_get_code_hash(APDU_DATA_PTR, &code_hash_size)) { + THROW(ERR_ATT_INTERNAL); + } + return TX_FOR_DATA_SIZE(code_hash_size); default: THROW(ERR_ATT_PROT_INVALID); break; } + return 0; } diff --git a/ledger/src/signer/src/attestation.h b/firmware/src/powhsm/src/attestation.h similarity index 100% rename from ledger/src/signer/src/attestation.h rename to firmware/src/powhsm/src/attestation.h diff --git a/ledger/src/signer/src/auth.c b/firmware/src/powhsm/src/auth.c similarity index 92% rename from ledger/src/signer/src/auth.c rename to firmware/src/powhsm/src/auth.c index c821bc97..54508bab 100644 --- a/ledger/src/signer/src/auth.c +++ b/firmware/src/powhsm/src/auth.c @@ -24,14 +24,15 @@ #include -#include "os.h" +#include "hal/platform.h" +#include "hal/exceptions.h" + #include "auth.h" #include "err.h" -#include "sign.h" #include "mem.h" #include "compiletime.h" -#include "dbg.h" +#include "hal/log.h" /* * Transition to the given state, performing corresponding @@ -59,6 +60,7 @@ void auth_transition_to(uint8_t state) { */ unsigned int auth_sign(volatile unsigned int rx) { unsigned int tx; + uint8_t sig_size; // Sanity check: tx hash size and // last auth signed tx hash size @@ -95,12 +97,15 @@ unsigned int auth_sign(volatile unsigned int rx) { if (auth.state != STATE_AUTH_SIGN) THROW(ERR_AUTH_INVALID_STATE); // Invalid state - tx = do_sign(auth.path, - DERIVATION_PATH_PARTS, - auth.sig_hash, - sizeof(auth.sig_hash), - APDU_DATA_PTR, - APDU_TOTAL_DATA_SIZE_OUT); + sig_size = APDU_TOTAL_DATA_SIZE_OUT; + if (!seed_sign(auth.path, + sizeof(auth.path) / sizeof(auth.path[0]), + auth.sig_hash, + APDU_DATA_PTR, + &sig_size)) { + THROW(ERR_INTERNAL); + } + tx = sig_size; // Save the BTC tx hash to NVM if this signature required authorization if (auth.auth_required) { @@ -122,11 +127,6 @@ unsigned int auth_sign(volatile unsigned int rx) { } } - // Error signing? - if (tx == DO_SIGN_ERROR) { - THROW(ERR_INTERNAL); - } - SET_APDU_OP(P1_SUCCESS); auth_transition_to(STATE_AUTH_START); return TX_FOR_DATA_SIZE(tx); diff --git a/ledger/src/signer/src/auth.h b/firmware/src/powhsm/src/auth.h similarity index 98% rename from ledger/src/signer/src/auth.h rename to firmware/src/powhsm/src/auth.h index 644b465c..201c9202 100644 --- a/ledger/src/signer/src/auth.h +++ b/firmware/src/powhsm/src/auth.h @@ -28,6 +28,8 @@ #include #include +#include "hal/seed.h" + #include "auth_path.h" #include "auth_tx.h" #include "auth_receipt.h" @@ -85,7 +87,7 @@ typedef struct { uint8_t expected_bytes; bool auth_required; - uint32_t path[DERIVATION_PATH_PARTS]; + uint32_t path[BIP32_PATH_NUMPARTS]; uint32_t input_index_to_sign; uint8_t tx_hash[HASH_LENGTH]; diff --git a/ledger/src/signer/src/auth_constants.h b/firmware/src/powhsm/src/auth_constants.h similarity index 100% rename from ledger/src/signer/src/auth_constants.h rename to firmware/src/powhsm/src/auth_constants.h diff --git a/ledger/src/signer/src/auth_path.c b/firmware/src/powhsm/src/auth_path.c similarity index 98% rename from ledger/src/signer/src/auth_path.c rename to firmware/src/powhsm/src/auth_path.c index a3a00f40..a0640a19 100644 --- a/ledger/src/signer/src/auth_path.c +++ b/firmware/src/powhsm/src/auth_path.c @@ -22,7 +22,8 @@ * IN THE SOFTWARE. */ -#include "os.h" +#include "hal/platform.h" +#include "hal/exceptions.h" #include "auth.h" #include "pathAuth.h" @@ -106,4 +107,5 @@ unsigned int auth_sign_handle_path(volatile unsigned int rx) { // If no path match, then bail out // signalling invalid path THROW(ERR_AUTH_INVALID_PATH); + return 0; } diff --git a/ledger/src/signer/src/auth_path.h b/firmware/src/powhsm/src/auth_path.h similarity index 100% rename from ledger/src/signer/src/auth_path.h rename to firmware/src/powhsm/src/auth_path.h diff --git a/ledger/src/signer/src/auth_receipt.c b/firmware/src/powhsm/src/auth_receipt.c similarity index 96% rename from ledger/src/signer/src/auth_receipt.c rename to firmware/src/powhsm/src/auth_receipt.c index 5baaa59b..48c0dc4c 100644 --- a/ledger/src/signer/src/auth_receipt.c +++ b/firmware/src/powhsm/src/auth_receipt.c @@ -24,7 +24,8 @@ #include -#include "os.h" +#include "hal/platform.h" +#include "hal/exceptions.h" #include "auth.h" #include "auth_constants.h" @@ -34,7 +35,7 @@ #include "flags.h" #include "util.h" -#include "dbg.h" +#include "hal/log.h" // ----------------------------------------------------------------------- // RLP parser callbacks @@ -238,7 +239,7 @@ unsigned int auth_sign_handle_receipt(volatile unsigned int rx) { if (!HAS_FLAG(auth.receipt.flags, IS_INIT)) { rlp_start(&callbacks); - keccak_init(&auth.receipt.hash_ctx); + hash_keccak256_init(&auth.receipt.hash_ctx); SET_FLAG(auth.receipt.flags, IS_INIT); } @@ -249,12 +250,13 @@ unsigned int auth_sign_handle_receipt(volatile unsigned int rx) { } auth.receipt.remaining_bytes -= APDU_DATA_SIZE(rx); - keccak_update(&auth.receipt.hash_ctx, APDU_DATA_PTR, APDU_DATA_SIZE(rx)); + hash_keccak256_update( + &auth.receipt.hash_ctx, APDU_DATA_PTR, APDU_DATA_SIZE(rx)); if (auth.receipt.remaining_bytes == 0) { if (HAS_FLAG(auth.receipt.flags, IS_MATCH)) { // Finalize the hash calculation - keccak_final(&auth.receipt.hash_ctx, auth.receipt_hash); + hash_keccak256_final(&auth.receipt.hash_ctx, auth.receipt_hash); // Log hash for debugging purposes LOG_HEX( diff --git a/ledger/src/signer/src/auth_receipt.h b/firmware/src/powhsm/src/auth_receipt.h similarity index 96% rename from ledger/src/signer/src/auth_receipt.h rename to firmware/src/powhsm/src/auth_receipt.h index 8639f892..b978bac5 100644 --- a/ledger/src/signer/src/auth_receipt.h +++ b/firmware/src/powhsm/src/auth_receipt.h @@ -27,8 +27,9 @@ #include +#include "hal/hash.h" + #include "srlp.h" -#include "keccak256.h" #define RECEIPT_MAX_DEPTH (4) #define RECEIPT_MAX_BUFFER_SIZE (32) @@ -43,7 +44,7 @@ typedef struct { uint8_t aux[RECEIPT_MAX_BUFFER_SIZE]; uint8_t aux_offset; - SHA3_CTX hash_ctx; + hash_keccak256_ctx_t hash_ctx; } receipt_auth_ctx_t; /* diff --git a/ledger/src/signer/src/auth_trie.c b/firmware/src/powhsm/src/auth_trie.c similarity index 95% rename from ledger/src/signer/src/auth_trie.c rename to firmware/src/powhsm/src/auth_trie.c index f188b4e0..0d247205 100644 --- a/ledger/src/signer/src/auth_trie.c +++ b/firmware/src/powhsm/src/auth_trie.c @@ -24,14 +24,16 @@ #include -#include "os.h" +#include "hal/hash.h" +#include "hal/platform.h" +#include "hal/exceptions.h" #include "auth.h" #include "mem.h" #include "memutil.h" #include "bc_state.h" -#include "dbg.h" +#include "hal/log.h" #define REQUEST_MORE_IF_NEED() \ { \ @@ -57,7 +59,7 @@ static void trie_cb(const trie_cb_event_t event) { // Update node hash - keccak_update( + hash_keccak256_update( &auth.trie.hash_ctx, auth.trie.ctx.raw, auth.trie.ctx.raw_size); switch (event) { @@ -141,12 +143,12 @@ static void trie_cb(const trie_cb_event_t event) { case TRIE_EV_LEFT_NODE_EMBEDDED_START: case TRIE_EV_RIGHT_NODE_EMBEDDED_START: FAIL_IF_LEAF(); - keccak_init(&auth.trie.aux_hash_ctx); + hash_keccak256_init(&auth.trie.aux_hash_ctx); break; case TRIE_EV_LEFT_NODE_EMBEDDED_DATA: case TRIE_EV_RIGHT_NODE_EMBEDDED_DATA: FAIL_IF_LEAF(); - keccak_update( + hash_keccak256_update( &auth.trie.aux_hash_ctx, auth.trie.ctx.raw, auth.trie.ctx.raw_size); break; case TRIE_EV_LEFT_NODE_END: @@ -156,7 +158,7 @@ static void trie_cb(const trie_cb_event_t event) { FAIL_IF_LEAF(); if (event == TRIE_EV_LEFT_NODE_EMBEDDED_END || event == TRIE_EV_RIGHT_NODE_EMBEDDED_END) - keccak_final(&auth.trie.aux_hash_ctx, auth.trie.child_hash); + hash_keccak256_final(&auth.trie.aux_hash_ctx, auth.trie.child_hash); if (!memcmp(auth.trie.node_hash, auth.trie.child_hash, sizeof(auth.trie.node_hash))) @@ -197,7 +199,7 @@ unsigned int auth_sign_handle_merkleproof(volatile unsigned int rx) { THROW(ERR_AUTH_INVALID_DATA_SIZE); } trie_init(&auth.trie.ctx, &trie_cb, APDU_DATA_PTR[apdu_offset++]); - keccak_init(&auth.trie.hash_ctx); + hash_keccak256_init(&auth.trie.hash_ctx); auth.trie.state = AUTH_TRIE_STATE_NODE; auth.trie.num_linked = 0; @@ -213,7 +215,7 @@ unsigned int auth_sign_handle_merkleproof(volatile unsigned int rx) { // Reusing an existing error code due to legacy protocol THROW(ERR_AUTH_RECEIPT_ROOT_MISMATCH); } else if (trie_result() == TRIE_ST_DONE) { - keccak_final(&auth.trie.hash_ctx, auth.trie.node_hash); + hash_keccak256_final(&auth.trie.hash_ctx, auth.trie.node_hash); LOG("MP@%u ", auth.trie.current_node); LOG_HEX( "hash: ", auth.trie.node_hash, sizeof(auth.trie.node_hash)); diff --git a/ledger/src/signer/src/auth_trie.h b/firmware/src/powhsm/src/auth_trie.h similarity index 95% rename from ledger/src/signer/src/auth_trie.h rename to firmware/src/powhsm/src/auth_trie.h index 9c45d4ab..963d0b60 100644 --- a/ledger/src/signer/src/auth_trie.h +++ b/firmware/src/powhsm/src/auth_trie.h @@ -27,8 +27,9 @@ #include +#include "hal/hash.h" + #include "trie.h" -#include "keccak256.h" #include "defs.h" #define AUTH_TRIE_STATE_NODE_LENGTH (0) @@ -42,8 +43,8 @@ typedef struct { uint8_t state; trie_ctx_t ctx; - SHA3_CTX hash_ctx; - SHA3_CTX aux_hash_ctx; + hash_keccak256_ctx_t hash_ctx; + hash_keccak256_ctx_t aux_hash_ctx; uint8_t num_linked; uint8_t offset; diff --git a/ledger/src/signer/src/auth_tx.c b/firmware/src/powhsm/src/auth_tx.c similarity index 76% rename from ledger/src/signer/src/auth_tx.c rename to firmware/src/powhsm/src/auth_tx.c index ceb3b073..666b50bc 100644 --- a/ledger/src/signer/src/auth_tx.c +++ b/firmware/src/powhsm/src/auth_tx.c @@ -22,14 +22,16 @@ * IN THE SOFTWARE. */ -#include "os.h" +#include "hal/hash.h" +#include "hal/platform.h" +#include "hal/exceptions.h" #include "auth.h" #include "svarint.h" #include "mem.h" #include "memutil.h" -#include "dbg.h" +#include "hal/log.h" // IMPORTANT: This callback only executes for the scriptSig at the desired input // (the one that is requested to sign) @@ -49,19 +51,20 @@ static void btcscript_cb(const btcscript_cb_event_t event) { svarint_encode(auth.tx.script_ctx.operand_size, redeemscript_length, sizeof(redeemscript_length)); - sha256_update(&auth.tx.sig_hash_ctx, - redeemscript_length, - redeemscript_length_size); + hash_sha256_update(&auth.tx.sig_hash_ctx, + redeemscript_length, + redeemscript_length_size); } else if (event == BTCSCRIPT_EV_OPERAND && auth.tx.redeemscript_found) { - sha256_update(&auth.tx.sig_hash_ctx, - &auth.tx.script_ctx.operand_byte, - sizeof(auth.tx.script_ctx.operand_byte)); + hash_sha256_update(&auth.tx.sig_hash_ctx, + &auth.tx.script_ctx.operand_byte, + sizeof(auth.tx.script_ctx.operand_byte)); } } static void btctx_cb(const btctx_cb_event_t event) { // Update txhash - sha256_update(&auth.tx.tx_hash_ctx, auth.tx.ctx.raw, auth.tx.ctx.raw_size); + hash_sha256_update( + &auth.tx.tx_hash_ctx, auth.tx.ctx.raw, auth.tx.ctx.raw_size); // The bridge currently only generates pegout transactions with // versions 1 or 2. Validate that. @@ -89,7 +92,7 @@ static void btctx_cb(const btctx_cb_event_t event) { } else { // All other scriptSigs get replaced by an empty scriptSig // when calculating the sigHash - sha256_update(&auth.tx.sig_hash_ctx, (uint8_t[]){0x00}, 1); + hash_sha256_update(&auth.tx.sig_hash_ctx, (uint8_t[]){0x00}, 1); } } else if (event == BTCTX_EV_VIN_SCRIPT_DATA && auth.tx.ctx.inout_current == auth.input_index_to_sign) { @@ -118,28 +121,29 @@ static void btctx_cb(const btctx_cb_event_t event) { } } } else if (event != BTCTX_EV_VIN_SCRIPT_DATA) { - sha256_update( + hash_sha256_update( &auth.tx.sig_hash_ctx, auth.tx.ctx.raw, auth.tx.ctx.raw_size); } } static void btctx_cb_segwit(const btctx_cb_event_t event) { // Update txhash - sha256_update(&auth.tx.tx_hash_ctx, auth.tx.ctx.raw, auth.tx.ctx.raw_size); + hash_sha256_update( + &auth.tx.tx_hash_ctx, auth.tx.ctx.raw, auth.tx.ctx.raw_size); if (event == BTCTX_EV_VERSION) { - sha256_update( + hash_sha256_update( &auth.tx.sig_hash_ctx, auth.tx.ctx.raw, auth.tx.ctx.raw_size); } if (event == BTCTX_EV_VIN_COUNT) { - sha256_init(&auth.tx.prevouts_hash_ctx); - sha256_init(&auth.tx.sequence_hash_ctx); + hash_sha256_init(&auth.tx.prevouts_hash_ctx); + hash_sha256_init(&auth.tx.sequence_hash_ctx); auth.tx.aux_offset = 0; } if (event == BTCTX_EV_VIN_TXH_DATA || event == BTCTX_EV_VIN_TXIX) { - sha256_update( + hash_sha256_update( &auth.tx.prevouts_hash_ctx, auth.tx.ctx.raw, auth.tx.ctx.raw_size); if (auth.tx.ctx.inout_current == auth.input_index_to_sign) { @@ -156,7 +160,7 @@ static void btctx_cb_segwit(const btctx_cb_event_t event) { } if (event == BTCTX_EV_VIN_SEQNO) { - sha256_update( + hash_sha256_update( &auth.tx.sequence_hash_ctx, auth.tx.ctx.raw, auth.tx.ctx.raw_size); if (auth.tx.ctx.inout_current == auth.input_index_to_sign) { @@ -172,45 +176,45 @@ static void btctx_cb_segwit(const btctx_cb_event_t event) { } if (event == BTCTX_EV_VOUT_COUNT) { - sha256_final(&auth.tx.prevouts_hash_ctx, auth.tx.aux_hash); - sha256_init(&auth.tx.prevouts_hash_ctx); - sha256_update(&auth.tx.prevouts_hash_ctx, - auth.tx.aux_hash, - sizeof(auth.tx.aux_hash)); - sha256_final(&auth.tx.prevouts_hash_ctx, auth.tx.aux_hash); - sha256_update( + hash_sha256_final(&auth.tx.prevouts_hash_ctx, auth.tx.aux_hash); + hash_sha256_init(&auth.tx.prevouts_hash_ctx); + hash_sha256_update(&auth.tx.prevouts_hash_ctx, + auth.tx.aux_hash, + sizeof(auth.tx.aux_hash)); + hash_sha256_final(&auth.tx.prevouts_hash_ctx, auth.tx.aux_hash); + hash_sha256_update( &auth.tx.sig_hash_ctx, auth.tx.aux_hash, sizeof(auth.tx.aux_hash)); - sha256_final(&auth.tx.sequence_hash_ctx, auth.tx.aux_hash); - sha256_init(&auth.tx.sequence_hash_ctx); - sha256_update(&auth.tx.sequence_hash_ctx, - auth.tx.aux_hash, - sizeof(auth.tx.aux_hash)); - sha256_final(&auth.tx.sequence_hash_ctx, auth.tx.aux_hash); - sha256_update( + hash_sha256_final(&auth.tx.sequence_hash_ctx, auth.tx.aux_hash); + hash_sha256_init(&auth.tx.sequence_hash_ctx); + hash_sha256_update(&auth.tx.sequence_hash_ctx, + auth.tx.aux_hash, + sizeof(auth.tx.aux_hash)); + hash_sha256_final(&auth.tx.sequence_hash_ctx, auth.tx.aux_hash); + hash_sha256_update( &auth.tx.sig_hash_ctx, auth.tx.aux_hash, sizeof(auth.tx.aux_hash)); // Previously saved outpoint of input to sign - sha256_update(&auth.tx.sig_hash_ctx, - auth.tx.ip_prevout, - sizeof(auth.tx.ip_prevout)); + hash_sha256_update(&auth.tx.sig_hash_ctx, + auth.tx.ip_prevout, + sizeof(auth.tx.ip_prevout)); - sha256_init(&auth.tx.outputs_hash_ctx); + hash_sha256_init(&auth.tx.outputs_hash_ctx); } if (event == BTCTX_EV_VOUT_VALUE || event == BTCTX_EV_VOUT_SLENGTH || event == BTCTX_EV_VOUT_SCRIPT_DATA) { - sha256_update( + hash_sha256_update( &auth.tx.outputs_hash_ctx, auth.tx.ctx.raw, auth.tx.ctx.raw_size); } if (event == BTCTX_EV_LOCKTIME) { - sha256_final(&auth.tx.outputs_hash_ctx, auth.tx.outputs_hash); - sha256_init(&auth.tx.outputs_hash_ctx); - sha256_update(&auth.tx.outputs_hash_ctx, - auth.tx.outputs_hash, - sizeof(auth.tx.outputs_hash)); - sha256_final(&auth.tx.outputs_hash_ctx, auth.tx.outputs_hash); + hash_sha256_final(&auth.tx.outputs_hash_ctx, auth.tx.outputs_hash); + hash_sha256_init(&auth.tx.outputs_hash_ctx); + hash_sha256_update(&auth.tx.outputs_hash_ctx, + auth.tx.outputs_hash, + sizeof(auth.tx.outputs_hash)); + hash_sha256_final(&auth.tx.outputs_hash_ctx, auth.tx.outputs_hash); SAFE_MEMMOVE(auth.tx.lock_time, sizeof(auth.tx.lock_time), @@ -251,8 +255,8 @@ unsigned int auth_sign_handle_btctx(volatile unsigned int rx) { auth.tx.remaining_bytes -= BTCTX_LENGTH_SIZE + SIGHASH_COMP_MODE_SIZE + EXTRADATA_SIZE; // Init both hash operations - sha256_init(&auth.tx.tx_hash_ctx); - sha256_init(&auth.tx.sig_hash_ctx); + hash_sha256_init(&auth.tx.tx_hash_ctx); + hash_sha256_init(&auth.tx.sig_hash_ctx); apdu_offset = BTCTX_LENGTH_SIZE; // Following three bytes indicate the sighash computation // mode (1 byte) and extradata size (2 bytes LE, for segwit) @@ -297,10 +301,10 @@ unsigned int auth_sign_handle_btctx(volatile unsigned int rx) { } // Finalize TX hash computation - sha256_final(&auth.tx.tx_hash_ctx, auth.tx_hash); - sha256_init(&auth.tx.tx_hash_ctx); - sha256_update(&auth.tx.tx_hash_ctx, auth.tx_hash, 32); - sha256_final(&auth.tx.tx_hash_ctx, auth.tx_hash); + hash_sha256_final(&auth.tx.tx_hash_ctx, auth.tx_hash); + hash_sha256_init(&auth.tx.tx_hash_ctx); + hash_sha256_update(&auth.tx.tx_hash_ctx, auth.tx_hash, 32); + hash_sha256_final(&auth.tx.tx_hash_ctx, auth.tx_hash); for (int j = 0; j < 16; j++) { uint8_t aux = auth.tx_hash[j]; auth.tx_hash[j] = auth.tx_hash[31 - j]; @@ -319,7 +323,8 @@ unsigned int auth_sign_handle_btctx(volatile unsigned int rx) { } } else { // Hash extradata - sha256_update(&auth.tx.sig_hash_ctx, APDU_DATA_PTR, APDU_DATA_SIZE(rx)); + hash_sha256_update( + &auth.tx.sig_hash_ctx, APDU_DATA_PTR, APDU_DATA_SIZE(rx)); auth.tx.remaining_bytes -= APDU_DATA_SIZE(rx); if (auth.tx.remaining_bytes == 0) { auth.tx.finalise = true; @@ -329,26 +334,26 @@ unsigned int auth_sign_handle_btctx(volatile unsigned int rx) { if (auth.tx.finalise) { if (auth.tx.sighash_computation_mode == SIGHASH_COMPUTE_MODE_SEGWIT) { // Remaining tx items to hash for segwit - sha256_update(&auth.tx.sig_hash_ctx, - auth.tx.ip_seqno, - sizeof(auth.tx.ip_seqno)); - sha256_update(&auth.tx.sig_hash_ctx, - auth.tx.outputs_hash, - sizeof(auth.tx.outputs_hash)); - sha256_update(&auth.tx.sig_hash_ctx, - auth.tx.lock_time, - sizeof(auth.tx.lock_time)); + hash_sha256_update(&auth.tx.sig_hash_ctx, + auth.tx.ip_seqno, + sizeof(auth.tx.ip_seqno)); + hash_sha256_update(&auth.tx.sig_hash_ctx, + auth.tx.outputs_hash, + sizeof(auth.tx.outputs_hash)); + hash_sha256_update(&auth.tx.sig_hash_ctx, + auth.tx.lock_time, + sizeof(auth.tx.lock_time)); } // Add SIGHASH_ALL hash type at the end - sha256_update(&auth.tx.sig_hash_ctx, - (uint8_t[])SIGHASH_ALL_BYTES, - sizeof(SIGHASH_ALL_SIZE)); - sha256_final(&auth.tx.sig_hash_ctx, auth.sig_hash); - - sha256_init(&auth.tx.sig_hash_ctx); - sha256_update(&auth.tx.sig_hash_ctx, auth.sig_hash, 32); - sha256_final(&auth.tx.sig_hash_ctx, auth.sig_hash); + hash_sha256_update(&auth.tx.sig_hash_ctx, + (uint8_t[])SIGHASH_ALL_BYTES, + sizeof(SIGHASH_ALL_SIZE)); + hash_sha256_final(&auth.tx.sig_hash_ctx, auth.sig_hash); + + hash_sha256_init(&auth.tx.sig_hash_ctx); + hash_sha256_update(&auth.tx.sig_hash_ctx, auth.sig_hash, 32); + hash_sha256_final(&auth.tx.sig_hash_ctx, auth.sig_hash); // Log hashes for debugging purposes LOG_HEX("TX hash: ", auth.tx_hash, sizeof(auth.tx_hash)); diff --git a/ledger/src/signer/src/auth_tx.h b/firmware/src/powhsm/src/auth_tx.h similarity index 91% rename from ledger/src/signer/src/auth_tx.h rename to firmware/src/powhsm/src/auth_tx.h index 9766b9a8..dfd690a5 100644 --- a/ledger/src/signer/src/auth_tx.h +++ b/firmware/src/powhsm/src/auth_tx.h @@ -27,7 +27,8 @@ #include -#include "sha256.h" +#include "hal/hash.h" + #include "btctx.h" #include "btcscript.h" @@ -48,8 +49,8 @@ typedef struct { bool finalise; btctx_ctx_t ctx; btcscript_ctx_t script_ctx; - SHA256_CTX tx_hash_ctx; - SHA256_CTX sig_hash_ctx; + hash_sha256_ctx_t tx_hash_ctx; + hash_sha256_ctx_t sig_hash_ctx; uint8_t sighash_computation_mode; @@ -58,11 +59,11 @@ typedef struct { bool segwit_processing_extradata; uint16_t segwit_extradata_size; union { - SHA256_CTX prevouts_hash_ctx; - SHA256_CTX outputs_hash_ctx; + hash_sha256_ctx_t prevouts_hash_ctx; + hash_sha256_ctx_t outputs_hash_ctx; uint8_t lock_time[BTCTX_LOCKTIME_SIZE]; }; - SHA256_CTX sequence_hash_ctx; + hash_sha256_ctx_t sequence_hash_ctx; union { uint8_t aux_hash[BTCTX_HASH_SIZE]; uint8_t outputs_hash[BTCTX_HASH_SIZE]; diff --git a/ledger/src/signer/src/bc.h b/firmware/src/powhsm/src/bc.h similarity index 100% rename from ledger/src/signer/src/bc.h rename to firmware/src/powhsm/src/bc.h diff --git a/ledger/src/signer/src/bc_advance.c b/firmware/src/powhsm/src/bc_advance.c similarity index 98% rename from ledger/src/signer/src/bc_advance.c rename to firmware/src/powhsm/src/bc_advance.c index 5f975712..d95a61d3 100644 --- a/ledger/src/signer/src/bc_advance.c +++ b/firmware/src/powhsm/src/bc_advance.c @@ -24,10 +24,8 @@ #include -#include "os.h" - #include "bc.h" -#include "dbg.h" +#include "hal/log.h" #include "defs.h" #include "ints.h" #include "mem.h" @@ -55,15 +53,14 @@ // 0x000001d5, 0, 0, 0, 0, 0, 0 }; // Here we take it from an external definition (see Makefile for details) -#ifdef PARAM_MIN_REQUIRED_DIFFICULTY +#if defined(HSM_PLATFORM_LEDGER) && defined(PARAM_MIN_REQUIRED_DIFFICULTY) static const DIGIT_T MIN_REQUIRED_DIFFICULTY[BIGINT_LEN] = PARAM_MIN_REQUIRED_DIFFICULTY; +#elif defined(HSM_PLATFORM_X86) +DIGIT_T MIN_REQUIRED_DIFFICULTY[BIGINT_LEN]; #else -#ifndef HSM_SIMULATOR #error "Minimum required difficulty not defined!" #endif -DIGIT_T MIN_REQUIRED_DIFFICULTY[BIGINT_LEN]; -#endif // ----------------------------------------------------------------------- // Blockchain advance validation state @@ -192,15 +189,15 @@ static void compute_cb_txn_hash() { memset(block.wa_buf + CB_MIDSTATE_PREFIX + CB_MIDSTATE_DATA, 0, CB_MIDSTATE_SUFFIX); - sha256_init(&block.mid_ctx); - sha256_midstate(&block.mid_ctx, block.wa_buf); - sha256_update(&block.mid_ctx, - block.cb_txn + CB_MIDSTATE_DATA, - block.cb_off - CB_MIDSTATE_DATA); - sha256_final(&block.mid_ctx, block.wa_buf); - sha256_init(&block.mid_ctx); - sha256_update(&block.mid_ctx, block.wa_buf, HASH_SIZE); - sha256_final(&block.mid_ctx, block.wa_buf); + hash_sha256_ms_init(&block.mid_ctx); + hash_sha256_ms_midstate(&block.mid_ctx, block.wa_buf); + hash_sha256_ms_update(&block.mid_ctx, + block.cb_txn + CB_MIDSTATE_DATA, + block.cb_off - CB_MIDSTATE_DATA); + hash_sha256_ms_final(&block.mid_ctx, block.wa_buf); + hash_sha256_ms_init(&block.mid_ctx); + hash_sha256_ms_update(&block.mid_ctx, block.wa_buf, HASH_SIZE); + hash_sha256_ms_final(&block.mid_ctx, block.wa_buf); REV_HASH(block.wa_buf); } diff --git a/ledger/src/signer/src/bc_advance.h b/firmware/src/powhsm/src/bc_advance.h similarity index 100% rename from ledger/src/signer/src/bc_advance.h rename to firmware/src/powhsm/src/bc_advance.h diff --git a/ledger/src/signer/src/bc_ancestor.c b/firmware/src/powhsm/src/bc_ancestor.c similarity index 99% rename from ledger/src/signer/src/bc_ancestor.c rename to firmware/src/powhsm/src/bc_ancestor.c index db7d4d56..f5fbda44 100644 --- a/ledger/src/signer/src/bc_ancestor.c +++ b/firmware/src/powhsm/src/bc_ancestor.c @@ -24,10 +24,8 @@ #include -#include "os.h" - #include "bc.h" -#include "dbg.h" +#include "hal/log.h" #include "defs.h" #include "ints.h" #include "mem.h" diff --git a/ledger/src/signer/src/bc_ancestor.h b/firmware/src/powhsm/src/bc_ancestor.h similarity index 100% rename from ledger/src/signer/src/bc_ancestor.h rename to firmware/src/powhsm/src/bc_ancestor.h diff --git a/ledger/src/signer/src/bc_block.h b/firmware/src/powhsm/src/bc_block.h similarity index 96% rename from ledger/src/signer/src/bc_block.h rename to firmware/src/powhsm/src/bc_block.h index 3c1bc557..14d9db61 100644 --- a/ledger/src/signer/src/bc_block.h +++ b/firmware/src/powhsm/src/bc_block.h @@ -27,8 +27,9 @@ #include +#include "hal/hash.h" + #include "bigdigits.h" -#include "sha256.h" #include "bc.h" #include "bc_hash.h" @@ -73,8 +74,8 @@ typedef struct { }; union { - sha256_ctx_t ctx; // Global sha256 context - SHA256_CTX mid_ctx; // Sha256 supporting midstate + hash_sha256_ctx_t ctx; // Global sha256 context + hash_sha256_ms_ctx_t mid_ctx; // Sha256 supporting midstate }; union { diff --git a/ledger/src/signer/src/bc_blockutils.h b/firmware/src/powhsm/src/bc_blockutils.h similarity index 100% rename from ledger/src/signer/src/bc_blockutils.h rename to firmware/src/powhsm/src/bc_blockutils.h diff --git a/ledger/src/signer/src/bc_diff.c b/firmware/src/powhsm/src/bc_diff.c similarity index 99% rename from ledger/src/signer/src/bc_diff.c rename to firmware/src/powhsm/src/bc_diff.c index 3f3bb0b1..a765da17 100644 --- a/ledger/src/signer/src/bc_diff.c +++ b/firmware/src/powhsm/src/bc_diff.c @@ -25,7 +25,7 @@ #include #include "bc_diff.h" -#include "dbg.h" +#include "hal/log.h" #include "memutil.h" // Maximum difficulty for block difficulty capping (network dependent) @@ -33,7 +33,7 @@ static const DIGIT_T MAX_BLOCK_DIFFICULTY[BIGINT_LEN] = BCDIFF_MBD_TESTNET; #elif defined(REGTEST) static const DIGIT_T MAX_BLOCK_DIFFICULTY[BIGINT_LEN] = BCDIFF_MBD_REGTEST; -#elif defined(HSM_SIMULATOR) +#elif defined(HSM_PLATFORM_X86) DIGIT_T MAX_BLOCK_DIFFICULTY[BIGINT_LEN]; #else static const DIGIT_T MAX_BLOCK_DIFFICULTY[BIGINT_LEN] = BCDIFF_MBD_MAINNET; diff --git a/ledger/src/signer/src/bc_diff.h b/firmware/src/powhsm/src/bc_diff.h similarity index 99% rename from ledger/src/signer/src/bc_diff.h rename to firmware/src/powhsm/src/bc_diff.h index 9fec7c38..e268f398 100644 --- a/ledger/src/signer/src/bc_diff.h +++ b/firmware/src/powhsm/src/bc_diff.h @@ -39,7 +39,7 @@ #define BCDIFF_MBD_REGTEST {0x14, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}; // 20 -#ifdef HSM_SIMULATOR +#ifdef HSM_PLATFORM_X86 extern DIGIT_T MAX_BLOCK_DIFFICULTY[BIGINT_LEN]; #endif diff --git a/ledger/src/signer/src/bc_err.c b/firmware/src/powhsm/src/bc_err.c similarity index 97% rename from ledger/src/signer/src/bc_err.c rename to firmware/src/powhsm/src/bc_err.c index 6178d19a..e06b2dae 100644 --- a/ledger/src/signer/src/bc_err.c +++ b/firmware/src/powhsm/src/bc_err.c @@ -24,9 +24,9 @@ #include "bc_err.h" -#ifdef HSM_SIMULATOR +#ifdef HSM_PLATFORM_X86 -#include +#include "hal/log.h" static struct err_entry { err_code_t errcode; @@ -74,7 +74,7 @@ void show_error(err_code_t errcode) { break; } } - fprintf(stderr, "*** ERROR: %s\n", msg); + LOG("*** ERROR: %s\n", msg); } #else void show_error(err_code_t errcode) { diff --git a/ledger/src/signer/src/bc_err.h b/firmware/src/powhsm/src/bc_err.h similarity index 99% rename from ledger/src/signer/src/bc_err.h rename to firmware/src/powhsm/src/bc_err.h index 4c0c3376..5b197986 100644 --- a/ledger/src/signer/src/bc_err.h +++ b/firmware/src/powhsm/src/bc_err.h @@ -25,6 +25,8 @@ #ifndef __BC_ERR_H #define __BC_ERR_H +#include "hal/exceptions.h" + // Error codes returned by blockchain protocols typedef enum { UNKNOWN = 0, diff --git a/ledger/src/signer/src/bc_hash.c b/firmware/src/powhsm/src/bc_hash.c similarity index 100% rename from ledger/src/signer/src/bc_hash.c rename to firmware/src/powhsm/src/bc_hash.c diff --git a/ledger/src/signer/src/bc_hash.h b/firmware/src/powhsm/src/bc_hash.h similarity index 85% rename from ledger/src/signer/src/bc_hash.h rename to firmware/src/powhsm/src/bc_hash.h index 413dcff9..2750dfcf 100644 --- a/ledger/src/signer/src/bc_hash.h +++ b/firmware/src/powhsm/src/bc_hash.h @@ -37,22 +37,20 @@ // - Ledger (the real thing): use BOLOS_SDK, version 1.3 // ----------------------------------------------------------------------- -#include "os.h" +#include -typedef cx_sha256_t sha256_ctx_t; -typedef cx_sha3_t keccak_ctx_t; +#include "hal/hash.h" -#define SHA256_INIT(ctx) cx_sha256_init(ctx) -#define SHA256_UPDATE(ctx, data, len) \ - cx_hash((cx_hash_t*)(ctx), 0, data, len, NULL) -#define SHA256_FINAL(ctx, hash) \ - cx_hash((cx_hash_t*)(ctx), CX_LAST, NULL, 0, hash) +typedef hash_sha256_ctx_t sha256_ctx_t; +typedef hash_keccak256_ctx_t keccak_ctx_t; -#define KECCAK_INIT(ctx) cx_keccak_init(ctx, 256) -#define KECCAK_UPDATE(ctx, data, len) \ - cx_hash((cx_hash_t*)(ctx), 0, (uint8_t*)data, len, NULL) -#define KECCAK_FINAL(ctx, hash) \ - cx_hash((cx_hash_t*)(ctx), CX_LAST, NULL, 0, hash) +#define SHA256_INIT(ctx) hash_sha256_init(ctx) +#define SHA256_UPDATE(ctx, data, len) hash_sha256_update(ctx, data, len) +#define SHA256_FINAL(ctx, hash) hash_sha256_final(ctx, hash) + +#define KECCAK_INIT(ctx) hash_keccak256_init(ctx) +#define KECCAK_UPDATE(ctx, data, len) hash_keccak256_update(ctx, data, len) +#define KECCAK_FINAL(ctx, hash) hash_keccak256_final(ctx, hash) // Convenience macros to deal with frequent hash ops #define HEQ(h0, h1) (memcmp(h0, h1, HASH_SIZE) == 0) diff --git a/ledger/src/signer/src/bc_mm.c b/firmware/src/powhsm/src/bc_mm.c similarity index 100% rename from ledger/src/signer/src/bc_mm.c rename to firmware/src/powhsm/src/bc_mm.c diff --git a/ledger/src/signer/src/bc_mm.h b/firmware/src/powhsm/src/bc_mm.h similarity index 100% rename from ledger/src/signer/src/bc_mm.h rename to firmware/src/powhsm/src/bc_mm.h diff --git a/ledger/src/signer/src/bc_nu.h b/firmware/src/powhsm/src/bc_nu.h similarity index 99% rename from ledger/src/signer/src/bc_nu.h rename to firmware/src/powhsm/src/bc_nu.h index a2ad7dad..78d87343 100644 --- a/ledger/src/signer/src/bc_nu.h +++ b/firmware/src/powhsm/src/bc_nu.h @@ -71,7 +71,7 @@ typedef enum { #define SET_NETWORK_UPGRADE(bn, x) \ { *(x) = NU_IRIS; } #define GET_NETWORK_IDENTIFIER() NETID_REGTEST -#elif defined(HSM_SIMULATOR) +#elif defined(HSM_PLATFORM_X86) #include "hsmsim_nu.h" #define SET_NETWORK_UPGRADE(bn, x) hsmsim_set_network_upgrade(bn, x) #define GET_NETWORK_IDENTIFIER() hsmsim_get_network_identifier() diff --git a/ledger/src/signer/src/bc_state.c b/firmware/src/powhsm/src/bc_state.c similarity index 98% rename from ledger/src/signer/src/bc_state.c rename to firmware/src/powhsm/src/bc_state.c index 106b385c..633a5857 100644 --- a/ledger/src/signer/src/bc_state.c +++ b/firmware/src/powhsm/src/bc_state.c @@ -28,7 +28,7 @@ #include "runtime.h" #include "defs.h" #include "err.h" -#include "dbg.h" +#include "hal/log.h" #include "nvm.h" #include "memutil.h" @@ -42,14 +42,13 @@ // ----------------------------------------------------------------------- // Here we take it from an external definition (see Makefile for details) -#ifdef PARAM_INITIAL_BLOCK_HASH +#if defined(HSM_PLATFORM_LEDGER) && defined(PARAM_INITIAL_BLOCK_HASH) static const uint8_t INITIAL_BLOCK_HASH[] = PARAM_INITIAL_BLOCK_HASH; +#elif defined(HSM_PLATFORM_X86) +uint8_t INITIAL_BLOCK_HASH[HASH_LENGTH]; #else -#ifndef HSM_SIMULATOR #error "Initial block hash not defined!" #endif -uint8_t INITIAL_BLOCK_HASH[HASH_LENGTH]; -#endif /* * Initialize blockchain state. @@ -238,6 +237,7 @@ unsigned int bc_get_state(volatile unsigned int rx) { } FAIL(PROT_INVALID); + return 0; } /* diff --git a/ledger/src/signer/src/bc_state.h b/firmware/src/powhsm/src/bc_state.h similarity index 99% rename from ledger/src/signer/src/bc_state.h rename to firmware/src/powhsm/src/bc_state.h index 7165d993..0551af4c 100644 --- a/ledger/src/signer/src/bc_state.h +++ b/firmware/src/powhsm/src/bc_state.h @@ -32,7 +32,7 @@ #include #include -#include "os.h" +#include "hal/platform.h" #include "bigdigits.h" #include "nvm.h" diff --git a/ledger/src/signer/src/bigdigits.c b/firmware/src/powhsm/src/bigdigits.c similarity index 93% rename from ledger/src/signer/src/bigdigits.c rename to firmware/src/powhsm/src/bigdigits.c index c62fe3e3..cf2f7128 100644 --- a/ledger/src/signer/src/bigdigits.c +++ b/firmware/src/powhsm/src/bigdigits.c @@ -1,27 +1,27 @@ -/** - * The MIT License (MIT) - * - * Copyright (c) 2021 RSK Labs Ltd - * - * 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. - */ - +/** + * The MIT License (MIT) + * + * Copyright (c) 2021 RSK Labs Ltd + * + * 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. + */ + /* $Id: bigdigits.c $ */ /***** BEGIN LICENSE BLOCK ***** @@ -47,6 +47,7 @@ #define assert(x) #include "bigdigits.h" +#include "hal/log.h" #define BITS_PER_HALF_DIGIT (BITS_PER_DIGIT / 2) #define LOHALF(x) ((DIGIT_T)((x) & MAX_HALF_DIGIT)) @@ -763,3 +764,31 @@ DIGIT_T spDivide(DIGIT_T *q, DIGIT_T *r, const DIGIT_T u[2], DIGIT_T v) *r = uu[0]; return q2; } + +// Platform-dependent code +#ifndef HSM_PLATFORM_LEDGER + +void LOG_BIGD_HEX(const char *prefix, + const DIGIT_T *a, + size_t len, + const char *suffix) { + if (prefix) + LOG("%s", prefix); + /* Trim leading digits which are zero */ + while (len--) { + if (a[len] != 0) + break; + } + len++; + if (0 == len) + len = 1; + /* print first digit without leading zeros */ + LOG("0x%" PRIxBIGD, a[--len]); + while (len--) { + LOG("%08" PRIxBIGD, a[len]); + } + if (suffix) + LOG("%s", suffix); +} + +#endif \ No newline at end of file diff --git a/ledger/src/signer/src/bigdigits.h b/firmware/src/powhsm/src/bigdigits.h similarity index 90% rename from ledger/src/signer/src/bigdigits.h rename to firmware/src/powhsm/src/bigdigits.h index 898e5ae3..c1d9cd61 100644 --- a/ledger/src/signer/src/bigdigits.h +++ b/firmware/src/powhsm/src/bigdigits.h @@ -157,4 +157,26 @@ DIGIT_T mpShortDiv(DIGIT_T q[], const DIGIT_T u[], DIGIT_T d, size_t ndigits); } #endif +// Platform-dependent code +#ifndef HSM_PLATFORM_LEDGER + +/** + * @brief Print big integer in hex format with optional prefix and suffix strings + * + * @param prefix the log prefix (the general log prefix will be prepended too) + * @param a the big integer to print as hexadecimal + * @param len the size of a in bigint digits + * @param suffix the log suffix + */ +void LOG_BIGD_HEX(const char *prefix, + const DIGIT_T *a, + size_t len, + const char *suffix); + +#else + +#define LOG_BIGD_HEX(...) + +#endif // !HSM_PLATFORM_LEDGER + #endif // __BIGDIGITS_H diff --git a/ledger/src/signer/src/bigdtypes.h b/firmware/src/powhsm/src/bigdtypes.h similarity index 100% rename from ledger/src/signer/src/bigdtypes.h rename to firmware/src/powhsm/src/bigdtypes.h diff --git a/ledger/src/signer/src/btcscript.c b/firmware/src/powhsm/src/btcscript.c similarity index 100% rename from ledger/src/signer/src/btcscript.c rename to firmware/src/powhsm/src/btcscript.c diff --git a/ledger/src/signer/src/btcscript.h b/firmware/src/powhsm/src/btcscript.h similarity index 100% rename from ledger/src/signer/src/btcscript.h rename to firmware/src/powhsm/src/btcscript.h diff --git a/ledger/src/signer/src/btctx.c b/firmware/src/powhsm/src/btctx.c similarity index 100% rename from ledger/src/signer/src/btctx.c rename to firmware/src/powhsm/src/btctx.c diff --git a/ledger/src/signer/src/btctx.h b/firmware/src/powhsm/src/btctx.h similarity index 100% rename from ledger/src/signer/src/btctx.h rename to firmware/src/powhsm/src/btctx.h diff --git a/ledger/src/common/test/memutil/os.h b/firmware/src/powhsm/src/common_requirements.h similarity index 87% rename from ledger/src/common/test/memutil/os.h rename to firmware/src/powhsm/src/common_requirements.h index bdafac20..13dd7e6f 100644 --- a/ledger/src/common/test/memutil/os.h +++ b/firmware/src/powhsm/src/common_requirements.h @@ -22,4 +22,10 @@ * IN THE SOFTWARE. */ -void os_memmove(void *dst, const void *src, unsigned int length); \ No newline at end of file +#ifndef __COMMON_REQUIREMENTS_H +#define __COMMON_REQUIREMENTS_H + +#include "hal/communication.h" +#include "hal/platform.h" + +#endif // __COMMON_REQUIREMENTS_H diff --git a/ledger/src/signer/src/defs.h b/firmware/src/powhsm/src/defs.h similarity index 97% rename from ledger/src/signer/src/defs.h rename to firmware/src/powhsm/src/defs.h index b96749ab..1a0b14fb 100644 --- a/ledger/src/signer/src/defs.h +++ b/firmware/src/powhsm/src/defs.h @@ -25,7 +25,7 @@ #ifndef __DEFS_H #define __DEFS_H -#include "constants.h" +#include "hal/constants.h" // Version and patchlevel #define VERSION_MAJOR 0x05 diff --git a/ledger/src/signer/src/err.h b/firmware/src/powhsm/src/err.h similarity index 100% rename from ledger/src/signer/src/err.h rename to firmware/src/powhsm/src/err.h diff --git a/ledger/src/signer/src/flags.h b/firmware/src/powhsm/src/flags.h similarity index 100% rename from ledger/src/signer/src/flags.h rename to firmware/src/powhsm/src/flags.h diff --git a/ledger/src/signer/src/heartbeat.c b/firmware/src/powhsm/src/heartbeat.c similarity index 87% rename from ledger/src/signer/src/heartbeat.c rename to firmware/src/powhsm/src/heartbeat.c index 19ab4ad4..6e01605d 100644 --- a/ledger/src/signer/src/heartbeat.c +++ b/firmware/src/powhsm/src/heartbeat.c @@ -24,7 +24,10 @@ #include -#include "os.h" +#include "hal/endorsement.h" +#include "hal/platform.h" +#include "hal/exceptions.h" + #include "heartbeat.h" #include "apdu.h" #include "defs.h" @@ -75,6 +78,8 @@ unsigned int get_heartbeat(volatile unsigned int rx, COMPILE_TIME_ASSERT(MAX_HEARTBEAT_MESSAGE_SIZE <= APDU_TOTAL_DATA_SIZE_OUT); + uint8_t out_size; + switch (APDU_OP()) { case OP_HBT_UD_VALUE: // Should receive a user-defined value @@ -138,8 +143,13 @@ unsigned int get_heartbeat(volatile unsigned int rx, check_state(heartbeat_ctx, STATE_HEARTBEAT_READY); // Sign message - int endorsement_size = os_endorsement_key2_derive_sign_data( - heartbeat_ctx->msg, heartbeat_ctx->msg_offset, APDU_DATA_PTR); + uint8_t endorsement_size = APDU_TOTAL_DATA_SIZE_OUT; + if (!endorsement_sign(heartbeat_ctx->msg, + heartbeat_ctx->msg_offset, + APDU_DATA_PTR, + &endorsement_size)) { + THROW(ERR_HBT_INTERNAL); + } return TX_FOR_DATA_SIZE(endorsement_size); case OP_HBT_GET_MESSAGE: @@ -156,13 +166,21 @@ unsigned int get_heartbeat(volatile unsigned int rx, return TX_FOR_DATA_SIZE(heartbeat_ctx->msg_offset); case OP_HBT_APP_HASH: - return TX_FOR_DATA_SIZE(os_endorsement_get_code_hash(APDU_DATA_PTR)); + out_size = APDU_TOTAL_DATA_SIZE_OUT; + if (!endorsement_get_code_hash(APDU_DATA_PTR, &out_size)) { + THROW(ERR_HBT_INTERNAL); + } + return TX_FOR_DATA_SIZE(out_size); case OP_HBT_PUBKEY: - return TX_FOR_DATA_SIZE(os_endorsement_get_public_key( - ENDORSEMENT_SCHEME_INDEX, APDU_DATA_PTR)); + out_size = APDU_TOTAL_DATA_SIZE_OUT; + if (!endorsement_get_public_key(APDU_DATA_PTR, &out_size)) { + THROW(ERR_HBT_INTERNAL); + } + return TX_FOR_DATA_SIZE(out_size); default: reset_heartbeat(heartbeat_ctx); THROW(ERR_HBT_PROT_INVALID); break; } + return 0; } diff --git a/ledger/src/signer/src/heartbeat.h b/firmware/src/powhsm/src/heartbeat.h similarity index 97% rename from ledger/src/signer/src/heartbeat.h rename to firmware/src/powhsm/src/heartbeat.h index ba8de8c9..4b68a1ee 100644 --- a/ledger/src/signer/src/heartbeat.h +++ b/firmware/src/powhsm/src/heartbeat.h @@ -55,9 +55,6 @@ typedef enum { // to include in the message #define LAST_SIGNED_TX_BYTES 8 // bytes -// Index of the endorsement scheme -#define ENDORSEMENT_SCHEME_INDEX 2 - // Maximum heartbeat message to sign size #define MAX_HEARTBEAT_MESSAGE_SIZE 80 diff --git a/ledger/src/signer/src/hsm.c b/firmware/src/powhsm/src/hsm.c similarity index 77% rename from ledger/src/signer/src/hsm.c rename to firmware/src/powhsm/src/hsm.c index 4f47062c..e1a0f12f 100644 --- a/ledger/src/signer/src/hsm.c +++ b/firmware/src/powhsm/src/hsm.c @@ -24,9 +24,12 @@ #include +#include "hal/communication.h" +#include "hal/seed.h" +#include "hal/platform.h" +#include "hal/exceptions.h" + #include "hsm.h" -#include "os.h" -#include "os_io_seproxyhal.h" #include "defs.h" #include "instructions.h" @@ -37,7 +40,6 @@ #include "pathAuth.h" #include "auth.h" -#include "sign.h" #include "bc_state.h" #include "bc_advance.h" @@ -46,12 +48,12 @@ #include "attestation.h" #include "heartbeat.h" -#include "dbg.h" +#include "hal/log.h" // Macro that throws an error unless // the device is onboarded -#define REQUIRE_ONBOARDED() \ - if (os_perso_isonboarded() != 1) \ +#define REQUIRE_ONBOARDED() \ + if (!seed_available()) \ THROW(ERR_DEVICE_NOT_ONBOARDED); // Operation being currently executed @@ -85,19 +87,13 @@ static void reset_if_starting(unsigned char cmd) { // Exit the application static void app_exit(void) { - BEGIN_TRY_L(exit) { - TRY_L(exit) { - os_sched_exit(-1); - _hsm_exit_requested = true; - } - FINALLY_L(exit) { - } - } - END_TRY_L(exit); + platform_request_exit(); + _hsm_exit_requested = true; } -unsigned int hsm_process_apdu(volatile unsigned int rx) { +static unsigned int hsm_process_apdu(volatile unsigned int rx) { unsigned int tx = 0; + uint8_t pubkey_length; // No apdu received if (rx == 0) { @@ -107,7 +103,8 @@ unsigned int hsm_process_apdu(volatile unsigned int rx) { // Zero out commonly read APDU buffer offsets, // to avoid reading uninitialized memory if (rx < MIN_APDU_BYTES) { - explicit_bzero(G_io_apdu_buffer + rx, MIN_APDU_BYTES - rx); + explicit_bzero(communication_get_msg_buffer() + rx, + MIN_APDU_BYTES - rx); } // Invalid CLA @@ -127,7 +124,7 @@ unsigned int hsm_process_apdu(volatile unsigned int rx) { case RSK_IS_ONBOARD: reset_if_starting(RSK_IS_ONBOARD); uint8_t output_index = CMDPOS; - SET_APDU_AT(output_index++, os_perso_isonboarded()); + SET_APDU_AT(output_index++, seed_available() ? 1 : 0); SET_APDU_AT(output_index++, VERSION_MAJOR); SET_APDU_AT(output_index++, VERSION_MINOR); SET_APDU_AT(output_index++, VERSION_PATCH); @@ -141,7 +138,7 @@ unsigned int hsm_process_apdu(volatile unsigned int rx) { reset_if_starting(INS_GET_PUBLIC_KEY); // Check the received data size - if (rx != DATA + sizeof(uint32_t) * DERIVATION_PATH_PARTS) + if (rx != DATA + sizeof(uint32_t) * BIP32_PATH_NUMPARTS) THROW(ERR_INVALID_DATA_SIZE); // Wrong buffer size // Check for path validity before returning the public key @@ -164,16 +161,17 @@ unsigned int hsm_process_apdu(volatile unsigned int rx) { MEMMOVE_ZERO_OFFSET, sizeof(auth.path), THROW(ERR_INVALID_PATH)); - tx = do_pubkey(auth.path, - DERIVATION_PATH_PARTS, - G_io_apdu_buffer, - sizeof(G_io_apdu_buffer)); - // Error deriving? - if (tx == DO_PUBKEY_ERROR) { + pubkey_length = communication_get_msg_buffer_size(); + if (!seed_derive_pubkey(auth.path, + sizeof(auth.path) / sizeof(auth.path[0]), + communication_get_msg_buffer(), + &pubkey_length)) { THROW(ERR_INTERNAL); } + tx = pubkey_length; + break; case INS_SIGN: @@ -253,7 +251,8 @@ unsigned int hsm_process_apdu(volatile unsigned int rx) { return tx; } -unsigned int hsm_process_exception(unsigned short code, unsigned int tx) { +static unsigned int hsm_process_exception(unsigned short code, + unsigned int tx) { unsigned short sw = 0; // Always reset the full state when an error occurs @@ -275,7 +274,7 @@ unsigned int hsm_process_exception(unsigned short code, unsigned int tx) { // Append resulting code to APDU // (check for a potential overflow first) - if (tx + 2 > sizeof(G_io_apdu_buffer)) { + if (tx + 2 > communication_get_msg_buffer_size()) { tx = 0; sw = 0x6983; } @@ -285,6 +284,10 @@ unsigned int hsm_process_exception(unsigned short code, unsigned int tx) { return tx; } +static bool hsm_exit_requested() { + return _hsm_exit_requested; +} + void hsm_init() { // Initialize current operation // (0 = no operation being executed) @@ -297,6 +300,34 @@ void hsm_init() { bc_init_state(); } -bool hsm_exit_requested() { - return _hsm_exit_requested; +void hsm_main_loop() { + volatile unsigned int rx = 0; + volatile unsigned int tx = 0; + + // DESIGN NOTE: the bootloader ignores the way APDU are fetched. The only + // goal is to retrieve APDU. + // When APDU are to be fetched from multiple IOs, like NFC+USB+BLE, make + // sure the io_event is called with a + // switch event, before the apdu is replied to the bootloader. This avoid + // APDU injection faults. + while (!hsm_exit_requested()) { + BEGIN_TRY { + TRY { + // ensure no race in catch_other if io_exchange throws + // an error + rx = tx; + tx = 0; + rx = communication_io_exchange(rx); + + tx = hsm_process_apdu(rx); + THROW(0x9000); + } + CATCH_OTHER(e) { + tx = hsm_process_exception(e, tx); + } + FINALLY { + } + } + END_TRY; + } } diff --git a/ledger/src/signer/src/hsm.h b/firmware/src/powhsm/src/hsm.h similarity index 86% rename from ledger/src/signer/src/hsm.h rename to firmware/src/powhsm/src/hsm.h index 72a5bda2..be9a5048 100644 --- a/ledger/src/signer/src/hsm.h +++ b/firmware/src/powhsm/src/hsm.h @@ -29,10 +29,12 @@ void hsm_init(); -unsigned int hsm_process_apdu(volatile unsigned int rx); +void hsm_main_loop(); -unsigned int hsm_process_exception(unsigned short code, unsigned int tx); +// unsigned int hsm_process_apdu(volatile unsigned int rx); -bool hsm_exit_requested(); +// unsigned int hsm_process_exception(unsigned short code, unsigned int tx); + +// bool hsm_exit_requested(); #endif // __HSM_H diff --git a/ledger/src/signer/src/instructions.h b/firmware/src/powhsm/src/instructions.h similarity index 100% rename from ledger/src/signer/src/instructions.h rename to firmware/src/powhsm/src/instructions.h diff --git a/ledger/src/signer/src/mem.c b/firmware/src/powhsm/src/mem.c similarity index 100% rename from ledger/src/signer/src/mem.c rename to firmware/src/powhsm/src/mem.c diff --git a/ledger/src/signer/src/mem.h b/firmware/src/powhsm/src/mem.h similarity index 89% rename from ledger/src/signer/src/mem.h rename to firmware/src/powhsm/src/mem.h index 97731a5d..ac610f20 100644 --- a/ledger/src/signer/src/mem.h +++ b/firmware/src/powhsm/src/mem.h @@ -25,6 +25,10 @@ #ifndef __MEM_H #define __MEM_H +#include "hal/constants.h" +#include "hal/seed.h" +#include "hal/hash.h" + #include "bc_block.h" #include "bc_state.h" #include "btctx.h" @@ -41,13 +45,12 @@ #define MAX_ATT_MESSAGE_SIZE 50 typedef struct att_s { - sha256_ctx_t hash_ctx; // Attestation public keys hashing context + hash_sha256_ctx_t hash_ctx; // Attestation public keys hashing context uint8_t msg[MAX_ATT_MESSAGE_SIZE]; // Attestation message - unsigned int path[DERIVATION_PATH_PARTS]; - cx_ecfp_public_key_t pub_key; - cx_ecfp_private_key_t priv_key; - unsigned char priv_key_data[PRIVATE_KEY_LENGTH]; + uint32_t path[BIP32_PATH_NUMPARTS]; + uint8_t pubkey[PUBKEY_UNCMP_LENGTH]; + uint8_t pubkey_length; } att_t; typedef union { diff --git a/ledger/src/signer/src/nvm.h b/firmware/src/powhsm/src/nvm.h similarity index 77% rename from ledger/src/signer/src/nvm.h rename to firmware/src/powhsm/src/nvm.h index 88128753..d3d90788 100644 --- a/ledger/src/signer/src/nvm.h +++ b/firmware/src/powhsm/src/nvm.h @@ -25,12 +25,9 @@ #ifndef __NVM_H #define __NVM_H -// ----------------------------------------------------------------------- -// Portable non-volatile memory access. -// ----------------------------------------------------------------------- +#include "hal/nvmem.h" -#include "os.h" -#define NVM_RESET(dst, size) nvm_write((void*)(dst), NULL, size) -#define NVM_WRITE(dst, src, size) nvm_write((void*)(dst), (void*)(src), size) +#define NVM_RESET(dst, size) nvmem_write((void*)(dst), NULL, size) +#define NVM_WRITE(dst, src, size) nvmem_write((void*)(dst), (void*)(src), size) #endif // __NVM_H diff --git a/ledger/src/signer/src/pathAuth.c b/firmware/src/powhsm/src/pathAuth.c similarity index 100% rename from ledger/src/signer/src/pathAuth.c rename to firmware/src/powhsm/src/pathAuth.c diff --git a/ledger/src/signer/src/pathAuth.h b/firmware/src/powhsm/src/pathAuth.h similarity index 100% rename from ledger/src/signer/src/pathAuth.h rename to firmware/src/powhsm/src/pathAuth.h diff --git a/ledger/src/signer/src/protocol.txt b/firmware/src/powhsm/src/protocol.txt similarity index 100% rename from ledger/src/signer/src/protocol.txt rename to firmware/src/powhsm/src/protocol.txt diff --git a/ledger/src/signer/src/srlp.c b/firmware/src/powhsm/src/srlp.c similarity index 96% rename from ledger/src/signer/src/srlp.c rename to firmware/src/powhsm/src/srlp.c index b24b6549..b01cb638 100644 --- a/ledger/src/signer/src/srlp.c +++ b/firmware/src/powhsm/src/srlp.c @@ -26,11 +26,11 @@ #include #include -#include "srlp.h" - -#include "os.h" +#include "hal/platform.h" +#include "hal/log.h" -#include "dbg.h" +#include "srlp.h" +#include "runtime.h" // This code tinkers with function pointers referenced from // const data structures, so we need to use the PIC macro. @@ -181,6 +181,20 @@ void rlp_start(const rlp_callbacks_t* cbs) { } \ } +/** Print the given SRLP context (see srlp.h) */ +#ifdef DEBUG_SRLP +static void LOG_SRLP_CTX(uint8_t v, rlp_ctx_t ctx[], uint8_t ptr) { + LOG("'0x%02x' ; <%u> ; ", v, ptr); + for (int i = ptr; i >= 0; --i) { + rlp_ctx_t cur = ctx[i]; + LOG("{%d, %u, %u} ; ", cur.state, cur.size, cur.cursor); + } + LOG("{EOC}\n"); +} +#else +#define LOG_SRLP_CTX(...) +#endif + /* * Consume a chunk of bytes. * diff --git a/ledger/src/signer/src/srlp.h b/firmware/src/powhsm/src/srlp.h similarity index 100% rename from ledger/src/signer/src/srlp.h rename to firmware/src/powhsm/src/srlp.h diff --git a/ledger/src/signer/src/svarint.c b/firmware/src/powhsm/src/svarint.c similarity index 100% rename from ledger/src/signer/src/svarint.c rename to firmware/src/powhsm/src/svarint.c diff --git a/ledger/src/signer/src/svarint.h b/firmware/src/powhsm/src/svarint.h similarity index 100% rename from ledger/src/signer/src/svarint.h rename to firmware/src/powhsm/src/svarint.h diff --git a/ledger/src/signer/src/trie.c b/firmware/src/powhsm/src/trie.c similarity index 100% rename from ledger/src/signer/src/trie.c rename to firmware/src/powhsm/src/trie.c diff --git a/ledger/src/signer/src/trie.h b/firmware/src/powhsm/src/trie.h similarity index 100% rename from ledger/src/signer/src/trie.h rename to firmware/src/powhsm/src/trie.h diff --git a/ledger/src/signer/src/util.h b/firmware/src/powhsm/src/util.h similarity index 100% rename from ledger/src/signer/src/util.h rename to firmware/src/powhsm/src/util.h diff --git a/firmware/src/powhsm/test/btcscript/Makefile b/firmware/src/powhsm/test/btcscript/Makefile new file mode 100644 index 00000000..f1ee3833 --- /dev/null +++ b/firmware/src/powhsm/test/btcscript/Makefile @@ -0,0 +1,38 @@ +# The MIT License (MIT) +# +# Copyright (c) 2021 RSK Labs Ltd +# +# 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 ../common/common.mk + +PROG = test.out +OBJS = test_fwk.o btcscript.o hex_reader.o test_btcscript.o + +all: $(PROG) + +$(PROG): $(OBJS) + $(CC) $(COVFLAGS) -o $@ $^ + +.PHONY: clean test +clean: + rm -f $(PROG) *.o $(COVFILES) + +test: all + ./$(PROG) diff --git a/firmware/src/powhsm/test/btcscript/btcscript.o b/firmware/src/powhsm/test/btcscript/btcscript.o new file mode 100644 index 00000000..acae6192 Binary files /dev/null and b/firmware/src/powhsm/test/btcscript/btcscript.o differ diff --git a/firmware/src/powhsm/test/btcscript/hex_reader.o b/firmware/src/powhsm/test/btcscript/hex_reader.o new file mode 100644 index 00000000..4826ca38 Binary files /dev/null and b/firmware/src/powhsm/test/btcscript/hex_reader.o differ diff --git a/firmware/src/powhsm/test/btcscript/test.out b/firmware/src/powhsm/test/btcscript/test.out new file mode 100755 index 00000000..c8500186 Binary files /dev/null and b/firmware/src/powhsm/test/btcscript/test.out differ diff --git a/ledger/src/signer/test/btcscript/test_btcscript.c b/firmware/src/powhsm/test/btcscript/test_btcscript.c similarity index 100% rename from ledger/src/signer/test/btcscript/test_btcscript.c rename to firmware/src/powhsm/test/btcscript/test_btcscript.c diff --git a/firmware/src/powhsm/test/btcscript/test_btcscript.o b/firmware/src/powhsm/test/btcscript/test_btcscript.o new file mode 100644 index 00000000..f665c504 Binary files /dev/null and b/firmware/src/powhsm/test/btcscript/test_btcscript.o differ diff --git a/firmware/src/powhsm/test/btcscript/test_fwk.o b/firmware/src/powhsm/test/btcscript/test_fwk.o new file mode 100644 index 00000000..4ebfd3ef Binary files /dev/null and b/firmware/src/powhsm/test/btcscript/test_fwk.o differ diff --git a/firmware/src/powhsm/test/btctx/Makefile b/firmware/src/powhsm/test/btctx/Makefile new file mode 100644 index 00000000..cc6aedeb --- /dev/null +++ b/firmware/src/powhsm/test/btctx/Makefile @@ -0,0 +1,38 @@ +# The MIT License (MIT) +# +# Copyright (c) 2021 RSK Labs Ltd +# +# 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 ../common/common.mk + +PROG = test.out +OBJS = test_fwk.o btctx.o svarint.o hex_reader.o test_btctx.o platform.o log.o + +all: $(PROG) + +$(PROG): $(OBJS) + $(CC) $(COVFLAGS) -o $@ $^ + +.PHONY: clean test +clean: + rm -f $(PROG) *.o $(COVFILES) + +test: all + ./$(PROG) diff --git a/firmware/src/powhsm/test/btctx/hex_reader.o b/firmware/src/powhsm/test/btctx/hex_reader.o new file mode 100644 index 00000000..4826ca38 Binary files /dev/null and b/firmware/src/powhsm/test/btctx/hex_reader.o differ diff --git a/ledger/src/signer/test/btctx/resources/tx-001.hex b/firmware/src/powhsm/test/btctx/resources/tx-001.hex similarity index 100% rename from ledger/src/signer/test/btctx/resources/tx-001.hex rename to firmware/src/powhsm/test/btctx/resources/tx-001.hex diff --git a/ledger/src/signer/test/btctx/resources/tx-002.hex b/firmware/src/powhsm/test/btctx/resources/tx-002.hex similarity index 100% rename from ledger/src/signer/test/btctx/resources/tx-002.hex rename to firmware/src/powhsm/test/btctx/resources/tx-002.hex diff --git a/ledger/src/signer/test/btctx/resources/tx-003.hex b/firmware/src/powhsm/test/btctx/resources/tx-003.hex similarity index 100% rename from ledger/src/signer/test/btctx/resources/tx-003.hex rename to firmware/src/powhsm/test/btctx/resources/tx-003.hex diff --git a/ledger/src/signer/test/btctx/resources/tx-004.hex b/firmware/src/powhsm/test/btctx/resources/tx-004.hex similarity index 100% rename from ledger/src/signer/test/btctx/resources/tx-004.hex rename to firmware/src/powhsm/test/btctx/resources/tx-004.hex diff --git a/firmware/src/powhsm/test/btctx/svarint.o b/firmware/src/powhsm/test/btctx/svarint.o new file mode 100644 index 00000000..64db7f1f Binary files /dev/null and b/firmware/src/powhsm/test/btctx/svarint.o differ diff --git a/ledger/src/signer/test/btctx/test_btctx.c b/firmware/src/powhsm/test/btctx/test_btctx.c similarity index 100% rename from ledger/src/signer/test/btctx/test_btctx.c rename to firmware/src/powhsm/test/btctx/test_btctx.c diff --git a/firmware/src/powhsm/test/btctx/test_fwk.o b/firmware/src/powhsm/test/btctx/test_fwk.o new file mode 100644 index 00000000..4ebfd3ef Binary files /dev/null and b/firmware/src/powhsm/test/btctx/test_fwk.o differ diff --git a/firmware/src/powhsm/test/common/common.mk b/firmware/src/powhsm/test/common/common.mk new file mode 100644 index 00000000..a451158f --- /dev/null +++ b/firmware/src/powhsm/test/common/common.mk @@ -0,0 +1,15 @@ +TESTCOMMONDIR = ../common +SRCDIR = ../../src +HALINCDIR = ../../../hal/include +HALSRCDIR = ../../../hal/src/x86 +COMMONDIR = ../../../common/src +CFLAGS = -iquote $(SRCDIR) -iquote $(HALINCDIR) -iquote $(HALSRCDIR) +CFLAGS += -iquote $(TESTCOMMONDIR) -iquote $(COMMONDIR) +CFLAGS += -iquote $(TESTCOMMONDIR) -iquote $(COMMONDIR) +CFLAGS += -DHSM_PLATFORM_X86 + +VPATH += $(TESTCOMMONDIR):$(SRCDIR):$(HALSRCDIR):$(COMMONDIR) + +include ../../../../coverage/coverage.mk + +CFLAGS += $(COVFLAGS) diff --git a/ledger/src/signer/test/common/test_fwk.c b/firmware/src/powhsm/test/common/test_fwk.c similarity index 100% rename from ledger/src/signer/test/common/test_fwk.c rename to firmware/src/powhsm/test/common/test_fwk.c diff --git a/firmware/src/powhsm/test/common/ui_deps.h b/firmware/src/powhsm/test/common/ui_deps.h new file mode 100644 index 00000000..e69de29b diff --git a/firmware/src/powhsm/test/difficulty/Makefile b/firmware/src/powhsm/test/difficulty/Makefile new file mode 100644 index 00000000..0ce518cb --- /dev/null +++ b/firmware/src/powhsm/test/difficulty/Makefile @@ -0,0 +1,38 @@ +# The MIT License (MIT) +# +# Copyright (c) 2021 RSK Labs Ltd +# +# 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 ../common/common.mk + +PROG = test.out +OBJS = test_fwk.o bigdigits.o bc_diff.o test_difficulty.o platform.o log.o + +all: $(PROG) + +$(PROG): $(OBJS) + $(CC) $(COVFLAGS) -o $@ $^ + +.PHONY: clean test +clean: + rm -f $(PROG) *.o $(COVFILES) + +test: all + ./$(PROG) diff --git a/ledger/src/signer/test/difficulty/test_difficulty.c b/firmware/src/powhsm/test/difficulty/test_difficulty.c similarity index 100% rename from ledger/src/signer/test/difficulty/test_difficulty.c rename to firmware/src/powhsm/test/difficulty/test_difficulty.c diff --git a/firmware/src/powhsm/test/difficulty/test_difficulty.o b/firmware/src/powhsm/test/difficulty/test_difficulty.o new file mode 100644 index 00000000..8fd2864c Binary files /dev/null and b/firmware/src/powhsm/test/difficulty/test_difficulty.o differ diff --git a/firmware/src/powhsm/test/difficulty/test_fwk.o b/firmware/src/powhsm/test/difficulty/test_fwk.o new file mode 100644 index 00000000..4ebfd3ef Binary files /dev/null and b/firmware/src/powhsm/test/difficulty/test_fwk.o differ diff --git a/ledger/src/signer/test/run-all.sh b/firmware/src/powhsm/test/run-all.sh similarity index 100% rename from ledger/src/signer/test/run-all.sh rename to firmware/src/powhsm/test/run-all.sh diff --git a/ledger/src/signer/test/sha256/Makefile b/firmware/src/powhsm/test/sha256/Makefile similarity index 78% rename from ledger/src/signer/test/sha256/Makefile rename to firmware/src/powhsm/test/sha256/Makefile index e116ece6..220e9e67 100644 --- a/ledger/src/signer/test/sha256/Makefile +++ b/firmware/src/powhsm/test/sha256/Makefile @@ -20,11 +20,7 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -TESTCOMMONDIR = ../common -SRCDIR = ../../src -CFLAGS = -I $(SRCDIR) -I $(TESTCOMMONDIR) - -include ../../../../coverage/coverage.mk +include ../common/common.mk PROG = test.out OBJS = test_fwk.o sha256.o test_sha256.o @@ -34,16 +30,6 @@ all: $(PROG) $(PROG): $(OBJS) $(CC) $(COVFLAGS) -o $@ $^ -test_fwk.o: $(TESTCOMMONDIR)/test_fwk.c - $(CC) $(CFLAGS) -c -o $@ $^ - -sha256.o: $(SRCDIR)/sha256.c - $(CC) $(CFLAGS) $(COVFLAGS) -c -o $@ $^ - -test_sha256.o: test_sha256.c test_fwk.o sha256.o - -$(SRCDIR)/sha256.c: $(SRCDIR)/sha256.h - .PHONY: clean test clean: rm -f $(PROG) *.o $(COVFILES) diff --git a/firmware/src/powhsm/test/sha256/sha256.o b/firmware/src/powhsm/test/sha256/sha256.o new file mode 100644 index 00000000..fcb8c696 Binary files /dev/null and b/firmware/src/powhsm/test/sha256/sha256.o differ diff --git a/firmware/src/powhsm/test/sha256/test.out b/firmware/src/powhsm/test/sha256/test.out new file mode 100755 index 00000000..b48a2106 Binary files /dev/null and b/firmware/src/powhsm/test/sha256/test.out differ diff --git a/firmware/src/powhsm/test/sha256/test_fwk.o b/firmware/src/powhsm/test/sha256/test_fwk.o new file mode 100644 index 00000000..4ebfd3ef Binary files /dev/null and b/firmware/src/powhsm/test/sha256/test_fwk.o differ diff --git a/ledger/src/signer/test/sha256/test_sha256.c b/firmware/src/powhsm/test/sha256/test_sha256.c similarity index 100% rename from ledger/src/signer/test/sha256/test_sha256.c rename to firmware/src/powhsm/test/sha256/test_sha256.c diff --git a/firmware/src/powhsm/test/sha256/test_sha256.o b/firmware/src/powhsm/test/sha256/test_sha256.o new file mode 100644 index 00000000..8746029e Binary files /dev/null and b/firmware/src/powhsm/test/sha256/test_sha256.o differ diff --git a/firmware/src/powhsm/test/srlp/Makefile b/firmware/src/powhsm/test/srlp/Makefile new file mode 100644 index 00000000..81f30a92 --- /dev/null +++ b/firmware/src/powhsm/test/srlp/Makefile @@ -0,0 +1,43 @@ +# The MIT License (MIT) +# +# Copyright (c) 2021 RSK Labs Ltd +# +# 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 ../common/common.mk + +# For debugging purposes +ifneq ($(DEBUG),) + CFLAGS += -DDEBUG_SRLP +endif + +PROG = test.out +OBJS = test_fwk.o srlp.o test_srlp.o log.o + +all: $(PROG) + +$(PROG): $(OBJS) + $(CC) $(COVFLAGS) -o $@ $^ + +.PHONY: clean test +clean: + rm -f $(PROG) *.o $(COVFILES) + +test: all + ./$(PROG) diff --git a/ledger/src/signer/test/srlp/mocks/os.h b/firmware/src/powhsm/test/srlp/mocks/os.h similarity index 100% rename from ledger/src/signer/test/srlp/mocks/os.h rename to firmware/src/powhsm/test/srlp/mocks/os.h diff --git a/ledger/src/signer/test/srlp/resources/block-0900123.rlp b/firmware/src/powhsm/test/srlp/resources/block-0900123.rlp similarity index 100% rename from ledger/src/signer/test/srlp/resources/block-0900123.rlp rename to firmware/src/powhsm/test/srlp/resources/block-0900123.rlp diff --git a/ledger/src/signer/test/srlp/resources/block-1234000.rlp b/firmware/src/powhsm/test/srlp/resources/block-1234000.rlp similarity index 100% rename from ledger/src/signer/test/srlp/resources/block-1234000.rlp rename to firmware/src/powhsm/test/srlp/resources/block-1234000.rlp diff --git a/ledger/src/signer/test/srlp/resources/block-1900456.rlp b/firmware/src/powhsm/test/srlp/resources/block-1900456.rlp similarity index 100% rename from ledger/src/signer/test/srlp/resources/block-1900456.rlp rename to firmware/src/powhsm/test/srlp/resources/block-1900456.rlp diff --git a/ledger/src/signer/test/srlp/resources/block-2221171.rlp b/firmware/src/powhsm/test/srlp/resources/block-2221171.rlp similarity index 100% rename from ledger/src/signer/test/srlp/resources/block-2221171.rlp rename to firmware/src/powhsm/test/srlp/resources/block-2221171.rlp diff --git a/ledger/src/signer/test/srlp/resources/block-fakelen.rlp b/firmware/src/powhsm/test/srlp/resources/block-fakelen.rlp similarity index 100% rename from ledger/src/signer/test/srlp/resources/block-fakelen.rlp rename to firmware/src/powhsm/test/srlp/resources/block-fakelen.rlp diff --git a/ledger/src/signer/test/srlp/resources/block-post-wasabi.rlp b/firmware/src/powhsm/test/srlp/resources/block-post-wasabi.rlp similarity index 100% rename from ledger/src/signer/test/srlp/resources/block-post-wasabi.rlp rename to firmware/src/powhsm/test/srlp/resources/block-post-wasabi.rlp diff --git a/ledger/src/signer/test/srlp/resources/block-pre-wasabi.rlp b/firmware/src/powhsm/test/srlp/resources/block-pre-wasabi.rlp similarity index 100% rename from ledger/src/signer/test/srlp/resources/block-pre-wasabi.rlp rename to firmware/src/powhsm/test/srlp/resources/block-pre-wasabi.rlp diff --git a/firmware/src/powhsm/test/srlp/test_fwk.o b/firmware/src/powhsm/test/srlp/test_fwk.o new file mode 100644 index 00000000..4ebfd3ef Binary files /dev/null and b/firmware/src/powhsm/test/srlp/test_fwk.o differ diff --git a/ledger/src/signer/test/srlp/test_srlp.c b/firmware/src/powhsm/test/srlp/test_srlp.c similarity index 100% rename from ledger/src/signer/test/srlp/test_srlp.c rename to firmware/src/powhsm/test/srlp/test_srlp.c diff --git a/firmware/src/powhsm/test/srlp/test_srlp.o b/firmware/src/powhsm/test/srlp/test_srlp.o new file mode 100644 index 00000000..6ec09981 Binary files /dev/null and b/firmware/src/powhsm/test/srlp/test_srlp.o differ diff --git a/ledger/src/signer/test/svarint/Makefile b/firmware/src/powhsm/test/svarint/Makefile similarity index 78% rename from ledger/src/signer/test/svarint/Makefile rename to firmware/src/powhsm/test/svarint/Makefile index de931bda..b40a4e8f 100644 --- a/ledger/src/signer/test/svarint/Makefile +++ b/firmware/src/powhsm/test/svarint/Makefile @@ -20,11 +20,7 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -TESTCOMMONDIR = ../common -SRCDIR = ../../src -CFLAGS = -I $(SRCDIR) -I $(TESTCOMMONDIR) - -include ../../../../coverage/coverage.mk +include ../common/common.mk PROG = test.out OBJS = test_fwk.o svarint.o test_svarint.o @@ -34,16 +30,6 @@ all: $(PROG) $(PROG): $(OBJS) $(CC) $(COVFLAGS) -o $@ $^ -test_fwk.o: $(TESTCOMMONDIR)/test_fwk.c - $(CC) $(CFLAGS) -c -o $@ $^ - -svarint.o: $(SRCDIR)/svarint.c - $(CC) $(CFLAGS) $(COVFLAGS) -c -o $@ $^ - -test_svarint.o: test_svarint.c test_fwk.o svarint.o - -$(SRCDIR)/svarint.c: $(SRCDIR)/svarint.h - .PHONY: clean test clean: rm -f $(PROG) *.o $(COVFILES) diff --git a/firmware/src/powhsm/test/svarint/svarint.o b/firmware/src/powhsm/test/svarint/svarint.o new file mode 100644 index 00000000..64db7f1f Binary files /dev/null and b/firmware/src/powhsm/test/svarint/svarint.o differ diff --git a/firmware/src/powhsm/test/svarint/test.out b/firmware/src/powhsm/test/svarint/test.out new file mode 100755 index 00000000..a23bc5af Binary files /dev/null and b/firmware/src/powhsm/test/svarint/test.out differ diff --git a/firmware/src/powhsm/test/svarint/test_fwk.o b/firmware/src/powhsm/test/svarint/test_fwk.o new file mode 100644 index 00000000..4ebfd3ef Binary files /dev/null and b/firmware/src/powhsm/test/svarint/test_fwk.o differ diff --git a/ledger/src/signer/test/svarint/test_svarint.c b/firmware/src/powhsm/test/svarint/test_svarint.c similarity index 100% rename from ledger/src/signer/test/svarint/test_svarint.c rename to firmware/src/powhsm/test/svarint/test_svarint.c diff --git a/firmware/src/powhsm/test/svarint/test_svarint.o b/firmware/src/powhsm/test/svarint/test_svarint.o new file mode 100644 index 00000000..a4f24c47 Binary files /dev/null and b/firmware/src/powhsm/test/svarint/test_svarint.o differ diff --git a/firmware/src/powhsm/test/trie/Makefile b/firmware/src/powhsm/test/trie/Makefile new file mode 100644 index 00000000..2b4af0ce --- /dev/null +++ b/firmware/src/powhsm/test/trie/Makefile @@ -0,0 +1,38 @@ +# The MIT License (MIT) +# +# Copyright (c) 2021 RSK Labs Ltd +# +# 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 ../common/common.mk + +PROG = test.out +OBJS = test_fwk.o trie.o svarint.o hex_reader.o test_trie.o platform.o log.o + +all: $(PROG) + +$(PROG): $(OBJS) + $(CC) $(COVFLAGS) -o $@ $^ + +.PHONY: clean test +clean: + rm -f $(PROG) *.o $(COVFILES) + +test: all + ./$(PROG) diff --git a/firmware/src/powhsm/test/trie/hex_reader.o b/firmware/src/powhsm/test/trie/hex_reader.o new file mode 100644 index 00000000..4826ca38 Binary files /dev/null and b/firmware/src/powhsm/test/trie/hex_reader.o differ diff --git a/firmware/src/powhsm/test/trie/svarint.o b/firmware/src/powhsm/test/trie/svarint.o new file mode 100644 index 00000000..64db7f1f Binary files /dev/null and b/firmware/src/powhsm/test/trie/svarint.o differ diff --git a/firmware/src/powhsm/test/trie/test_fwk.o b/firmware/src/powhsm/test/trie/test_fwk.o new file mode 100644 index 00000000..4ebfd3ef Binary files /dev/null and b/firmware/src/powhsm/test/trie/test_fwk.o differ diff --git a/ledger/src/signer/test/trie/test_trie.c b/firmware/src/powhsm/test/trie/test_trie.c similarity index 100% rename from ledger/src/signer/test/trie/test_trie.c rename to firmware/src/powhsm/test/trie/test_trie.c diff --git a/firmware/src/powhsm/test/trie/test_trie.o b/firmware/src/powhsm/test/trie/test_trie.o new file mode 100644 index 00000000..7f9bf22b Binary files /dev/null and b/firmware/src/powhsm/test/trie/test_trie.o differ diff --git a/ledger/src/signer/test/utils/block-0900123-exp.txt b/firmware/src/powhsm/test/utils/block-0900123-exp.txt similarity index 100% rename from ledger/src/signer/test/utils/block-0900123-exp.txt rename to firmware/src/powhsm/test/utils/block-0900123-exp.txt diff --git a/ledger/src/signer/test/utils/block-0900123.txt b/firmware/src/powhsm/test/utils/block-0900123.txt similarity index 100% rename from ledger/src/signer/test/utils/block-0900123.txt rename to firmware/src/powhsm/test/utils/block-0900123.txt diff --git a/ledger/src/signer/test/utils/block-1234000.txt b/firmware/src/powhsm/test/utils/block-1234000.txt similarity index 100% rename from ledger/src/signer/test/utils/block-1234000.txt rename to firmware/src/powhsm/test/utils/block-1234000.txt diff --git a/ledger/src/signer/test/utils/block-1900456.exp.txt b/firmware/src/powhsm/test/utils/block-1900456.exp.txt similarity index 100% rename from ledger/src/signer/test/utils/block-1900456.exp.txt rename to firmware/src/powhsm/test/utils/block-1900456.exp.txt diff --git a/ledger/src/signer/test/utils/block-1900456.txt b/firmware/src/powhsm/test/utils/block-1900456.txt similarity index 100% rename from ledger/src/signer/test/utils/block-1900456.txt rename to firmware/src/powhsm/test/utils/block-1900456.txt diff --git a/ledger/src/signer/test/utils/block-2221171.txt b/firmware/src/powhsm/test/utils/block-2221171.txt similarity index 100% rename from ledger/src/signer/test/utils/block-2221171.txt rename to firmware/src/powhsm/test/utils/block-2221171.txt diff --git a/ledger/src/signer/test/utils/block-fakelen.rlp b/firmware/src/powhsm/test/utils/block-fakelen.rlp similarity index 100% rename from ledger/src/signer/test/utils/block-fakelen.rlp rename to firmware/src/powhsm/test/utils/block-fakelen.rlp diff --git a/ledger/src/signer/test/utils/block-fakelen.txt b/firmware/src/powhsm/test/utils/block-fakelen.txt similarity index 100% rename from ledger/src/signer/test/utils/block-fakelen.txt rename to firmware/src/powhsm/test/utils/block-fakelen.txt diff --git a/ledger/src/signer/test/utils/block-post-wasabi.txt b/firmware/src/powhsm/test/utils/block-post-wasabi.txt similarity index 100% rename from ledger/src/signer/test/utils/block-post-wasabi.txt rename to firmware/src/powhsm/test/utils/block-post-wasabi.txt diff --git a/ledger/src/signer/test/utils/block-pre-wasabi.txt b/firmware/src/powhsm/test/utils/block-pre-wasabi.txt similarity index 100% rename from ledger/src/signer/test/utils/block-pre-wasabi.txt rename to firmware/src/powhsm/test/utils/block-pre-wasabi.txt diff --git a/ledger/src/signer/test/utils/bt.py b/firmware/src/powhsm/test/utils/bt.py similarity index 100% rename from ledger/src/signer/test/utils/bt.py rename to firmware/src/powhsm/test/utils/bt.py diff --git a/ledger/src/tcpsigner/Makefile b/firmware/src/tcpsigner/Makefile similarity index 61% rename from ledger/src/tcpsigner/Makefile rename to firmware/src/tcpsigner/Makefile index 39b3cc99..f6529efc 100644 --- a/ledger/src/tcpsigner/Makefile +++ b/firmware/src/tcpsigner/Makefile @@ -20,14 +20,25 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -SRCPATH = ../signer/src +SRCPATH = ./src +POWHSMSRCPATH = ../powhsm/src COMMONPATH = ../common/src -VPATH = $(SRCPATH):$(COMMONPATH) - -include ../../coverage/coverage.mk - -CFLAGS += -g -O0 -I$(SRCPATH) -I$(COMMONPATH) -I. -I /usr/local/include -DHSM_SIMULATOR -CFLAGS += -Werror +HALSRCPATH = ../hal/src/x86 +HALINCPATH = ../hal/include +HALPATH = $(HALINCPATH):$(HALSRCPATH) +VPATH = $(SRCPATH):$(POWHSMSRCPATH):$(COMMONPATH):$(HALPATH) + +# We don't need the code coverage definitions for AFL builds +ifeq ($(HSM_AFL),) + include ../../coverage/coverage.mk +endif + +CFLAGS += -g -O0 -iquote $(SRCPATH) +CFLAGS += -iquote $(POWHSMSRCPATH) +CFLAGS += -iquote $(COMMONPATH) +CFLAGS += -iquote $(HALINCPATH) -iquote $(HALSRCPATH) +CFLAGS += -I /usr/local/include -Werror +CFLAGS += -DHSM_PLATFORM_X86 LDFLAGS = -lsecp256k1 @@ -39,14 +50,17 @@ DEPFLAGS = -MT $@ -MMD -MP -MF $(DEPDIR)/$*.d COMPILE.c = $(CC) $(DEPFLAGS) $(CFLAGS) -c -SIGN_SRCS = $(filter-out %/main.c, $(wildcard $(SRCPATH)/*.c)) +SIGN_SRCS = $(wildcard $(POWHSMSRCPATH)/*.c) COMMON_SRCS = $(wildcard $(COMMONPATH)/*.c) -SIGN_OBJS = $(patsubst $(SRCPATH)/%.c, $(OBJDIR)/%.o, $(SIGN_SRCS)) $(patsubst $(COMMONPATH)/%.c, $(OBJDIR)/%.o, $(COMMON_SRCS)) +HAL_SRCS = $(wildcard $(HALSRCPATH)/*.c) +SIGN_OBJS = $(patsubst $(POWHSMSRCPATH)/%.c, $(OBJDIR)/%.o, $(SIGN_SRCS)) +SIGN_OBJS += $(patsubst $(COMMONPATH)/%.c, $(OBJDIR)/%.o, $(COMMON_SRCS)) +SIGN_OBJS += $(patsubst $(HALSRCPATH)/%.c, $(OBJDIR)/%.o, $(HAL_SRCS)) -SIM_SRCS = $(wildcard *.c) -SIM_OBJS = $(patsubst %.c, $(OBJDIR)/%.o, $(SIM_SRCS)) +SIM_SRCS = $(wildcard $(SRCPATH)/*.c) +SIM_OBJS = $(patsubst $(SRCPATH)/%.c, $(OBJDIR)/%.o, $(SIM_SRCS)) -SRCS = $(SIGN_SRCS) $(COMMON_SRCS) $(SIM_SRCS) +SRCS = $(SIGN_SRCS) $(COMMON_SRCS) $(HAL_SRCS) $(SIM_SRCS) OBJS = $(SIGN_OBJS) $(SIM_OBJS) @@ -58,7 +72,8 @@ $(OBJDIR)/%.o: %.c $(DEPDIR)/%.d | $(DEPDIR) $(COMPILE.c) $(COVFLAGS) -o $@ $< $(DEPDIR): ; @mkdir -p $@ -DEPFILES := $(patsubst $(DEPDIR)/$(SRCPATH)/%.d, $(DEPDIR)/%.d, $(SRCS:%.c=$(DEPDIR)/%.d)) $(patsubst $(DEPDIR)/$(COMMONPATH)/%.d, $(DEPDIR)/%.d, $(SRCS:%.c=$(DEPDIR)/%.d)) + +DEPFILES := $(patsubst %.c, $(DEPDIR)/%.d, $(notdir $(SRCS))) $(DEPFILES): diff --git a/ledger/src/tcpsigner/hsmsim_admin.c b/firmware/src/tcpsigner/src/hsmsim_admin.c similarity index 60% rename from ledger/src/tcpsigner/hsmsim_admin.c rename to firmware/src/tcpsigner/src/hsmsim_admin.c index 2b9947c8..11d5844f 100644 --- a/ledger/src/tcpsigner/hsmsim_admin.c +++ b/firmware/src/tcpsigner/src/hsmsim_admin.c @@ -22,18 +22,20 @@ * IN THE SOFTWARE. */ +#include + +#include "hal/seed.h" +#include "hal/log.h" #include "hsmsim_admin.h" #include "apdu.h" #include "bc_state.h" -#include "log.h" #include "ints.h" static hsmsim_admin_data_t hsmsim_admin_data; void hsmsim_admin_init() { memset(&hsmsim_admin_data, 0, sizeof(hsmsim_admin_data)); - hsmsim_admin_data.is_onboarded = HSMSIM_ADMIN_DEFAULT_IS_ONBOARDED; - info("ADMIN: Init OK.\n"); + LOG("ADMIN: Init OK.\n"); } bool hsmsim_admin_need_process(unsigned int rx) { @@ -42,51 +44,46 @@ bool hsmsim_admin_need_process(unsigned int rx) { static unsigned int hsmsim_admin_error(uint16_t code) { unsigned int tx = 0; - G_io_apdu_buffer[tx++] = HSMSIM_ADMIN_CLA; + SET_APDU_AT(tx++, HSMSIM_ADMIN_CLA); SET_APDU_AT(tx++, code >> 8); SET_APDU_AT(tx++, code); return tx; } static unsigned int hsmsim_admin_ok(unsigned int tx) { - if ((tx + 2 * sizeof(G_io_apdu_buffer[0])) > sizeof(G_io_apdu_buffer)) { - info("ADMIN: Buffer overflow on G_io_apdu_buffer when trying to reply " - "to the host.\n"); + if ((tx + 2 * APDU_ELEMENT_SIZE) > APDU_TOTAL_SIZE) { + LOG("ADMIN: Buffer overflow on I/O when trying to reply " + "to the host.\n"); return hsmsim_admin_error(HSMSIM_ADMIN_ERROR_BUFFER_OVERFLOW); } - G_io_apdu_buffer[tx++] = 0x90; - G_io_apdu_buffer[tx++] = 0x00; + SET_APDU_AT(tx++, 0x90); + SET_APDU_AT(tx++, 0x00); return tx; } -static void hsmsim_admin_nvm_stats_reset() { - memset( - &hsmsim_admin_data.nvm_stats, 0, sizeof(hsmsim_admin_data.nvm_stats)); - info("ADMIN: reset NVM stats OK.\n"); -} - unsigned int hsmsim_admin_process_apdu(unsigned int rx) { unsigned int tx; unsigned int offset; + nvmmem_stats_t nvmmem_stats; if (APDU_CLA() != HSMSIM_ADMIN_CLA) { - info("ADMIN: Invalid CLA: %d.\n", APDU_CLA()); + LOG("ADMIN: Invalid CLA: %d.\n", APDU_CLA()); return hsmsim_admin_error(HSMSIM_ADMIN_ERROR_INVALID_PROTOCOL); } if (rx < MIN_ADMIN_BYTES) { - info("ADMIN: Too few bytes in operation: %d.\n", rx); + LOG("ADMIN: Too few bytes in operation: %d.\n", rx); return hsmsim_admin_error(HSMSIM_ADMIN_ERROR_INVALID_PROTOCOL); } switch (APDU_CMD()) { case HSMSIM_ADMIN_CMD_SET_ANCESTOR_RCPT_ROOT: if (APDU_DATA_SIZE(rx) != HASH_LENGTH) { - info("ADMIN: Invalid ancestor receipts root size. Expected %d " - "bytes, got %d.\n", - HASH_LENGTH, - APDU_DATA_SIZE(rx)); + LOG("ADMIN: Invalid ancestor receipts root size. Expected %d " + "bytes, got %d.\n", + HASH_LENGTH, + APDU_DATA_SIZE(rx)); return hsmsim_admin_error(HSMSIM_ADMIN_ERROR_DATA_SIZE); } memcpy(hsmsim_admin_data.old_ancestor_receipts_root, @@ -94,73 +91,62 @@ unsigned int hsmsim_admin_process_apdu(unsigned int rx) { HASH_LENGTH); memcpy(N_bc_state.ancestor_receipt_root, APDU_DATA_PTR, HASH_LENGTH); hsmsim_admin_data.ancestor_receipts_root_set = true; - info_hex("ADMIN: Ancestor receipts root set to", - N_bc_state.ancestor_receipt_root, - HASH_LENGTH); + LOG_HEX("ADMIN: Ancestor receipts root set to", + N_bc_state.ancestor_receipt_root, + HASH_LENGTH); tx = TX_FOR_DATA_SIZE(0); break; case HSMSIM_ADMIN_CMD_RESET_ANCESTOR_RCPT_ROOT: if (!hsmsim_admin_data.ancestor_receipts_root_set) { - info("ADMIN: Cannot reset ancestor receipts root: not set.\n", - HASH_LENGTH, - APDU_DATA_SIZE(rx)); + LOG("ADMIN: Cannot reset ancestor receipts root: not set.\n"); return hsmsim_admin_error(HSMSIM_ADMIN_ERROR_INVALID_STATE); } memcpy(N_bc_state.ancestor_receipt_root, hsmsim_admin_data.old_ancestor_receipts_root, HASH_LENGTH); hsmsim_admin_data.ancestor_receipts_root_set = false; - info_hex("ADMIN: Ancestor receipts root reset to", - N_bc_state.ancestor_receipt_root, - HASH_LENGTH); + LOG_HEX("ADMIN: Ancestor receipts root reset to", + N_bc_state.ancestor_receipt_root, + HASH_LENGTH); tx = TX_FOR_DATA_SIZE(0); break; case HSMSIM_ADMIN_CMD_RESET_NVM_STATS: - hsmsim_admin_nvm_stats_reset(); + nvmem_stats_reset(); tx = TX_FOR_DATA_SIZE(0); break; case HSMSIM_ADMIN_CMD_GET_NVM_STATS: offset = 0; + nvmmem_stats = nvmem_get_stats(); APDU_DATA_PTR[offset++] = - (unsigned char)sizeof(hsmsim_admin_data.nvm_stats.write_count); + (unsigned char)sizeof(nvmmem_stats.write_count); VAR_BIGENDIAN_TO(APDU_DATA_PTR + offset, - hsmsim_admin_data.nvm_stats.write_count, - sizeof(hsmsim_admin_data.nvm_stats.write_count)); - offset += sizeof(hsmsim_admin_data.nvm_stats.write_count); + nvmmem_stats.write_count, + sizeof(nvmmem_stats.write_count)); + offset += sizeof(nvmmem_stats.write_count); tx = TX_FOR_DATA_SIZE(offset); - info("ADMIN: got NVM stats - %u writes.\n", - hsmsim_admin_data.nvm_stats.write_count); + LOG("ADMIN: got NVM stats - %u writes.\n", nvmmem_stats.write_count); break; case HSMSIM_ADMIN_CMD_GET_IS_ONBOARDED: - APDU_DATA_PTR[0] = (unsigned char)hsmsim_admin_data.is_onboarded; + APDU_DATA_PTR[0] = (unsigned char)seed_available(); tx = TX_FOR_DATA_SIZE(1); - info("ADMIN: got is_onboarded status.\n"); + LOG("ADMIN: got is_onboarded status.\n"); break; case HSMSIM_ADMIN_CMD_SET_IS_ONBOARDED: if (APDU_DATA_SIZE(rx) != 1) { - info("ADMIN: Invalid is_onboarded value size. Expected 1 " - "byte, got %d.\n", - APDU_DATA_SIZE(rx)); + LOG("ADMIN: Invalid is_onboarded value size. Expected 1 " + "byte, got %d.\n", + APDU_DATA_SIZE(rx)); return hsmsim_admin_error(HSMSIM_ADMIN_ERROR_DATA_SIZE); } - hsmsim_admin_data.is_onboarded = (bool)APDU_DATA_PTR[0]; - info("ADMIN: is_onboarded set to %d.\n", - hsmsim_admin_data.is_onboarded); + seed_set_is_onboarded((bool)APDU_DATA_PTR[0]); + LOG("ADMIN: is_onboarded set to %d.\n", + (unsigned char)seed_available()); tx = TX_FOR_DATA_SIZE(0); break; default: - info("ADMIN: Invalid CMD: %d.\n", APDU_CMD()); + LOG("ADMIN: Invalid CMD: %d.\n", APDU_CMD()); return hsmsim_admin_error(HSMSIM_ADMIN_ERROR_INVALID_PROTOCOL); } return hsmsim_admin_ok(tx); } - -void hsmsim_admin_nvm_record_write() { - hsmsim_admin_data.nvm_stats.write_count++; -} - -unsigned int hsmsim_admin_get_is_onboarded() { - return hsmsim_admin_data.is_onboarded ? HSMSIM_ADMIN_IS_ONBOARDED_YES - : HSMSIM_ADMIN_IS_ONBOARDED_NO; -} diff --git a/ledger/src/tcpsigner/hsmsim_admin.h b/firmware/src/tcpsigner/src/hsmsim_admin.h similarity index 82% rename from ledger/src/tcpsigner/hsmsim_admin.h rename to firmware/src/tcpsigner/src/hsmsim_admin.h index 60ce1ad1..4099d299 100644 --- a/ledger/src/tcpsigner/hsmsim_admin.h +++ b/firmware/src/tcpsigner/src/hsmsim_admin.h @@ -28,7 +28,7 @@ #include #include -#include "constants.h" +#include "hal/constants.h" // Admin APDU constants #define MIN_ADMIN_BYTES 2 @@ -46,25 +46,9 @@ #define HSMSIM_ADMIN_ERROR_INVALID_STATE 0x6f02 #define HSMSIM_ADMIN_ERROR_BUFFER_OVERFLOW 0x6f03 -// Misc constants -#define HSMSIM_ADMIN_DEFAULT_IS_ONBOARDED (true) - -#define HSMSIM_ADMIN_IS_ONBOARDED_YES (1) -#define HSMSIM_ADMIN_IS_ONBOARDED_NO (0) - -#define HSMSIM_RETRIES (3) - -typedef struct hsmsim_admin_nvm_info_s { - unsigned int write_count; -} hsmsim_admin_nvm_info_t; - typedef struct hsmsim_admin_data_s { bool ancestor_receipts_root_set; uint8_t old_ancestor_receipts_root[HASH_LENGTH]; - - hsmsim_admin_nvm_info_t nvm_stats; - - bool is_onboarded; } hsmsim_admin_data_t; void hsmsim_admin_init(); @@ -73,8 +57,4 @@ bool hsmsim_admin_need_process(unsigned int rx); unsigned int hsmsim_admin_process_apdu(unsigned int rx); -void hsmsim_admin_nvm_record_write(); - -unsigned int hsmsim_admin_get_is_onboarded(); - #endif // __HSMSIM_ADMIN_H diff --git a/ledger/src/tcpsigner/hsmsim_nu.c b/firmware/src/tcpsigner/src/hsmsim_nu.c similarity index 100% rename from ledger/src/tcpsigner/hsmsim_nu.c rename to firmware/src/tcpsigner/src/hsmsim_nu.c diff --git a/ledger/src/tcpsigner/hsmsim_nu.h b/firmware/src/tcpsigner/src/hsmsim_nu.h similarity index 100% rename from ledger/src/tcpsigner/hsmsim_nu.h rename to firmware/src/tcpsigner/src/hsmsim_nu.h diff --git a/firmware/src/tcpsigner/src/signer_authorization_status.c b/firmware/src/tcpsigner/src/signer_authorization_status.c new file mode 120000 index 00000000..75ec23ac --- /dev/null +++ b/firmware/src/tcpsigner/src/signer_authorization_status.c @@ -0,0 +1 @@ +../../ledger/ui/src/signer_authorization_status.c \ No newline at end of file diff --git a/firmware/src/tcpsigner/src/signer_authorization_status.h b/firmware/src/tcpsigner/src/signer_authorization_status.h new file mode 120000 index 00000000..46bb88f4 --- /dev/null +++ b/firmware/src/tcpsigner/src/signer_authorization_status.h @@ -0,0 +1 @@ +../../ledger/ui/src/signer_authorization_status.h \ No newline at end of file diff --git a/ledger/src/tcpsigner/tcpsigner.c b/firmware/src/tcpsigner/src/tcpsigner.c similarity index 80% rename from ledger/src/tcpsigner/tcpsigner.c rename to firmware/src/tcpsigner/src/tcpsigner.c index dde1c35c..a049f844 100644 --- a/ledger/src/tcpsigner/tcpsigner.c +++ b/firmware/src/tcpsigner/src/tcpsigner.c @@ -37,32 +37,39 @@ #include #include -#include "os.h" -#include "tcp.h" -#include "hsmsim_exceptions.h" +#include "hal/communication.h" +#include "hal/seed.h" +#include "hal/endorsement.h" +#include "hal/log.h" + #include "hsmsim_nu.h" -#include "hsmsim_ecdsa.h" -#include "hsmsim_attestation.h" #include "hsmsim_admin.h" #include "hsm.h" -#include "hsm-ledger.h" #include "ui_heartbeat.h" #include "bc_advance.h" #include "bc_state.h" #include "bc_diff.h" #include "defs.h" - #include "hex_reader.h" -#include "log.h" - typedef enum { ARG_NU_WASABI = 0xaa00, ARG_NU_PAPYRUS, ARG_NU_IRIS, } arg_non_printable_t; +// Hardcoded BIP32 paths for the JSON keyfile +const char *BIP32_PATHS[] = { + "m/44'/0'/0'/0/0", // BTC + "m/44'/1'/0'/0/0", // tBTC + "m/44'/1'/1'/0/0", // tRSK + "m/44'/1'/2'/0/0", // tMST + "m/44'/137'/0'/0/0", // RSK + "m/44'/137'/1'/0/0", // MST +}; +const size_t BIP32_PATHS_COUNT = sizeof(BIP32_PATHS) / sizeof(BIP32_PATHS[0]); + /** * UI heartbeat memory area * There's probably a better @@ -173,7 +180,7 @@ static error_t parse_opt(int key, char *arg, struct argp_state *state) { 1, 0, "Difficulty must be a hex encoded string (optionally " - "prefixed with 0x) of at most %u bytes", + "prefixed with 0x) of at most %lu bytes", sizeof(arguments->difficulty_b)); } uint8_t dif_offset = @@ -243,6 +250,15 @@ static error_t parse_opt(int key, char *arg, struct argp_state *state) { return 0; } +static unsigned short admin_process(unsigned short rx) { + if (hsmsim_admin_need_process(rx)) { + return hsmsim_admin_process_apdu(rx); + } + + // Signal nothing needed to process + return 0; +} + // The argp parser static struct argp argp = { options, @@ -251,7 +267,7 @@ static struct argp argp = { "TCPSigner -- an x86 implementation of the HSM signer"}; static void finalise() { - printf("Caught termination signal. Bye.\n"); + LOG("Caught termination signal. Bye.\n"); exit(0); } @@ -315,21 +331,21 @@ void main(int argc, char **argv) { argp_parse(&argp, argc, argv, 0, 0, &arguments); // Output welcome message & parameters - info("TCPSigner starting.\n"); + LOG("TCPSigner starting.\n"); // Output signer version - info("Signer version: %u.%u.%u\n", - VERSION_MAJOR, - VERSION_MINOR, - VERSION_PATCH); - - info("Signer parameters:\n"); - info_hex("Checkpoint:", arguments.checkpoint, sizeof(arguments.checkpoint)); - info_bigd_hex("Difficulty: ", - arguments.difficulty, - sizeof(arguments.difficulty) / - sizeof(arguments.difficulty[0])); - info("Network: %s\n", arguments.network); + LOG("Signer version: %u.%u.%u\n", + VERSION_MAJOR, + VERSION_MINOR, + VERSION_PATCH); + + LOG("Signer parameters:\n"); + LOG_HEX("Checkpoint:", arguments.checkpoint, sizeof(arguments.checkpoint)); + LOG_BIGD_HEX("Difficulty: ", + arguments.difficulty, + sizeof(arguments.difficulty) / sizeof(arguments.difficulty[0]), + "\n"); + LOG("Network: %s\n", arguments.network); // Set checkpoint memmove( @@ -347,36 +363,37 @@ void main(int argc, char **argv) { arguments.difficulty_cap, sizeof(arguments.difficulty_cap)); } - info_bigd_hex("Block difficulty cap: ", - MAX_BLOCK_DIFFICULTY, - sizeof(MAX_BLOCK_DIFFICULTY) / - sizeof(MAX_BLOCK_DIFFICULTY[0])); + LOG_BIGD_HEX("Block difficulty cap: ", + MAX_BLOCK_DIFFICULTY, + sizeof(MAX_BLOCK_DIFFICULTY) / sizeof(MAX_BLOCK_DIFFICULTY[0]), + "\n"); // Set network upgrade activation overrides for (int i = 0; i < arguments.network_upgrade_overrides_count; i++) hsmsim_set_network_upgrade_block_number( arguments.network_upgrade_overrides[i]); // Display network upgrade activation configuration - info("Network upgrade activation block numbers (latest takes " - "precedence):\n"); + LOG("Network upgrade activation block numbers (latest takes " + "precedence):\n"); network_upgrade_activation_t *activations = hsmsim_get_network_upgrade_activations(); for (int i = 0; i < hsmsim_get_network_upgrade_activations_count(); i++) { - info("\t%s: %u\n", - hsmsim_get_network_upgrade_name(activations[i].network_upgrade), - activations[i].activation_bn); + LOG("\t%s: %u\n", + hsmsim_get_network_upgrade_name(activations[i].network_upgrade), + activations[i].activation_bn); } - // Initialize ECDSA - if (!hsmsim_ecdsa_initialize(arguments.key_file_path)) { - info("Error during ECDSA initialization\n"); + // Initialize the seed module + if (!seed_init(arguments.key_file_path, BIP32_PATHS, BIP32_PATHS_COUNT)) { + LOG("Error during seed module initialization\n"); exit(1); } - info("ECDSA initialized.\n"); + + LOG("Seed module initialized.\n"); // Initialize Attestation - if (!hsmsim_attestation_initialize(arguments.att_file_path)) { - info("Error during Attestation initialization\n"); + if (!endorsement_init(arguments.att_file_path)) { + LOG("Error during endorsement module initialization\n"); exit(1); } @@ -391,48 +408,50 @@ void main(int argc, char **argv) { #endif FILE *inputfd; if (arguments.filemode) { - info("Using file %s as input\n", arguments.inputfile); + LOG("Using file %s as input\n", arguments.inputfile); if ((inputfd = fopen(arguments.inputfile, "rb")) == NULL) { - info("Error opening file %s as input\n", arguments.inputfile); + LOG("Error opening file %s as input\n", arguments.inputfile); exit(1); } - os_io_set_input_file(inputfd); + communication_set_input_file(inputfd); } else { - info("Starting TCP server on %s:%i\n", - arguments.bind, - arguments.port); - int server = start_server(arguments.port, arguments.bind); - os_io_set_server(server); + LOG("Starting TCP server on %s:%i\n", + arguments.bind, + arguments.port); + communication_set_and_start_server(arguments.port, arguments.bind); } FILE *replicafd; if (strlen(arguments.replicafile) > 0) { - info("Using file %s as replica\n", arguments.replicafile); + LOG("Using file %s as replica\n", arguments.replicafile); if ((replicafd = fopen(arguments.replicafile, "ab")) == NULL) { - info("Error opening file %s as replica\n", - arguments.replicafile); + LOG("Error opening file %s as replica\n", + arguments.replicafile); exit(1); }; - os_io_set_replica_file(replicafd); + communication_set_replica_file(replicafd); }; + // Set the admin module callback for the communication module + communication_set_external_module_process(&admin_process); + // Run the Signer main loop and the // UI heartbeat main loop in an alternate // fashion. while (true) { - info("Running signer main loop...\n"); + LOG("Running signer main loop...\n"); hsm_init(); - hsm_ledger_main_loop(); + hsm_main_loop(); // Send an empty reply so that the client // doesn't hang waiting - io_exchange_reply(); + communication_reply(); - info("Running UI heartbeat main loop...\n"); + LOG("Running UI heartbeat main loop...\n"); ui_heartbeat_init(&ui_heartbeat_ctx); ui_heartbeat_main(&ui_heartbeat_ctx); // Ditto - io_exchange_reply(); + communication_reply(); } if (replicafd != NULL) { diff --git a/firmware/src/tcpsigner/src/ui_comm.c b/firmware/src/tcpsigner/src/ui_comm.c new file mode 120000 index 00000000..179ef4da --- /dev/null +++ b/firmware/src/tcpsigner/src/ui_comm.c @@ -0,0 +1 @@ +../../ledger/ui/src/ui_comm.c \ No newline at end of file diff --git a/firmware/src/tcpsigner/src/ui_comm.h b/firmware/src/tcpsigner/src/ui_comm.h new file mode 120000 index 00000000..c843c64e --- /dev/null +++ b/firmware/src/tcpsigner/src/ui_comm.h @@ -0,0 +1 @@ +../../ledger/ui/src/ui_comm.h \ No newline at end of file diff --git a/ledger/src/tcpsigner/os_attestation.c b/firmware/src/tcpsigner/src/ui_deps.c similarity index 67% rename from ledger/src/tcpsigner/os_attestation.c rename to firmware/src/tcpsigner/src/ui_deps.c index 3fd97247..a35ed7cb 100644 --- a/ledger/src/tcpsigner/os_attestation.c +++ b/firmware/src/tcpsigner/src/ui_deps.c @@ -24,38 +24,29 @@ #include -#include "os_attestation.h" -#include "hsmsim_attestation.h" -#include "hsmsim_exceptions.h" -#include "os_ecdsa.h" +#include "hal/constants.h" +#include "hal/seed.h" +#include "hal/endorsement.h" +#include "hal/communication.h" +#include "hal/exceptions.h" +#include "hal/log.h" + +#include "ui_deps.h" +#include "ui_err.h" #include "sha256.h" #include "hmac_sha256.h" +#define UI_DEPS_PIN_RETRIES (3) + unsigned int os_endorsement_key2_derive_sign_data(unsigned char *src, unsigned int srcLength, unsigned char *signature) { - uint8_t pubkey[PUBKEY_UNCMP_LENGTH]; - uint8_t tweak[HMAC_SHA256_SIZE]; - uint8_t hash[HASH_LENGTH]; - - sha256(src, srcLength, hash, sizeof(hash)); - - if (hsmsim_helper_getpubkey( - attestation_id.key, pubkey, sizeof(pubkey), false) != - sizeof(pubkey)) { - THROW(HSMSIM_EXC_SECP_ERROR); - } - - if (hmac_sha256(attestation_id.code_hash, - sizeof(attestation_id.code_hash), - pubkey, - sizeof(pubkey), - tweak, - sizeof(tweak)) != sizeof(tweak)) { - THROW(HSMSIM_EXC_HMAC_ERROR); + uint8_t signature_length = MAX_SIGNATURE_LENGTH; + if (!endorsement_sign(src, srcLength, signature, &signature_length)) { + LOG("UI error endorsing message\n"); + THROW(ERR_UI_INTERNAL); } - - return hsmsim_helper_tweak_sign(attestation_id.key, tweak, hash, signature); + return signature_length; } unsigned int os_endorsement_get_code_hash(unsigned char *buffer) { @@ -66,8 +57,16 @@ unsigned int os_endorsement_get_code_hash(unsigned char *buffer) { unsigned int os_endorsement_get_public_key(unsigned char index, unsigned char *buffer) { uint8_t tempbuf[PUBKEY_UNCMP_LENGTH]; - size_t tempbuf_size = hsmsim_helper_getpubkey( - attestation_id.key, tempbuf, sizeof(tempbuf), false); + size_t tempbuf_size = + seed_derive_pubkey_format(attestation_id.key, tempbuf, false); memcpy(buffer, tempbuf, tempbuf_size); return tempbuf_size; +} + +unsigned int os_global_pin_retries() { + return UI_DEPS_PIN_RETRIES; +} + +unsigned short io_exchange(unsigned char channel_and_flags, unsigned short tx) { + return communication_io_exchange(tx); } \ No newline at end of file diff --git a/ledger/src/tcpsigner/os_attestation.h b/firmware/src/tcpsigner/src/ui_deps.h similarity index 88% rename from ledger/src/tcpsigner/os_attestation.h rename to firmware/src/tcpsigner/src/ui_deps.h index 8db43ca3..b0c7695e 100644 --- a/ledger/src/tcpsigner/os_attestation.h +++ b/firmware/src/tcpsigner/src/ui_deps.h @@ -22,8 +22,10 @@ * IN THE SOFTWARE. */ -#ifndef __SIMULATOR_OS_ATTESTATION_H -#define __SIMULATOR_OS_ATTESTATION_H +#ifndef __UI_DEPS_H +#define __UI_DEPS_H + +#define CHANNEL_APDU (123) unsigned int os_endorsement_key2_derive_sign_data(unsigned char *src, unsigned int srcLength, @@ -34,4 +36,8 @@ unsigned int os_endorsement_get_code_hash(unsigned char *buffer); unsigned int os_endorsement_get_public_key(unsigned char index, unsigned char *buffer); -#endif // __SIMULATOR_OS_ATTESTATION_H +unsigned int os_global_pin_retries(); + +unsigned short io_exchange(unsigned char channel_and_flags, unsigned short tx); + +#endif // __UI_DEPS_H diff --git a/firmware/src/tcpsigner/src/ui_err.h b/firmware/src/tcpsigner/src/ui_err.h new file mode 120000 index 00000000..d0d2490c --- /dev/null +++ b/firmware/src/tcpsigner/src/ui_err.h @@ -0,0 +1 @@ +../../ledger/ui/src/ui_err.h \ No newline at end of file diff --git a/firmware/src/tcpsigner/src/ui_heartbeat.c b/firmware/src/tcpsigner/src/ui_heartbeat.c new file mode 120000 index 00000000..af68be46 --- /dev/null +++ b/firmware/src/tcpsigner/src/ui_heartbeat.c @@ -0,0 +1 @@ +../../ledger/ui/src/ui_heartbeat.c \ No newline at end of file diff --git a/firmware/src/tcpsigner/src/ui_heartbeat.h b/firmware/src/tcpsigner/src/ui_heartbeat.h new file mode 120000 index 00000000..9850b56c --- /dev/null +++ b/firmware/src/tcpsigner/src/ui_heartbeat.h @@ -0,0 +1 @@ +../../ledger/ui/src/ui_heartbeat.h \ No newline at end of file diff --git a/firmware/src/tcpsigner/src/ui_instructions.h b/firmware/src/tcpsigner/src/ui_instructions.h new file mode 120000 index 00000000..f968d39c --- /dev/null +++ b/firmware/src/tcpsigner/src/ui_instructions.h @@ -0,0 +1 @@ +../../ledger/ui/src/ui_instructions.h \ No newline at end of file diff --git a/ledger/static-analysis/.gitignore b/firmware/static-analysis/.gitignore similarity index 100% rename from ledger/static-analysis/.gitignore rename to firmware/static-analysis/.gitignore diff --git a/ledger/static-analysis/gen-static-analysis b/firmware/static-analysis/gen-static-analysis similarity index 94% rename from ledger/static-analysis/gen-static-analysis rename to firmware/static-analysis/gen-static-analysis index b25f8d72..992f58b9 100755 --- a/ledger/static-analysis/gen-static-analysis +++ b/firmware/static-analysis/gen-static-analysis @@ -4,8 +4,8 @@ if [[ $1 == "exec" ]]; then BASEDIR=$(realpath $(dirname $0)) SRCDIR=$(realpath $BASEDIR/../src) REPOROOT=$(realpath $BASEDIR/../..) - SIGNER_SRC_DIR=$REPOROOT/ledger/src/signer - UI_SRC_DIR=$REPOROOT/ledger/src/ui + SIGNER_SRC_DIR=$REPOROOT/firmware/src/ledger/signer + UI_SRC_DIR=$REPOROOT/firmware/src/ledger/ui SIGNER_OUTPUT=$BASEDIR/output/signer UI_OUTPUT=$BASEDIR/output/ui diff --git a/ledger/test/.gitignore b/firmware/test/.gitignore similarity index 100% rename from ledger/test/.gitignore rename to firmware/test/.gitignore diff --git a/ledger/test/README.md b/firmware/test/README.md similarity index 55% rename from ledger/test/README.md rename to firmware/test/README.md index 21e1bc09..0b85768d 100644 --- a/ledger/test/README.md +++ b/firmware/test/README.md @@ -1,6 +1,6 @@ -# Ledger signer firmware test suite +# powHSM firmware test suite -## Build parameters for a physical dongle +## Build parameters for a physical Ledger Nano S *Checkpoint:* 0xbdcb3c17c7aee714cec8ad900341bfd987b452280220dcbd6e7191f67ea4209b *Difficulty:* 0x32 (50) @@ -9,7 +9,7 @@ ### Example command to build a signer to run the tests against ```bash -~/repo> ledger/build/build-signer 0xbdcb3c17c7aee714cec8ad900341bfd987b452280220dcbd6e7191f67ea4209b 50 regtest +~/repo> firmware/build/build-ledger-signer 0xbdcb3c17c7aee714cec8ad900341bfd987b452280220dcbd6e7191f67ea4209b 50 regtest ``` ## Running the tests @@ -17,11 +17,11 @@ To test using the TCPSigner, issue: ```bash -~/repo> ledger/test/test-all +~/repo> firmware/test/test-all ``` To test against a physical dongle, issue: ```bash -~/repo> ledger/test/test-all dongle +~/repo> firmware/test/test-all dongle ``` diff --git a/ledger/test/cases/__init__.py b/firmware/test/cases/__init__.py similarity index 100% rename from ledger/test/cases/__init__.py rename to firmware/test/cases/__init__.py diff --git a/ledger/test/cases/admin_is_onboarded.py b/firmware/test/cases/admin_is_onboarded.py similarity index 100% rename from ledger/test/cases/admin_is_onboarded.py rename to firmware/test/cases/admin_is_onboarded.py diff --git a/ledger/test/cases/advance.py b/firmware/test/cases/advance.py similarity index 100% rename from ledger/test/cases/advance.py rename to firmware/test/cases/advance.py diff --git a/ledger/test/cases/case.py b/firmware/test/cases/case.py similarity index 100% rename from ledger/test/cases/case.py rename to firmware/test/cases/case.py diff --git a/ledger/test/cases/get.py b/firmware/test/cases/get.py similarity index 100% rename from ledger/test/cases/get.py rename to firmware/test/cases/get.py diff --git a/ledger/test/cases/heartbeat.py b/firmware/test/cases/heartbeat.py similarity index 100% rename from ledger/test/cases/heartbeat.py rename to firmware/test/cases/heartbeat.py diff --git a/ledger/test/cases/nvm_stats.py b/firmware/test/cases/nvm_stats.py similarity index 100% rename from ledger/test/cases/nvm_stats.py rename to firmware/test/cases/nvm_stats.py diff --git a/ledger/test/cases/parameters.py b/firmware/test/cases/parameters.py similarity index 100% rename from ledger/test/cases/parameters.py rename to firmware/test/cases/parameters.py diff --git a/ledger/test/cases/reconnect.py b/firmware/test/cases/reconnect.py similarity index 100% rename from ledger/test/cases/reconnect.py rename to firmware/test/cases/reconnect.py diff --git a/ledger/test/cases/reset.py b/firmware/test/cases/reset.py similarity index 100% rename from ledger/test/cases/reset.py rename to firmware/test/cases/reset.py diff --git a/ledger/test/cases/sign_auth.py b/firmware/test/cases/sign_auth.py similarity index 100% rename from ledger/test/cases/sign_auth.py rename to firmware/test/cases/sign_auth.py diff --git a/ledger/test/cases/sign_helpers.py b/firmware/test/cases/sign_helpers.py similarity index 100% rename from ledger/test/cases/sign_helpers.py rename to firmware/test/cases/sign_helpers.py diff --git a/ledger/test/cases/sign_noauth.py b/firmware/test/cases/sign_noauth.py similarity index 100% rename from ledger/test/cases/sign_noauth.py rename to firmware/test/cases/sign_noauth.py diff --git a/ledger/test/cases/suite.py b/firmware/test/cases/suite.py similarity index 100% rename from ledger/test/cases/suite.py rename to firmware/test/cases/suite.py diff --git a/ledger/test/cases/update.py b/firmware/test/cases/update.py similarity index 100% rename from ledger/test/cases/update.py rename to firmware/test/cases/update.py diff --git a/ledger/test/comm b/firmware/test/comm similarity index 100% rename from ledger/test/comm rename to firmware/test/comm diff --git a/ledger/test/ledger b/firmware/test/ledger similarity index 100% rename from ledger/test/ledger rename to firmware/test/ledger diff --git a/ledger/test/misc/blockbin.py b/firmware/test/misc/blockbin.py similarity index 98% rename from ledger/test/misc/blockbin.py rename to firmware/test/misc/blockbin.py index 61ec10b2..0f6bc426 100644 --- a/ledger/test/misc/blockbin.py +++ b/firmware/test/misc/blockbin.py @@ -23,7 +23,7 @@ """Turn a json rlp block list into a binary byte array. This command is specially designed to produce test data for -ledger/src/simul/bc_advance_host.c +firmware/src/powhsm/src/{bc_advance.c,bc_update.c} """ import click diff --git a/ledger/test/misc/blockdump.py b/firmware/test/misc/blockdump.py similarity index 100% rename from ledger/test/misc/blockdump.py rename to firmware/test/misc/blockdump.py diff --git a/ledger/test/misc/blocksplit.py b/firmware/test/misc/blocksplit.py similarity index 100% rename from ledger/test/misc/blocksplit.py rename to firmware/test/misc/blocksplit.py diff --git a/ledger/test/misc/comm b/firmware/test/misc/comm similarity index 100% rename from ledger/test/misc/comm rename to firmware/test/misc/comm diff --git a/ledger/test/misc/genPaths.py b/firmware/test/misc/genPaths.py similarity index 100% rename from ledger/test/misc/genPaths.py rename to firmware/test/misc/genPaths.py diff --git a/ledger/test/misc/hex2c.py b/firmware/test/misc/hex2c.py similarity index 100% rename from ledger/test/misc/hex2c.py rename to firmware/test/misc/hex2c.py diff --git a/ledger/test/misc/ledger b/firmware/test/misc/ledger similarity index 100% rename from ledger/test/misc/ledger rename to firmware/test/misc/ledger diff --git a/ledger/test/misc/mine.py b/firmware/test/misc/mine.py similarity index 100% rename from ledger/test/misc/mine.py rename to firmware/test/misc/mine.py diff --git a/ledger/test/misc/rsk_block.py b/firmware/test/misc/rsk_block.py similarity index 100% rename from ledger/test/misc/rsk_block.py rename to firmware/test/misc/rsk_block.py diff --git a/ledger/test/misc/rsk_netparams.py b/firmware/test/misc/rsk_netparams.py similarity index 100% rename from ledger/test/misc/rsk_netparams.py rename to firmware/test/misc/rsk_netparams.py diff --git a/ledger/test/misc/rsk_utils.py b/firmware/test/misc/rsk_utils.py similarity index 100% rename from ledger/test/misc/rsk_utils.py rename to firmware/test/misc/rsk_utils.py diff --git a/ledger/test/misc/tcpsigner_admin.py b/firmware/test/misc/tcpsigner_admin.py similarity index 100% rename from ledger/test/misc/tcpsigner_admin.py rename to firmware/test/misc/tcpsigner_admin.py diff --git a/ledger/test/misc/thirdparty b/firmware/test/misc/thirdparty similarity index 100% rename from ledger/test/misc/thirdparty rename to firmware/test/misc/thirdparty diff --git a/ledger/test/options.py b/firmware/test/options.py similarity index 100% rename from ledger/test/options.py rename to firmware/test/options.py diff --git a/ledger/test/output.py b/firmware/test/output.py similarity index 100% rename from ledger/test/output.py rename to firmware/test/output.py diff --git a/ledger/test/resources/000-blockchain-parameters.json b/firmware/test/resources/000-blockchain-parameters.json similarity index 100% rename from ledger/test/resources/000-blockchain-parameters.json rename to firmware/test/resources/000-blockchain-parameters.json diff --git a/ledger/test/resources/001-get-at-startup.json b/firmware/test/resources/001-get-at-startup.json similarity index 100% rename from ledger/test/resources/001-get-at-startup.json rename to firmware/test/resources/001-get-at-startup.json diff --git a/ledger/test/resources/002-sign-noauth.json b/firmware/test/resources/002-sign-noauth.json similarity index 100% rename from ledger/test/resources/002-sign-noauth.json rename to firmware/test/resources/002-sign-noauth.json diff --git a/ledger/test/resources/003-heartbeat-initial.json b/firmware/test/resources/003-heartbeat-initial.json similarity index 100% rename from ledger/test/resources/003-heartbeat-initial.json rename to firmware/test/resources/003-heartbeat-initial.json diff --git a/ledger/test/resources/100-reset.json b/firmware/test/resources/100-reset.json similarity index 100% rename from ledger/test/resources/100-reset.json rename to firmware/test/resources/100-reset.json diff --git a/ledger/test/resources/101-get-initial.json b/firmware/test/resources/101-get-initial.json similarity index 100% rename from ledger/test/resources/101-get-initial.json rename to firmware/test/resources/101-get-initial.json diff --git a/ledger/test/resources/102-advance.json b/firmware/test/resources/102-advance.json similarity index 100% rename from ledger/test/resources/102-advance.json rename to firmware/test/resources/102-advance.json diff --git a/ledger/test/resources/103-get-after-advance.json b/firmware/test/resources/103-get-after-advance.json similarity index 100% rename from ledger/test/resources/103-get-after-advance.json rename to firmware/test/resources/103-get-after-advance.json diff --git a/ledger/test/resources/104-heartbeat-after-advance.json b/firmware/test/resources/104-heartbeat-after-advance.json similarity index 100% rename from ledger/test/resources/104-heartbeat-after-advance.json rename to firmware/test/resources/104-heartbeat-after-advance.json diff --git a/ledger/test/resources/105-advance-brothers.json b/firmware/test/resources/105-advance-brothers.json similarity index 100% rename from ledger/test/resources/105-advance-brothers.json rename to firmware/test/resources/105-advance-brothers.json diff --git a/ledger/test/resources/106-get-after-advance-brothers.json b/firmware/test/resources/106-get-after-advance-brothers.json similarity index 100% rename from ledger/test/resources/106-get-after-advance-brothers.json rename to firmware/test/resources/106-get-after-advance-brothers.json diff --git a/ledger/test/resources/110-get-initial-partial.json b/firmware/test/resources/110-get-initial-partial.json similarity index 100% rename from ledger/test/resources/110-get-initial-partial.json rename to firmware/test/resources/110-get-initial-partial.json diff --git a/ledger/test/resources/111-advance-partial.json b/firmware/test/resources/111-advance-partial.json similarity index 100% rename from ledger/test/resources/111-advance-partial.json rename to firmware/test/resources/111-advance-partial.json diff --git a/ledger/test/resources/112-get-final-partial.json b/firmware/test/resources/112-get-final-partial.json similarity index 100% rename from ledger/test/resources/112-get-final-partial.json rename to firmware/test/resources/112-get-final-partial.json diff --git a/ledger/test/resources/113-reset.json b/firmware/test/resources/113-reset.json similarity index 100% rename from ledger/test/resources/113-reset.json rename to firmware/test/resources/113-reset.json diff --git a/ledger/test/resources/114-advance-partial.json b/firmware/test/resources/114-advance-partial.json similarity index 100% rename from ledger/test/resources/114-advance-partial.json rename to firmware/test/resources/114-advance-partial.json diff --git a/ledger/test/resources/115-get-final-partial.json b/firmware/test/resources/115-get-final-partial.json similarity index 100% rename from ledger/test/resources/115-get-final-partial.json rename to firmware/test/resources/115-get-final-partial.json diff --git a/ledger/test/resources/116-reset.json b/firmware/test/resources/116-reset.json similarity index 100% rename from ledger/test/resources/116-reset.json rename to firmware/test/resources/116-reset.json diff --git a/ledger/test/resources/117-advance-partial.json b/firmware/test/resources/117-advance-partial.json similarity index 100% rename from ledger/test/resources/117-advance-partial.json rename to firmware/test/resources/117-advance-partial.json diff --git a/ledger/test/resources/118-get-final-partial.json b/firmware/test/resources/118-get-final-partial.json similarity index 100% rename from ledger/test/resources/118-get-final-partial.json rename to firmware/test/resources/118-get-final-partial.json diff --git a/ledger/test/resources/120-reset.json b/firmware/test/resources/120-reset.json similarity index 100% rename from ledger/test/resources/120-reset.json rename to firmware/test/resources/120-reset.json diff --git a/ledger/test/resources/121-advance-cap.json b/firmware/test/resources/121-advance-cap.json similarity index 100% rename from ledger/test/resources/121-advance-cap.json rename to firmware/test/resources/121-advance-cap.json diff --git a/ledger/test/resources/122-get-final-cap.json b/firmware/test/resources/122-get-final-cap.json similarity index 100% rename from ledger/test/resources/122-get-final-cap.json rename to firmware/test/resources/122-get-final-cap.json diff --git a/ledger/test/resources/123-reset.json b/firmware/test/resources/123-reset.json similarity index 100% rename from ledger/test/resources/123-reset.json rename to firmware/test/resources/123-reset.json diff --git a/ledger/test/resources/124-advance-cap.json b/firmware/test/resources/124-advance-cap.json similarity index 100% rename from ledger/test/resources/124-advance-cap.json rename to firmware/test/resources/124-advance-cap.json diff --git a/ledger/test/resources/125-get-final-cap.json b/firmware/test/resources/125-get-final-cap.json similarity index 100% rename from ledger/test/resources/125-get-final-cap.json rename to firmware/test/resources/125-get-final-cap.json diff --git a/ledger/test/resources/200-update-iris.json b/firmware/test/resources/200-update-iris.json similarity index 100% rename from ledger/test/resources/200-update-iris.json rename to firmware/test/resources/200-update-iris.json diff --git a/ledger/test/resources/201-get-after-update-iris.json b/firmware/test/resources/201-get-after-update-iris.json similarity index 100% rename from ledger/test/resources/201-get-after-update-iris.json rename to firmware/test/resources/201-get-after-update-iris.json diff --git a/ledger/test/resources/202-sign-iris.json b/firmware/test/resources/202-sign-iris.json similarity index 100% rename from ledger/test/resources/202-sign-iris.json rename to firmware/test/resources/202-sign-iris.json diff --git a/ledger/test/resources/203-get-after-sign-iris.json b/firmware/test/resources/203-get-after-sign-iris.json similarity index 100% rename from ledger/test/resources/203-get-after-sign-iris.json rename to firmware/test/resources/203-get-after-sign-iris.json diff --git a/ledger/test/resources/204-heartbeat-after-sign-iris.json b/firmware/test/resources/204-heartbeat-after-sign-iris.json similarity index 100% rename from ledger/test/resources/204-heartbeat-after-sign-iris.json rename to firmware/test/resources/204-heartbeat-after-sign-iris.json diff --git a/ledger/test/resources/210-advance-for-segwit.json b/firmware/test/resources/210-advance-for-segwit.json similarity index 100% rename from ledger/test/resources/210-advance-for-segwit.json rename to firmware/test/resources/210-advance-for-segwit.json diff --git a/ledger/test/resources/211-update-segwit.json b/firmware/test/resources/211-update-segwit.json similarity index 100% rename from ledger/test/resources/211-update-segwit.json rename to firmware/test/resources/211-update-segwit.json diff --git a/ledger/test/resources/212-get-after-advance-segwit.json b/firmware/test/resources/212-get-after-advance-segwit.json similarity index 100% rename from ledger/test/resources/212-get-after-advance-segwit.json rename to firmware/test/resources/212-get-after-advance-segwit.json diff --git a/ledger/test/resources/213-sign-segwit-t1i0.json b/firmware/test/resources/213-sign-segwit-t1i0.json similarity index 100% rename from ledger/test/resources/213-sign-segwit-t1i0.json rename to firmware/test/resources/213-sign-segwit-t1i0.json diff --git a/ledger/test/resources/214-sign-segwit-t1i1.json b/firmware/test/resources/214-sign-segwit-t1i1.json similarity index 100% rename from ledger/test/resources/214-sign-segwit-t1i1.json rename to firmware/test/resources/214-sign-segwit-t1i1.json diff --git a/ledger/test/resources/215-sign-segwit-t2i0.json b/firmware/test/resources/215-sign-segwit-t2i0.json similarity index 100% rename from ledger/test/resources/215-sign-segwit-t2i0.json rename to firmware/test/resources/215-sign-segwit-t2i0.json diff --git a/ledger/test/resources/216-sign-segwit-t2i1.json b/firmware/test/resources/216-sign-segwit-t2i1.json similarity index 100% rename from ledger/test/resources/216-sign-segwit-t2i1.json rename to firmware/test/resources/216-sign-segwit-t2i1.json diff --git a/ledger/test/resources/299-advance-cap-for-partial-check.json b/firmware/test/resources/299-advance-cap-for-partial-check.json similarity index 100% rename from ledger/test/resources/299-advance-cap-for-partial-check.json rename to firmware/test/resources/299-advance-cap-for-partial-check.json diff --git a/ledger/test/resources/300-update.json b/firmware/test/resources/300-update.json similarity index 100% rename from ledger/test/resources/300-update.json rename to firmware/test/resources/300-update.json diff --git a/ledger/test/resources/301-get-after-update.json b/firmware/test/resources/301-get-after-update.json similarity index 100% rename from ledger/test/resources/301-get-after-update.json rename to firmware/test/resources/301-get-after-update.json diff --git a/ledger/test/resources/302-sign.json b/firmware/test/resources/302-sign.json similarity index 100% rename from ledger/test/resources/302-sign.json rename to firmware/test/resources/302-sign.json diff --git a/ledger/test/resources/303-get-after-sign.json b/firmware/test/resources/303-get-after-sign.json similarity index 100% rename from ledger/test/resources/303-get-after-sign.json rename to firmware/test/resources/303-get-after-sign.json diff --git a/ledger/test/resources/304-sign-noauth.json b/firmware/test/resources/304-sign-noauth.json similarity index 100% rename from ledger/test/resources/304-sign-noauth.json rename to firmware/test/resources/304-sign-noauth.json diff --git a/ledger/test/resources/305-get-after-sign-noauth.json b/firmware/test/resources/305-get-after-sign-noauth.json similarity index 100% rename from ledger/test/resources/305-get-after-sign-noauth.json rename to firmware/test/resources/305-get-after-sign-noauth.json diff --git a/ledger/test/resources/306-heartbeat-after-sign.json b/firmware/test/resources/306-heartbeat-after-sign.json similarity index 100% rename from ledger/test/resources/306-heartbeat-after-sign.json rename to firmware/test/resources/306-heartbeat-after-sign.json diff --git a/ledger/test/resources/307-reconnect-dongle.json b/firmware/test/resources/307-reconnect-dongle.json similarity index 100% rename from ledger/test/resources/307-reconnect-dongle.json rename to firmware/test/resources/307-reconnect-dongle.json diff --git a/ledger/test/resources/308-get-after-reconnection.json b/firmware/test/resources/308-get-after-reconnection.json similarity index 100% rename from ledger/test/resources/308-get-after-reconnection.json rename to firmware/test/resources/308-get-after-reconnection.json diff --git a/ledger/test/resources/309-heartbeat-after-reconnection.json b/firmware/test/resources/309-heartbeat-after-reconnection.json similarity index 100% rename from ledger/test/resources/309-heartbeat-after-reconnection.json rename to firmware/test/resources/309-heartbeat-after-reconnection.json diff --git a/ledger/test/resources/400-advance-partial-before-sign.json b/firmware/test/resources/400-advance-partial-before-sign.json similarity index 100% rename from ledger/test/resources/400-advance-partial-before-sign.json rename to firmware/test/resources/400-advance-partial-before-sign.json diff --git a/ledger/test/resources/401-get-before-sign.json b/firmware/test/resources/401-get-before-sign.json similarity index 100% rename from ledger/test/resources/401-get-before-sign.json rename to firmware/test/resources/401-get-before-sign.json diff --git a/ledger/test/resources/410-sign-fail-invalid-version.json b/firmware/test/resources/410-sign-fail-invalid-version.json similarity index 100% rename from ledger/test/resources/410-sign-fail-invalid-version.json rename to firmware/test/resources/410-sign-fail-invalid-version.json diff --git a/ledger/test/resources/411-sign-fail-zero-byte-tx.json b/firmware/test/resources/411-sign-fail-zero-byte-tx.json similarity index 100% rename from ledger/test/resources/411-sign-fail-zero-byte-tx.json rename to firmware/test/resources/411-sign-fail-zero-byte-tx.json diff --git a/ledger/test/resources/412-sign-fail-malformed-redeem-script.json b/firmware/test/resources/412-sign-fail-malformed-redeem-script.json similarity index 100% rename from ledger/test/resources/412-sign-fail-malformed-redeem-script.json rename to firmware/test/resources/412-sign-fail-malformed-redeem-script.json diff --git a/ledger/test/resources/413-sign-fail-malformed-output.json b/firmware/test/resources/413-sign-fail-malformed-output.json similarity index 100% rename from ledger/test/resources/413-sign-fail-malformed-output.json rename to firmware/test/resources/413-sign-fail-malformed-output.json diff --git a/ledger/test/resources/414-sign-fail-receipt-nomatch.json b/firmware/test/resources/414-sign-fail-receipt-nomatch.json similarity index 100% rename from ledger/test/resources/414-sign-fail-receipt-nomatch.json rename to firmware/test/resources/414-sign-fail-receipt-nomatch.json diff --git a/ledger/test/resources/415-sign-fail-receipt-no-match-single-log.json b/firmware/test/resources/415-sign-fail-receipt-no-match-single-log.json similarity index 100% rename from ledger/test/resources/415-sign-fail-receipt-no-match-single-log.json rename to firmware/test/resources/415-sign-fail-receipt-no-match-single-log.json diff --git a/ledger/test/resources/416-sign-fail-receipt-top-level-size-mismatch.json b/firmware/test/resources/416-sign-fail-receipt-top-level-size-mismatch.json similarity index 100% rename from ledger/test/resources/416-sign-fail-receipt-top-level-size-mismatch.json rename to firmware/test/resources/416-sign-fail-receipt-top-level-size-mismatch.json diff --git a/ledger/test/resources/417-sign-fail-receipt-malformed-nologs.json b/firmware/test/resources/417-sign-fail-receipt-malformed-nologs.json similarity index 100% rename from ledger/test/resources/417-sign-fail-receipt-malformed-nologs.json rename to firmware/test/resources/417-sign-fail-receipt-malformed-nologs.json diff --git a/ledger/test/resources/418-sign-fail-proof-only-receipts-root.json b/firmware/test/resources/418-sign-fail-proof-only-receipts-root.json similarity index 100% rename from ledger/test/resources/418-sign-fail-proof-only-receipts-root.json rename to firmware/test/resources/418-sign-fail-proof-only-receipts-root.json diff --git a/ledger/test/resources/419-sign-fail-proof-first-non-leaf.json b/firmware/test/resources/419-sign-fail-proof-first-non-leaf.json similarity index 100% rename from ledger/test/resources/419-sign-fail-proof-first-non-leaf.json rename to firmware/test/resources/419-sign-fail-proof-first-non-leaf.json diff --git a/ledger/test/resources/420-sign-fail-proof-leaf-nomatch.json b/firmware/test/resources/420-sign-fail-proof-leaf-nomatch.json similarity index 100% rename from ledger/test/resources/420-sign-fail-proof-leaf-nomatch.json rename to firmware/test/resources/420-sign-fail-proof-leaf-nomatch.json diff --git a/ledger/test/resources/421-sign-fail-proof-wrong-version-node.json b/firmware/test/resources/421-sign-fail-proof-wrong-version-node.json similarity index 100% rename from ledger/test/resources/421-sign-fail-proof-wrong-version-node.json rename to firmware/test/resources/421-sign-fail-proof-wrong-version-node.json diff --git a/ledger/test/resources/422-sign-fail-proof-does-not-connect.json b/firmware/test/resources/422-sign-fail-proof-does-not-connect.json similarity index 100% rename from ledger/test/resources/422-sign-fail-proof-does-not-connect.json rename to firmware/test/resources/422-sign-fail-proof-does-not-connect.json diff --git a/ledger/test/resources/423-sign-auth-fail-invalid-path.json b/firmware/test/resources/423-sign-auth-fail-invalid-path.json similarity index 100% rename from ledger/test/resources/423-sign-auth-fail-invalid-path.json rename to firmware/test/resources/423-sign-auth-fail-invalid-path.json diff --git a/ledger/test/resources/424-sign-noauth-fail-invalid-path.json b/firmware/test/resources/424-sign-noauth-fail-invalid-path.json similarity index 100% rename from ledger/test/resources/424-sign-noauth-fail-invalid-path.json rename to firmware/test/resources/424-sign-noauth-fail-invalid-path.json diff --git a/ledger/test/resources/425-sign-auth-fail-invalid-length.json b/firmware/test/resources/425-sign-auth-fail-invalid-length.json similarity index 100% rename from ledger/test/resources/425-sign-auth-fail-invalid-length.json rename to firmware/test/resources/425-sign-auth-fail-invalid-length.json diff --git a/ledger/test/resources/426-sign-noauth-fail-invalid-length.json b/firmware/test/resources/426-sign-noauth-fail-invalid-length.json similarity index 100% rename from ledger/test/resources/426-sign-noauth-fail-invalid-length.json rename to firmware/test/resources/426-sign-noauth-fail-invalid-length.json diff --git a/ledger/test/resources/499-get-after-failed-sign.json b/firmware/test/resources/499-get-after-failed-sign.json similarity index 100% rename from ledger/test/resources/499-get-after-failed-sign.json rename to firmware/test/resources/499-get-after-failed-sign.json diff --git a/ledger/test/resources/500-advance-inconsistent-list-length.json b/firmware/test/resources/500-advance-inconsistent-list-length.json similarity index 100% rename from ledger/test/resources/500-advance-inconsistent-list-length.json rename to firmware/test/resources/500-advance-inconsistent-list-length.json diff --git a/ledger/test/resources/501-advance-long-mmmp.json b/firmware/test/resources/501-advance-long-mmmp.json similarity index 100% rename from ledger/test/resources/501-advance-long-mmmp.json rename to firmware/test/resources/501-advance-long-mmmp.json diff --git a/ledger/test/resources/502-advance-brother-pow-invalid-mp.json b/firmware/test/resources/502-advance-brother-pow-invalid-mp.json similarity index 100% rename from ledger/test/resources/502-advance-brother-pow-invalid-mp.json rename to firmware/test/resources/502-advance-brother-pow-invalid-mp.json diff --git a/ledger/test/resources/503-advance-brother-pow-invalid-dif.json b/firmware/test/resources/503-advance-brother-pow-invalid-dif.json similarity index 100% rename from ledger/test/resources/503-advance-brother-pow-invalid-dif.json rename to firmware/test/resources/503-advance-brother-pow-invalid-dif.json diff --git a/ledger/test/resources/504-advance-brother-pow-invalid-mmh.json b/firmware/test/resources/504-advance-brother-pow-invalid-mmh.json similarity index 100% rename from ledger/test/resources/504-advance-brother-pow-invalid-mmh.json rename to firmware/test/resources/504-advance-brother-pow-invalid-mmh.json diff --git a/ledger/test/resources/505-advance-brother-too-many.json b/firmware/test/resources/505-advance-brother-too-many.json similarity index 100% rename from ledger/test/resources/505-advance-brother-too-many.json rename to firmware/test/resources/505-advance-brother-too-many.json diff --git a/ledger/test/resources/506-advance-brother-not-brother.json b/firmware/test/resources/506-advance-brother-not-brother.json similarity index 100% rename from ledger/test/resources/506-advance-brother-not-brother.json rename to firmware/test/resources/506-advance-brother-not-brother.json diff --git a/ledger/test/resources/507-advance-brother-same-as-block.json b/firmware/test/resources/507-advance-brother-same-as-block.json similarity index 100% rename from ledger/test/resources/507-advance-brother-same-as-block.json rename to firmware/test/resources/507-advance-brother-same-as-block.json diff --git a/ledger/test/resources/508-advance-brothers-not-ordered.json b/firmware/test/resources/508-advance-brothers-not-ordered.json similarity index 100% rename from ledger/test/resources/508-advance-brothers-not-ordered.json rename to firmware/test/resources/508-advance-brothers-not-ordered.json diff --git a/ledger/test/resources/509-get-after-failed-advance.json b/firmware/test/resources/509-get-after-failed-advance.json similarity index 100% rename from ledger/test/resources/509-get-after-failed-advance.json rename to firmware/test/resources/509-get-after-failed-advance.json diff --git a/ledger/test/resources/600-advance-partial-before-sign.json b/firmware/test/resources/600-advance-partial-before-sign.json similarity index 100% rename from ledger/test/resources/600-advance-partial-before-sign.json rename to firmware/test/resources/600-advance-partial-before-sign.json diff --git a/ledger/test/resources/601-get-before-sign.json b/firmware/test/resources/601-get-before-sign.json similarity index 100% rename from ledger/test/resources/601-get-before-sign.json rename to firmware/test/resources/601-get-before-sign.json diff --git a/ledger/test/resources/602-sign-long-redeemscript.json b/firmware/test/resources/602-sign-long-redeemscript.json similarity index 100% rename from ledger/test/resources/602-sign-long-redeemscript.json rename to firmware/test/resources/602-sign-long-redeemscript.json diff --git a/ledger/test/resources/610-sign-tx-with-many-inputs.json b/firmware/test/resources/610-sign-tx-with-many-inputs.json similarity index 100% rename from ledger/test/resources/610-sign-tx-with-many-inputs.json rename to firmware/test/resources/610-sign-tx-with-many-inputs.json diff --git a/ledger/test/resources/612-sign-sample-mainnet-tx.json b/firmware/test/resources/612-sign-sample-mainnet-tx.json similarity index 100% rename from ledger/test/resources/612-sign-sample-mainnet-tx.json rename to firmware/test/resources/612-sign-sample-mainnet-tx.json diff --git a/ledger/test/resources/613-sign-sample-testnet-tx-erp.json b/firmware/test/resources/613-sign-sample-testnet-tx-erp.json similarity index 100% rename from ledger/test/resources/613-sign-sample-testnet-tx-erp.json rename to firmware/test/resources/613-sign-sample-testnet-tx-erp.json diff --git a/ledger/test/resources/614-sign-match-not-last-log.json b/firmware/test/resources/614-sign-match-not-last-log.json similarity index 100% rename from ledger/test/resources/614-sign-match-not-last-log.json rename to firmware/test/resources/614-sign-match-not-last-log.json diff --git a/ledger/test/resources/615-sign-match-long-proof.json b/firmware/test/resources/615-sign-match-long-proof.json similarity index 100% rename from ledger/test/resources/615-sign-match-long-proof.json rename to firmware/test/resources/615-sign-match-long-proof.json diff --git a/ledger/test/resources/616-sign-3input-5output-testnet.json b/firmware/test/resources/616-sign-3input-5output-testnet.json similarity index 100% rename from ledger/test/resources/616-sign-3input-5output-testnet.json rename to firmware/test/resources/616-sign-3input-5output-testnet.json diff --git a/ledger/test/resources/617-get-after-success-sign.json b/firmware/test/resources/617-get-after-success-sign.json similarity index 100% rename from ledger/test/resources/617-get-after-success-sign.json rename to firmware/test/resources/617-get-after-success-sign.json diff --git a/ledger/test/resources/620-sign-segwit-basic.json b/firmware/test/resources/620-sign-segwit-basic.json similarity index 100% rename from ledger/test/resources/620-sign-segwit-basic.json rename to firmware/test/resources/620-sign-segwit-basic.json diff --git a/ledger/test/resources/621-sign-segwit-with-many-inputs.json b/firmware/test/resources/621-sign-segwit-with-many-inputs.json similarity index 100% rename from ledger/test/resources/621-sign-segwit-with-many-inputs.json rename to firmware/test/resources/621-sign-segwit-with-many-inputs.json diff --git a/ledger/test/resources/622-sign-segwit-long-witnessscript.json b/firmware/test/resources/622-sign-segwit-long-witnessscript.json similarity index 100% rename from ledger/test/resources/622-sign-segwit-long-witnessscript.json rename to firmware/test/resources/622-sign-segwit-long-witnessscript.json diff --git a/ledger/test/resources/700-dongle-fake-receipt-root-fails.json b/firmware/test/resources/700-dongle-fake-receipt-root-fails.json similarity index 100% rename from ledger/test/resources/700-dongle-fake-receipt-root-fails.json rename to firmware/test/resources/700-dongle-fake-receipt-root-fails.json diff --git a/ledger/test/resources/800-advance-single-block-with-brothers.json b/firmware/test/resources/800-advance-single-block-with-brothers.json similarity index 100% rename from ledger/test/resources/800-advance-single-block-with-brothers.json rename to firmware/test/resources/800-advance-single-block-with-brothers.json diff --git a/ledger/test/resources/801-get-after-single-block-with-brothers.json b/firmware/test/resources/801-get-after-single-block-with-brothers.json similarity index 100% rename from ledger/test/resources/801-get-after-single-block-with-brothers.json rename to firmware/test/resources/801-get-after-single-block-with-brothers.json diff --git a/ledger/test/resources/900-set-is-onboarded-no.json b/firmware/test/resources/900-set-is-onboarded-no.json similarity index 100% rename from ledger/test/resources/900-set-is-onboarded-no.json rename to firmware/test/resources/900-set-is-onboarded-no.json diff --git a/ledger/test/resources/901-no-onboarded-sign-noauth-fails.json b/firmware/test/resources/901-no-onboarded-sign-noauth-fails.json similarity index 100% rename from ledger/test/resources/901-no-onboarded-sign-noauth-fails.json rename to firmware/test/resources/901-no-onboarded-sign-noauth-fails.json diff --git a/ledger/test/resources/902-no-onboard-sign-auth-fails.json b/firmware/test/resources/902-no-onboard-sign-auth-fails.json similarity index 100% rename from ledger/test/resources/902-no-onboard-sign-auth-fails.json rename to firmware/test/resources/902-no-onboard-sign-auth-fails.json diff --git a/ledger/test/resources/903-no-onboarded-get-bs-fails.json b/firmware/test/resources/903-no-onboarded-get-bs-fails.json similarity index 100% rename from ledger/test/resources/903-no-onboarded-get-bs-fails.json rename to firmware/test/resources/903-no-onboarded-get-bs-fails.json diff --git a/ledger/test/resources/904-no-onboarded-advance-fails.json b/firmware/test/resources/904-no-onboarded-advance-fails.json similarity index 100% rename from ledger/test/resources/904-no-onboarded-advance-fails.json rename to firmware/test/resources/904-no-onboarded-advance-fails.json diff --git a/ledger/test/resources/905-no-onboard-update-fails.json b/firmware/test/resources/905-no-onboard-update-fails.json similarity index 100% rename from ledger/test/resources/905-no-onboard-update-fails.json rename to firmware/test/resources/905-no-onboard-update-fails.json diff --git a/ledger/test/resources/906-set-is-onboarded-yes.json b/firmware/test/resources/906-set-is-onboarded-yes.json similarity index 100% rename from ledger/test/resources/906-set-is-onboarded-yes.json rename to firmware/test/resources/906-set-is-onboarded-yes.json diff --git a/ledger/test/resources/907-dongle-set-is-onboarded-fails.json b/firmware/test/resources/907-dongle-set-is-onboarded-fails.json similarity index 100% rename from ledger/test/resources/907-dongle-set-is-onboarded-fails.json rename to firmware/test/resources/907-dongle-set-is-onboarded-fails.json diff --git a/ledger/test/resources/nvm/00-blockchain-parameters.json b/firmware/test/resources/nvm/00-blockchain-parameters.json similarity index 100% rename from ledger/test/resources/nvm/00-blockchain-parameters.json rename to firmware/test/resources/nvm/00-blockchain-parameters.json diff --git a/ledger/test/resources/nvm/01-nvm-stats-reset.json b/firmware/test/resources/nvm/01-nvm-stats-reset.json similarity index 100% rename from ledger/test/resources/nvm/01-nvm-stats-reset.json rename to firmware/test/resources/nvm/01-nvm-stats-reset.json diff --git a/ledger/test/resources/nvm/10-reset.json b/firmware/test/resources/nvm/10-reset.json similarity index 100% rename from ledger/test/resources/nvm/10-reset.json rename to firmware/test/resources/nvm/10-reset.json diff --git a/ledger/test/resources/nvm/11-get-initial-mainnet.json b/firmware/test/resources/nvm/11-get-initial-mainnet.json similarity index 100% rename from ledger/test/resources/nvm/11-get-initial-mainnet.json rename to firmware/test/resources/nvm/11-get-initial-mainnet.json diff --git a/ledger/test/resources/nvm/12-advance-mainnet.json b/firmware/test/resources/nvm/12-advance-mainnet.json similarity index 100% rename from ledger/test/resources/nvm/12-advance-mainnet.json rename to firmware/test/resources/nvm/12-advance-mainnet.json diff --git a/ledger/test/resources/nvm/13-get-after-advance-mainnet.json b/firmware/test/resources/nvm/13-get-after-advance-mainnet.json similarity index 100% rename from ledger/test/resources/nvm/13-get-after-advance-mainnet.json rename to firmware/test/resources/nvm/13-get-after-advance-mainnet.json diff --git a/ledger/test/resources/nvm/20-nvm-stats-print.json b/firmware/test/resources/nvm/20-nvm-stats-print.json similarity index 100% rename from ledger/test/resources/nvm/20-nvm-stats-print.json rename to firmware/test/resources/nvm/20-nvm-stats-print.json diff --git a/ledger/test/run.py b/firmware/test/run.py similarity index 100% rename from ledger/test/run.py rename to firmware/test/run.py diff --git a/ledger/test/test-all b/firmware/test/test-all similarity index 75% rename from ledger/test/test-all rename to firmware/test/test-all index 93f9c0b4..239ba396 100755 --- a/ledger/test/test-all +++ b/firmware/test/test-all @@ -35,18 +35,18 @@ if [[ "$WITH_DONGLE" == "no" ]]; then # Build and run tcp signer $TEST_ROOT/../build/build-tcpsigner - $TEST_ROOT/../../docker/mware/do-notty-nousb /hsm2/ledger/src/tcpsigner ./tcpsigner --checkpoint 0xbdcb3c17c7aee714cec8ad900341bfd987b452280220dcbd6e7191f67ea4209b --difficulty 0x32 --network regtest > /dev/null & + $TEST_ROOT/../../docker/mware/do-notty-nousb /hsm2/firmware/src/tcpsigner ./tcpsigner --checkpoint 0xbdcb3c17c7aee714cec8ad900341bfd987b452280220dcbd6e7191f67ea4209b --difficulty 0x32 --network regtest > /dev/null & sleep 1 # Run tests - docker exec -t -w /hsm2/ledger/test hsm-mware-notty python run.py + docker exec -t -w /hsm2/firmware/test hsm-mware-notty python run.py err_code=$? # Kill (and remove) container docker kill hsm-mware-notty > /dev/null else # Run tests against a dongle - $TEST_ROOT/../../docker/mware/do /hsm2/ledger/test "python run.py -d ${RUN_ARGS}" + $TEST_ROOT/../../docker/mware/do /hsm2/firmware/test "python run.py -d ${RUN_ARGS}" err_code=$? fi diff --git a/ledger/test/thirdparty b/firmware/test/thirdparty similarity index 100% rename from ledger/test/thirdparty rename to firmware/test/thirdparty diff --git a/ledger/deploy/.gitignore b/ledger/deploy/.gitignore deleted file mode 100644 index 5ceb3864..00000000 --- a/ledger/deploy/.gitignore +++ /dev/null @@ -1 +0,0 @@ -venv diff --git a/ledger/src/.gitignore b/ledger/src/.gitignore deleted file mode 100644 index 4157b184..00000000 --- a/ledger/src/.gitignore +++ /dev/null @@ -1,19 +0,0 @@ -bin/ -debug/ -dep/ -obj/ - -# TCPSigner -tcpsigner/tcpsigner -tcpsigner/objs -tcpsigner/test/**/*.o -tcpsigner/test/**/test.out -tcpsigner/**/*.json - -# Icons hex -signer/icon.hex -ui/icon.hex - -# Code coverage artifacts -*.gcda -*.gcno diff --git a/ledger/src/common/test/.gitignore b/ledger/src/common/test/.gitignore deleted file mode 100644 index eb46c5fd..00000000 --- a/ledger/src/common/test/.gitignore +++ /dev/null @@ -1,3 +0,0 @@ -# Ignore generated artifacts -**/*.o -**/*.out diff --git a/ledger/src/signer/.gitignore b/ledger/src/signer/.gitignore deleted file mode 100644 index 2916a8cd..00000000 --- a/ledger/src/signer/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -bin -debug -dep -obj -static-analysis -test/**/*.o -test/**/*.out diff --git a/ledger/src/signer/src/sign.h b/ledger/src/signer/src/sign.h deleted file mode 100644 index 4968a36b..00000000 --- a/ledger/src/signer/src/sign.h +++ /dev/null @@ -1,67 +0,0 @@ -/** - * The MIT License (MIT) - * - * Copyright (c) 2021 RSK Labs Ltd - * - * 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. - */ - -#ifndef __SIGN_H -#define __SIGN_H - -#define DO_SIGN_ERROR (0) -#define DO_PUBKEY_ERROR (0) - -/* - * Derive the public key for a given path. - * Store the public key into the given destination buffer. - * - * @arg[in] path derivation path - * @arg[in] path_length length of the derivation path - * @arg[in] dest destination buffer - * @arg[in] dest destination buffer size - * @ret size of the public key derived, - * or DO_PUBKEY_ERROR in case of error - */ -int do_pubkey(unsigned int* path, - unsigned char path_length, - unsigned char* dest, - size_t dest_size); - -/* - * Sign a message with a given path. - * Store the signature into the given destination buffer. - * - * @arg[in] path derivation path - * @arg[in] path_length length of the derivation path - * @arg[in] message message buffer - * @arg[in] message_size message size - * @arg[in] dest destination buffer - * @arg[in] dest destination buffer size - * @ret size of the signature produced, - * or DO_SIGN_ERROR in case of error - */ -int do_sign(unsigned int* path, - unsigned char path_length, - unsigned char* message, - size_t message_size, - unsigned char* dest, - size_t dest_size); - -#endif // __SIGN_H diff --git a/ledger/src/signer/test/btcscript/Makefile b/ledger/src/signer/test/btcscript/Makefile deleted file mode 100644 index 797276c9..00000000 --- a/ledger/src/signer/test/btcscript/Makefile +++ /dev/null @@ -1,57 +0,0 @@ -# The MIT License (MIT) -# -# Copyright (c) 2021 RSK Labs Ltd -# -# 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. - -TESTCOMMONDIR = ../common -SRCDIR = ../../src -TCPSIGNERSRCDIR = ../../../tcpsigner -CFLAGS = -I $(SRCDIR) -I $(TCPSIGNERSRCDIR) -I $(TESTCOMMONDIR) - -include ../../../../coverage/coverage.mk - -PROG = test.out -OBJS = test_fwk.o btcscript.o hex_reader.o test_btcscript.o - -all: $(PROG) - -$(PROG): $(OBJS) - $(CC) $(COVFLAGS) -o $@ $^ - -test_fwk.o: $(TESTCOMMONDIR)/test_fwk.c - $(CC) $(CFLAGS) -c -o $@ $^ - -btcscript.o: $(SRCDIR)/btcscript.c - $(CC) $(CFLAGS) $(COVFLAGS) -c -o $@ $^ - -hex_reader.o: $(TCPSIGNERSRCDIR)/hex_reader.c - $(CC) $(CFLAGS) -c -o $@ $^ - -test_btcscript.o: test_btcscript.c test_fwk.o btcscript.o hex_reader.o - -$(SRCDIR)/btcscript.c: $(SRCDIR)/btcscript.h -$(TCPSIGNERSRCDIR)/hex_reader.c: $(TCPSIGNERSRCDIR)/hex_reader.h - -.PHONY: clean test -clean: - rm -f $(PROG) *.o $(COVFILES) - -test: all - ./$(PROG) diff --git a/ledger/src/signer/test/btctx/Makefile b/ledger/src/signer/test/btctx/Makefile deleted file mode 100644 index ba3c350e..00000000 --- a/ledger/src/signer/test/btctx/Makefile +++ /dev/null @@ -1,65 +0,0 @@ -# The MIT License (MIT) -# -# Copyright (c) 2021 RSK Labs Ltd -# -# 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. - -TESTCOMMONDIR = ../common -SRCDIR = ../../src -TCPSIGNERSRCDIR = ../../../tcpsigner -COMMONPATH = ../../../common/src -CFLAGS = -I $(SRCDIR) -I $(TCPSIGNERSRCDIR) -I $(COMMONPATH) -I $(TESTCOMMONDIR) - -include ../../../../coverage/coverage.mk - -PROG = test.out -OBJS = test_fwk.o btctx.o svarint.o hex_reader.o os.o test_btctx.o - -all: $(PROG) - -$(PROG): $(OBJS) - $(CC) $(COVFLAGS) -o $@ $^ - -test_fwk.o: $(TESTCOMMONDIR)/test_fwk.c - $(CC) $(CFLAGS) -c -o $@ $^ - -btctx.o: $(SRCDIR)/btctx.c - $(CC) $(CFLAGS) $(COVFLAGS) -c -o $@ $^ - -svarint.o: $(SRCDIR)/svarint.c - $(CC) $(CFLAGS) $(COVFLAGS) -c -o $@ $^ - -hex_reader.o: $(TCPSIGNERSRCDIR)/hex_reader.c - $(CC) $(CFLAGS) -c -o $@ $^ - -os.o: $(TCPSIGNERSRCDIR)/os.c - $(CC) $(CFLAGS) -c -o $@ $^ - -test_btctx.o: test_btctx.c test_fwk.o btctx.o svarint.o hex_reader.o os.o - -$(SRCDIR)/btctx.c: $(SRCDIR)/btctx.h -$(SRCDIR)/svarint.c: $(SRCDIR)/svarint.h -$(TCPSIGNERSRCDIR)/hex_reader.c: $(TCPSIGNERSRCDIR)/hex_reader.h - -.PHONY: clean test -clean: - rm -f $(PROG) *.o $(COVFILES) - -test: all - ./$(PROG) diff --git a/ledger/src/signer/test/difficulty/Makefile b/ledger/src/signer/test/difficulty/Makefile deleted file mode 100644 index cc2421c0..00000000 --- a/ledger/src/signer/test/difficulty/Makefile +++ /dev/null @@ -1,62 +0,0 @@ -# The MIT License (MIT) -# -# Copyright (c) 2021 RSK Labs Ltd -# -# 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. - -TESTCOMMONDIR = ../common -SRCDIR = ../../src -COMMONPATH = ../../../common/src -TCPSIGNERPATH = ../../../tcpsigner - -include ../../../../coverage/coverage.mk - -CFLAGS = -I $(SRCDIR) -I $(COMMONPATH) -I $(TCPSIGNERPATH) -I $(TESTCOMMONDIR) -DFEDHM_EMULATOR -DDEBUG_DIFF - -PROG = test.out -OBJS = test_fwk.o bigdigits.o bc_diff.o os.o test_difficulty.o - -all: $(PROG) - -$(PROG): $(OBJS) - $(CC) $(COVFLAGS) -o $@ $^ - -test_fwk.o: $(TESTCOMMONDIR)/test_fwk.c - $(CC) $(CFLAGS) -c -o $@ $^ - -bigdigits.o: $(SRCDIR)/bigdigits.c - $(CC) $(CFLAGS) $(COVFLAGS) -c -o $@ $^ - -os.o: $(TCPSIGNERPATH)/os.c - $(CC) $(CFLAGS) -c -o $@ $^ - -bc_diff.o: $(SRCDIR)/bc_diff.c - $(CC) $(CFLAGS) $(COVFLAGS) -c -o $@ $^ - -test_difficulty.o: test_difficulty.c test_fwk.o bigdigits.o bc_diff.o os.o - -$(SRCDIR)/bigdigits.c: $(SRCDIR)/bigdigits.h $(SRCDIR)/bigdtypes.h -$(SRCDIR)/bc_diff.c: $(SRCDIR)/bc_diff.h $(SRCDIR)/bigdigits.h $(SRCDIR)/bigdtypes.h $(TCPSIGNERPATH)/os_exceptions.h - -.PHONY: clean test -clean: - rm -f $(PROG) *.o $(COVFILES) - -test: all - ./$(PROG) diff --git a/ledger/src/signer/test/srlp/Makefile b/ledger/src/signer/test/srlp/Makefile deleted file mode 100644 index faaa9cd8..00000000 --- a/ledger/src/signer/test/srlp/Makefile +++ /dev/null @@ -1,52 +0,0 @@ -# The MIT License (MIT) -# -# Copyright (c) 2021 RSK Labs Ltd -# -# 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. - -TESTCOMMONDIR = ../common -SRCDIR = ../../src -CFLAGS = -I $(SRCDIR) -I $(TESTCOMMONDIR) -Imocks/ -DMAX_RLP_CTX_DEPTH=10 - -include ../../../../coverage/coverage.mk - -PROG = test.out -OBJS = test_fwk.o srlp.o test_srlp.o - -all: $(PROG) - -$(PROG): $(OBJS) - $(CC) $(COVFLAGS) -o $@ $^ - -test_fwk.o: $(TESTCOMMONDIR)/test_fwk.c - $(CC) $(CFLAGS) -c -o $@ $^ - -srlp.o: $(SRCDIR)/srlp.c - $(CC) $(CFLAGS) $(COVFLAGS) -c -o $@ $^ - -test_srlp.o: test_srlp.c test_fwk.o srlp.o - -$(SRCDIR)/srlp.c: $(SRCDIR)/srlp.h - -.PHONY: clean test -clean: - rm -f $(PROG) *.o $(COVFILES) - -test: all - ./$(PROG) diff --git a/ledger/src/signer/test/trie/Makefile b/ledger/src/signer/test/trie/Makefile deleted file mode 100644 index 4f1a30d1..00000000 --- a/ledger/src/signer/test/trie/Makefile +++ /dev/null @@ -1,65 +0,0 @@ -# The MIT License (MIT) -# -# Copyright (c) 2021 RSK Labs Ltd -# -# 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. - -TESTCOMMONDIR = ../common -SRCDIR = ../../src -TCPSIGNERSRCDIR = ../../../tcpsigner -COMMONPATH = ../../../common/src -CFLAGS = -I $(SRCDIR) -I $(TCPSIGNERSRCDIR) -I $(COMMONPATH) -I $(TESTCOMMONDIR) - -include ../../../../coverage/coverage.mk - -PROG = test.out -OBJS = test_fwk.o trie.o svarint.o hex_reader.o os.o test_trie.o - -all: $(PROG) - -$(PROG): $(OBJS) - $(CC) $(COVFLAGS) -o $@ $^ - -test_fwk.o: $(TESTCOMMONDIR)/test_fwk.c - $(CC) $(CFLAGS) -c -o $@ $^ - -trie.o: $(SRCDIR)/trie.c - $(CC) $(CFLAGS) $(COVFLAGS) -c -o $@ $^ - -svarint.o: $(SRCDIR)/svarint.c - $(CC) $(CFLAGS) $(COVFLAGS) -c -o $@ $^ - -hex_reader.o: $(TCPSIGNERSRCDIR)/hex_reader.c - $(CC) $(CFLAGS) -c -o $@ $^ - -os.o: $(TCPSIGNERSRCDIR)/os.c - $(CC) $(CFLAGS) -c -o $@ $^ - -test_trie.o: test_trie.c test_fwk.o trie.o svarint.o hex_reader.o os.o - -$(SRCDIR)/trie.c: $(SRCDIR)/trie.h -$(SRCDIR)/svarint.c: $(SRCDIR)/svarint.h -$(TCPSIGNERSRCDIR)/hex_reader.c: $(TCPSIGNERSRCDIR)/hex_reader.h - -.PHONY: clean test -clean: - rm -f $(PROG) *.o $(COVFILES) - -test: all - ./$(PROG) diff --git a/ledger/src/tcpsigner/communication.c b/ledger/src/tcpsigner/communication.c deleted file mode 120000 index c15649fd..00000000 --- a/ledger/src/tcpsigner/communication.c +++ /dev/null @@ -1 +0,0 @@ -../ui/src/communication.c \ No newline at end of file diff --git a/ledger/src/tcpsigner/communication.h b/ledger/src/tcpsigner/communication.h deleted file mode 120000 index b6a13099..00000000 --- a/ledger/src/tcpsigner/communication.h +++ /dev/null @@ -1 +0,0 @@ -../ui/src/communication.h \ No newline at end of file diff --git a/ledger/src/tcpsigner/cx.h b/ledger/src/tcpsigner/cx.h deleted file mode 100644 index 8ab2ccdc..00000000 --- a/ledger/src/tcpsigner/cx.h +++ /dev/null @@ -1,23 +0,0 @@ -/** - * The MIT License (MIT) - * - * Copyright (c) 2021 RSK Labs Ltd - * - * 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. - */ diff --git a/ledger/src/tcpsigner/dbg.c b/ledger/src/tcpsigner/dbg.c deleted file mode 100644 index ef7c8ed8..00000000 --- a/ledger/src/tcpsigner/dbg.c +++ /dev/null @@ -1,95 +0,0 @@ -/** - * The MIT License (MIT) - * - * Copyright (c) 2021 RSK Labs Ltd - * - * 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. - */ - -/******************************************************************************* - * powHSM - * - * Debug functions for TCPSigner - ********************************************************************************/ - -#ifdef HSM_SIMULATOR - -#include -#include - -#include "bigdigits.h" -#include "srlp.h" - -/** Print buffer in hex format with prefix */ -void LOG_HEX(const char *prefix, void *buffer, size_t size) { - printf("%s ", prefix); - if (size > 0) { - printf("0x"); - for (unsigned int i = 0; i < size; i++) { - printf("%02x", ((unsigned char *)buffer)[i]); - } - } else { - printf("EMPTY"); - } - printf("\n"); -} - -/** Print big integer in hex format with optional prefix and suffix strings */ -void LOG_BIGD_HEX(const char *prefix, - const DIGIT_T *a, - size_t len, - const char *suffix) { - if (prefix) - printf("%s", prefix); - /* Trim leading digits which are zero */ - while (len--) { - if (a[len] != 0) - break; - } - len++; - if (0 == len) - len = 1; - /* print first digit without leading zeros */ - printf("0x%" PRIxBIGD, a[--len]); - while (len--) { - printf("%08" PRIxBIGD, a[len]); - } - if (suffix) - printf("%s", suffix); -} - -/** Print N copies of a given char */ -void LOG_N_CHARS(const char c, unsigned int times) { - for (unsigned int i = 0; i < times; i++) - printf("%c", c); -} - -/** Print the given SRLP context (see srlp.h) */ -void LOG_SRLP_CTX(uint8_t v, rlp_ctx_t ctx[], uint8_t ptr) { -#ifdef DEBUG_SRLP - printf("'0x%02x' ; <%u> ; ", v, ptr); - for (int i = ptr; i >= 0; --i) { - rlp_ctx_t cur = ctx[i]; - printf("{%d, %u, %u} ; ", cur.state, cur.size, cur.cursor); - } - printf("{EOC}\n"); -#endif -} - -#endif \ No newline at end of file diff --git a/ledger/src/tcpsigner/hsmsim_attestation.c b/ledger/src/tcpsigner/hsmsim_attestation.c deleted file mode 100644 index 47ce9a21..00000000 --- a/ledger/src/tcpsigner/hsmsim_attestation.c +++ /dev/null @@ -1,147 +0,0 @@ -/** - * The MIT License (MIT) - * - * Copyright (c) 2021 RSK Labs Ltd - * - * 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 "hsmsim_attestation.h" - -#include -#include -#include - -#include "hsmsim_random.h" -#include "cJSON.h" -#include "json.h" -#include "hex_reader.h" -#include "os_ecdsa.h" -#include "log.h" - -#define ATTESTATION_KEY_KEY "attestationKey" -#define CODE_HASH_KEY "codeHash" - -attestation_id_t attestation_id; - -/** - * Write current attestation id in JSON-format to the given path - */ -static bool write_attestation_id_file(char* attid_file_path) { - cJSON* json = cJSON_CreateObject(); - - unsigned long max_size = - sizeof(attestation_id.key) > sizeof(attestation_id.code_hash) - ? sizeof(attestation_id.key) - : sizeof(attestation_id.code_hash); - - char hex_str[max_size * 2 + 1]; - - // Write attestation key - for (int i = 0; i < sizeof(attestation_id.key); i++) - sprintf(hex_str + i * 2, "%02x", attestation_id.key[i]); - hex_str[sizeof(attestation_id.key) * 2] = '\0'; - cJSON_AddStringToObject(json, ATTESTATION_KEY_KEY, hex_str); - - // Write code hash - for (int i = 0; i < sizeof(attestation_id.code_hash); i++) - sprintf(hex_str + i * 2, "%02x", attestation_id.code_hash[i]); - hex_str[sizeof(attestation_id.code_hash) * 2] = '\0'; - cJSON_AddStringToObject(json, CODE_HASH_KEY, hex_str); - - return write_json_file(attid_file_path, json); -} - -static inline bool read_hex_value_into(cJSON* json, - char* key, - unsigned char* dest) { - cJSON* entry = cJSON_GetObjectItemCaseSensitive(json, key); - if (entry == NULL || !cJSON_IsString(entry)) - return false; - char* hex_value = cJSON_GetStringValue(entry); - read_hex(hex_value, strlen(hex_value), dest); - return true; -} - -bool hsmsim_attestation_initialize(char* att_file_path) { - info("Loading attestation file '%s'\n", att_file_path); - cJSON* json = read_json_file(att_file_path); - - if (json == NULL) { - info("Attestation file not found or file format incorrect. Creating a " - "random attestation id (key and code hash pair)\n"); - - // Init new random key and code hash - getrandom(attestation_id.key, sizeof(attestation_id.key), 0); - getrandom( - attestation_id.code_hash, sizeof(attestation_id.code_hash), 0); - - // Write attestation id to the file - if (!write_attestation_id_file(att_file_path)) { - info("Error writing attestation id to %s\n", att_file_path); - return false; - } - info("Attestation id created and saved to %s\n", att_file_path); - } else { - // Load attestation id into memory - if (!cJSON_IsObject(json)) { - info("Expected an object as top level element of %s\n", - att_file_path); - return false; - } - - // Read attestation key - if (!read_hex_value_into( - json, ATTESTATION_KEY_KEY, attestation_id.key)) { - info( - "'%s' not found in '%s'\n", ATTESTATION_KEY_KEY, att_file_path); - return false; - } - - // Read code hash - if (!read_hex_value_into( - json, CODE_HASH_KEY, attestation_id.code_hash)) { - info("'%s' not found in '%s'\n", CODE_HASH_KEY, att_file_path); - return false; - } - } - - // Init OS ECDSA - os_ecdsa_initialize(); - - // Grab attestation id public key - unsigned char pubkey[PUBKEY_CMP_LENGTH]; - if (hsmsim_helper_getpubkey( - attestation_id.key, pubkey, sizeof(pubkey), true) != - PUBKEY_CMP_LENGTH) { - info("Error getting compressed public key for attestation id key\n"); - return false; - } - info("Loaded attestation id:\n"); - printf("\tPublic key: "); - for (int i = 0; i < sizeof(pubkey); i++) - printf("%02x", pubkey[i]); - printf("\n"); - printf("\tCode hash: "); - for (int i = 0; i < sizeof(attestation_id.code_hash); i++) - printf("%02x", attestation_id.code_hash[i]); - printf("\n"); - - return true; -} diff --git a/ledger/src/tcpsigner/hsmsim_attestation.h b/ledger/src/tcpsigner/hsmsim_attestation.h deleted file mode 100644 index b836c326..00000000 --- a/ledger/src/tcpsigner/hsmsim_attestation.h +++ /dev/null @@ -1,49 +0,0 @@ -/** - * The MIT License (MIT) - * - * Copyright (c) 2021 RSK Labs Ltd - * - * 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. - */ - -#ifndef __SIMULATOR_HSMSIM_ATTESTATION_H -#define __SIMULATOR_HSMSIM_ATTESTATION_H - -#include - -#include "constants.h" - -// An attestation ID (in lack of a better name) -// is simply a pair consisting of a secp256k1 private key -// representing the device attestation private key and -// a code hash representing the hash of the running -// application that is attestating. Together, they can -// be used to construct another secp256k1 private key -// which is the attestation private key used to sign the -// attestation messages. -typedef struct { - unsigned char key[PRIVATE_KEY_LENGTH]; - unsigned char code_hash[HASH_LENGTH]; -} attestation_id_t; - -extern attestation_id_t attestation_id; - -bool hsmsim_attestation_initialize(char* att_file_path); - -#endif // __SIMULATOR_HSMSIM_ATTESTATION_H diff --git a/ledger/src/tcpsigner/hsmsim_ecdsa.c b/ledger/src/tcpsigner/hsmsim_ecdsa.c deleted file mode 100644 index 7cc490e2..00000000 --- a/ledger/src/tcpsigner/hsmsim_ecdsa.c +++ /dev/null @@ -1,157 +0,0 @@ -/** - * The MIT License (MIT) - * - * Copyright (c) 2021 RSK Labs Ltd - * - * 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 "hsmsim_ecdsa.h" -#include "os_ecdsa.h" - -#include -#include -#include - -#include "hsmsim_random.h" -#include "pathAuth.h" -#include "constants.h" -#include "cJSON.h" -#include "json.h" -#include "hex_reader.h" -#include "log.h" - -struct private_key_mapping_s { - const unsigned char* path; - unsigned char key[PRIVATE_KEY_LENGTH]; -}; - -static struct private_key_mapping_s private_keys[TOTAL_AUTHORIZED_PATHS]; - -// Hardcoded BIP32 paths for the JSON keyfile -// (no real use in writing conversion routines to/from binary -// since there's no real use for the paths themselves -// other than serving as map keys) -// The order is based on the 'ordered_paths' constant defined in 'pathAuth.c' -// (which means that if that changes, this should be updated accordingly) -const char bip32_paths[][20] = { - "m/44'/0'/0'/0/0", // BTC - "m/44'/1'/0'/0/0", // tBTC - "m/44'/1'/1'/0/0", // tRSK - "m/44'/1'/2'/0/0", // tMST - "m/44'/137'/0'/0/0", // RSK - "m/44'/137'/1'/0/0", // MST -}; - -/** - * Write current private keys in JSON-format to the given path - */ -static bool write_key_file(char* key_file_path) { - cJSON* json = cJSON_CreateObject(); - char hex_key[sizeof(private_keys[0].key) * 2 + 1]; - char bip32_path[100]; - - for (int i = 0; i < KEY_PATH_COUNT(); i++) { - for (int j = 0; j < sizeof(private_keys[0].key); j++) - sprintf(hex_key + j * 2, "%02x", private_keys[i].key[j]); - hex_key[sizeof(hex_key) - 1] = '\0'; - cJSON* json_hex_key = cJSON_CreateString(hex_key); - cJSON_AddStringToObject(json, bip32_paths[i], hex_key); - } - - return write_json_file(key_file_path, json); -} - -bool hsmsim_ecdsa_initialize(char* key_file_path) { - info("Loading key file '%s'\n", key_file_path); - cJSON* json = read_json_file(key_file_path); - - if (json == NULL) { - info("Keyfile not found or file format incorrect. Creating a new " - "random set of keys\n"); - // Init new random keys - for (int i = 0; i < KEY_PATH_COUNT(); i++) { - private_keys[i].path = (const unsigned char*)get_ordered_path(i); - getrandom(private_keys[i].key, sizeof(private_keys[i].key), 0); - } - - // Write keys to the file - if (!write_key_file(key_file_path)) { - info("Error writing keys to %s\n", key_file_path); - return false; - } - info("Keys created and saved to %s\n", key_file_path); - } else { - // Load keys into memory - if (!cJSON_IsObject(json)) { - info("Expected an object as top level element of %s\n", - key_file_path); - return false; - } - - for (int i = 0; i < KEY_PATH_COUNT(); i++) { - cJSON* key_entry = - cJSON_GetObjectItemCaseSensitive(json, bip32_paths[i]); - if (key_entry == NULL || !cJSON_IsString(key_entry)) { - info("Path '%s' not found in '%s'\n", - bip32_paths[i], - key_file_path); - return false; - } - private_keys[i].path = (const unsigned char*)get_ordered_path(i); - char* hex_key = cJSON_GetStringValue(key_entry); - read_hex(hex_key, strlen(hex_key), private_keys[i].key); - } - } - - // Init OS ECDSA - os_ecdsa_initialize(); - - unsigned char pubkey[PUBKEY_CMP_LENGTH]; - info("Loaded keys:\n"); - for (int i = 0; i < KEY_PATH_COUNT(); i++) { - if (hsmsim_helper_getpubkey( - private_keys[i].key, pubkey, sizeof(pubkey), true) != - PUBKEY_CMP_LENGTH) { - info("Error getting public key for key '%s'\n", bip32_paths[i]); - return false; - } - printf("\t%s: ", bip32_paths[i]); - for (int j = 0; j < sizeof(pubkey); j++) - printf("%02x", pubkey[j]); - printf("\n"); - } - - return true; -} - -bool hsmsim_ecdsa_get_key(unsigned char* path, unsigned char* dest) { - bool found = false; - for (int i = 0; i < TOTAL_AUTHORIZED_PATHS; i++) { - // Compare paths, skip first byte of stored path (length, not included - // in the path parameter) - if (!memcmp( - path, private_keys[i].path + 1, SINGLE_PATH_SIZE_BYTES - 1)) { - found = true; - memmove(dest, private_keys[i].key, sizeof(private_keys[i].key)); - break; - } - } - return found; -} diff --git a/ledger/src/tcpsigner/hsmsim_exceptions.c b/ledger/src/tcpsigner/hsmsim_exceptions.c deleted file mode 100644 index 8ab2ccdc..00000000 --- a/ledger/src/tcpsigner/hsmsim_exceptions.c +++ /dev/null @@ -1,23 +0,0 @@ -/** - * The MIT License (MIT) - * - * Copyright (c) 2021 RSK Labs Ltd - * - * 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. - */ diff --git a/ledger/src/tcpsigner/os_ecdsa.c b/ledger/src/tcpsigner/os_ecdsa.c deleted file mode 100644 index 5eaa6816..00000000 --- a/ledger/src/tcpsigner/os_ecdsa.c +++ /dev/null @@ -1,141 +0,0 @@ -/** - * The MIT License (MIT) - * - * Copyright (c) 2021 RSK Labs Ltd - * - * 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 "os_ecdsa.h" - -#include -#include - -#include "hsmsim_ecdsa.h" -#include "hsmsim_exceptions.h" -#include "constants.h" - -#include "hsmsim_random.h" - -#define PUBKEY_UNCOMPRESSED_LENGTH 65 - -static secp256k1_context *sp_ctx = NULL; - -void os_ecdsa_initialize() { - // Init the secp256k1 context - if (!sp_ctx) - sp_ctx = secp256k1_context_create(SECP256K1_CONTEXT_SIGN); -} - -void os_perso_derive_node_bip32(cx_curve_t curve, - unsigned int *path, - unsigned int pathLength, - unsigned char *privateKey, - unsigned char *chain) { - - if (!hsmsim_ecdsa_get_key((unsigned char *)path, privateKey)) { - THROW(HSMSIM_EXC_INVALID_PATH); - } -} - -int cx_ecdsa_init_private_key(cx_curve_t curve, - unsigned char *rawkey, - unsigned int key_len, - cx_ecfp_private_key_t *key) { - - memmove(key->K, rawkey, key_len); - return 0; // Return value not used atm -} - -int cx_ecfp_generate_pair(cx_curve_t curve, - cx_ecfp_public_key_t *pubkey, - cx_ecfp_private_key_t *privkey, - int keepprivate) { - - secp256k1_pubkey sp_pubkey; - - // Calculate the public key and serialize it uncompressed - if (!secp256k1_ec_pubkey_create(sp_ctx, &sp_pubkey, privkey->K)) { - THROW(HSMSIM_EXC_SECP_ERROR); - } - size_t pubkey_size = sizeof(pubkey->W); - secp256k1_ec_pubkey_serialize( - sp_ctx, pubkey->W, &pubkey_size, &sp_pubkey, SECP256K1_EC_UNCOMPRESSED); - pubkey->W_len = (unsigned int)pubkey_size; - return 0; // Return value not used atm -} - -int cx_ecdsa_sign(cx_ecfp_private_key_t *key, - int mode, - cx_md_t hashID, - unsigned char *hash, - unsigned int hash_len, - unsigned char *sig) { - - secp256k1_ecdsa_signature sp_sig; - size_t sig_serialized_size = MAX_SIGNATURE_LENGTH; - - // Sign and serialize as DER - secp256k1_ecdsa_sign(sp_ctx, &sp_sig, hash, key->K, NULL, NULL); - secp256k1_ecdsa_signature_serialize_der( - sp_ctx, sig, &sig_serialized_size, &sp_sig); - - return (int)sig_serialized_size; -} - -size_t hsmsim_helper_getpubkey(const unsigned char *key, - unsigned char *dest, - size_t dest_size, - bool compressed) { - secp256k1_pubkey pubkey; - - // Calculate the public key and serialize it compressed - if (!secp256k1_ec_pubkey_create(sp_ctx, &pubkey, key)) { - return 0; - } - secp256k1_ec_pubkey_serialize(sp_ctx, - dest, - &dest_size, - &pubkey, - compressed ? SECP256K1_EC_COMPRESSED - : SECP256K1_EC_UNCOMPRESSED); - - return dest_size; -} - -size_t hsmsim_helper_tweak_sign(const unsigned char *key, - const unsigned char *tweak, - const unsigned char *hash, - unsigned char *sig) { - unsigned char tweaked_key[PRIVATE_KEY_LENGTH]; - secp256k1_ecdsa_signature sp_sig; - size_t sig_serialized_size = MAX_SIGNATURE_LENGTH; - - // Tweak private key - memmove(tweaked_key, key, sizeof(tweaked_key)); - if (!secp256k1_ec_privkey_tweak_add(sp_ctx, tweaked_key, tweak)) - return 0; - - // Sign and serialize as DER - secp256k1_ecdsa_sign(sp_ctx, &sp_sig, hash, tweaked_key, NULL, NULL); - secp256k1_ecdsa_signature_serialize_der( - sp_ctx, sig, &sig_serialized_size, &sp_sig); - - return (int)sig_serialized_size; -} diff --git a/ledger/src/tcpsigner/os_ecdsa.h b/ledger/src/tcpsigner/os_ecdsa.h deleted file mode 100644 index 2a1449ad..00000000 --- a/ledger/src/tcpsigner/os_ecdsa.h +++ /dev/null @@ -1,86 +0,0 @@ -/** - * The MIT License (MIT) - * - * Copyright (c) 2021 RSK Labs Ltd - * - * 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. - */ - -#ifndef __SIMULATOR_OS_ECDSA_H -#define __SIMULATOR_OS_ECDSA_H - -#include -#include - -// TODO: in the future, actual enum definitions for these -// two types could be copied from the nanos SDK and used -// to e.g. verify calls are made with expected parameters. -// Ignore for now, define as char. -#define CX_CURVE_256K1 0 -#define CX_RND_RFC6979 0 -#define CX_LAST 0 -#define CX_SHA256 0 -typedef char cx_md_t; -typedef char cx_curve_t; - -typedef struct cx_ecfp_private_key_s { - unsigned char K[32]; -} cx_ecfp_private_key_t; - -typedef struct cx_ecfp_public_key_s { - unsigned int W_len; - unsigned char W[65]; -} cx_ecfp_public_key_t; - -void os_ecdsa_initialize(); - -void os_perso_derive_node_bip32(cx_curve_t curve, - unsigned int *path, - unsigned int pathLength, - unsigned char *privateKey, - unsigned char *chain); - -int cx_ecdsa_init_private_key(cx_curve_t curve, - unsigned char *rawkey, - unsigned int key_len, - cx_ecfp_private_key_t *key); - -int cx_ecfp_generate_pair(cx_curve_t curve, - cx_ecfp_public_key_t *pubkey, - cx_ecfp_private_key_t *privkey, - int keepprivate); - -int cx_ecdsa_sign(cx_ecfp_private_key_t *key, - int mode, - cx_md_t hashID, - unsigned char *hash, - unsigned int hash_len, - unsigned char *sig); - -size_t hsmsim_helper_getpubkey(const unsigned char *key, - unsigned char *dest, - size_t dest_size, - bool compressed); - -size_t hsmsim_helper_tweak_sign(const unsigned char *key, - const unsigned char *tweak, - const unsigned char *hash, - unsigned char *sig); - -#endif // __SIMULATOR_OS_ECDSA_H diff --git a/ledger/src/tcpsigner/os_hash.c b/ledger/src/tcpsigner/os_hash.c deleted file mode 100644 index 103b9eae..00000000 --- a/ledger/src/tcpsigner/os_hash.c +++ /dev/null @@ -1,63 +0,0 @@ -/** - * The MIT License (MIT) - * - * Copyright (c) 2021 RSK Labs Ltd - * - * 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 "os_hash.h" -#include "os_exceptions.h" -#include "dbg.h" - -int cx_sha256_init(cx_sha256_t *hash) { - hash->header.algo = CX_ALGO_SHA256; - sha256_init(&hash->ctx); -} - -int cx_keccak_init(cx_sha3_t *hash, int size) { - hash->header.algo = CX_ALGO_KECCAK256; - keccak_init(&hash->ctx); -} - -int cx_hash(cx_hash_t *hash, - int mode, - unsigned char *in, - unsigned int len, - unsigned char *out) { - switch (hash->algo) { - case CX_ALGO_SHA256: - if (!out) { - sha256_update(&((cx_sha256_t *)hash)->ctx, in, len); - } else { - sha256_final(&((cx_sha256_t *)hash)->ctx, out); - } - break; - case CX_ALGO_KECCAK256: - if (!out) { - keccak_update(&((cx_sha3_t *)hash)->ctx, in, len); - } else { - keccak_final(&((cx_sha3_t *)hash)->ctx, out); - } - break; - default: - LOG("Invalid hash algorithm given to cx_hash: %d", hash->algo); - THROW(0x9999); // TODO: define proper simulator-only error codes - } -} diff --git a/ledger/src/tcpsigner/os_hash.h b/ledger/src/tcpsigner/os_hash.h deleted file mode 100644 index 829ee6a8..00000000 --- a/ledger/src/tcpsigner/os_hash.h +++ /dev/null @@ -1,57 +0,0 @@ -/** - * The MIT License (MIT) - * - * Copyright (c) 2021 RSK Labs Ltd - * - * 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. - */ - -#ifndef __SIMULATOR_OS_HASHING_H -#define __SIMULATOR_OS_HASHING_H - -#include "sha256.h" -#include "keccak256.h" - -typedef enum { CX_ALGO_SHA256 = 0x01, CX_ALGO_KECCAK256 } cx_algo_t; - -typedef struct cx_hash_header_s { - cx_algo_t algo; -} cx_hash_t; - -typedef struct cx_sha256_s { - cx_hash_t header; - SHA256_CTX ctx; -} cx_sha256_t; - -typedef struct cx_sha3_s { - cx_hash_t header; - SHA3_CTX ctx; -} cx_sha3_t; - -int cx_sha256_init(cx_sha256_t *hash); - -int cx_keccak_init(cx_sha3_t *hash, int size); - -int cx_hash(cx_hash_t *hash, - int mode, - unsigned char *in, - unsigned int len, - unsigned char *out); - -#endif // __SIMULATOR_OS_HASHING_H diff --git a/ledger/src/tcpsigner/os_io.h b/ledger/src/tcpsigner/os_io.h deleted file mode 100644 index 16095370..00000000 --- a/ledger/src/tcpsigner/os_io.h +++ /dev/null @@ -1,98 +0,0 @@ -/** - * The MIT License (MIT) - * - * Copyright (c) 2021 RSK Labs Ltd - * - * 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. - */ - -#ifndef __SIMULATOR_OS_IO_H -#define __SIMULATOR_OS_IO_H - -#include - -/** - * APDU buffer - */ -#define CHANNEL_APDU 0 -#define IO_APDU_BUFFER_SIZE 85 -extern unsigned char G_io_apdu_buffer[IO_APDU_BUFFER_SIZE]; - -/* - * Sets the server on which io_exchange will perform - * the IO operations - * Either this or os_io_set_input_file must be called before - * using io_exchange. - */ -void os_io_set_server(int svr); - -/* - * Sets the input file from which io_exchange will - * read the input. - * Either this or os_io_set_server must be called before - * using io_exchange. - */ -void os_io_set_input_file(FILE *_input_file); - -/* - * Sets the replica file to which io_exchange will - * write the input. Optional. - */ -void os_io_set_replica_file(FILE *_replica_file); - -/** - * Perform an empty message - * write on the IO channel - */ -void io_exchange_reply(); - -/* - * This function performs the input / output to a simulated dongle, - * either via a TCP server of via an input file depending on global state. - * @arg[in] channel_and_flags must be CHANNEL_APDU - * @arg[in] tx amount of bytes to transmit to the client - * @ret amount of bytes received from the client - */ -unsigned short io_exchange(unsigned char channel_and_flags, unsigned short tx); -/* - * This function emulates USB device, writing bytes to tcpsocket instead - * @arg[in] channel_and_flags must be CHANNEL_APDU - * @arg[in] tx amount of bytes to transmit to the client - * @ret amount of bytes received from the client - */ -unsigned short io_exchange_server(unsigned char channel_and_flags, - unsigned short tx); - -/* This function emulates the HOST device, reading bytes to a file instead - * @arg[in] channel_and_flags must be CHANNEL_APDU - * @arg[in] tx_len amount of bytes to transmit to the client - * @ret amount of bytes received from the client - */ -unsigned short io_exchange_file(unsigned char channel_and_flags, - unsigned char tx_len, - FILE *inputfd); - -/* Append a received command to file - * @arg[in] filename Binary file to append commands - * @arg[in] rx Lenght of the command - * @ret number of bytes written - */ -unsigned int replicate_to_file(FILE *replica_file, unsigned short rx); - -#endif // __SIMULATOR_OS_IO_H diff --git a/ledger/src/tcpsigner/signer_authorization_status.c b/ledger/src/tcpsigner/signer_authorization_status.c deleted file mode 120000 index 105c1b9b..00000000 --- a/ledger/src/tcpsigner/signer_authorization_status.c +++ /dev/null @@ -1 +0,0 @@ -../ui/src/signer_authorization_status.c \ No newline at end of file diff --git a/ledger/src/tcpsigner/signer_authorization_status.h b/ledger/src/tcpsigner/signer_authorization_status.h deleted file mode 120000 index 4295054c..00000000 --- a/ledger/src/tcpsigner/signer_authorization_status.h +++ /dev/null @@ -1 +0,0 @@ -../ui/src/signer_authorization_status.h \ No newline at end of file diff --git a/ledger/src/tcpsigner/tcp.c b/ledger/src/tcpsigner/tcp.c deleted file mode 100644 index a93f12ad..00000000 --- a/ledger/src/tcpsigner/tcp.c +++ /dev/null @@ -1,120 +0,0 @@ -/** - * The MIT License (MIT) - * - * Copyright (c) 2021 RSK Labs Ltd - * - * 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. - */ - -/******************************************************************************* - * powHSM - * - * USB over TCP simulator layer for TCPSigner - ********************************************************************************/ - -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "os.h" -#include "tcp.h" -#include "hsmsim_exceptions.h" - -#include "log.h" - -// Global socket variables -struct sockaddr_in servaddr, cli; - -/* start server, return a socket on connection - * @arg[in] PORT tcp port - * @arg[in] HOST HOST string - * @ret socket file descriptor - */ -int start_server(int port, const char *host) { - int sockfd; - struct hostent *hostinfo; - hostinfo = gethostbyname(host); - - if (hostinfo == NULL) { - info("Host not found.\n"); - exit(1); - } - - // socket create and verification - sockfd = socket(AF_INET, SOCK_STREAM, 0); - if (sockfd == -1) { - info("Socket creation failed...\n"); - exit(1); - } - - bzero(&servaddr, sizeof(servaddr)); - - if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)) < - 0) { - info("Socket option setting failed failed\n"); - exit(1); - } - - if (setsockopt(sockfd, SOL_TCP, TCP_NODELAY, &(int){1}, sizeof(int)) < 0) { - info("Socket option setting failed failed\n"); - exit(1); - } - - // Set address and port - servaddr.sin_family = AF_INET; - memcpy(&servaddr.sin_addr, hostinfo->h_addr_list[0], hostinfo->h_length); - servaddr.sin_port = htons(port); - - // Binding newly created socket to given IP and verification - if ((bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr))) != 0) { - info("Socket bind failed...\n"); - exit(1); - } - - // Now server is ready to listen and verification - if ((listen(sockfd, 5)) != 0) { - info("Listen failed...\n"); - exit(1); - } - - info("Server listening...\n"); - return sockfd; -} - -/* Accept the data packet from client and verification - * @arg[in] sockfd server socket - * @ret connection file descriptor - */ -int accept_connection(int sockfd) { - int len = sizeof(cli); - int connfd = accept(sockfd, (struct sockaddr *)&cli, &len); - if (connfd < 0) { - info("Client connection failed...\n"); - exit(1); - } - - info("Client connected...\n"); - return connfd; -} diff --git a/ledger/src/tcpsigner/tcp.h b/ledger/src/tcpsigner/tcp.h deleted file mode 100644 index 9c21ae1b..00000000 --- a/ledger/src/tcpsigner/tcp.h +++ /dev/null @@ -1,37 +0,0 @@ -/** - * The MIT License (MIT) - * - * Copyright (c) 2021 RSK Labs Ltd - * - * 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. - */ - -/******************************************************************************* - * powHSM - * - * USB over TCP simulator layer for TCPSigner - ********************************************************************************/ - -#define EXCEPTION_SOCKET -1 - -// Setup server socket. Returns server socket FD -int start_server(int PORT, const char *HOST); - -// Accept connection. Returns connection socket FD -int accept_connection(int sockfd); diff --git a/ledger/src/tcpsigner/ui_err.h b/ledger/src/tcpsigner/ui_err.h deleted file mode 120000 index 717d3db2..00000000 --- a/ledger/src/tcpsigner/ui_err.h +++ /dev/null @@ -1 +0,0 @@ -../ui/src/ui_err.h \ No newline at end of file diff --git a/ledger/src/tcpsigner/ui_heartbeat.c b/ledger/src/tcpsigner/ui_heartbeat.c deleted file mode 120000 index 114336f0..00000000 --- a/ledger/src/tcpsigner/ui_heartbeat.c +++ /dev/null @@ -1 +0,0 @@ -../ui/src/ui_heartbeat.c \ No newline at end of file diff --git a/ledger/src/tcpsigner/ui_heartbeat.h b/ledger/src/tcpsigner/ui_heartbeat.h deleted file mode 120000 index fe78c323..00000000 --- a/ledger/src/tcpsigner/ui_heartbeat.h +++ /dev/null @@ -1 +0,0 @@ -../ui/src/ui_heartbeat.h \ No newline at end of file diff --git a/ledger/src/tcpsigner/ui_instructions.h b/ledger/src/tcpsigner/ui_instructions.h deleted file mode 120000 index 3c094b86..00000000 --- a/ledger/src/tcpsigner/ui_instructions.h +++ /dev/null @@ -1 +0,0 @@ -../ui/src/ui_instructions.h \ No newline at end of file diff --git a/ledger/src/ui/.gitignore b/ledger/src/ui/.gitignore deleted file mode 100644 index 020cf959..00000000 --- a/ledger/src/ui/.gitignore +++ /dev/null @@ -1,9 +0,0 @@ -bin -debug -dep -obj -static-analysis -src/glyphs.c -src/glyphs.h -test/**/*.o -test/**/*.out diff --git a/ledger/src/ui/test/communication/Makefile b/ledger/src/ui/test/communication/Makefile deleted file mode 100644 index 39385e62..00000000 --- a/ledger/src/ui/test/communication/Makefile +++ /dev/null @@ -1,53 +0,0 @@ -# The MIT License (MIT) -# -# Copyright (c) 2021 RSK Labs Ltd -# -# 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. - -SRCDIR = ../../src -COMMONDIR = ../../../common/src -MOCKDIR = ../mock -CFLAGS = -I$(COMMONDIR) -I$(MOCKDIR) -I$(SRCDIR) - -include ../../../../coverage/coverage.mk - -PROG = test.out -OBJS = mock.o communication.o test_communication.o - -all: $(PROG) - -$(PROG): $(OBJS) - $(CC) $(COVFLAGS) -o $@ $^ - -test_communication.o: test_communication.c - $(CC) $(CFLAGS) -c -o $@ $^ - -communication.o: $(SRCDIR)/communication.c - $(CC) $(CFLAGS) $(COVFLAGS) -c -o $@ $^ - -mock.o: $(MOCKDIR)/mock.c - $(CC) $(CFLAGS) -c -o $@ $^ - -.PHONY: clean test - -clean: - rm -f $(PROG) *.o $(COVFILES) - -test: all - ./$(PROG) diff --git a/ledger/src/ui/test/mock/apdu.h b/ledger/src/ui/test/mock/apdu.h deleted file mode 120000 index 946c51db..00000000 --- a/ledger/src/ui/test/mock/apdu.h +++ /dev/null @@ -1 +0,0 @@ -../../../common/src/apdu.h \ No newline at end of file diff --git a/ledger/src/ui/test/mock/os_exceptions.h b/ledger/src/ui/test/mock/os_exceptions.h deleted file mode 120000 index 7f262726..00000000 --- a/ledger/src/ui/test/mock/os_exceptions.h +++ /dev/null @@ -1 +0,0 @@ -../../../tcpsigner/os_exceptions.h \ No newline at end of file diff --git a/lint-c b/lint-c index 90d811da..65270971 100755 --- a/lint-c +++ b/lint-c @@ -11,12 +11,12 @@ if [[ $1 == "exec" ]]; then CLANG_ARGS="-i" fi - SRC_DIR="ledger/src" - SEARCH_DIRS="$SRC_DIR/signer $SRC_DIR/ui $SRC_DIR/tcpsigner $SRC_DIR/common" + SRC_DIR="firmware/src" + SEARCH_DIRS="$SRC_DIR/ledger/signer $SRC_DIR/ledger/ui $SRC_DIR/tcpsigner $SRC_DIR/common $SRC_DIR/hal" find $SEARCH_DIRS -name "*.[ch]" | \ egrep -v "(bigdigits|bigdtypes|keccak256)\.[ch]$" | \ - egrep -v "ledger/src/ui/src/glyphs.[ch]" | \ + egrep -v "firmware/src/ledger/ui/src/glyphs.[ch]" | \ xargs clang-format-10 --style=file $CLANG_ARGS else # Script directory diff --git a/middleware/README.md b/middleware/README.md index e8237b0e..fd6f2e93 100644 --- a/middleware/README.md +++ b/middleware/README.md @@ -66,8 +66,8 @@ Aside from the main `manager.py` and `manager-tcp.py` scripts, there are other t - `adm.py`: administrative utility for a powHSM dongle. It provides common utilities that can be performed on a powHSM dongle. - `lbutils.py`: common frontend to some of the `ledgerblue` modules. In particular, it ultimately serves the purpose of being able to build a binary for these utilities. -- `signapp.py`: signer authorization generator. Serves the purpose of generating authorization files for Signer versions (see [the signer authorization documentation](../docs/signer-authorization.md) for details). It can be used to sign with a powHSM Certificate Signer Ledger app (see [the ledger readme](../ledger/README.md) for details), to add manually fed signatures (externally generated), or to sign with a manually input key (for testing purposes). It can also be used to calculate the message to be signed to authorize a specific signer version (so that then the signature can be generated on a third-party application, e.g., MetaMask). Last, it has an option to calculate and output a ledger app's hash. -- `signonetime.py`: ledger app signer. Serves the purpose of signing firmware builds with a securely generated random one-time key. It is used in the distribution building process targeting the initial device setup process. +- `signapp.py`: signer authorization generator. Serves the purpose of generating authorization files for Signer versions (see [the signer authorization documentation](../docs/signer-authorization.md) for details). It can be used to add externally generated signatures, or to sign with a manually input key (intended for testing purposes only). It can also be used to calculate the message to be signed to authorize a specific signer version (so that then the signature can be generated on a third-party application, e.g., MetaMask). Last, it has an option to calculate and output a Ledger app's hash. +- `signonetime.py`: ledger app signer. Serves the purpose of signing Ledger Nano S firmware builds with a securely generated random one-time key. It is used in the distribution building process targeting the initial device setup process. The remaining `client.py` is a shorthand client utility for manually testing communication with a running manager or TCP manager. diff --git a/utils/tcpsigner-bundle/build.sh b/utils/tcpsigner-bundle/build.sh index dd0122d9..b3198bda 100755 --- a/utils/tcpsigner-bundle/build.sh +++ b/utils/tcpsigner-bundle/build.sh @@ -8,8 +8,8 @@ mkdir -p $DESTDIR echo "Building TCPSigner..." -$ROOTDIR/ledger/build/build-tcpsigner > /dev/null 2>&1 -cp $ROOTDIR/ledger/src/tcpsigner/tcpsigner $DESTDIR +$ROOTDIR/firmware/build/build-tcpsigner > /dev/null 2>&1 +cp $ROOTDIR/firmware/src/tcpsigner/tcpsigner $DESTDIR echo "Building TCPManager..."