├── .git-blame-ignore-revs ├── .github └── workflows │ ├── ci.yml │ └── documentation.yml ├── .gitignore ├── .pre-commit-config.yaml ├── LICENSE ├── MANIFEST.in ├── README.md ├── doc ├── Makefile └── source │ ├── _static │ └── theme_overrides.css │ ├── conf.py │ ├── index.rst │ ├── script_reference.rst │ └── scripts.rst ├── experimental └── bluepy │ └── commBLE.py ├── ledgerblue ├── BleComm.py ├── BlueHSMServer_pb2.py ├── Dongle.py ├── HowToRecover.md ├── __init__.py ├── checkGenuine.py ├── checkGenuineRemote.py ├── comm.py ├── commException.py ├── commHTTP.py ├── commTCP.py ├── commU2F.py ├── deleteApp.py ├── deployed.py ├── derivePassphrase.py ├── ecWrapper.py ├── endorsementSetup.py ├── endorsementSetupLedger.py ├── endorsementSetupLedger2.py ├── genCAPair.py ├── getMemInfo.py ├── hashApp.py ├── hexLoader.py ├── hexParser.py ├── hostOnboard.py ├── ledgerWrapper.py ├── listApps.py ├── loadApp.py ├── loadMCU.py ├── mcuBootloader.py ├── readElfMetadata.py ├── recoverBackup.py ├── recoverDeleteBackup.py ├── recoverDeleteCA.py ├── recoverMutualAuth.py ├── recoverRestore.py ├── recoverSCP.py ├── recoverSetCA.py ├── recoverUtil.py ├── resetCustomCA.py ├── runApp.py ├── runScript.py ├── setupCustomCA.py ├── signApp.py ├── updateFirmware.py ├── updateFirmware2.py ├── verifyApp.py ├── verifyEndorsement1.py ├── verifyEndorsement2.py └── vss.py ├── pyproject.toml └── ruff.toml /.git-blame-ignore-revs: -------------------------------------------------------------------------------- 1 | # Run this command to always ignore formatting commits in `git blame` 2 | # git config blame.ignoreRevsFile .git-blame-ignore-revs 3 | 4 | # Formatting commit 5 | 10e7047631b5807a951676eab6ede37200011283 6 | 8a8b4c89769dcd2ee4c890c14518759aa4e62394 7 | -------------------------------------------------------------------------------- /.github/workflows/ci.yml: -------------------------------------------------------------------------------- 1 | name: Build, test and deploy LedgerWallet 2 | 3 | on: 4 | workflow_dispatch: 5 | push: 6 | tags: 7 | - '*' 8 | branches: 9 | - master 10 | pull_request: 11 | branches: 12 | - master 13 | - develop 14 | 15 | permissions: 16 | id-token: write 17 | attestations: write 18 | 19 | jobs: 20 | build_install: 21 | name: Build and install the Ledgerblue Python package 22 | runs-on: ubuntu-latest 23 | strategy: 24 | fail-fast: false 25 | matrix: 26 | python_version: ['3.8', '3.9', '3.10', '3.11', '3.12', '3.13'] 27 | steps: 28 | - name: Clone 29 | uses: actions/checkout@v4 30 | 31 | - name: Setup Python version 32 | uses: actions/setup-python@v5 33 | with: 34 | python-version: ${{ matrix.python_version }} 35 | 36 | - name: Build & install 37 | run: | 38 | pip install -U pip 39 | pip install -U . 40 | 41 | package-deploy: 42 | name: Build the Python package, and deploy if needed 43 | runs-on: public-ledgerhq-shared-small 44 | needs: build_install 45 | steps: 46 | - name: Clone 47 | uses: actions/checkout@v3 48 | with: 49 | fetch-depth: 0 50 | 51 | - name: Install dependencies 52 | run: | 53 | # Needed to workaround this bug https://github.com/pypa/setuptools/issues/4759 54 | # To be removed when it's fixed 55 | pip install -U packaging 56 | 57 | python -m pip install pip --upgrade 58 | pip install build twine 59 | 60 | - name: Build the Python package 61 | run: | 62 | python -m build 63 | twine check dist/* 64 | echo "TAG_VERSION=$(python -c 'from ledgerblue import __version__; print(__version__)')" >> "$GITHUB_ENV" 65 | 66 | - name: Display current status 67 | run: | 68 | echo "Current status is:" 69 | if [[ ${{ github.ref }} == "refs/tags/"* ]]; 70 | then 71 | echo "- Triggered from tag, will be deployed on pypi.org"; 72 | else 73 | echo "- Not triggered from tag, will be deployed on test.pypi.org"; 74 | fi 75 | echo "- Tag version: ${{ env.TAG_VERSION }}"; 76 | 77 | - name: Publish Python package on pypi.org 78 | if: success() && github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') 79 | run: python -m twine upload dist/* 80 | env: 81 | TWINE_USERNAME: __token__ 82 | TWINE_PASSWORD: ${{ secrets.PYPI_PUBLIC_API_TOKEN }} 83 | TWINE_NON_INTERACTIVE: 1 84 | 85 | - name: Login to Ledger Artifactory 86 | if: success() && github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') 87 | timeout-minutes: 10 88 | id: jfrog-login 89 | uses: LedgerHQ/actions-security/actions/jfrog-login@actions/jfrog-login-1 90 | 91 | - name: Publish Python package on Ledger Artifactory 92 | if: success() && github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') 93 | run: python -m twine upload dist/* 94 | env: 95 | TWINE_REPOSITORY_URL: https://jfrog.ledgerlabs.net/artifactory/api/pypi/embedded-apps-pypi-prod-green 96 | TWINE_USERNAME: ${{ steps.jfrog-login.outputs.oidc-user }} 97 | TWINE_PASSWORD: ${{ steps.jfrog-login.outputs.oidc-token }} 98 | TWINE_NON_INTERACTIVE: 1 99 | 100 | - name: Generate library build attestations 101 | if: success() && github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') 102 | timeout-minutes: 10 103 | uses: LedgerHQ/actions-security/actions/attest@actions/attest-1 104 | with: 105 | subject-path: dist/* 106 | 107 | - name: Sign library artifacts 108 | if: success() && github.event_name == 'push' && startsWith(github.ref, 'refs/tags/') 109 | timeout-minutes: 10 110 | uses: LedgerHQ/actions-security/actions/sign-blob@actions/sign-blob-1 111 | with: 112 | path: dist 113 | 114 | - name: Publish a release on the repo 115 | if: | 116 | success() && 117 | github.event_name == 'push' && 118 | startsWith(github.ref, 'refs/tags/') 119 | uses: "marvinpinto/action-automatic-releases@latest" 120 | with: 121 | automatic_release_tag: "v${{ env.TAG_VERSION }}" 122 | repo_token: "${{ secrets.GITHUB_TOKEN }}" 123 | prerelease: false 124 | files: | 125 | LICENSE 126 | dist/ 127 | -------------------------------------------------------------------------------- /.github/workflows/documentation.yml: -------------------------------------------------------------------------------- 1 | name: Documentation generation & update 2 | 3 | on: 4 | push: 5 | tags: 6 | - '*' 7 | branches: 8 | - master 9 | pull_request: 10 | branches: 11 | - master 12 | - develop 13 | 14 | jobs: 15 | generate: 16 | name: Generate the documentation 17 | runs-on: ubuntu-latest 18 | steps: 19 | - name: Clone 20 | uses: actions/checkout@v3 21 | with: 22 | fetch-depth: 0 23 | - name: Install Python dependencies 24 | run: | 25 | pip install -U pip 26 | pip install -U .[doc] 27 | - name: Generate the documentation 28 | run: (cd doc && make html) 29 | - name: Upload documentation bundle 30 | uses: actions/upload-artifact@v4 31 | with: 32 | name: documentation 33 | path: doc/build/html/ 34 | 35 | deploy: 36 | name: Deploy the documentation on Github pages 37 | runs-on: ubuntu-latest 38 | needs: generate 39 | if: github.event_name == 'push' && (github.ref == 'refs/heads/master' || startsWith(github.ref, 'refs/tags/')) 40 | steps: 41 | - name: Download documentation bundle 42 | uses: actions/download-artifact@v3 43 | - name: Deploy documentation on pages 44 | uses: peaceiris/actions-gh-pages@v3 45 | with: 46 | github_token: ${{ secrets.GITHUB_TOKEN }} 47 | publish_dir: documentation/ 48 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | dist/ 3 | ledgerblue.egg-info/ 4 | __pycache__ 5 | .python-version 6 | 7 | __version__.py 8 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | # See https://pre-commit.com for more information 2 | # See https://pre-commit.com/hooks.html for more hooks 3 | repos: 4 | - repo: https://github.com/pre-commit/pre-commit-hooks 5 | rev: v3.2.0 6 | hooks: 7 | - id: trailing-whitespace 8 | - id: end-of-file-fixer 9 | - id: check-yaml 10 | - id: check-added-large-files 11 | - repo: https://github.com/astral-sh/ruff-pre-commit 12 | # Ruff version. 13 | rev: v0.3.7 14 | hooks: 15 | # Run the linter. 16 | - id: ruff 17 | args: [ --fix ] 18 | # Run the formatter. 19 | - id: ruff-format 20 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include README.md 2 | 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Ledgerblue - Python tools for Ledger devices 2 | 3 | This package contains Python tools to communicate with Ledger devices and manage applications life cycle. 4 | 5 | ## Installation 6 | 7 | It is recommended to install this package in a [Virtual Environment](http://docs.python-guide.org/en/latest/dev/virtualenvs/) in your native environment (not a Docker image) to avoid hidapi issues. 8 | 9 | ``` 10 | python3 -m venv ledger 11 | source ledger/bin/activate 12 | pip install ledgerblue 13 | ``` 14 | 15 | ## Supported devices 16 | 17 | At the moment these tools work for all ledger devices, but only for special Nano X developer units which are not available to the general public. 18 | The Recover scripts, will work with Nano X starting from a specific version. 19 | 20 | Please check [Ledger Developer Portal](https://developers.ledger.com/docs/nano-app/introduction/) to see how to debug your application on a Nano X simulator using [Speculos](https://github.com/LedgerHQ/speculos) 21 | 22 | ## Installation pre-requisites 23 | 24 | 25 | * libudev-dev 26 | * libusb-1.0-0-dev 27 | * python-dev (python >= 3.6) 28 | 29 | This package can optionally work with [libsecp256k1](https://github.com/ludbb/secp256k1-py) Python bindings compiled with ECDH support. If you wish to enable libsecp256k1 bindings, make sure to install libsecp256k1 as follows: 30 | 31 | ``` 32 | SECP_BUNDLED_EXPERIMENTAL=1 pip --no-cache-dir install --no-binary secp256k1 secp256k1 33 | ``` 34 | 35 | To install the custom secp256k1 package on MacOS, you previously need to run: 36 | ``` 37 | brew install libtool 38 | ``` 39 | Which would end up installing glibtool and glibtoolize utilities required for the build process. 40 | 41 | ## Giving permissions on udev 42 | 43 | When running on Linux, make sure the following rules have been added to `/etc/udev/rules.d/`: 44 | 45 | ``` 46 | SUBSYSTEMS=="usb", ATTRS{idVendor}=="2c97", MODE="0660", TAG+="uaccess", TAG+="udev-acl" OWNER="" 47 | 48 | KERNEL=="hidraw*", ATTRS{idVendor}=="2c97", MODE="0660" OWNER="" 49 | ``` 50 | 51 | ## Target ID 52 | 53 | Use the following Target IDs (--targetId option) when running commands directly: 54 | 55 | 56 | | Device name | Firmware Version | Target ID | 57 | |------------------|------------------------------------|--------------| 58 | | `Flex` | all | `0x33300004` | 59 | | `Stax` | all | `0x33200004` | 60 | | `Nano S Plus` | all | `0x33100004` | 61 | | `Nano X` | (**developer units only**) | `0x33000004` | 62 | | `Nano S` | <= 1.3.1 | `0x31100002` | 63 | | `Nano S` | 1.4.x | `0x31100003` | 64 | | `Nano S` | \>= 1.5.x | `0x31100004` | 65 | | `Ledger Blue` | <= 2.0 | `0x31000002` | 66 | | `Ledger Blue` | 2.1.x | `0x31000004` | 67 | | `Ledger Blue v2` | 2.1.x | `0x31010004` | 68 | 69 | 70 | ## Ledgerblue documentation 71 | 72 | You can generate the Ledgerblue documentation locally. 73 | 74 | Firstly, make sure you have [pip installed](https://pip.pypa.io/en/stable/installing/) and `make` 75 | installed. 76 | 77 | Then, install the documentation dependencies: 78 | 79 | ```bash 80 | # from the top of the Git repository 81 | pip install .[doc] 82 | ``` 83 | 84 | Finally, generate the documentation: 85 | 86 | ```bash 87 | # from the top of the Git repository 88 | (cd doc/ && make html) 89 | ``` 90 | 91 | The documentation will be generated into the `doc/build/` directory. 92 | -------------------------------------------------------------------------------- /doc/Makefile: -------------------------------------------------------------------------------- 1 | # Minimal Makefile for Sphinx documentation 2 | 3 | # You can set these variables from the command line. 4 | SPHINXOPTS = 5 | SPHINXBUILD = python -msphinx 6 | SPHINXPROJ = BOLOSPythonLoader 7 | SOURCEDIR = source 8 | BUILDDIR = build 9 | 10 | # Put it first so that "make" without argument is like "make help". 11 | help: 12 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 13 | 14 | .PHONY: help Makefile 15 | 16 | # Catch-all target: route all unknown targets to Sphinx using the new 17 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 18 | %: Makefile 19 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 20 | -------------------------------------------------------------------------------- /doc/source/_static/theme_overrides.css: -------------------------------------------------------------------------------- 1 | /* override table width restrictions */ 2 | @media screen and (min-width: 767px) { 3 | 4 | .wy-table-responsive table td { 5 | /* !important prevents the common CSS stylesheets from overriding 6 | this as on RTD they are loaded after this stylesheet */ 7 | white-space: normal !important; 8 | } 9 | 10 | .wy-table-responsive { 11 | overflow: visible !important; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /doc/source/conf.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | # 3 | # BOLOS Python Loader documentation build configuration file. 4 | 5 | import os 6 | import sys 7 | 8 | from ledgerblue.__version__ import __version__ 9 | 10 | 11 | def setup(app): 12 | app.add_css_file("theme_overrides.css") # Override wide tables in RTD theme 13 | 14 | 15 | # General Configuration 16 | # ===================== 17 | 18 | extensions = [] 19 | 20 | source_suffix = [".rst"] 21 | 22 | master_doc = "index" 23 | 24 | project = "BOLOS Python Loader" 25 | copyright = "2017, Ledger Team" 26 | author = "Ledger Team" 27 | 28 | version = __version__ 29 | release = __version__ 30 | 31 | pygments_style = "sphinx" 32 | 33 | # Options for HTML Output 34 | # ======================= 35 | 36 | html_theme = "sphinx_rtd_theme" 37 | 38 | html_static_path = ["_static"] 39 | 40 | # sphinxarg 41 | # ========= 42 | 43 | extensions += ["sphinxarg.ext"] 44 | -------------------------------------------------------------------------------- /doc/source/index.rst: -------------------------------------------------------------------------------- 1 | BOLOS Python Loader 2 | =================== 3 | 4 | The BOLOS Python loader is a Python library and collection of scripts for 5 | interfacing with and managing BOLOS devices from a host computer. See the 6 | `Python loader GitHub repository 7 | `_ for download and installation 8 | instructions. 9 | 10 | .. toctree:: 11 | :maxdepth: 1 12 | 13 | scripts 14 | script_reference 15 | -------------------------------------------------------------------------------- /doc/source/script_reference.rst: -------------------------------------------------------------------------------- 1 | Script Reference 2 | ================ 3 | 4 | .. _checkGenuine.py: 5 | 6 | checkGenuine.py 7 | --------------- 8 | 9 | .. argparse:: 10 | :module: ledgerblue.checkGenuine 11 | :func: get_argparser 12 | :prog: python -m ledgerblue.checkGenuine 13 | 14 | .. _deleteApp.py: 15 | 16 | deleteApp.py 17 | ------------ 18 | 19 | .. argparse:: 20 | :module: ledgerblue.deleteApp 21 | :func: get_argparser 22 | :prog: python -m ledgerblue.deleteApp 23 | 24 | .. _derivePassphrase.py: 25 | 26 | derivePassphrase.py 27 | ------------------- 28 | 29 | .. argparse:: 30 | :module: ledgerblue.derivePassphrase 31 | :func: get_argparser 32 | :prog: python -m ledgerblue.derivePassphrase 33 | 34 | .. _endorsementSetupLedger.py: 35 | 36 | endorsementSetupLedger.py 37 | ------------------------- 38 | 39 | .. argparse:: 40 | :module: ledgerblue.endorsementSetupLedger 41 | :func: get_argparser 42 | :prog: python -m ledgerblue.endorsementSetupLedger 43 | 44 | .. _endorsementSetup.py: 45 | 46 | endorsementSetup.py 47 | ------------------- 48 | 49 | .. argparse:: 50 | :module: ledgerblue.endorsementSetup 51 | :func: get_argparser 52 | :prog: python -m ledgerblue.endorsementSetup 53 | 54 | .. _genCAPair.py: 55 | 56 | genCAPair.py 57 | ------------ 58 | 59 | .. argparse:: 60 | :module: ledgerblue.genCAPair 61 | :func: get_argparser 62 | :prog: python -m ledgerblue.genCAPair 63 | 64 | .. _hashApp.py: 65 | 66 | hashApp.py 67 | ---------- 68 | 69 | .. argparse:: 70 | :module: ledgerblue.hashApp 71 | :func: get_argparser 72 | :prog: python -m ledgerblue.hashApp 73 | 74 | .. _hostOnboard.py: 75 | 76 | hostOnboard.py 77 | -------------- 78 | 79 | .. argparse:: 80 | :module: ledgerblue.hostOnboard 81 | :func: get_argparser 82 | :prog: python -m ledgerblue.hostOnboard 83 | 84 | .. _listApps.py: 85 | 86 | listApps.py 87 | ----------- 88 | 89 | .. argparse:: 90 | :module: ledgerblue.listApps 91 | :func: get_argparser 92 | :prog: python -m ledgerblue.listApps 93 | 94 | .. _loadApp.py: 95 | 96 | loadApp.py 97 | ---------- 98 | 99 | .. argparse:: 100 | :module: ledgerblue.loadApp 101 | :func: get_argparser 102 | :prog: python -m ledgerblue.loadApp 103 | 104 | .. _loadMCU.py: 105 | 106 | loadMCU.py 107 | ---------- 108 | 109 | .. argparse:: 110 | :module: ledgerblue.loadMCU 111 | :func: get_argparser 112 | :prog: python -m ledgerblue.loadMCU 113 | 114 | .. _mcuBootloader.py: 115 | 116 | mcuBootloader.py 117 | ---------------- 118 | 119 | .. argparse:: 120 | :module: ledgerblue.mcuBootloader 121 | :func: get_argparser 122 | :prog: python -m ledgerblue.mcuBootloader 123 | 124 | .. _resetCustomCA.py: 125 | 126 | resetCustomCA.py 127 | ---------------- 128 | 129 | .. argparse:: 130 | :module: ledgerblue.resetCustomCA 131 | :func: get_argparser 132 | :prog: python -m ledgerblue.resetCustomCA 133 | 134 | .. _runApp.py: 135 | 136 | runApp.py 137 | --------- 138 | 139 | .. argparse:: 140 | :module: ledgerblue.runApp 141 | :func: get_argparser 142 | :prog: python -m ledgerblue.runApp 143 | 144 | .. _runScript.py: 145 | 146 | runScript.py 147 | ------------ 148 | 149 | .. argparse:: 150 | :module: ledgerblue.runScript 151 | :func: get_argparser 152 | :prog: python -m ledgerblue.runScript 153 | 154 | .. _setupCustomCA.py: 155 | 156 | setupCustomCA.py 157 | ---------------- 158 | 159 | .. argparse:: 160 | :module: ledgerblue.setupCustomCA 161 | :func: get_argparser 162 | :prog: python -m ledgerblue.setupCustomCA 163 | 164 | .. _signApp.py: 165 | 166 | signApp.py 167 | ---------- 168 | 169 | See :ref:`loadApp `, and its `--signApp` flag. 170 | 171 | .. _updateFirmware.py: 172 | 173 | updateFirmware.py 174 | ----------------- 175 | 176 | .. argparse:: 177 | :module: ledgerblue.updateFirmware 178 | :func: get_argparser 179 | :prog: python -m ledgerblue.updateFirmware 180 | 181 | .. _verifyApp.py: 182 | 183 | verifyApp.py 184 | ------------ 185 | 186 | .. argparse:: 187 | :module: ledgerblue.verifyApp 188 | :func: get_argparser 189 | :prog: python -m ledgerblue.verifyApp 190 | 191 | .. _verifyEndorsement1.py: 192 | 193 | verifyEndorsement1.py 194 | --------------------- 195 | 196 | .. argparse:: 197 | :module: ledgerblue.verifyEndorsement1 198 | :func: get_argparser 199 | :prog: python -m ledgerblue.verifyEndorsement1 200 | 201 | .. _verifyEndorsement2.py: 202 | 203 | verifyEndorsement2.py 204 | --------------------- 205 | 206 | .. argparse:: 207 | :module: ledgerblue.verifyEndorsement2 208 | :func: get_argparser 209 | :prog: python -m ledgerblue.verifyEndorsement2 210 | -------------------------------------------------------------------------------- /doc/source/scripts.rst: -------------------------------------------------------------------------------- 1 | Scripts 2 | ======= 3 | 4 | The Python loader includes a collection of useful scripts for managing BOLOS 5 | devices. This section includes an overview of some of the most important scripts 6 | and how they can be used. 7 | 8 | In order to use any of these scripts, the device must be in the dashboard 9 | application (no apps are open, the device should display a list of installed 10 | apps). 11 | 12 | Here is an example using the :ref:`deleteApp.py` script from the command-line: 13 | 14 | .. code-block:: bash 15 | 16 | python -m ledgerblue.deleteApp --targetId 0x31100002 --appName "Hello World" 17 | 18 | The above command will delete the app named "Hello World" from the connected 19 | Leger Nano S. 20 | 21 | See the :doc:`script_reference` for the detailed documentation about each 22 | script. 23 | -------------------------------------------------------------------------------- /experimental/bluepy/commBLE.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | from ledgerblue.comm import Dongle 21 | from ledgerblue.commException import CommException 22 | from ledgerblue.ledgerWrapper import wrapCommandAPDU, unwrapResponseAPDU 23 | from binascii import hexlify 24 | from bluepy import btle 25 | 26 | SERVICE_UUID = "D973F2E0-B19E-11E2-9E96-0800200C9A66" 27 | WRITE_CHARACTERISTICS_UUID = "D973F2E2-B19E-11E2-9E96-0800200C9A66" 28 | NOTIFY_CHARACTERISTICS_UUID = "D973F2E1-B19E-11E2-9E96-0800200C9A66" 29 | CLIENT_CHARACTERISTICS_CONFIG_DESCRIPTOR_UUID = "00002902-0000-1000-8000-00805f9b34fb" 30 | ENABLE_NOTIFICATION = "0100".decode('hex') 31 | DEFAULT_BLE_CHUNK = 20 32 | BLE_NOTIFICATION_TIMEOUT = 5.0 33 | 34 | class BLEDongleDelegate(btle.DefaultDelegate): 35 | def __init__(self, dongle): 36 | btle.DefaultDelegate.__init__(self) 37 | self.dongle = dongle 38 | 39 | def handleNotification(self, cHandle, data): 40 | self.dongle.result += bytearray(data) 41 | 42 | class BLEDongle(Dongle): 43 | 44 | # Must be called with the Client Characteristics Configuration descriptor handle as bluepy fails to retrieve it 45 | # From gatttools 46 | # [device mac][LE]> char-desc 47 | # handle: 0x000f, uuid: 00002902-0000-1000-8000-00805f9b34fb 48 | def __init__(self, bleAddress, configDescriptor, debug=False): 49 | self.device = btle.Peripheral(bleAddress) 50 | self.device.setDelegate(BLEDongleDelegate(self)) 51 | self.service = self.device.getServiceByUUID(SERVICE_UUID) 52 | self.writeCharacteristic = self.service.getCharacteristics(forUUID=WRITE_CHARACTERISTICS_UUID)[0] 53 | self.device.writeCharacteristic(configDescriptor, ENABLE_NOTIFICATION, withResponse=True) 54 | self.debug = debug 55 | self.opened = True 56 | 57 | def exchange(self, apdu, timeout=20000): 58 | if self.debug: 59 | print("=> %s" % hexlify(apdu)) 60 | apdu = wrapCommandAPDU(0, apdu, DEFAULT_BLE_CHUNK, True) 61 | offset = 0 62 | while offset < len(apdu): 63 | data = apdu[offset:offset + DEFAULT_BLE_CHUNK] 64 | self.writeCharacteristic.write(data, withResponse=True) 65 | offset += DEFAULT_BLE_CHUNK 66 | self.result = "" 67 | while True: 68 | if not self.device.waitForNotifications(BLE_NOTIFICATION_TIMEOUT): 69 | raise CommException("Timeout") 70 | response = unwrapResponseAPDU(0, self.result, DEFAULT_BLE_CHUNK, True) 71 | if response is not None: 72 | result = response 73 | dataStart = 0 74 | swOffset = len(response) - 2 75 | dataLength = len(response) - 2 76 | break 77 | sw = (result[swOffset] << 8) + result[swOffset + 1] 78 | response = result[dataStart : dataLength + dataStart] 79 | if self.debug: 80 | print("<= %s%.2x" % (hexlify(response), sw)) 81 | if sw != 0x9000: 82 | raise CommException("Invalid status %04x" % sw, sw) 83 | return response 84 | 85 | def close(self): 86 | if self.opened: 87 | try: 88 | self.device.disconnect() 89 | except: 90 | pass 91 | self.opened = False 92 | -------------------------------------------------------------------------------- /ledgerblue/BleComm.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | import argparse 3 | import os 4 | from bleak import BleakScanner, BleakClient 5 | from bleak.backends.device import BLEDevice 6 | from bleak.backends.scanner import AdvertisementData 7 | from typing import List 8 | 9 | LEDGER_SERVICE_UUID_EUROPA = "13d63400-2c97-3004-0000-4c6564676572" 10 | LEDGER_SERVICE_UUID_STAX = "13d63400-2c97-6004-0000-4c6564676572" 11 | LEDGER_SERVICE_UUID_NANOX = "13d63400-2c97-0004-0000-4c6564676572" 12 | 13 | TAG_ID = b"\x05" 14 | 15 | 16 | def get_argparser(): 17 | parser = argparse.ArgumentParser(description="Manage ledger ble devices.") 18 | parser.add_argument( 19 | "--show", help="Show currently selected ledger device.", action="store_true" 20 | ) 21 | parser.add_argument( 22 | "--demo", 23 | help="Get version demo (connect to ble device, send get version, print response and disconnect).", 24 | action="store_true", 25 | ) 26 | return parser 27 | 28 | 29 | class NoLedgerDeviceDetected(Exception): 30 | pass 31 | 32 | 33 | class BleScanner(object): 34 | def __init__(self): 35 | self.devices = [] 36 | 37 | def __scan_callback(self, device: BLEDevice, advertisement_data: AdvertisementData): 38 | if ( 39 | LEDGER_SERVICE_UUID_STAX in advertisement_data.service_uuids 40 | or LEDGER_SERVICE_UUID_NANOX in advertisement_data.service_uuids 41 | or LEDGER_SERVICE_UUID_EUROPA in advertisement_data.service_uuids 42 | ): 43 | device_is_in_list = False 44 | for dev in self.devices: 45 | if device.address == dev[0]: 46 | device_is_in_list = True 47 | if not device_is_in_list: 48 | self.devices.append((device.address, device.name)) 49 | 50 | async def scan(self): 51 | scanner = BleakScanner( 52 | self.__scan_callback, 53 | ) 54 | await scanner.start() 55 | counter = 0 56 | while counter < 5000: 57 | await asyncio.sleep(0.01) 58 | counter += 1 59 | await scanner.stop() 60 | 61 | 62 | queue: asyncio.Queue = asyncio.Queue() 63 | 64 | 65 | def callback(sender, data): 66 | response = bytes(data) 67 | queue.put_nowait(response) 68 | 69 | 70 | async def _get_client(address: str) -> BleakClient: 71 | # Connect to client 72 | client = BleakClient(address) 73 | await client.connect() 74 | 75 | characteristic_notify = None 76 | characteristic_write_with_rsp = None 77 | characteristic_write_cmd = None 78 | for service in client.services: 79 | if service.uuid in [ 80 | LEDGER_SERVICE_UUID_NANOX, 81 | LEDGER_SERVICE_UUID_STAX, 82 | LEDGER_SERVICE_UUID_EUROPA, 83 | ]: 84 | for char in service.characteristics: 85 | if "0001" in char.uuid: 86 | characteristic_notify = char 87 | if "0002" in char.uuid: 88 | characteristic_write_with_rsp = char 89 | if "0003" in char.uuid: 90 | characteristic_write_cmd = char 91 | 92 | assert characteristic_notify != None 93 | 94 | # Choose write cmd to speed up transfers 95 | characteristic_write = characteristic_write_cmd 96 | if characteristic_write == None: 97 | characteristic_write = characteristic_write_with_rsp 98 | 99 | # Register notifications callback 100 | await client.start_notify(characteristic_notify, callback) 101 | 102 | # Enable notifications 103 | await client.write_gatt_char(characteristic_write.uuid, bytes.fromhex("0001")) 104 | assert await queue.get() == b"\x00\x00\x00\x00\x00" 105 | 106 | # Get MTU value 107 | await client.write_gatt_char(characteristic_write.uuid, bytes.fromhex("0800000000")) 108 | response = await queue.get() 109 | mtu = int.from_bytes(response[5:6], "big") 110 | 111 | print("[BLE] MTU {:d}".format(mtu)) 112 | 113 | return client, mtu, characteristic_write 114 | 115 | 116 | async def _read(mtu) -> bytes: 117 | response = await queue.get() 118 | assert len(response) >= 5 119 | assert response[0] == TAG_ID[0] 120 | sequence = int.from_bytes(response[1:3], "big") 121 | assert sequence == 0 122 | total_size = int.from_bytes(response[3:5], "big") 123 | 124 | total_size_bkup = total_size 125 | if total_size >= (mtu - 5): 126 | apdu = response[5:mtu] 127 | total_size -= mtu - 5 128 | 129 | response = await queue.get() 130 | assert response[0] == TAG_ID[0] 131 | assert len(response) >= 3 132 | next_sequence = int.from_bytes(response[1:3], "big") 133 | assert next_sequence == sequence + 1 134 | sequence = next_sequence 135 | 136 | while total_size >= (mtu - 3): 137 | apdu += response[3:mtu] 138 | total_size -= mtu - 3 139 | response = await queue.get() 140 | assert response[0] == TAG_ID[0] 141 | assert len(response) >= 3 142 | sequence = int.from_bytes(response[1:3], "big") 143 | assert next_sequence == sequence + 1 144 | sequence = next_sequence 145 | 146 | if total_size > 0: 147 | apdu += response[3 : 3 + total_size] 148 | else: 149 | apdu = response[5:] 150 | 151 | assert len(apdu) == total_size_bkup 152 | return apdu 153 | 154 | 155 | async def _write(client: BleakClient, data: bytes, write_characteristic, mtu: int = 20): 156 | chunks: List[bytes] = [] 157 | buffer = data 158 | while buffer: 159 | if not chunks: 160 | size = 5 161 | else: 162 | size = 3 163 | size = mtu - size 164 | chunks.append(buffer[:size]) 165 | buffer = buffer[size:] 166 | 167 | for i, chunk in enumerate(chunks): 168 | header = TAG_ID 169 | header += i.to_bytes(2, "big") 170 | if i == 0: 171 | header += len(data).to_bytes(2, "big") 172 | await client.write_gatt_char(write_characteristic.uuid, header + chunk) 173 | 174 | 175 | class BleDevice(object): 176 | def __init__(self, address): 177 | self.address = address 178 | self.loop = None 179 | self.client = None 180 | self.opened = False 181 | self.mtu = 20 182 | self.write_characteristic = None 183 | 184 | def open(self): 185 | self.loop = asyncio.new_event_loop() 186 | self.client, self.mtu, self.write_characteristic = self.loop.run_until_complete( 187 | _get_client(self.address) 188 | ) 189 | self.opened = True 190 | 191 | def close(self): 192 | if self.opened: 193 | self.loop.run_until_complete(self.client.disconnect()) 194 | self.opened = False 195 | self.loop.close() 196 | 197 | def __write(self, data: bytes): 198 | self.loop.run_until_complete( 199 | _write(self.client, data, self.write_characteristic, self.mtu) 200 | ) 201 | 202 | def __read(self) -> bytes: 203 | return self.loop.run_until_complete(_read(self.mtu)) 204 | 205 | def exchange(self, data: bytes, timeout=1000) -> bytes: 206 | self.__write(data) 207 | return self.__read() 208 | 209 | 210 | if __name__ == "__main__": 211 | args = get_argparser().parse_args() 212 | try: 213 | if args.show: 214 | print( 215 | f"Environment variable LEDGER_BLE_MAC currently set to '{os.environ['LEDGER_BLE_MAC']}'" 216 | ) 217 | elif args.demo: 218 | try: 219 | ble_device = BleDevice(os.environ["LEDGER_BLE_MAC"]) 220 | except Exception as ex: 221 | print( 222 | f"Please run 'python -m ledgerblue.BleComm' to select wich device to connect to" 223 | ) 224 | raise ex 225 | print( 226 | "-----------------------------Get version BLE demo------------------------------" 227 | ) 228 | ble_device.open() 229 | print(f"Connected to {ble_device.address}") 230 | get_version_apdu = bytes.fromhex("e001000000") 231 | print(f"[BLE] => {get_version_apdu.hex()}") 232 | result = ble_device.exchange(get_version_apdu) 233 | print(f"[BLE] <= {result.hex()}") 234 | ble_device.close() 235 | print(f"Disconnected from {ble_device.address}") 236 | print(79 * "-") 237 | else: 238 | scanner = BleScanner() 239 | asyncio.run(scanner.scan()) 240 | devices_str = "" 241 | device_idx = 0 242 | if len(scanner.devices): 243 | for device in scanner.devices: 244 | devices_str += ( 245 | f' -{device_idx + 1}- mac="{device[0]}" name="{device[1]}"\n' 246 | ) 247 | device_idx += 1 248 | index = int(input(f"Select device by index\n{devices_str}")) 249 | print( 250 | f"Please run 'export LEDGER_BLE_MAC=\"{scanner.devices[index - 1][0]}\"' to select which device to connect to" 251 | ) 252 | else: 253 | raise NoLedgerDeviceDetected 254 | except NoLedgerDeviceDetected as ex: 255 | print(ex) 256 | except Exception as ex: 257 | raise ex 258 | -------------------------------------------------------------------------------- /ledgerblue/Dongle.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | from abc import ABCMeta, abstractmethod 21 | 22 | TIMEOUT = 20000 23 | 24 | 25 | class DongleWait(object): 26 | __metaclass__ = ABCMeta 27 | 28 | @abstractmethod 29 | def waitFirstResponse(self, timeout): 30 | pass 31 | 32 | 33 | class Dongle(object): 34 | __metaclass__ = ABCMeta 35 | 36 | @abstractmethod 37 | def exchange(self, apdu, timeout=TIMEOUT): 38 | pass 39 | 40 | @abstractmethod 41 | def apduMaxDataSize(self): 42 | pass 43 | 44 | @abstractmethod 45 | def close(self): 46 | pass 47 | 48 | def setWaitImpl(self, waitImpl): 49 | self.waitImpl = waitImpl 50 | -------------------------------------------------------------------------------- /ledgerblue/__init__.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | try: 21 | from ledgerblue.__version__ import __version__ # noqa 22 | except ImportError: 23 | __version__ = "unknown version" # noqa 24 | -------------------------------------------------------------------------------- /ledgerblue/checkGenuine.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import argparse 21 | 22 | DEFAULT_ISSUER_KEY = "0490f5c9d15a0134bb019d2afd0bf297149738459706e7ac5be4abc350a1f818057224fce12ec9a65de18ec34d6e8c24db927835ea1692b14c32e9836a75dad609" 23 | 24 | 25 | def get_argparser(): 26 | parser = argparse.ArgumentParser( 27 | description="""Use attestation to determine if the device is a genuine Ledger 28 | device.""" 29 | ) 30 | parser.add_argument( 31 | "--targetId", 32 | help="The device's target ID (default is Ledger Blue)", 33 | type=auto_int, 34 | default=0x31000002, 35 | ) 36 | parser.add_argument( 37 | "--issuerKey", 38 | help="Issuer key (hex encoded, default is batch 1)", 39 | default=DEFAULT_ISSUER_KEY, 40 | ) 41 | parser.add_argument("--apdu", help="Display APDU log", action="store_true") 42 | return parser 43 | 44 | 45 | def auto_int(x): 46 | return int(x, 0) 47 | 48 | 49 | def getDeployedSecretV2(dongle, masterPrivate, targetId, issuerKey): 50 | testMaster = PrivateKey(bytes(masterPrivate)) 51 | testMasterPublic = bytearray(testMaster.pubkey.serialize(compressed=False)) 52 | targetid = bytearray(struct.pack(">I", targetId)) 53 | 54 | # identify 55 | apdu = bytearray([0xE0, 0x04, 0x00, 0x00]) + bytearray([len(targetid)]) + targetid 56 | dongle.exchange(apdu) 57 | 58 | # walk the chain 59 | nonce = os.urandom(8) 60 | apdu = bytearray([0xE0, 0x50, 0x00, 0x00]) + bytearray([len(nonce)]) + nonce 61 | auth_info = dongle.exchange(apdu) 62 | batch_signer_serial = auth_info[0:4] 63 | deviceNonce = auth_info[4:12] 64 | 65 | # if not found, get another pair 66 | # if cardKey != testMasterPublic: 67 | # raise Exception("Invalid batch public key") 68 | 69 | dataToSign = bytes(bytearray([0x01]) + testMasterPublic) 70 | signature = testMaster.ecdsa_sign(bytes(dataToSign)) 71 | signature = testMaster.ecdsa_serialize(signature) 72 | certificate = ( 73 | bytearray([len(testMasterPublic)]) 74 | + testMasterPublic 75 | + bytearray([len(signature)]) 76 | + signature 77 | ) 78 | apdu = ( 79 | bytearray([0xE0, 0x51, 0x00, 0x00]) 80 | + bytearray([len(certificate)]) 81 | + certificate 82 | ) 83 | dongle.exchange(apdu) 84 | 85 | # provide the ephemeral certificate 86 | ephemeralPrivate = PrivateKey() 87 | ephemeralPublic = bytearray(ephemeralPrivate.pubkey.serialize(compressed=False)) 88 | dataToSign = bytes(bytearray([0x11]) + nonce + deviceNonce + ephemeralPublic) 89 | signature = testMaster.ecdsa_sign(bytes(dataToSign)) 90 | signature = testMaster.ecdsa_serialize(signature) 91 | certificate = ( 92 | bytearray([len(ephemeralPublic)]) 93 | + ephemeralPublic 94 | + bytearray([len(signature)]) 95 | + signature 96 | ) 97 | apdu = ( 98 | bytearray([0xE0, 0x51, 0x80, 0x00]) 99 | + bytearray([len(certificate)]) 100 | + certificate 101 | ) 102 | dongle.exchange(apdu) 103 | 104 | # walk the device certificates to retrieve the public key to use for authentication 105 | index = 0 106 | last_pub_key = PublicKey(binascii.unhexlify(issuerKey), raw=True) 107 | devicePublicKey = None 108 | while True: 109 | if index == 0: 110 | certificate = bytearray(dongle.exchange(bytearray.fromhex("E052000000"))) 111 | elif index == 1: 112 | certificate = bytearray(dongle.exchange(bytearray.fromhex("E052800000"))) 113 | else: 114 | break 115 | offset = 1 116 | certificateHeader = certificate[offset : offset + certificate[offset - 1]] 117 | offset += certificate[offset - 1] + 1 118 | certificatePublicKey = certificate[offset : offset + certificate[offset - 1]] 119 | offset += certificate[offset - 1] + 1 120 | certificateSignatureArray = certificate[ 121 | offset : offset + certificate[offset - 1] 122 | ] 123 | certificateSignature = last_pub_key.ecdsa_deserialize( 124 | bytes(certificateSignatureArray) 125 | ) 126 | # first cert contains a header field which holds the certificate's public key role 127 | if index == 0: 128 | devicePublicKey = certificatePublicKey 129 | certificateSignedData = ( 130 | bytearray([0x02]) + certificateHeader + certificatePublicKey 131 | ) 132 | # Could check if the device certificate is signed by the issuer public key 133 | # ephemeral key certificate 134 | else: 135 | certificateSignedData = ( 136 | bytearray([0x12]) + deviceNonce + nonce + certificatePublicKey 137 | ) 138 | if not last_pub_key.ecdsa_verify( 139 | bytes(certificateSignedData), certificateSignature 140 | ): 141 | return None 142 | last_pub_key = PublicKey(bytes(certificatePublicKey), raw=True) 143 | index = index + 1 144 | 145 | # Commit device ECDH channel 146 | dongle.exchange(bytearray.fromhex("E053000000")) 147 | secret = last_pub_key.ecdh(binascii.unhexlify(ephemeralPrivate.serialize())) 148 | if targetId & 0xF == 0x2: 149 | return secret[0:16] 150 | elif targetId & 0xF >= 0x3: 151 | ret = {} 152 | ret["ecdh_secret"] = secret 153 | ret["devicePublicKey"] = devicePublicKey 154 | return ret 155 | 156 | 157 | if __name__ == "__main__": 158 | from .ecWrapper import PrivateKey, PublicKey 159 | from .comm import getDongle 160 | from .hexLoader import HexLoader 161 | import struct 162 | import os 163 | import binascii 164 | 165 | args = get_argparser().parse_args() 166 | 167 | privateKey = PrivateKey() 168 | publicKey = str(privateKey.pubkey.serialize(compressed=False)) 169 | args.rootPrivateKey = privateKey.serialize() 170 | 171 | genuine = False 172 | ui = False 173 | customCA = False 174 | 175 | dongle = getDongle(args.apdu) 176 | version = None 177 | 178 | secret = getDeployedSecretV2( 179 | dongle, bytearray.fromhex(args.rootPrivateKey), args.targetId, args.issuerKey 180 | ) 181 | if secret != None: 182 | try: 183 | loader = HexLoader(dongle, 0xE0, True, secret) 184 | version = loader.getVersion() 185 | genuine = True 186 | apps = loader.listApp() 187 | while len(apps) != 0: 188 | for app in apps: 189 | if app["flags"] & 0x08: 190 | ui = True 191 | if app["flags"] & 0x400: 192 | customCA = True 193 | apps = loader.listApp(False) 194 | except: 195 | genuine = False 196 | if genuine: 197 | if ui: 198 | print("WARNING : Product is genuine but has a UI application loaded") 199 | if customCA: 200 | print("WARNING : Product is genuine but has a Custom CA loaded") 201 | if not ui and not customCA: 202 | print("Product is genuine") 203 | print("SE Version " + version["osVersion"]) 204 | print("MCU Version " + version["mcuVersion"]) 205 | if "mcuHash" in version: 206 | print("MCU Hash " + binascii.hexlify(version["mcuHash"]).decode("ascii")) 207 | else: 208 | print("Product is NOT genuine") 209 | 210 | dongle.close() 211 | -------------------------------------------------------------------------------- /ledgerblue/checkGenuineRemote.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import argparse 21 | 22 | 23 | def get_argparser(): 24 | parser = argparse.ArgumentParser( 25 | "Update the firmware by using Ledger to open a Secure Channel." 26 | ) 27 | parser.add_argument( 28 | "--url", 29 | help="Websocket URL", 30 | default="wss://scriptrunner.api.live.ledger.com/update/genuine", 31 | ) 32 | parser.add_argument("--apdu", help="Display APDU log", action="store_true") 33 | parser.add_argument( 34 | "--perso", 35 | help="""A reference to the personalization key; this is a reference to the specific 36 | Issuer keypair used by Ledger to sign the device's Issuer Certificate""", 37 | default="perso_11", 38 | ) 39 | parser.add_argument( 40 | "--targetId", 41 | help="The device's target ID (default is Ledger Blue)", 42 | type=auto_int, 43 | default=0x31000002, 44 | ) 45 | return parser 46 | 47 | 48 | def auto_int(x): 49 | return int(x, 0) 50 | 51 | 52 | def process(dongle, request): 53 | response = {} 54 | apdusList = [] 55 | try: 56 | response["nonce"] = request["nonce"] 57 | if request["query"] == "exchange": 58 | apdusList.append(binascii.unhexlify(request["data"])) 59 | elif request["query"] == "bulk": 60 | for apdu in request["data"]: 61 | apdusList.append(binascii.unhexlify(apdu)) 62 | else: 63 | response["response"] = "unsupported" 64 | except: 65 | response["response"] = "parse error" 66 | 67 | if len(apdusList) != 0: 68 | try: 69 | for apdu in apdusList: 70 | response["data"] = dongle.exchange(apdu).hex() 71 | if len(response["data"]) == 0: 72 | response["data"] = "9000" 73 | response["response"] = "success" 74 | except: 75 | response["response"] = "I/O" # or error, and SW in data 76 | 77 | return response 78 | 79 | 80 | if __name__ == "__main__": 81 | import urllib.parse as urlparse 82 | from .comm import getDongle 83 | from websocket import create_connection 84 | import json 85 | import binascii 86 | 87 | args = get_argparser().parse_args() 88 | 89 | dongle = getDongle(args.apdu) 90 | 91 | url = args.url 92 | queryParameters = {} 93 | queryParameters["targetId"] = args.targetId 94 | queryParameters["perso"] = args.perso 95 | queryString = urlparse.urlencode(queryParameters) 96 | ws = create_connection(args.url + "?" + queryString) 97 | while True: 98 | result = json.loads(ws.recv()) 99 | if result["query"] == "success": 100 | break 101 | if result["query"] == "error": 102 | raise Exception( 103 | result["data"] + " on " + result["uuid"] + "/" + result["session"] 104 | ) 105 | response = process(dongle, result) 106 | ws.send(json.dumps(response)) 107 | ws.close() 108 | 109 | print("Product is genuine") 110 | 111 | dongle.close() 112 | -------------------------------------------------------------------------------- /ledgerblue/commException.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | 21 | class CommException(Exception): 22 | def __init__(self, message, sw=0x6F00, data=None): 23 | self.message = message 24 | self.sw = sw 25 | self.data = data 26 | 27 | def __str__(self): 28 | buf = "Exception : " + self.message 29 | return buf 30 | -------------------------------------------------------------------------------- /ledgerblue/commHTTP.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import time 21 | 22 | import requests 23 | 24 | 25 | class HTTPProxy(object): 26 | def __init__(self, remote_host="localhost:8081", debug=False): 27 | self.remote_host = "http://" + remote_host 28 | self.debug = debug 29 | 30 | def exchange(self, apdu): 31 | if self.debug: 32 | print("=> %s" % apdu.hex()) 33 | 34 | try: 35 | ret = requests.post( 36 | self.remote_host + "/send_apdu", params={"data": apdu.hex()} 37 | ) 38 | 39 | while True: 40 | ret = requests.post(self.remote_host + "/fetch_apdu") 41 | if ret.text != "no response apdu yet": 42 | print("<= %s" % ret.text) 43 | break 44 | else: 45 | time.sleep(0.1) 46 | 47 | return bytearray(str(ret.text).decode("hex")) 48 | except Exception as e: 49 | print(e) 50 | 51 | def exchange_seph_event(self, event): 52 | if self.debug >= 3: 53 | print("=> %s" % event.hex()) 54 | 55 | try: 56 | ret = requests.post( 57 | self.remote_host + "/send_seph_event", 58 | params={"data": event.encode("hex")}, 59 | ) 60 | return ret.text 61 | except Exception as e: 62 | print(e) 63 | 64 | def poll_status(self): 65 | if self.debug >= 5: 66 | print("=> Waiting for a status") 67 | 68 | try: 69 | while True: 70 | ret = requests.post(self.remote_host + "/fetch_status") 71 | if ret.text != "no status yet": 72 | break 73 | else: 74 | time.sleep(0.05) 75 | 76 | return bytearray(str(ret.text).decode("hex")) 77 | except Exception as e: 78 | print(e) 79 | 80 | def reset(self): 81 | if self.debug: 82 | print("=> Reset") 83 | 84 | try: 85 | ret = requests.post(self.remote_host + "/reset") 86 | except Exception as e: 87 | print(e) 88 | 89 | 90 | def getDongle(remote_host="localhost", debug=False): 91 | return HTTPProxy(remote_host, debug) 92 | -------------------------------------------------------------------------------- /ledgerblue/commTCP.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2019 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | from .commException import CommException 21 | from binascii import hexlify 22 | import socket 23 | import struct 24 | 25 | 26 | class DongleServer(object): 27 | def __init__(self, server, port, debug=False): 28 | self.server = server 29 | self.port = port 30 | self.debug = debug 31 | self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 32 | self.opened = True 33 | try: 34 | self.socket.connect((self.server, self.port)) 35 | except: 36 | raise CommException("Proxy connection failed") 37 | 38 | def exchange(self, apdu, timeout=20000): 39 | def send_apdu(apdu): 40 | if self.debug: 41 | print("=> %s" % hexlify(apdu)) 42 | self.socket.send(struct.pack(">I", len(apdu))) 43 | self.socket.send(apdu) 44 | 45 | def get_data(): 46 | size = struct.unpack(">I", self.socket.recv(4))[0] 47 | response = self.socket.recv(size) 48 | sw = struct.unpack(">H", self.socket.recv(2))[0] 49 | if self.debug: 50 | print("<= %s%.2x" % (hexlify(response), sw)) 51 | return sw, response 52 | 53 | send_apdu(apdu) 54 | (sw, response) = get_data() 55 | if sw == 0x9000: 56 | return bytearray(response) 57 | else: 58 | # handle the get response case: 59 | # When more data is available, the chip sends 0x61XX 60 | # So 0x61xx as a SW must not be interpreted as an error 61 | if (sw & 0xFF00) != 0x6100: 62 | raise CommException("Invalid status %04x" % sw, sw, data=response) 63 | else: 64 | while (sw & 0xFF00) == 0x6100: 65 | send_apdu(bytes.fromhex("00c0000000")) # GET RESPONSE 66 | (sw, data) = get_data() 67 | response += data 68 | 69 | # Check that the last received SW is indeed 0x9000 70 | if sw == 0x9000: 71 | return bytearray(response) 72 | 73 | # In any other case return an exception 74 | raise CommException("Invalid status %04x" % sw, sw, data=response) 75 | 76 | def apduMaxDataSize(self): 77 | return 240 78 | 79 | def close(self): 80 | try: 81 | self.socket.shutdown(socket.SHUT_RD) 82 | self.socket.close() 83 | self.socket = None 84 | except: 85 | pass 86 | self.opened = False 87 | 88 | 89 | def getDongle(server="127.0.0.1", port=9999, debug=False): 90 | return DongleServer(server, port, debug) 91 | -------------------------------------------------------------------------------- /ledgerblue/deleteApp.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import argparse 21 | 22 | 23 | def get_argparser(): 24 | parser = argparse.ArgumentParser( 25 | description="Delete the app with the specified name." 26 | ) 27 | parser.add_argument( 28 | "--targetId", 29 | help="The device's target ID (default is Ledger Blue)", 30 | type=auto_int, 31 | default=0x31000002, 32 | ) 33 | parser.add_argument( 34 | "--appName", help="The name of the application to delete", action="append" 35 | ) 36 | parser.add_argument("--appHash", help="Set the application hash") 37 | parser.add_argument( 38 | "--rootPrivateKey", 39 | help="A private key used to establish a Secure Channel (hex encoded)", 40 | ) 41 | parser.add_argument("--apdu", help="Display APDU log", action="store_true") 42 | parser.add_argument( 43 | "--deployLegacy", help="Use legacy deployment API", action="store_true" 44 | ) 45 | parser.add_argument( 46 | "--offline", 47 | help="Request to only output application load APDUs into given filename", 48 | ) 49 | return parser 50 | 51 | 52 | def auto_int(x): 53 | return int(x, 0) 54 | 55 | 56 | if __name__ == "__main__": 57 | from .ecWrapper import PrivateKey 58 | from .comm import getDongle 59 | from .deployed import getDeployedSecretV1, getDeployedSecretV2 60 | from .hexLoader import HexLoader 61 | import binascii 62 | 63 | args = get_argparser().parse_args() 64 | 65 | if (args.appName == None or len(args.appName) == 0) and args.appHash == None: 66 | raise Exception("Missing appName or appHash") 67 | 68 | if args.appName != None and len(args.appName) > 0: 69 | for i in range(0, len(args.appName)): 70 | args.appName[i] = bytes(args.appName[i], "ascii") 71 | 72 | if args.appHash != None: 73 | args.appHash = bytes(args.appHash, "ascii") 74 | args.appHash = bytearray.fromhex(args.appHash) 75 | 76 | if args.rootPrivateKey == None: 77 | privateKey = PrivateKey() 78 | publicKey = binascii.hexlify(privateKey.pubkey.serialize(compressed=False)) 79 | print("Generated random root public key : %s" % publicKey) 80 | args.rootPrivateKey = privateKey.serialize() 81 | 82 | dongle = None 83 | secret = None 84 | if not args.offline: 85 | dongle = getDongle(args.apdu) 86 | 87 | if args.deployLegacy: 88 | secret = getDeployedSecretV1( 89 | dongle, bytearray.fromhex(args.rootPrivateKey), args.targetId 90 | ) 91 | else: 92 | secret = getDeployedSecretV2( 93 | dongle, bytearray.fromhex(args.rootPrivateKey), args.targetId 94 | ) 95 | else: 96 | fileTarget = open(args.offline, "wb") 97 | 98 | class FileCard: 99 | def __init__(self, target): 100 | self.target = target 101 | 102 | def exchange(self, apdu): 103 | if args.apdu: 104 | print(binascii.hexlify(apdu)) 105 | apdu = binascii.hexlify(apdu) 106 | self.target.write(apdu + "\n".encode()) 107 | return bytearray([]) 108 | 109 | def apduMaxDataSize(self): 110 | # ensure to allow for encryption of those apdu afterward 111 | return 240 112 | 113 | def close(self): 114 | self.target.close() 115 | 116 | dongle = FileCard(fileTarget) 117 | 118 | loader = HexLoader(dongle, 0xE0, not args.offline, secret) 119 | 120 | if args.appName != None and len(args.appName) > 0: 121 | for name in args.appName: 122 | loader.deleteApp(name) 123 | if args.appHash != None: 124 | loader.deleteAppByHash(args.appHash) 125 | 126 | dongle.close() 127 | -------------------------------------------------------------------------------- /ledgerblue/deployed.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | from .ecWrapper import PrivateKey, PublicKey 21 | import os 22 | import struct 23 | import binascii 24 | 25 | 26 | def getDeployedSecretV1(dongle, masterPrivate, targetId): 27 | testMaster = PrivateKey(bytes(masterPrivate)) 28 | testMasterPublic = bytearray(testMaster.pubkey.serialize(compressed=False)) 29 | targetid = bytearray(struct.pack(">I", targetId)) 30 | 31 | if targetId & 0xF != 0x1: 32 | raise BaseException("Target ID does not support SCP V1") 33 | 34 | # identify 35 | apdu = bytearray([0xE0, 0x04, 0x00, 0x00]) + bytearray([len(targetid)]) + targetid 36 | dongle.exchange(apdu) 37 | 38 | # walk the chain 39 | batch_info = bytearray(dongle.exchange(bytearray.fromhex("E050000000"))) 40 | cardKey = batch_info[5 : 5 + batch_info[4]] 41 | 42 | # if not found, get another pair 43 | # if cardKey != testMasterPublic: 44 | # raise Exception("Invalid batch public key") 45 | 46 | # provide the ephemeral certificate 47 | ephemeralPrivate = PrivateKey() 48 | ephemeralPublic = bytearray(ephemeralPrivate.pubkey.serialize(compressed=False)) 49 | print("Using ephemeral key %s" % binascii.hexlify(ephemeralPublic)) 50 | signature = testMaster.ecdsa_sign(bytes(ephemeralPublic)) 51 | signature = testMaster.ecdsa_serialize(signature) 52 | certificate = ( 53 | bytearray([len(ephemeralPublic)]) 54 | + ephemeralPublic 55 | + bytearray([len(signature)]) 56 | + signature 57 | ) 58 | apdu = ( 59 | bytearray([0xE0, 0x51, 0x00, 0x00]) 60 | + bytearray([len(certificate)]) 61 | + certificate 62 | ) 63 | dongle.exchange(apdu) 64 | 65 | # walk the device certificates to retrieve the public key to use for authentication 66 | index = 0 67 | last_pub_key = PublicKey(bytes(testMasterPublic), raw=True) 68 | while True: 69 | certificate = bytearray(dongle.exchange(bytearray.fromhex("E052000000"))) 70 | if len(certificate) == 0: 71 | break 72 | certificatePublic = certificate[1 : 1 + certificate[0]] 73 | certificateSignature = last_pub_key.ecdsa_deserialize( 74 | bytes(certificate[2 + certificate[0] :]) 75 | ) 76 | if not last_pub_key.ecdsa_verify( 77 | bytes(certificatePublic), certificateSignature 78 | ): 79 | if index == 0: 80 | # Not an error if loading from user key 81 | print("Broken certificate chain - loading from user key") 82 | else: 83 | raise Exception("Broken certificate chain") 84 | last_pub_key = PublicKey(bytes(certificatePublic), raw=True) 85 | index = index + 1 86 | 87 | # Commit device ECDH channel 88 | dongle.exchange(bytearray.fromhex("E053000000")) 89 | secret = last_pub_key.ecdh(bytes(ephemeralPrivate.serialize().decode("hex"))) 90 | return secret[0:16] 91 | 92 | 93 | def getDeployedSecretV2( 94 | dongle, masterPrivate, targetId, signerCertChain=None, ecdh_secret_format=None 95 | ): 96 | testMaster = PrivateKey(bytes(masterPrivate)) 97 | testMasterPublic = bytearray(testMaster.pubkey.serialize(compressed=False)) 98 | targetid = bytearray(struct.pack(">I", targetId)) 99 | 100 | if targetId & 0xF < 2: 101 | raise BaseException("Target ID does not support SCP V2") 102 | 103 | # identify 104 | apdu = bytearray([0xE0, 0x04, 0x00, 0x00]) + bytearray([len(targetid)]) + targetid 105 | dongle.exchange(apdu) 106 | 107 | # walk the chain 108 | nonce = os.urandom(8) 109 | apdu = bytearray([0xE0, 0x50, 0x00, 0x00]) + bytearray([len(nonce)]) + nonce 110 | auth_info = dongle.exchange(apdu) 111 | batch_signer_serial = auth_info[0:4] 112 | deviceNonce = auth_info[4:12] 113 | 114 | # if not found, get another pair 115 | # if cardKey != testMasterPublic: 116 | # raise Exception("Invalid batch public key") 117 | 118 | if signerCertChain: 119 | for cert in signerCertChain: 120 | apdu = bytearray([0xE0, 0x51, 0x00, 0x00]) + bytearray([len(cert)]) + cert 121 | dongle.exchange(apdu) 122 | else: 123 | print("Using test master key %s " % binascii.hexlify(testMasterPublic)) 124 | dataToSign = bytes(bytearray([0x01]) + testMasterPublic) 125 | signature = testMaster.ecdsa_sign(bytes(dataToSign)) 126 | signature = testMaster.ecdsa_serialize(signature) 127 | certificate = ( 128 | bytearray([len(testMasterPublic)]) 129 | + testMasterPublic 130 | + bytearray([len(signature)]) 131 | + signature 132 | ) 133 | apdu = ( 134 | bytearray([0xE0, 0x51, 0x00, 0x00]) 135 | + bytearray([len(certificate)]) 136 | + certificate 137 | ) 138 | dongle.exchange(apdu) 139 | 140 | # provide the ephemeral certificate 141 | ephemeralPrivate = PrivateKey() 142 | ephemeralPublic = bytearray(ephemeralPrivate.pubkey.serialize(compressed=False)) 143 | print("Using ephemeral key %s" % binascii.hexlify(ephemeralPublic)) 144 | dataToSign = bytes(bytearray([0x11]) + nonce + deviceNonce + ephemeralPublic) 145 | signature = testMaster.ecdsa_sign(bytes(dataToSign)) 146 | signature = testMaster.ecdsa_serialize(signature) 147 | certificate = ( 148 | bytearray([len(ephemeralPublic)]) 149 | + ephemeralPublic 150 | + bytearray([len(signature)]) 151 | + signature 152 | ) 153 | apdu = ( 154 | bytearray([0xE0, 0x51, 0x80, 0x00]) 155 | + bytearray([len(certificate)]) 156 | + certificate 157 | ) 158 | dongle.exchange(apdu) 159 | 160 | # walk the device certificates to retrieve the public key to use for authentication 161 | index = 0 162 | last_dev_pub_key = PublicKey(bytes(testMasterPublic), raw=True) 163 | devicePublicKey = None 164 | while True: 165 | if index == 0: 166 | certificate = bytearray(dongle.exchange(bytearray.fromhex("E052000000"))) 167 | elif index == 1: 168 | certificate = bytearray(dongle.exchange(bytearray.fromhex("E052800000"))) 169 | else: 170 | break 171 | if len(certificate) == 0: 172 | break 173 | offset = 1 174 | certificateHeader = certificate[offset : offset + certificate[offset - 1]] 175 | offset += certificate[offset - 1] + 1 176 | certificatePublicKey = certificate[offset : offset + certificate[offset - 1]] 177 | offset += certificate[offset - 1] + 1 178 | certificateSignatureArray = certificate[ 179 | offset : offset + certificate[offset - 1] 180 | ] 181 | certificateSignature = last_dev_pub_key.ecdsa_deserialize( 182 | bytes(certificateSignatureArray) 183 | ) 184 | # first cert contains a header field which holds the certificate's public key role 185 | if index == 0: 186 | devicePublicKey = certificatePublicKey 187 | certificateSignedData = ( 188 | bytearray([0x02]) + certificateHeader + certificatePublicKey 189 | ) 190 | # Could check if the device certificate is signed by the issuer public key 191 | # ephemeral key certificate 192 | else: 193 | certificateSignedData = ( 194 | bytearray([0x12]) + deviceNonce + nonce + certificatePublicKey 195 | ) 196 | if not last_dev_pub_key.ecdsa_verify( 197 | bytes(certificateSignedData), certificateSignature 198 | ): 199 | if index == 0: 200 | # Not an error if loading from user key 201 | print("Broken certificate chain - loading from user key") 202 | else: 203 | raise Exception("Broken certificate chain") 204 | last_dev_pub_key = PublicKey(bytes(certificatePublicKey), raw=True) 205 | index = index + 1 206 | 207 | # Commit device ECDH channel 208 | dongle.exchange(bytearray.fromhex("E053000000")) 209 | secret = last_dev_pub_key.ecdh(binascii.unhexlify(ephemeralPrivate.serialize())) 210 | 211 | # forced to specific version 212 | if ecdh_secret_format == 1 or targetId & 0xF == 0x2: 213 | return secret[0:16] 214 | elif targetId & 0xF >= 0x3: 215 | ret = {} 216 | ret["ecdh_secret"] = secret 217 | ret["devicePublicKey"] = devicePublicKey 218 | return ret 219 | -------------------------------------------------------------------------------- /ledgerblue/derivePassphrase.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import argparse 21 | 22 | 23 | def get_argparser(): 24 | parser = argparse.ArgumentParser( 25 | description="Set a BIP 39 passphrase on the device." 26 | ) 27 | parser.add_argument( 28 | "--persistent", 29 | help="""Persist passphrase as secondary PIN (otherwise, it's set as a temporary 30 | passphrase)""", 31 | action="store_true", 32 | ) 33 | return parser 34 | 35 | 36 | def auto_int(x): 37 | return int(x, 0) 38 | 39 | 40 | if __name__ == "__main__": 41 | from .comm import getDongle 42 | import getpass 43 | import unicodedata 44 | import sys 45 | 46 | args = get_argparser().parse_args() 47 | 48 | dongle = getDongle(False) 49 | 50 | passphrase = getpass.getpass("Enter BIP39 passphrase : ") 51 | if isinstance(passphrase, bytes): 52 | passphrase = passphrase.decode(sys.stdin.encoding) 53 | if len(passphrase) != 0: 54 | if args.persistent: 55 | p1 = 0x02 56 | else: 57 | p1 = 0x01 58 | passphrase = unicodedata.normalize("NFKD", passphrase) 59 | apdu = bytearray([0xE0, 0xD0, p1, 0x00, len(passphrase)]) + bytearray( 60 | passphrase, "utf8" 61 | ) 62 | dongle.exchange(apdu, timeout=300) 63 | 64 | dongle.close() 65 | -------------------------------------------------------------------------------- /ledgerblue/ecWrapper.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import hashlib 21 | 22 | try: 23 | import secp256k1 24 | 25 | USE_SECP = secp256k1.HAS_ECDH 26 | except (ImportError, AttributeError): 27 | USE_SECP = False 28 | 29 | if not USE_SECP: 30 | import ecpy 31 | from builtins import int 32 | from ecpy.curves import Curve, Point 33 | from ecpy.keys import ECPublicKey, ECPrivateKey 34 | from ecpy.ecdsa import ECDSA 35 | 36 | CURVE_SECP256K1 = Curve.get_curve("secp256k1") 37 | SIGNER = ECDSA() 38 | 39 | 40 | class PublicKey(object): 41 | def __init__(self, pubkey=None, raw=False): 42 | if USE_SECP: 43 | self.obj = secp256k1.PublicKey(pubkey, raw) 44 | else: 45 | if not raw: 46 | raise Exception("Non raw init unsupported") 47 | pubkey = pubkey[1:] 48 | x = int.from_bytes(pubkey[0:32], "big") 49 | y = int.from_bytes(pubkey[32:], "big") 50 | self.obj = ECPublicKey(Point(x, y, CURVE_SECP256K1)) 51 | 52 | def ecdsa_deserialize(self, ser_sig): 53 | if USE_SECP: 54 | return self.obj.ecdsa_deserialize(ser_sig) 55 | else: 56 | return ser_sig 57 | 58 | def serialize(self, compressed=True): 59 | if USE_SECP: 60 | return self.obj.serialize(compressed) 61 | else: 62 | if not compressed: 63 | out = b"\x04" 64 | out += self.obj.W.x.to_bytes(32, "big") 65 | out += self.obj.W.y.to_bytes(32, "big") 66 | else: 67 | out = b"\x03" if ((self.obj.W.y & 1) != 0) else "\x02" 68 | out += self.obj.W.x.to_bytes(32, "big") 69 | return out 70 | 71 | def ecdh(self, scalar, scpv3=False): 72 | if USE_SECP: 73 | return self.obj.ecdh(scalar) 74 | else: 75 | scalar = int.from_bytes(scalar, "big") 76 | point = self.obj.W * scalar 77 | if not scpv3: 78 | # libsecp256k1 style secret 79 | out = b"\x03" if ((point.y & 1) != 0) else b"\x02" 80 | out += point.x.to_bytes(32, "big") 81 | else: 82 | out = point.x.to_bytes(32, "big") 83 | out += b"\x00\x00\x00\x01" 84 | hash = hashlib.sha256() 85 | hash.update(out) 86 | return hash.digest() 87 | 88 | def tweak_add(self, scalar): 89 | if USE_SECP: 90 | self.obj = self.obj.tweak_add(scalar) 91 | else: 92 | scalar = int.from_bytes(scalar, "big") 93 | privKey = ECPrivateKey(scalar, CURVE_SECP256K1) 94 | self.obj = ECPublicKey(self.obj.W + privKey.get_public_key().W) 95 | 96 | def ecdsa_verify(self, msg, raw_sig, raw=False, digest=hashlib.sha256): 97 | if USE_SECP: 98 | return self.obj.ecdsa_verify(msg, raw_sig, raw, digest) 99 | else: 100 | if not raw: 101 | h = digest() 102 | h.update(msg) 103 | msg = h.digest() 104 | raw_sig = bytearray(raw_sig) 105 | return SIGNER.verify(msg, raw_sig, self.obj) 106 | 107 | 108 | class PrivateKey(object): 109 | def __init__(self, privkey=None, raw=True): 110 | if USE_SECP: 111 | self.obj = secp256k1.PrivateKey(privkey, raw) 112 | self.pubkey = self.obj.pubkey 113 | else: 114 | if not raw: 115 | raise Exception("Non raw init unsupported") 116 | if privkey == None: 117 | privkey = ecpy.ecrand.rnd(CURVE_SECP256K1.order) 118 | else: 119 | privkey = int.from_bytes(privkey, "big") 120 | self.obj = ECPrivateKey(privkey, CURVE_SECP256K1) 121 | pubkey = self.obj.get_public_key().W 122 | out = b"\x04" 123 | out += pubkey.x.to_bytes(32, "big") 124 | out += pubkey.y.to_bytes(32, "big") 125 | self.pubkey = PublicKey(out, raw=True) 126 | 127 | def serialize(self): 128 | if USE_SECP: 129 | return self.obj.serialize() 130 | else: 131 | return "%.64x" % self.obj.d 132 | 133 | def ecdsa_serialize(self, raw_sig): 134 | if USE_SECP: 135 | return self.obj.ecdsa_serialize(raw_sig) 136 | else: 137 | return raw_sig 138 | 139 | def ecdsa_sign(self, msg, raw=False, digest=hashlib.sha256, rfc6979=False): 140 | if USE_SECP: 141 | return self.obj.ecdsa_sign(msg, raw, digest) 142 | else: 143 | if not raw: 144 | h = digest() 145 | h.update(msg) 146 | msg = h.digest() 147 | if rfc6979: 148 | signature = SIGNER.sign_rfc6979(msg, self.obj, digest, True) 149 | else: 150 | signature = SIGNER.sign(msg, self.obj, True) 151 | return signature 152 | -------------------------------------------------------------------------------- /ledgerblue/endorsementSetup.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import argparse 21 | 22 | DEFAULT_ISSUER_KEY = "0490f5c9d15a0134bb019d2afd0bf297149738459706e7ac5be4abc350a1f818057224fce12ec9a65de18ec34d6e8c24db927835ea1692b14c32e9836a75dad609" 23 | 24 | 25 | def get_argparser(): 26 | parser = argparse.ArgumentParser( 27 | description="""Generate an attestation keypair, using the provided Owner private 28 | key to sign the Owner Certificate.""" 29 | ) 30 | parser.add_argument( 31 | "--key", 32 | help="Which endorsement scheme to use", 33 | type=auto_int, 34 | choices=(1, 2), 35 | required=True, 36 | ) 37 | parser.add_argument( 38 | "--certificate", 39 | help="""Optional certificate to store if finalizing the endorsement (hex 40 | encoded), if no private key is specified""", 41 | ) 42 | parser.add_argument( 43 | "--privateKey", 44 | help="""Optional private key to use to create a test certificate (hex encoded), 45 | if no certificate is specified""", 46 | ) 47 | parser.add_argument( 48 | "--targetId", 49 | help="The device's target ID (default is Ledger Blue)", 50 | type=auto_int, 51 | default=0x31000002, 52 | ) 53 | parser.add_argument( 54 | "--issuerKey", 55 | help="Issuer key (hex encoded, default is batch 1)", 56 | default=DEFAULT_ISSUER_KEY, 57 | ) 58 | parser.add_argument("--rootPrivateKey", help="SCP Host private key") 59 | parser.add_argument("--apdu", help="Display APDU log", action="store_true") 60 | return parser 61 | 62 | 63 | def auto_int(x): 64 | return int(x, 0) 65 | 66 | 67 | def getDeployedSecretV2(dongle, masterPrivate, targetid, issuerKey): 68 | testMaster = PrivateKey(bytes(masterPrivate)) 69 | testMasterPublic = bytearray(testMaster.pubkey.serialize(compressed=False)) 70 | targetid = bytearray(struct.pack(">I", targetid)) 71 | 72 | # identify 73 | apdu = bytearray([0xE0, 0x04, 0x00, 0x00]) + bytearray([len(targetid)]) + targetid 74 | dongle.exchange(apdu) 75 | 76 | # walk the chain 77 | nonce = os.urandom(8) 78 | apdu = bytearray([0xE0, 0x50, 0x00, 0x00]) + bytearray([len(nonce)]) + nonce 79 | auth_info = dongle.exchange(apdu) 80 | batch_signer_serial = auth_info[0:4] 81 | deviceNonce = auth_info[4:12] 82 | 83 | # if not found, get another pair 84 | # if cardKey != testMasterPublic: 85 | # raise Exception("Invalid batch public key") 86 | 87 | dataToSign = bytes(bytearray([0x01]) + testMasterPublic) 88 | signature = testMaster.ecdsa_sign(bytes(dataToSign)) 89 | signature = testMaster.ecdsa_serialize(signature) 90 | certificate = ( 91 | bytearray([len(testMasterPublic)]) 92 | + testMasterPublic 93 | + bytearray([len(signature)]) 94 | + signature 95 | ) 96 | apdu = ( 97 | bytearray([0xE0, 0x51, 0x00, 0x00]) 98 | + bytearray([len(certificate)]) 99 | + certificate 100 | ) 101 | dongle.exchange(apdu) 102 | 103 | # provide the ephemeral certificate 104 | ephemeralPrivate = PrivateKey() 105 | ephemeralPublic = bytearray(ephemeralPrivate.pubkey.serialize(compressed=False)) 106 | dataToSign = bytes(bytearray([0x11]) + nonce + deviceNonce + ephemeralPublic) 107 | signature = testMaster.ecdsa_sign(bytes(dataToSign)) 108 | signature = testMaster.ecdsa_serialize(signature) 109 | certificate = ( 110 | bytearray([len(ephemeralPublic)]) 111 | + ephemeralPublic 112 | + bytearray([len(signature)]) 113 | + signature 114 | ) 115 | apdu = ( 116 | bytearray([0xE0, 0x51, 0x80, 0x00]) 117 | + bytearray([len(certificate)]) 118 | + certificate 119 | ) 120 | dongle.exchange(apdu) 121 | 122 | # walk the device certificates to retrieve the public key to use for authentication 123 | index = 0 124 | last_pub_key = PublicKey(binascii.unhexlify(issuerKey), raw=True) 125 | device_pub_key = None 126 | while True: 127 | if index == 0: 128 | certificate = bytearray(dongle.exchange(bytearray.fromhex("E052000000"))) 129 | elif index == 1: 130 | certificate = bytearray(dongle.exchange(bytearray.fromhex("E052800000"))) 131 | else: 132 | break 133 | if len(certificate) == 0: 134 | break 135 | offset = 1 136 | certificateHeader = certificate[offset : offset + certificate[offset - 1]] 137 | offset += certificate[offset - 1] + 1 138 | certificatePublicKey = certificate[offset : offset + certificate[offset - 1]] 139 | offset += certificate[offset - 1] + 1 140 | certificateSignatureArray = certificate[ 141 | offset : offset + certificate[offset - 1] 142 | ] 143 | certificateSignature = last_pub_key.ecdsa_deserialize( 144 | bytes(certificateSignatureArray) 145 | ) 146 | # first cert contains a header field which holds the certificate's public key role 147 | if index == 0: 148 | certificateSignedData = ( 149 | bytearray([0x02]) + certificateHeader + certificatePublicKey 150 | ) 151 | # Could check if the device certificate is signed by the issuer public key 152 | # ephemeral key certificate 153 | else: 154 | certificateSignedData = ( 155 | bytearray([0x12]) + deviceNonce + nonce + certificatePublicKey 156 | ) 157 | if not last_pub_key.ecdsa_verify( 158 | bytes(certificateSignedData), certificateSignature 159 | ): 160 | print("pub key not signed by last_pub_key") 161 | return None 162 | last_pub_key = PublicKey(bytes(certificatePublicKey), raw=True) 163 | if index == 0: 164 | device_pub_key = last_pub_key 165 | index = index + 1 166 | 167 | return device_pub_key 168 | 169 | 170 | if __name__ == "__main__": 171 | from .comm import getDongle 172 | from .ecWrapper import PrivateKey, PublicKey 173 | import hashlib 174 | import struct 175 | import os 176 | import binascii 177 | 178 | args = get_argparser().parse_args() 179 | 180 | if (args.privateKey != None) and (args.certificate != None): 181 | raise Exception("Cannot specify both certificate and privateKey") 182 | 183 | privateKey = PrivateKey() 184 | publicKey = str(privateKey.pubkey.serialize(compressed=False)) 185 | if not args.rootPrivateKey: 186 | args.rootPrivateKey = privateKey.serialize() 187 | else: 188 | # parse the issuer key from the rootprivate key 189 | issuerPrivKey = PrivateKey(bytes(bytearray.fromhex(args.rootPrivateKey))) 190 | args.issuerKey = binascii.hexlify( 191 | issuerPrivKey.pubkey.serialize(compressed=False) 192 | ).decode("utf-8") 193 | 194 | dongle = getDongle(args.apdu) 195 | print(args.rootPrivateKey) 196 | publicKey = getDeployedSecretV2( 197 | dongle, bytearray.fromhex(args.rootPrivateKey), args.targetId, args.issuerKey 198 | ) 199 | 200 | if args.certificate == None: 201 | apdu = bytearray([0xE0, 0xC0, args.key, 0x00, 0x00]) 202 | response = dongle.exchange(apdu) 203 | print("Public key " + response[0:65].hex()) 204 | m = hashlib.sha256() 205 | m.update(bytes(b"\xff")) # Endorsement role 206 | m.update(bytes(response[0:65])) 207 | digest = m.digest() 208 | signature = publicKey.ecdsa_deserialize(bytes(response[65:])) 209 | if not publicKey.ecdsa_verify(bytes(digest), signature, raw=True): 210 | raise Exception("Issuer certificate not verified") 211 | if args.privateKey != None: 212 | privateKey = PrivateKey(bytes(bytearray.fromhex(args.privateKey))) 213 | dataToSign = bytes(bytearray([0xFE]) + response[0:65]) 214 | signature = privateKey.ecdsa_sign(bytes(dataToSign)) 215 | args.certificate = privateKey.ecdsa_serialize(signature).hex() 216 | 217 | if args.certificate != None: 218 | certificate = bytearray.fromhex(args.certificate) 219 | apdu = bytearray([0xE0, 0xC2, 0x00, 0x00, len(certificate)]) + certificate 220 | dongle.exchange(apdu) 221 | print("Endorsement setup finalized") 222 | 223 | dongle.close() 224 | -------------------------------------------------------------------------------- /ledgerblue/endorsementSetupLedger.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import argparse 21 | import ssl 22 | 23 | 24 | def get_argparser(): 25 | parser = argparse.ArgumentParser( 26 | description="""Generate an attestation keypair, using Ledger to sign the Owner 27 | certificate.""" 28 | ) 29 | parser.add_argument( 30 | "--url", 31 | help="Server URL", 32 | default="https://hsmprod.hardwarewallet.com/hsm/process", 33 | ) 34 | parser.add_argument( 35 | "--bypass-ssl-check", 36 | help="Keep going even if remote certificate verification fails", 37 | action="store_true", 38 | default=False, 39 | ) 40 | parser.add_argument("--apdu", help="Display APDU log", action="store_true") 41 | parser.add_argument( 42 | "--perso", 43 | help="""A reference to the personalization key; this is a reference to the specific 44 | Issuer keypair used by Ledger to sign the device's Issuer Certificate""", 45 | default="perso_11", 46 | ) 47 | parser.add_argument( 48 | "--endorsement", 49 | help="""A reference to the endorsement key to use; this is a reference to the 50 | specific Owner keypair to be used by Ledger to sign the Owner Certificate""", 51 | default="attest_1", 52 | ) 53 | parser.add_argument( 54 | "--targetId", 55 | help="The device's target ID (default is Ledger Blue)", 56 | type=auto_int, 57 | ) 58 | parser.add_argument( 59 | "--key", 60 | help="Which endorsement scheme to use", 61 | type=auto_int, 62 | choices=(1, 2), 63 | required=True, 64 | ) 65 | return parser 66 | 67 | 68 | def auto_int(x): 69 | return int(x, 0) 70 | 71 | 72 | def serverQuery(request, url): 73 | data = request.SerializeToString() 74 | urll = urlparse.urlparse(args.url) 75 | req = urllib2.Request(args.url, data, {"Content-type": "application/octet-stream"}) 76 | if args.bypass_ssl_check: 77 | res = urllib2.urlopen(req, context=ssl._create_unverified_context()) 78 | else: 79 | res = urllib2.urlopen(req) 80 | data = res.read() 81 | response = Response() 82 | response.ParseFromString(data) 83 | if len(response.exception) != 0: 84 | raise Exception(response.exception) 85 | return response 86 | 87 | 88 | if __name__ == "__main__": 89 | import struct 90 | import urllib.request as urllib2 91 | import urllib.parse as urlparse 92 | from .BlueHSMServer_pb2 import Request, Response 93 | from .comm import getDongle 94 | 95 | args = get_argparser().parse_args() 96 | 97 | if args.targetId == None: 98 | args.targetId = 0x31000002 # Ledger Blue by default 99 | 100 | dongle = getDongle(args.apdu) 101 | 102 | # Identify 103 | 104 | targetid = bytearray(struct.pack(">I", args.targetId)) 105 | apdu = bytearray([0xE0, 0x04, 0x00, 0x00]) + bytearray([len(targetid)]) + targetid 106 | dongle.exchange(apdu) 107 | 108 | # Get nonce and ephemeral key 109 | 110 | request = Request() 111 | request.reference = "signEndorsement" 112 | parameter = request.remote_parameters.add() 113 | parameter.local = False 114 | parameter.alias = "persoKey" 115 | parameter.name = args.perso 116 | 117 | response = serverQuery(request, args.url) 118 | 119 | offset = 0 120 | 121 | remotePublicKey = response.response[offset : offset + 65] 122 | offset += 65 123 | nonce = response.response[offset : offset + 8] 124 | 125 | # Initialize chain 126 | 127 | apdu = bytearray([0xE0, 0x50, 0x00, 0x00, 0x08]) + nonce 128 | deviceInit = dongle.exchange(apdu) 129 | deviceNonce = deviceInit[4 : 4 + 8] 130 | 131 | # Get remote certificate 132 | 133 | request = Request() 134 | request.reference = "signEndorsement" 135 | request.id = response.id 136 | parameter = request.remote_parameters.add() 137 | parameter.local = False 138 | parameter.alias = "persoKey" 139 | parameter.name = args.perso 140 | request.parameters = bytes(deviceNonce) 141 | 142 | response = serverQuery(request, args.url) 143 | 144 | offset = 0 145 | 146 | responseLength = response.response[offset + 1] 147 | remotePublicKeySignatureLength = responseLength + 2 148 | remotePublicKeySignature = response.response[ 149 | offset : offset + remotePublicKeySignatureLength 150 | ] 151 | 152 | certificate = ( 153 | bytearray([len(remotePublicKey)]) 154 | + remotePublicKey 155 | + bytearray([len(remotePublicKeySignature)]) 156 | + remotePublicKeySignature 157 | ) 158 | apdu = ( 159 | bytearray([0xE0, 0x51, 0x80, 0x00]) 160 | + bytearray([len(certificate)]) 161 | + certificate 162 | ) 163 | dongle.exchange(apdu) 164 | 165 | # Walk the chain 166 | 167 | index = 0 168 | while True: 169 | if index == 0: 170 | certificate = bytearray(dongle.exchange(bytearray.fromhex("E052000000"))) 171 | elif index == 1: 172 | certificate = bytearray(dongle.exchange(bytearray.fromhex("E052800000"))) 173 | else: 174 | break 175 | if len(certificate) == 0: 176 | break 177 | request = Request() 178 | request.reference = "signEndorsement" 179 | request.id = response.id 180 | request.parameters = bytes(certificate) 181 | serverQuery(request, args.url) 182 | index += 1 183 | 184 | # Commit agreement 185 | 186 | request = Request() 187 | request.reference = "signEndorsement" 188 | request.id = response.id 189 | response = serverQuery(request, args.url) 190 | 191 | # Send endorsement request 192 | 193 | apdu = bytearray([0xE0, 0xC0, args.key, 0x00, 0x00]) 194 | endorsementData = dongle.exchange(apdu) 195 | 196 | request = Request() 197 | request.reference = "signEndorsement" 198 | parameter = request.remote_parameters.add() 199 | parameter.local = False 200 | parameter.alias = "endorsementKey" 201 | parameter.name = args.endorsement 202 | request.parameters = bytes(endorsementData) 203 | request.id = response.id 204 | response = serverQuery(request, args.url) 205 | certificate = bytearray(response.response) 206 | 207 | # Commit endorsement certificate 208 | 209 | apdu = bytearray([0xE0, 0xC2, 0x00, 0x00, len(certificate)]) + certificate 210 | dongle.exchange(apdu) 211 | print("Endorsement setup finalized") 212 | 213 | dongle.close() 214 | -------------------------------------------------------------------------------- /ledgerblue/endorsementSetupLedger2.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import argparse 21 | 22 | 23 | def get_argparser(): 24 | parser = argparse.ArgumentParser( 25 | "Update the firmware by using Ledger to open a Secure Channel." 26 | ) 27 | parser.add_argument( 28 | "--url", 29 | help="Websocket URL", 30 | default="wss://scriptrunner.api.live.ledger.com/update/endorse", 31 | ) 32 | parser.add_argument("--apdu", help="Display APDU log", action="store_true") 33 | parser.add_argument( 34 | "--perso", 35 | help="""A reference to the personalization key; this is a reference to the specific 36 | Issuer keypair used by Ledger to sign the device's Issuer Certificate""", 37 | default="perso_11", 38 | ) 39 | parser.add_argument( 40 | "--targetId", 41 | help="The device's target ID (default is Ledger Blue)", 42 | type=auto_int, 43 | default=0x31000002, 44 | ) 45 | parser.add_argument( 46 | "--endorsement", 47 | help="""A reference to the endorsement key to use; this is a reference to the 48 | specific Owner keypair to be used by Ledger to sign the Owner Certificate""", 49 | default="attest_1", 50 | ) 51 | parser.add_argument( 52 | "--key", 53 | help="Which endorsement scheme to use", 54 | type=auto_int, 55 | choices=(1, 2), 56 | required=True, 57 | ) 58 | return parser 59 | 60 | 61 | def auto_int(x): 62 | return int(x, 0) 63 | 64 | 65 | def process(dongle, request): 66 | response = {} 67 | apdusList = [] 68 | try: 69 | response["nonce"] = request["nonce"] 70 | if request["query"] == "exchange": 71 | apdusList.append(binascii.unhexlify(request["data"])) 72 | elif request["query"] == "bulk": 73 | for apdu in request["data"]: 74 | apdusList.append(binascii.unhexlify(apdu)) 75 | else: 76 | response["response"] = "unsupported" 77 | except: 78 | response["response"] = "parse error" 79 | 80 | if len(apdusList) != 0: 81 | try: 82 | for apdu in apdusList: 83 | response["data"] = dongle.exchange(apdu).hex() 84 | if len(response["data"]) == 0: 85 | response["data"] = "9000" 86 | response["response"] = "success" 87 | except: 88 | response["response"] = "I/O" # or error, and SW in data 89 | 90 | return response 91 | 92 | 93 | if __name__ == "__main__": 94 | import urllib.parse as urlparse 95 | from .comm import getDongle 96 | from websocket import create_connection 97 | import json 98 | import binascii 99 | 100 | args = get_argparser().parse_args() 101 | 102 | dongle = getDongle(args.apdu) 103 | 104 | url = args.url 105 | queryParameters = {} 106 | queryParameters["targetId"] = args.targetId 107 | queryParameters["perso"] = args.perso 108 | queryParameters["endorse"] = args.endorsement 109 | queryParameters["endorseScheme"] = args.key 110 | queryString = urlparse.urlencode(queryParameters) 111 | ws = create_connection(args.url + "?" + queryString) 112 | while True: 113 | result = json.loads(ws.recv()) 114 | if result["query"] == "success": 115 | break 116 | if result["query"] == "error": 117 | raise Exception( 118 | result["data"] + " on " + result["uuid"] + "/" + result["session"] 119 | ) 120 | response = process(dongle, result) 121 | ws.send(json.dumps(response)) 122 | ws.close() 123 | 124 | print("Script executed successfully") 125 | 126 | dongle.close() 127 | -------------------------------------------------------------------------------- /ledgerblue/genCAPair.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import argparse 21 | 22 | 23 | def get_argparser(): 24 | parser = argparse.ArgumentParser( 25 | description="Generate a Custom CA public-private keypair and print it to console." 26 | ) 27 | return parser 28 | 29 | 30 | if __name__ == "__main__": 31 | from .ecWrapper import PrivateKey 32 | 33 | get_argparser().parse_args() 34 | privateKey = PrivateKey() 35 | publicKey = privateKey.pubkey.serialize(compressed=False).hex() 36 | print("Public key : %s" % publicKey) 37 | print("Private key: %s" % privateKey.serialize()) 38 | -------------------------------------------------------------------------------- /ledgerblue/getMemInfo.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | from .ecWrapper import PrivateKey 21 | from .comm import getDongle 22 | from .deployed import getDeployedSecretV1, getDeployedSecretV2 23 | from .hexLoader import HexLoader 24 | import argparse 25 | import binascii 26 | 27 | 28 | def auto_int(x): 29 | return int(x, 0) 30 | 31 | 32 | parser = argparse.ArgumentParser() 33 | parser.add_argument( 34 | "--targetId", help="Set the chip target ID", type=auto_int, default=0x31100003 35 | ) 36 | parser.add_argument("--rootPrivateKey", help="Set the root private key") 37 | parser.add_argument("--apdu", help="Display APDU log", action="store_true") 38 | parser.add_argument( 39 | "--deployLegacy", help="Use legacy deployment API", action="store_true" 40 | ) 41 | 42 | args = parser.parse_args() 43 | 44 | print(args.targetId) 45 | 46 | if args.rootPrivateKey is None: 47 | privateKey = PrivateKey() 48 | publicKey = binascii.hexlify(privateKey.pubkey.serialize(compressed=False)) 49 | print("Generated random root public key : %s" % publicKey) 50 | args.rootPrivateKey = privateKey.serialize() 51 | 52 | dongle = getDongle(args.apdu) 53 | 54 | if args.deployLegacy: 55 | secret = getDeployedSecretV1( 56 | dongle, bytearray.fromhex(args.rootPrivateKey), args.targetId 57 | ) 58 | else: 59 | secret = getDeployedSecretV2( 60 | dongle, bytearray.fromhex(args.rootPrivateKey), args.targetId 61 | ) 62 | loader = HexLoader(dongle, 0xE0, True, secret) 63 | # apps = loader.listApp() 64 | memInfo = loader.getMemInfo() 65 | print(memInfo) 66 | 67 | dongle.close() 68 | -------------------------------------------------------------------------------- /ledgerblue/hashApp.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import argparse 21 | import struct 22 | 23 | 24 | def get_argparser(): 25 | parser = argparse.ArgumentParser( 26 | description="Calculate an application hash from the application's hex file." 27 | ) 28 | parser.add_argument( 29 | "--hex", help="The application hex file to be hashed", required=True 30 | ) 31 | parser.add_argument( 32 | "--targetId", 33 | help="The device's target ID (default is Ledger Blue)", 34 | type=auto_int, 35 | ) 36 | parser.add_argument("--targetVersion", help="Set the chip target version") 37 | return parser 38 | 39 | 40 | def auto_int(x): 41 | return int(x, 0) 42 | 43 | 44 | if __name__ == "__main__": 45 | from .hexParser import IntelHexParser 46 | import hashlib 47 | 48 | args = get_argparser().parse_args() 49 | 50 | # parse 51 | parser = IntelHexParser(args.hex) 52 | 53 | # prepare data 54 | m = hashlib.sha256() 55 | 56 | if args.targetId: 57 | m.update(struct.pack(">I", args.targetId)) 58 | 59 | if args.targetVersion: 60 | m.update(args.targetVersion) 61 | 62 | # consider areas are ordered by ascending address and non-overlaped 63 | for a in parser.getAreas(): 64 | m.update(a.data) 65 | dataToSign = m.digest() 66 | 67 | print(dataToSign.hex()) 68 | -------------------------------------------------------------------------------- /ledgerblue/hexParser.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | 21 | class IntelHexArea: 22 | def __init__(self, start, data): 23 | self.start = start 24 | self.data = data 25 | 26 | def getStart(self): 27 | return self.start 28 | 29 | def getData(self): 30 | return self.data 31 | 32 | def setData(self, data): 33 | self.data = data 34 | 35 | 36 | def insertAreaSorted(areas, area): 37 | i = 0 38 | while i < len(areas): 39 | if area.start < areas[i].start: 40 | break 41 | i += 1 42 | # areas = areas[0:i] + [area] 43 | areas[i:i] = [area] 44 | return areas 45 | 46 | 47 | class IntelHexParser: 48 | # order by start address 49 | def _addArea(self, area): 50 | self.areas = insertAreaSorted(self.areas, area) 51 | 52 | def __init__(self, fileName): 53 | self.bootAddr = 0 54 | self.areas = [] 55 | lineNumber = 0 56 | startZone = None 57 | startFirst = None 58 | current = None 59 | zoneData = b"" 60 | file = open(fileName, "r") 61 | for data in file: 62 | lineNumber += 1 63 | data = data.rstrip("\r\n") 64 | if len(data) == 0: 65 | continue 66 | if data[0] != ":": 67 | raise Exception("Invalid data at line %d" % lineNumber) 68 | data = bytearray.fromhex(data[1:]) 69 | count = data[0] 70 | address = (data[1] << 8) + data[2] 71 | recordType = data[3] 72 | if recordType == 0x00: 73 | if startZone == None: 74 | raise Exception( 75 | "Data record but no zone defined at line " + str(lineNumber) 76 | ) 77 | if startFirst == None: 78 | startFirst = address 79 | current = startFirst 80 | if address != current: 81 | self._addArea( 82 | IntelHexArea((startZone << 16) + startFirst, zoneData) 83 | ) 84 | zoneData = b"" 85 | startFirst = address 86 | current = address 87 | zoneData += data[4 : 4 + count] 88 | current += count 89 | if recordType == 0x01: 90 | if len(zoneData) != 0: 91 | self._addArea( 92 | IntelHexArea((startZone << 16) + startFirst, zoneData) 93 | ) 94 | zoneData = b"" 95 | startZone = None 96 | startFirst = None 97 | current = None 98 | if recordType == 0x02: 99 | raise Exception("Unsupported record 02") 100 | if recordType == 0x03: 101 | raise Exception("Unsupported record 03") 102 | if recordType == 0x04: 103 | if len(zoneData) != 0: 104 | self._addArea( 105 | IntelHexArea((startZone << 16) + startFirst, zoneData) 106 | ) 107 | zoneData = b"" 108 | startZone = None 109 | startFirst = None 110 | current = None 111 | startZone = (data[4] << 8) + data[5] 112 | if recordType == 0x05: 113 | self.bootAddr = ( 114 | ((data[4] & 0xFF) << 24) 115 | + ((data[5] & 0xFF) << 16) 116 | + ((data[6] & 0xFF) << 8) 117 | + (data[7] & 0xFF) 118 | ) 119 | # tail add of the last zone 120 | if len(zoneData) != 0: 121 | self._addArea(IntelHexArea((startZone << 16) + startFirst, zoneData)) 122 | zoneData = b"" 123 | startZone = None 124 | startFirst = None 125 | current = None 126 | file.close() 127 | 128 | def getAreas(self): 129 | return self.areas 130 | 131 | def getBootAddr(self): 132 | return self.bootAddr 133 | 134 | def maxAddr(self): 135 | addr = 0 136 | for a in self.areas: 137 | if a.start + len(a.data) > addr: 138 | addr = a.start + len(a.data) 139 | return addr 140 | 141 | def minAddr(self): 142 | addr = 0xFFFFFFFF 143 | for a in self.areas: 144 | if a.start < addr: 145 | addr = a.start 146 | return addr 147 | 148 | 149 | import binascii 150 | 151 | 152 | class IntelHexPrinter: 153 | def addArea(self, startaddress, data, insertFirst=False): 154 | # self.areas.append(IntelHexArea(startaddress, data)) 155 | if insertFirst: 156 | self.areas = [IntelHexArea(startaddress, data)] + self.areas 157 | else: 158 | # order by start address 159 | self.areas = insertAreaSorted(self.areas, IntelHexArea(startaddress, data)) 160 | 161 | def __init__(self, parser=None, eol="\r\n"): 162 | self.areas = [] 163 | self.eol = eol 164 | self.bootAddr = 0 165 | # build bound to the parser 166 | if parser: 167 | for a in parser.areas: 168 | self.addArea(a.start, a.data) 169 | self.bootAddr = parser.bootAddr 170 | 171 | def getAreas(self): 172 | return self.areas 173 | 174 | def getBootAddr(self): 175 | return self.bootAddr 176 | 177 | def maxAddr(self): 178 | addr = 0 179 | for a in self.areas: 180 | if a.start + len(a.data) > addr: 181 | addr = a.start + len(a.data) 182 | return addr 183 | 184 | def minAddr(self): 185 | addr = 0xFFFFFFFF 186 | for a in self.areas: 187 | if a.start < addr: 188 | addr = a.start 189 | return addr 190 | 191 | def setBootAddr(self, bootAddr): 192 | self.bootAddr = int(bootAddr) 193 | 194 | def checksum(self, bin): 195 | cks = 0 196 | for b in bin: 197 | cks += b 198 | cks = (-cks) & 0x0FF 199 | return cks 200 | 201 | def _emit_binary(self, file, bin): 202 | cks = self.checksum(bin) 203 | s = ( 204 | ":" 205 | + binascii.hexlify(bin).decode("utf-8") 206 | + hex(0x100 + cks)[3:] 207 | + self.eol 208 | ).upper() 209 | if file != None: 210 | file.write(s) 211 | else: 212 | print(s) 213 | 214 | def writeTo(self, fileName, blocksize=32): 215 | file = None 216 | if fileName != None: 217 | file = open(fileName, "w") 218 | for area in self.areas: 219 | off = 0 220 | # force the emission of selection record at start 221 | oldoff = area.start + 0x10000 222 | while off < len(area.data): 223 | # emit a offset selection record 224 | if (off & 0xFFFF0000) != (oldoff & 0xFFFF0000): 225 | self._emit_binary( 226 | file, 227 | bytearray.fromhex( 228 | "02000004" + hex(0x10000 + (area.start >> 16))[3:7] 229 | ), 230 | ) 231 | 232 | # emit data record 233 | if off + blocksize > len(area.data): 234 | self._emit_binary( 235 | file, 236 | bytearray.fromhex( 237 | hex(0x100 + (len(area.data) - off))[3:] 238 | + hex(0x10000 + off + (area.start & 0xFFFF))[3:] 239 | + "00" 240 | ) 241 | + area.data[off : len(area.data)], 242 | ) 243 | else: 244 | self._emit_binary( 245 | file, 246 | bytearray.fromhex( 247 | hex(0x100 + blocksize)[3:] 248 | + hex(0x10000 + off + (area.start & 0xFFFF))[3:] 249 | + "00" 250 | ) 251 | + area.data[off : off + blocksize], 252 | ) 253 | 254 | oldoff = off 255 | off += blocksize 256 | 257 | bootAddrHex = hex(0x100000000 + self.bootAddr)[3:] 258 | s = ( 259 | ":04000005" 260 | + bootAddrHex 261 | + hex(0x100 + self.checksum(bytearray.fromhex("04000005" + bootAddrHex)))[ 262 | 3: 263 | ] 264 | + self.eol 265 | ) 266 | if file != None: 267 | file.write(s) 268 | else: 269 | print(s) 270 | 271 | s = ":00000001FF" + self.eol 272 | 273 | if file != None: 274 | file.write(s) 275 | else: 276 | print(s) 277 | 278 | if file != None: 279 | file.close() 280 | -------------------------------------------------------------------------------- /ledgerblue/hostOnboard.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import argparse 21 | 22 | 23 | def get_argparser(): 24 | parser = argparse.ArgumentParser( 25 | description=""" 26 | .. warning:: 27 | 28 | Using this script undermines the security of the device. Caveat emptor. 29 | """ 30 | ) 31 | parser.add_argument("--apdu", help="Display APDU log", action="store_true") 32 | parser.add_argument( 33 | "--id", 34 | help="Identity to initialize", 35 | type=auto_int, 36 | choices=(0, 1, 2), 37 | required=True, 38 | ) 39 | parser.add_argument("--pin", help="Set a PINs to backup the seed for future use") 40 | parser.add_argument("--prefix", help="Derivation prefix") 41 | parser.add_argument("--passphrase", help="Derivation passphrase") 42 | parser.add_argument("--words", help="Derivation phrase") 43 | return parser 44 | 45 | 46 | def auto_int(x): 47 | return int(x, 0) 48 | 49 | 50 | if __name__ == "__main__": 51 | import getpass 52 | import unicodedata 53 | 54 | from .comm import getDongle 55 | 56 | args = get_argparser().parse_args() 57 | 58 | dongle = getDongle(args.apdu) 59 | 60 | def enter_if_none_and_normalize(hint, strg): 61 | if ( 62 | strg is None 63 | ): # or len(string) == 0: len 0 is accepted, to specify without being bothered by a message 64 | strg = getpass.getpass(hint) 65 | if len(strg) != 0: 66 | strg = unicodedata.normalize("NFKD", "" + strg) 67 | return strg 68 | 69 | if args.id < 2: 70 | args.pin = enter_if_none_and_normalize("PIN: ", args.pin) 71 | if args.pin is None or len(args.pin) == 0: 72 | raise Exception("Missing PIN for persistent identity") 73 | elif not args.pin is None: 74 | raise Exception("Can't set a PIN for the temporary identity") 75 | 76 | args.prefix = enter_if_none_and_normalize("Derivation prefix: ", args.prefix) 77 | args.passphrase = enter_if_none_and_normalize( 78 | "Derivation passphrase: ", args.passphrase 79 | ) 80 | args.words = enter_if_none_and_normalize("Derivation phrase: ", args.words) 81 | 82 | if args.pin: 83 | apdudata = bytearray([len(args.pin)]) + bytearray(args.pin, "utf8") 84 | else: 85 | apdudata = bytearray([0]) 86 | 87 | if args.prefix: 88 | apdudata += bytearray([len(args.prefix)]) + bytearray(args.prefix, "utf8") 89 | else: 90 | apdudata += bytearray([0]) 91 | 92 | if args.passphrase: 93 | apdudata += bytearray([len(args.passphrase)]) + bytearray( 94 | args.passphrase, "utf8" 95 | ) 96 | else: 97 | apdudata += bytearray([0]) 98 | 99 | if args.words: 100 | apdudata += bytearray([len(args.words)]) + bytearray(args.words, "utf8") 101 | else: 102 | apdudata += bytearray([0]) 103 | 104 | apdu = bytearray([0xE0, 0xD0, args.id, 0x00, len(apdudata)]) + apdudata 105 | dongle.exchange(apdu, timeout=3000) 106 | 107 | dongle.close() 108 | -------------------------------------------------------------------------------- /ledgerblue/ledgerWrapper.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import struct 21 | from .commException import CommException 22 | 23 | 24 | def wrapCommandAPDU(channel, command, packetSize, ble=False): 25 | if packetSize < 3: 26 | raise CommException( 27 | "Can't handle Ledger framing with less than 3 bytes for the report" 28 | ) 29 | sequenceIdx = 0 30 | offset = 0 31 | if not ble: 32 | result = struct.pack(">H", channel) 33 | extraHeaderSize = 2 34 | else: 35 | result = "" 36 | extraHeaderSize = 0 37 | result += struct.pack(">BHH", 0x05, sequenceIdx, len(command)) 38 | sequenceIdx = sequenceIdx + 1 39 | if len(command) > packetSize - 5 - extraHeaderSize: 40 | blockSize = packetSize - 5 - extraHeaderSize 41 | else: 42 | blockSize = len(command) 43 | result += command[offset : offset + blockSize] 44 | offset = offset + blockSize 45 | while offset != len(command): 46 | if not ble: 47 | result += struct.pack(">H", channel) 48 | result += struct.pack(">BH", 0x05, sequenceIdx) 49 | sequenceIdx = sequenceIdx + 1 50 | if (len(command) - offset) > packetSize - 3 - extraHeaderSize: 51 | blockSize = packetSize - 3 - extraHeaderSize 52 | else: 53 | blockSize = len(command) - offset 54 | result += command[offset : offset + blockSize] 55 | offset = offset + blockSize 56 | if not ble: 57 | while (len(result) % packetSize) != 0: 58 | result += b"\x00" 59 | return bytearray(result) 60 | 61 | 62 | def unwrapResponseAPDU(channel, data, packetSize, ble=False): 63 | sequenceIdx = 0 64 | offset = 0 65 | if not ble: 66 | extraHeaderSize = 2 67 | else: 68 | extraHeaderSize = 0 69 | if (data is None) or (len(data) < 5 + extraHeaderSize + 5): 70 | return None 71 | if not ble: 72 | if struct.unpack(">H", data[offset : offset + 2])[0] != channel: 73 | raise CommException("Invalid channel") 74 | offset += 2 75 | if data[offset] != 0x05: 76 | raise CommException("Invalid tag") 77 | offset += 1 78 | if struct.unpack(">H", data[offset : offset + 2])[0] != sequenceIdx: 79 | raise CommException("Invalid sequence") 80 | offset += 2 81 | responseLength = struct.unpack(">H", data[offset : offset + 2])[0] 82 | offset += 2 83 | if len(data) < 5 + extraHeaderSize + responseLength: 84 | return None 85 | if responseLength > packetSize - 5 - extraHeaderSize: 86 | blockSize = packetSize - 5 - extraHeaderSize 87 | else: 88 | blockSize = responseLength 89 | result = data[offset : offset + blockSize] 90 | offset += blockSize 91 | while len(result) != responseLength: 92 | sequenceIdx = sequenceIdx + 1 93 | if offset == len(data): 94 | return None 95 | if not ble: 96 | if struct.unpack(">H", data[offset : offset + 2])[0] != channel: 97 | raise CommException("Invalid channel") 98 | offset += 2 99 | if data[offset] != 0x05: 100 | raise CommException("Invalid tag") 101 | offset += 1 102 | if struct.unpack(">H", data[offset : offset + 2])[0] != sequenceIdx: 103 | raise CommException("Invalid sequence") 104 | offset += 2 105 | if (responseLength - len(result)) > packetSize - 3 - extraHeaderSize: 106 | blockSize = packetSize - 3 - extraHeaderSize 107 | else: 108 | blockSize = responseLength - len(result) 109 | result += data[offset : offset + blockSize] 110 | offset += blockSize 111 | return bytearray(result) 112 | -------------------------------------------------------------------------------- /ledgerblue/listApps.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import argparse 21 | 22 | 23 | def get_argparser(): 24 | parser = argparse.ArgumentParser(description="List all apps on the device.") 25 | parser.add_argument( 26 | "--targetId", 27 | help="The device's target ID (default is Ledger Blue)", 28 | type=auto_int, 29 | default=0x31000002, 30 | ) 31 | parser.add_argument( 32 | "--rootPrivateKey", 33 | help="""The Signer private key used to establish a Secure Channel 34 | (otherwise, a random one will be generated)""", 35 | ) 36 | parser.add_argument("--apdu", help="Display APDU log", action="store_true") 37 | parser.add_argument( 38 | "--deployLegacy", help="Use legacy deployment API", action="store_true" 39 | ) 40 | parser.add_argument( 41 | "--scp", help="Use a secure channel to list applications", action="store_true" 42 | ) 43 | return parser 44 | 45 | 46 | def auto_int(x): 47 | return int(x, 0) 48 | 49 | 50 | if __name__ == "__main__": 51 | from .ecWrapper import PrivateKey 52 | from .comm import getDongle 53 | from .deployed import getDeployedSecretV1, getDeployedSecretV2 54 | from .hexLoader import HexLoader 55 | import binascii 56 | 57 | args = get_argparser().parse_args() 58 | 59 | dongle = getDongle(args.apdu) 60 | 61 | if args.scp: 62 | if args.rootPrivateKey is None: 63 | privateKey = PrivateKey() 64 | publicKey = binascii.hexlify(privateKey.pubkey.serialize(compressed=False)) 65 | print("Generated random root public key : %s" % publicKey) 66 | args.rootPrivateKey = privateKey.serialize() 67 | 68 | if args.deployLegacy: 69 | secret = getDeployedSecretV1( 70 | dongle, bytearray.fromhex(args.rootPrivateKey), args.targetId 71 | ) 72 | else: 73 | secret = getDeployedSecretV2( 74 | dongle, bytearray.fromhex(args.rootPrivateKey), args.targetId 75 | ) 76 | else: 77 | secret = None 78 | loader = HexLoader(dongle, 0xE0, args.scp, secret) 79 | apps = loader.listApp() 80 | while len(apps) != 0: 81 | print(apps) 82 | apps = loader.listApp(False) 83 | 84 | dongle.close() 85 | -------------------------------------------------------------------------------- /ledgerblue/loadMCU.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import argparse 21 | 22 | 23 | def auto_int(x): 24 | return int(x, 0) 25 | 26 | 27 | def get_argparser(): 28 | parser = argparse.ArgumentParser( 29 | description="""Load the firmware onto the MCU. The MCU must already be in 30 | bootloader mode.""" 31 | ) 32 | parser.add_argument( 33 | "--targetId", help="The device's target ID", type=auto_int, required=True 34 | ) 35 | parser.add_argument( 36 | "--fileName", help="The name of the firmware file to load", required=True 37 | ) 38 | parser.add_argument("--bootAddr", help="The firmware's boot address", type=auto_int) 39 | parser.add_argument("--apdu", help="Display APDU log", action="store_true") 40 | parser.add_argument( 41 | "--reverse", 42 | help="Load HEX file in reverse from the highest address to the lowest", 43 | action="store_true", 44 | ) 45 | parser.add_argument( 46 | "--nocrc", 47 | help="Load HEX file without checking CRC of loaded sections", 48 | action="store_true", 49 | ) 50 | return parser 51 | 52 | 53 | if __name__ == "__main__": 54 | from .hexParser import IntelHexParser 55 | from .hexLoader import HexLoader 56 | from .comm import getDongle 57 | 58 | args = get_argparser().parse_args() 59 | 60 | parser = IntelHexParser(args.fileName) 61 | if args.bootAddr == None: 62 | args.bootAddr = parser.getBootAddr() 63 | 64 | dongle = getDongle(args.apdu) 65 | 66 | # relative load 67 | loader = HexLoader(dongle, 0xE0, False, None, False) 68 | 69 | loader.validateTargetId(args.targetId) 70 | hash = loader.load(0xFF, 0xF0, parser, reverse=args.reverse, doCRC=(not args.nocrc)) 71 | loader.run(args.bootAddr) 72 | 73 | dongle.close() 74 | -------------------------------------------------------------------------------- /ledgerblue/mcuBootloader.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import argparse 21 | 22 | 23 | def get_argparser(): 24 | parser = argparse.ArgumentParser( 25 | description="Request the MCU to execute its bootloader." 26 | ) 27 | parser.add_argument( 28 | "--targetId", 29 | help="The device's target ID (default is Ledger Blue)", 30 | type=auto_int, 31 | default=0x31000002, 32 | ) 33 | parser.add_argument( 34 | "--rootPrivateKey", 35 | help="""The Signer private key used to establish a Secure Channel (otherwise 36 | a random one will be generated)""", 37 | ) 38 | parser.add_argument("--apdu", help="Display APDU log", action="store_true") 39 | return parser 40 | 41 | 42 | def auto_int(x): 43 | return int(x, 0) 44 | 45 | 46 | if __name__ == "__main__": 47 | import binascii 48 | 49 | from .comm import getDongle 50 | from .deployed import getDeployedSecretV2 51 | from .ecWrapper import PrivateKey 52 | from .hexLoader import HexLoader 53 | 54 | args = get_argparser().parse_args() 55 | 56 | if args.rootPrivateKey is None: 57 | privateKey = PrivateKey() 58 | publicKey = binascii.hexlify(privateKey.pubkey.serialize(compressed=False)) 59 | print("Generated random root public key : %s" % publicKey) 60 | args.rootPrivateKey = privateKey.serialize() 61 | 62 | dongle = getDongle(args.apdu) 63 | 64 | secret = getDeployedSecretV2( 65 | dongle, bytearray.fromhex(args.rootPrivateKey), args.targetId 66 | ) 67 | loader = HexLoader(dongle, 0xE0, True, secret) 68 | loader.exchange(0xE0, 0, 0, 0, loader.encryptAES(b"\xb0")) 69 | 70 | dongle.close() 71 | -------------------------------------------------------------------------------- /ledgerblue/readElfMetadata.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2023 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import argparse 21 | import os 22 | from contextlib import contextmanager 23 | from elftools.elf.elffile import ELFFile 24 | 25 | __ELF_METADATA_SECTIONS = [ 26 | "target", 27 | "target_name", 28 | "target_id", 29 | "app_name", 30 | "app_version", 31 | "api_level", 32 | "sdk_version", 33 | "sdk_name", 34 | "sdk_hash", 35 | ] 36 | 37 | 38 | @contextmanager 39 | def _get_elf_file(filename): 40 | if os.path.exists(filename): 41 | with open(filename, "rb") as fp: 42 | yield ELFFile(fp) 43 | else: 44 | raise FileNotFoundError(f"File {filename} does not exist.") 45 | 46 | 47 | def _get_elf_section_value(elf, section_name): 48 | section = elf.get_section_by_name(f"ledger.{section_name}") 49 | section_value = "" 50 | if section: 51 | section_value = section.data().decode("utf-8").strip() 52 | return section_value 53 | 54 | 55 | def get_elf_section_value(filename, section_name): 56 | with _get_elf_file(filename) as elf: 57 | return _get_elf_section_value(elf, section_name) 58 | 59 | 60 | def get_target_id_from_elf(filename): 61 | return get_elf_section_value(filename, "target_id") 62 | 63 | 64 | def get_argparser(): 65 | parser = argparse.ArgumentParser( 66 | description="""Read the metadata of a Ledger device's ELF binary file.""" 67 | ) 68 | parser.add_argument( 69 | "--fileName", help="The name of the ELF binary file to read", required=True 70 | ) 71 | parser.add_argument( 72 | "--section", 73 | help=f"The name of the metadata section to be read. If no value is provided, all sections are read.", 74 | choices=__ELF_METADATA_SECTIONS + ["all"], 75 | default="all", 76 | ) 77 | return parser 78 | 79 | 80 | if __name__ == "__main__": 81 | args = get_argparser().parse_args() 82 | 83 | with _get_elf_file(args.fileName) as elf: 84 | if args.section == "all": 85 | for section_name in __ELF_METADATA_SECTIONS: 86 | section_value = _get_elf_section_value(elf, section_name) 87 | print(f"{section_name} : {section_value}") 88 | else: 89 | print(_get_elf_section_value(elf, args.section)) 90 | -------------------------------------------------------------------------------- /ledgerblue/recoverBackup.py: -------------------------------------------------------------------------------- 1 | from ledgerblue.comm import getDongle 2 | from ledgerblue.hexLoader import HexLoader 3 | from ledgerblue.recoverMutualAuth import recoverMutualAuth, SCPv3, recoverValidate 4 | from ledgerblue.recoverUtil import Recover 5 | from hashlib import sha256 6 | from Crypto.Cipher import AES 7 | import binascii 8 | import argparse 9 | import json 10 | import gnupg 11 | import os 12 | 13 | 14 | def get_argparser(): 15 | parser = argparse.ArgumentParser(description="Backup 3 shares of a seed.") 16 | parser.add_argument( 17 | "--targetId", help="The device's target ID (default is Nano X)", type=auto_int 18 | ) 19 | parser.add_argument( 20 | "--rootPrivateKey", help="The private key of the Certificate Authority" 21 | ) 22 | parser.add_argument( 23 | "--issuerPublicKey", 24 | help="The public key of the Issuer (used to verify the certificate of " 25 | "the device)", 26 | ) 27 | parser.add_argument( 28 | "--numberOfWords", 29 | help="The number of words in the mnemonic (default is 24 words)", 30 | type=auto_int, 31 | ) 32 | parser.add_argument( 33 | "-c", 34 | "--configuration", 35 | help="Configuration file", 36 | default=None, 37 | required=True, 38 | action="store", 39 | ) 40 | parser.add_argument( 41 | "--gpg", 42 | help="Encrypt the backup data. Enter the email address associated to your gpg key", 43 | default=None, 44 | action="store", 45 | ) 46 | return parser 47 | 48 | 49 | def auto_int(x): 50 | return int(x, 0) 51 | 52 | 53 | def decode_bytes(my_bytes): 54 | return my_bytes.decode("utf-8") 55 | 56 | 57 | if __name__ == "__main__": 58 | args = get_argparser().parse_args() 59 | 60 | # Read the configuration file 61 | try: 62 | with open(args.configuration, "r") as file: 63 | conf = json.load(file) 64 | except Exception as err: 65 | print(err) 66 | exit() 67 | 68 | if args.targetId is None: 69 | args.targetId = 0x33000004 70 | if args.rootPrivateKey is None: 71 | raise Exception("Missing Certificate Authority private key") 72 | if args.issuerPublicKey is None: 73 | args.issuerPublicKey = ( 74 | "0490f5c9d15a0134bb019d2afd0bf297149738459706e7ac5be4abc350a1f81805" 75 | "7224fce12ec9a65de18ec34d6e8c24db927835ea1692b14c32e9836a75dad609" 76 | ) 77 | if args.numberOfWords is None: 78 | # Default is 24 words 79 | args.numberOfWords = 24 80 | if not args.gpg: 81 | print("Your backup is going to be saved unencrypted !") 82 | else: 83 | home = os.path.join(os.environ["HOME"], ".gnupg") 84 | gpg = gnupg.GPG(gnupghome=home) 85 | 86 | dongle = getDongle(True) 87 | 88 | orchestratorPrivateKey = conf["orchestrator"]["key"] 89 | 90 | # Execute device-orchestrator secure channel protocol 91 | secret, devicePublicKey = SCPv3( 92 | dongle, 93 | bytearray.fromhex(args.issuerPublicKey), 94 | args.targetId, 95 | bytearray.fromhex(args.rootPrivateKey), 96 | bytearray.fromhex(orchestratorPrivateKey), 97 | ) 98 | loader = HexLoader(dongle, 0xE0, True, secret, scpv3=True) 99 | 100 | # Initialize the session with the info from the configuration file 101 | recoverSession = Recover(conf) 102 | confirmed = False 103 | 104 | for provider in conf["providers"]: 105 | backup_data = dict() 106 | delete_data = dict() 107 | name = provider["name"] 108 | privateKey = provider["key"] 109 | 110 | # Execute device-provider mutual authentication 111 | providerSk, providerPk = recoverValidate( 112 | loader, 113 | bytearray.fromhex(args.rootPrivateKey), 114 | name, 115 | bytearray.fromhex(privateKey), 116 | ) 117 | loader.recoverMutualAuth() 118 | sharedKey = recoverMutualAuth(providerSk, devicePublicKey) 119 | recoverSession.sharedKey = sharedKey 120 | 121 | # Send the user identity to the device 122 | if not confirmed: 123 | dataIdv = recoverSession.recoverPrepareDataIdv() 124 | cipher = AES.new(sharedKey, AES.MODE_SIV) 125 | ciphertext, tag = cipher.encrypt_and_digest(dataIdv) 126 | loader.recoverConfirmID(tag, ciphertext) 127 | confirmed = True 128 | 129 | dataHash = recoverSession.recoverPrepareDataHash(providerPk) 130 | cipher = AES.new(sharedKey, AES.MODE_SIV) 131 | ciphertext, tag = cipher.encrypt_and_digest(dataHash) 132 | 133 | # Validate backup data hash (device and backup provider agree on the same backup data) 134 | response = loader.recoverValidateHash(tag, ciphertext) 135 | 136 | # Get the share value and the number of words of the mnemonic (can be 12, 18 or 24) 137 | # The share is encrypted with the device-provider shared key 138 | resp = loader.recoverGetShare(value="shares") 139 | encryptedData = resp[: len(resp) - 1] 140 | numberOfWords = resp[len(resp) - 1] 141 | share, idx, deletePublicKey, commitHash = ( 142 | recoverSession.recoverBackupProviderDecrypt(encryptedData) 143 | ) 144 | 145 | # Get the commitments to the coefficients used to calculate the share 146 | commitments = loader.recoverGetShare(value="commitments") 147 | 148 | # Get the VSS point 149 | commitmentPoint = loader.recoverGetShare(value="point") 150 | 151 | h = sha256() 152 | h.update(commitments) 153 | calculatedCommitHash = h.digest() 154 | 155 | # Hashes of the commitments match on both side 156 | if not (commitHash == calculatedCommitHash): 157 | raise Exception("Hashes of the commitments don't match") 158 | 159 | # Verify whether the share is consistent 160 | result, shareCommit = recoverSession.recoverVerifyCommitments( 161 | share, idx, commitments, commitmentPoint 162 | ) 163 | if result: 164 | # Do the backup 165 | backup_data[name] = dict() 166 | backup_data[name]["share"] = decode_bytes(binascii.hexlify(share)) 167 | backup_data[name]["index"] = decode_bytes( 168 | binascii.hexlify(idx.to_bytes(4, "little")) 169 | ) 170 | backup_data[name]["commitments"] = decode_bytes( 171 | binascii.hexlify(commitments) 172 | ) 173 | backup_data[name]["share_commit"] = decode_bytes( 174 | binascii.hexlify(shareCommit) 175 | ) 176 | backup_data[name]["hash"] = decode_bytes(binascii.hexlify(commitHash)) 177 | backup_data[name]["point"] = decode_bytes(binascii.hexlify(commitmentPoint)) 178 | backup_data[name]["words_number"] = numberOfWords 179 | delete_data[name] = dict() 180 | delete_data[name]["public_key"] = decode_bytes( 181 | binascii.hexlify(deletePublicKey) 182 | ) 183 | else: 184 | raise Exception("Share's commitments not verified") 185 | 186 | # Validate the share's commitment 187 | recoverSession.recoverValidateShareCommit(loader, shareCommit) 188 | 189 | # Store the backup (it is up to the user to store it in a safe location) 190 | for name in backup_data: 191 | try: 192 | if args.gpg: 193 | with open(name + ".json.gpg", "w") as file: 194 | encode_backup_data = json.dumps( 195 | backup_data, indent=4, sort_keys=True 196 | ).encode("utf-8") 197 | encrypted_backup = gpg.encrypt( 198 | encode_backup_data, recipients=[args.gpg] 199 | ) 200 | file.write(str(encrypted_backup)) 201 | with open("Delete" + name + ".json.gpg", "w") as file: 202 | encode_delete_data = json.dumps(delete_data, indent=4).encode( 203 | "utf-8" 204 | ) 205 | encrypted_data = gpg.encrypt( 206 | encode_delete_data, recipients=[args.gpg] 207 | ) 208 | file.write(str(encrypted_data)) 209 | else: 210 | with open(name + ".json", "w") as file: 211 | json.dump(backup_data, file, indent=4, sort_keys=True) 212 | with open("Delete" + name + ".json", "w") as file: 213 | json.dump(delete_data, file, indent=4) 214 | except Exception as err: 215 | print(err) 216 | exit() 217 | -------------------------------------------------------------------------------- /ledgerblue/recoverDeleteBackup.py: -------------------------------------------------------------------------------- 1 | from ledgerblue.comm import getDongle 2 | from ledgerblue.hexLoader import HexLoader 3 | from ledgerblue.recoverMutualAuth import recoverMutualAuth, SCPv3, recoverValidate 4 | from ledgerblue.recoverUtil import Recover 5 | from Crypto.Cipher import AES 6 | import argparse 7 | import os 8 | import json 9 | import gnupg 10 | 11 | 12 | def get_argparser(): 13 | parser = argparse.ArgumentParser(description="Delete shares backups") 14 | parser.add_argument( 15 | "--targetId", help="The device's target ID (default is Nano X)", type=auto_int 16 | ) 17 | parser.add_argument( 18 | "--rootPrivateKey", help="The private key of the Certificate Authority" 19 | ) 20 | parser.add_argument( 21 | "--issuerPublicKey", 22 | help="The public key of the Issuer (used to verify the certificate of " 23 | "the device)", 24 | ) 25 | parser.add_argument( 26 | "-s", 27 | "--select", 28 | help="Select the backups to use", 29 | required=True, 30 | action="store", 31 | dest="backups", 32 | type=str, 33 | nargs="*", 34 | ) 35 | parser.add_argument( 36 | "-c", 37 | "--configuration", 38 | help="Configuration file", 39 | default=None, 40 | required=True, 41 | action="store", 42 | ) 43 | parser.add_argument( 44 | "--gpg", 45 | help="Decrypt the deletion public key. Enter the email address " 46 | "associated to your gpg key", 47 | default=None, 48 | action="store", 49 | ) 50 | return parser 51 | 52 | 53 | def auto_int(x): 54 | return int(x, 0) 55 | 56 | 57 | if __name__ == "__main__": 58 | args = get_argparser().parse_args() 59 | 60 | # Read the configuration file 61 | try: 62 | with open(args.configuration, "r") as file: 63 | conf = json.load(file) 64 | except Exception as err: 65 | print(err) 66 | exit() 67 | 68 | if args.targetId is None: 69 | args.targetId = 0x33000004 70 | if args.rootPrivateKey is None: 71 | raise Exception("Missing Certificate Authority private key") 72 | if args.issuerPublicKey is None: 73 | args.issuerPublicKey = ( 74 | "0490f5c9d15a0134bb019d2afd0bf297149738459706e7ac5be4abc350a1f81805" 75 | "7224fce12ec9a65de18ec34d6e8c24db927835ea1692b14c32e9836a75dad609" 76 | ) 77 | if not args.gpg: 78 | print("Reading your deletion public key from unencrypted files") 79 | else: 80 | home = os.path.join(os.environ["HOME"], ".gnupg") 81 | gpg = gnupg.GPG(gnupghome=home) 82 | 83 | dongle = getDongle(True) 84 | 85 | orchestratorPrivateKey = conf["orchestrator"]["key"] 86 | 87 | # Execute device-orchestrator secure channel protocol 88 | secret, devicePublicKey = SCPv3( 89 | dongle, 90 | bytearray.fromhex(args.issuerPublicKey), 91 | args.targetId, 92 | bytearray.fromhex(args.rootPrivateKey), 93 | bytearray.fromhex(orchestratorPrivateKey), 94 | ) 95 | loader = HexLoader(dongle, 0xE0, True, secret, scpv3=True) 96 | 97 | # Initialize the session with the info from the configuration file 98 | recoverSession = Recover(conf) 99 | confirmed = False 100 | 101 | for backup in args.backups: 102 | # Read the deletion public key 103 | try: 104 | with open(backup, "r") as file: 105 | if args.gpg: 106 | enc_delete_data = file.read() 107 | dec_data = gpg.decrypt(enc_delete_data) 108 | delete_data = json.loads(dec_data.data) 109 | else: 110 | delete_data = json.load(file) 111 | except Exception as err: 112 | print(err) 113 | exit() 114 | 115 | for p in conf["providers"]: 116 | if p["name"] == list(delete_data.keys())[0]: 117 | break 118 | name = p["name"] 119 | privateKey = p["key"] 120 | backupPublicKey = delete_data[name]["public_key"] 121 | 122 | # Execute device-provider mutual authentication 123 | providerSk, providerPk = recoverValidate( 124 | loader, 125 | bytearray.fromhex(args.rootPrivateKey), 126 | name, 127 | bytearray.fromhex(privateKey), 128 | ) 129 | loader.recoverMutualAuth() 130 | sharedKey = recoverMutualAuth(providerSk, devicePublicKey) 131 | recoverSession.sharedKey = sharedKey 132 | 133 | # Send the user identity to the device 134 | if not confirmed: 135 | dataIdv = recoverSession.recoverPrepareDataIdv(delete=True) 136 | cipher = AES.new(sharedKey, AES.MODE_SIV) 137 | ciphertext, tag = cipher.encrypt_and_digest(dataIdv) 138 | loader.recoverConfirmID(tag, ciphertext) 139 | confirmed = True 140 | 141 | dataHash = recoverSession.recoverPrepareDataHash(providerPk) 142 | cipher = AES.new(sharedKey, AES.MODE_SIV) 143 | ciphertext, tag = cipher.encrypt_and_digest(dataHash) 144 | 145 | # Validate backup data hash (device and backup provider agree on the same backup data) 146 | response = loader.recoverValidateHash(tag, ciphertext) 147 | 148 | # Verify whether the backup can be deleted 149 | recoverSession.recoverDeleteBackup(loader, bytearray.fromhex(backupPublicKey)) 150 | -------------------------------------------------------------------------------- /ledgerblue/recoverDeleteCA.py: -------------------------------------------------------------------------------- 1 | from ledgerblue.ecWrapper import PrivateKey 2 | from ledgerblue.comm import getDongle 3 | from ledgerblue.hexLoader import HexLoader 4 | from ledgerblue.recoverMutualAuth import SCPv3 5 | import binascii 6 | import argparse 7 | 8 | 9 | def get_argparser(): 10 | parser = argparse.ArgumentParser( 11 | description="Delete the custom Certificate Authority used to " 12 | "backup/restore a seed." 13 | ) 14 | parser.add_argument( 15 | "--targetId", help="The device's target ID (default is Nano X)", type=auto_int 16 | ) 17 | parser.add_argument("--name", help="The certificate's name", required=True) 18 | parser.add_argument( 19 | "--issuerPublicKey", 20 | help="The public key of the Issuer (used to verify the certificate of " 21 | "the device)", 22 | ) 23 | parser.add_argument( 24 | "--rootPrivateKey", 25 | help="The private key of the Signer used to establish a secure channel " 26 | "(otherwise a random one will be generated)", 27 | ) 28 | parser.add_argument( 29 | "--caPublicKey", 30 | help="The Custom CA's public key to be enrolled (hex encoded)", 31 | required=True, 32 | ) 33 | return parser 34 | 35 | 36 | def auto_int(x): 37 | return int(x, 0) 38 | 39 | 40 | if __name__ == "__main__": 41 | args = get_argparser().parse_args() 42 | 43 | if args.targetId is None: 44 | args.targetId = 0x33000004 45 | if args.name is None: 46 | raise Exception("Missing certificate's name") 47 | if args.issuerPublicKey is None: 48 | args.issuerPublicKey = ( 49 | "0490f5c9d15a0134bb019d2afd0bf297149738459706e7ac5be4abc350a1f81805" 50 | "7224fce12ec9a65de18ec34d6e8c24db927835ea1692b14c32e9836a75dad609" 51 | ) 52 | if args.rootPrivateKey is None: 53 | privateKey = PrivateKey() 54 | publicKey = binascii.hexlify(privateKey.pubkey.serialize(compressed=False)) 55 | print("Generated random root public key : %s" % publicKey) 56 | args.rootPrivateKey = privateKey.serialize() 57 | if args.caPublicKey is None: 58 | raise Exception("Missing CA's public key") 59 | 60 | publicKey = bytearray.fromhex(args.caPublicKey) 61 | dongle = getDongle(True) 62 | 63 | # Execute secure channel protocol (new version) 64 | secret, devicePublicKey = SCPv3( 65 | dongle, 66 | bytearray.fromhex(args.issuerPublicKey), 67 | args.targetId, 68 | None, 69 | bytearray.fromhex(args.rootPrivateKey), 70 | user_mode=True, 71 | ) 72 | loader = HexLoader(dongle, 0xE0, True, secret, scpv3=True) 73 | 74 | # Delete the Certificate Authority's public key 75 | loader.recoverDeleteCA(args.name, publicKey) 76 | -------------------------------------------------------------------------------- /ledgerblue/recoverMutualAuth.py: -------------------------------------------------------------------------------- 1 | from ledgerblue.ecWrapper import PublicKey, PrivateKey 2 | from ledgerblue.hexLoader import HexLoader 3 | from ledgerblue.recoverSCP import ( 4 | scp_derive_key, 5 | extract_from_certificate, 6 | decrypt_certificate, 7 | ) 8 | import binascii 9 | import struct 10 | import os 11 | 12 | CERT_ROLE_SIGNER = 0x1 13 | CERT_ROLE_SIGNER_EPHEMERAL = 0x11 14 | CERT_ROLE_DEVICE = 0x2 15 | CERT_ROLE_DEVICE_EPHEMERAL = 0x12 16 | CERT_ROLE_RECOVER_ORCHESTRATOR = 0x05 17 | CERT_ROLE_RECOVER_ORCHESTRATOR_EPHEMERAL = 0x15 18 | 19 | CERT_ROLE_RECOVER_PROVIDER = 0x4 20 | CERT_ROLE_RECOVER_PROVIDER_EPHEMERAL = 0x14 21 | CERT_FORMAT_VERSION = 0x01 22 | 23 | 24 | def SCPv3( 25 | dongle, 26 | issuer_public_key, 27 | target_id, 28 | ca_private_key=None, 29 | signer_private_key=None, 30 | user_mode=False, 31 | ): 32 | if not user_mode: 33 | ca_sk = PrivateKey(bytes(ca_private_key)) 34 | target = bytearray(struct.pack(">I", target_id)) 35 | scpv3 = 0x02 36 | 37 | apdu = bytearray([0xE0, 0x04, scpv3, 0x00]) + bytearray([len(target)]) + target 38 | dongle.exchange(apdu) 39 | 40 | # Initialize authentication 41 | nonce = os.urandom(8) 42 | apdu = bytearray([0xE0, 0x50, 0x00, 0x00]) + bytearray([len(nonce)]) + nonce 43 | 44 | auth_info = dongle.exchange(apdu) 45 | device_nonce = auth_info[4:12] 46 | 47 | if user_mode: 48 | role = CERT_ROLE_SIGNER 49 | ephemeral_role = CERT_ROLE_SIGNER_EPHEMERAL 50 | else: 51 | role = CERT_ROLE_RECOVER_ORCHESTRATOR 52 | ephemeral_role = CERT_ROLE_RECOVER_ORCHESTRATOR_EPHEMERAL 53 | 54 | # Validate signer static certificate 55 | certificate_id = 0x00 56 | if signer_private_key is not None: 57 | signer_sk = PrivateKey(bytes(signer_private_key)) 58 | signer_pk = bytearray(signer_sk.pubkey.serialize(compressed=False)) 59 | data_to_sign = bytes(bytearray([role]) + signer_pk) 60 | if user_mode: 61 | signature = signer_sk.ecdsa_sign(bytes(data_to_sign)) 62 | signature = signer_sk.ecdsa_serialize(signature) 63 | else: 64 | signature = ca_sk.ecdsa_sign(bytes(data_to_sign)) 65 | signature = ca_sk.ecdsa_serialize(signature) 66 | certificate_id = 0x01 67 | certificate = ( 68 | bytearray([len(signer_pk)]) 69 | + signer_pk 70 | + bytearray([len(signature)]) 71 | + signature 72 | ) 73 | apdu = ( 74 | bytearray([0xE0, 0x51, 0x00, certificate_id]) 75 | + bytearray([len(certificate)]) 76 | + certificate 77 | ) 78 | 79 | dongle.exchange(apdu) 80 | 81 | # Validate signer ephemeral certificate 82 | ephemeral_private = PrivateKey() 83 | ephemeral_public = bytearray(ephemeral_private.pubkey.serialize(compressed=False)) 84 | data_to_sign = bytes( 85 | bytearray([ephemeral_role]) + nonce + device_nonce + ephemeral_public 86 | ) 87 | signature = signer_sk.ecdsa_sign(bytes(data_to_sign)) 88 | signature = signer_sk.ecdsa_serialize(signature) 89 | certificate = ( 90 | bytearray([len(ephemeral_public)]) 91 | + ephemeral_public 92 | + bytearray([len(signature)]) 93 | + signature 94 | ) 95 | apdu = ( 96 | bytearray([0xE0, 0x51, 0x80, certificate_id]) 97 | + bytearray([len(certificate)]) 98 | + certificate 99 | ) 100 | 101 | dongle.exchange(apdu) 102 | 103 | # Get device certificates 104 | issuer_pk = PublicKey(bytes(issuer_public_key), raw=True) 105 | 106 | encrypted_certificate_static = dongle.exchange(bytearray.fromhex("E052000000")) 107 | 108 | # First extract the device ephemeral public key from the device ephemeral certificate 109 | certificate_ephemeral = bytearray(dongle.exchange(bytearray.fromhex("E052800000"))) 110 | 111 | certificate_header, certificate_public_key, certificate_signature_array = ( 112 | extract_from_certificate(certificate_ephemeral) 113 | ) 114 | 115 | # Check the certificate's header 116 | if not certificate_header == bytearray(): 117 | raise Exception("Device ephemeral certificate: error format") 118 | 119 | # Decrypt the device static certificate 120 | # Compute the shared key 121 | pub_key = PublicKey(bytes(certificate_public_key), raw=True) 122 | secret = pub_key.ecdh(binascii.unhexlify(ephemeral_private.serialize()), True) 123 | key = scp_derive_key(secret, 0, True) 124 | 125 | certificate_static = decrypt_certificate(encrypted_certificate_static, key) 126 | 127 | # Decrypt the signature from the ephemeral certificate 128 | certificate_signature_array = decrypt_certificate(certificate_signature_array, key) 129 | 130 | # Verify the device static certificate 131 | ( 132 | certificate_static_header, 133 | certificate_static_public_key, 134 | certificate_static_signature_array, 135 | ) = extract_from_certificate(certificate_static) 136 | certificate_signature = issuer_pk.ecdsa_deserialize( 137 | bytes(certificate_static_signature_array) 138 | ) 139 | certificate_signed_data = ( 140 | bytearray([CERT_ROLE_DEVICE]) 141 | + certificate_static_header 142 | + certificate_static_public_key 143 | ) 144 | 145 | if not issuer_pk.ecdsa_verify( 146 | bytes(certificate_signed_data), certificate_signature 147 | ): 148 | raise Exception("Device certificate not verified") 149 | 150 | # Verify the device ephemeral certificate 151 | device_pub_key = PublicKey(bytes(certificate_static_public_key), raw=True) 152 | certificate_signature = device_pub_key.ecdsa_deserialize( 153 | bytes(certificate_signature_array) 154 | ) 155 | certificate_signed_data = ( 156 | bytearray([CERT_ROLE_DEVICE_EPHEMERAL]) 157 | + device_nonce 158 | + nonce 159 | + certificate_public_key 160 | ) 161 | 162 | if not device_pub_key.ecdsa_verify( 163 | bytes(certificate_signed_data), certificate_signature 164 | ): 165 | raise Exception("Device ephemeral certificate not verified") 166 | 167 | dongle.exchange(bytearray.fromhex("E053000000")) 168 | 169 | return secret, certificate_public_key 170 | 171 | 172 | def recoverValidate(loader, caKey, name, staticPrivateKey): 173 | caPrivateKey = PrivateKey(bytes(caKey)) 174 | 175 | providerPrivateKey = PrivateKey(bytes(staticPrivateKey)) 176 | providerPublicKey = bytearray(providerPrivateKey.pubkey.serialize(compressed=False)) 177 | 178 | # Validate provider's static certificate 179 | role = bytearray([CERT_ROLE_RECOVER_PROVIDER]) 180 | version = bytearray([CERT_FORMAT_VERSION]) 181 | dataToSign = bytes( 182 | version 183 | + role 184 | + struct.pack(">B", len(name)) 185 | + name.encode() 186 | + struct.pack(">B", len(providerPublicKey)) 187 | + providerPublicKey 188 | ) 189 | signature = caPrivateKey.ecdsa_sign(bytes(dataToSign)) 190 | signature = caPrivateKey.ecdsa_serialize(signature) 191 | 192 | loader.recoverValidateCertificate( 193 | bytes(version), bytes(role), name, providerPublicKey, signature 194 | ) 195 | 196 | # Validate provider's ephemeral certificate 197 | ephemeralPrivate = PrivateKey() 198 | ephemeralPublic = bytearray(ephemeralPrivate.pubkey.serialize(compressed=False)) 199 | role = bytearray([CERT_ROLE_RECOVER_PROVIDER_EPHEMERAL]) 200 | dataToSign = bytes( 201 | version 202 | + role 203 | + struct.pack(">B", len(name)) 204 | + name.encode() 205 | + struct.pack(">B", len(ephemeralPublic)) 206 | + ephemeralPublic 207 | ) 208 | signature = providerPrivateKey.ecdsa_sign(bytes(dataToSign)) 209 | signature = providerPrivateKey.ecdsa_serialize(signature) 210 | 211 | loader.recoverValidateCertificate( 212 | bytes(version), bytes(role), name, ephemeralPublic, signature, True 213 | ) 214 | 215 | return ephemeralPrivate, ephemeralPublic 216 | 217 | 218 | def recoverMutualAuth(privateKey, devicePublicKey): 219 | # Compute the shared key 220 | pk = PublicKey(devicePublicKey, raw=True) 221 | secret = pk.ecdh(binascii.unhexlify(privateKey.serialize()), True) 222 | sharedKey = scp_derive_key(secret, 0, True) 223 | 224 | return sharedKey 225 | -------------------------------------------------------------------------------- /ledgerblue/recoverRestore.py: -------------------------------------------------------------------------------- 1 | from ledgerblue.comm import getDongle 2 | from ledgerblue.hexLoader import HexLoader 3 | from ledgerblue.recoverMutualAuth import recoverMutualAuth, SCPv3, recoverValidate 4 | from ledgerblue.recoverUtil import Recover 5 | from hashlib import sha256 6 | from Crypto.Cipher import AES 7 | import argparse 8 | import json 9 | import sys 10 | import gnupg 11 | import os 12 | 13 | 14 | def get_argparser(): 15 | parser = argparse.ArgumentParser(description="Restore a seed given 2 shares.") 16 | parser.add_argument( 17 | "--targetId", help="The device's target ID (default is Nano X)", type=auto_int 18 | ) 19 | parser.add_argument( 20 | "--rootPrivateKey", help="The private key of the Certificate Authority" 21 | ) 22 | parser.add_argument( 23 | "--issuerPublicKey", 24 | help="The public key of the Issuer (used to verify the certificate of " 25 | "the device)", 26 | ) 27 | parser.add_argument( 28 | "-s", 29 | "--select", 30 | help="Select the backups to use", 31 | required=True, 32 | action="store", 33 | dest="backups", 34 | type=str, 35 | nargs="*", 36 | ) 37 | parser.add_argument( 38 | "-c", 39 | "--configuration", 40 | help="Configuration file", 41 | default=None, 42 | required=True, 43 | action="store", 44 | ) 45 | parser.add_argument( 46 | "--gpg", 47 | help="Decrypt the backup data. Enter the email address associated to your gpg key", 48 | default=None, 49 | action="store", 50 | ) 51 | return parser 52 | 53 | 54 | def auto_int(x): 55 | return int(x, 0) 56 | 57 | 58 | if __name__ == "__main__": 59 | args = get_argparser().parse_args() 60 | 61 | # Read the configuration file 62 | try: 63 | with open(args.configuration, "r") as file: 64 | conf = json.load(file) 65 | except Exception as err: 66 | print(err) 67 | exit() 68 | 69 | if args.targetId is None: 70 | args.targetId = 0x33000004 71 | if args.rootPrivateKey is None: 72 | raise Exception("Missing Certificate Authority private key") 73 | if args.issuerPublicKey is None: 74 | args.issuerPublicKey = ( 75 | "0490f5c9d15a0134bb019d2afd0bf297149738459706e7ac5be4abc350a1f81805" 76 | "7224fce12ec9a65de18ec34d6e8c24db927835ea1692b14c32e9836a75dad609" 77 | ) 78 | if not args.gpg: 79 | print("Reading your backups from unencrypted files") 80 | else: 81 | home = os.path.join(os.environ["HOME"], ".gnupg") 82 | gpg = gnupg.GPG(gnupghome=home) 83 | dongle = getDongle(True) 84 | 85 | orchestratorPrivateKey = conf["orchestrator"]["key"] 86 | 87 | # Execute device-orchestrator secure channel protocol 88 | secret, devicePublicKey = SCPv3( 89 | dongle, 90 | bytearray.fromhex(args.issuerPublicKey), 91 | args.targetId, 92 | bytearray.fromhex(args.rootPrivateKey), 93 | bytearray.fromhex(orchestratorPrivateKey), 94 | ) 95 | loader = HexLoader(dongle, 0xE0, True, secret, scpv3=True) 96 | 97 | # Initialize the session with the info from the configuration file 98 | recoverSession = Recover(conf) 99 | confirmed = False 100 | 101 | for backup in args.backups: 102 | # Read the backup file 103 | try: 104 | with open(backup, "r") as file: 105 | if args.gpg: 106 | enc_restore_data = file.read() 107 | dec_data = gpg.decrypt(enc_restore_data) 108 | restore_data = json.loads(dec_data.data) 109 | else: 110 | restore_data = json.load(file) 111 | except Exception as err: 112 | print(err) 113 | exit() 114 | 115 | for p in conf["providers"]: 116 | if p["name"] == list(restore_data.keys())[0]: 117 | break 118 | name = p["name"] 119 | privateKey = p["key"] 120 | # Execute device-provider mutual authentication 121 | providerSk, providerPk = recoverValidate( 122 | loader, 123 | bytearray.fromhex(args.rootPrivateKey), 124 | name, 125 | bytearray.fromhex(privateKey), 126 | ) 127 | 128 | loader.recoverMutualAuth() 129 | sharedKey = recoverMutualAuth(providerSk, devicePublicKey) 130 | recoverSession.sharedKey = sharedKey 131 | 132 | # Send the user identity to the device 133 | if not confirmed: 134 | dataIdv = recoverSession.recoverPrepareDataIdv() 135 | cipher = AES.new(sharedKey, AES.MODE_SIV) 136 | ciphertext, tag = cipher.encrypt_and_digest(dataIdv) 137 | loader.recoverConfirmID(tag, ciphertext) 138 | confirmed = True 139 | 140 | dataHash = recoverSession.recoverPrepareDataHash(providerPk) 141 | cipher = AES.new(sharedKey, AES.MODE_SIV) 142 | ciphertext, tag = cipher.encrypt_and_digest(dataHash) 143 | 144 | # Validate backup data hash (device and backup provider agree on the same backup data) 145 | response = loader.recoverValidateHash(tag, ciphertext) 146 | cipher = AES.new(sharedKey, AES.MODE_SIV) 147 | clear_response = cipher.decrypt_and_verify(response[16:], response[:16]) 148 | assert clear_response == b"Confirm restore" 149 | 150 | share = restore_data[name]["share"] 151 | point = restore_data[name]["point"] 152 | commitments = restore_data[name]["commitments"] 153 | shareAndIndex = share + restore_data[name]["index"] 154 | numberOfWords = restore_data[name]["words_number"] 155 | 156 | shareCommit = recoverSession.recoverShareCommit( 157 | bytearray.fromhex(point), bytearray.fromhex(share) 158 | ) 159 | 160 | # Validate share's commitment 161 | recoverSession.recoverValidateCommit( 162 | loader, bytearray.fromhex(commitments), shareCommit 163 | ) 164 | 165 | # Send the share to the device (encrypted with the device-provider shared key) 166 | recoverSession.recoverRestoreSeed( 167 | loader, bytearray.fromhex(shareAndIndex), numberOfWords 168 | ) 169 | -------------------------------------------------------------------------------- /ledgerblue/recoverSCP.py: -------------------------------------------------------------------------------- 1 | from Cryptodome.Cipher import AES 2 | from ledgerblue.ecWrapper import PrivateKey 3 | from ecpy.curves import Curve 4 | import hashlib 5 | import struct 6 | 7 | 8 | def decrypt_certificate(encrypted_certificate, key): 9 | tag = encrypted_certificate[:16] 10 | ciphertext = encrypted_certificate[16:] 11 | aes_siv = AES.new(key, mode=AES.MODE_SIV) 12 | certificate = aes_siv.decrypt_and_verify(ciphertext, tag) 13 | return certificate 14 | 15 | 16 | def extract_from_certificate(certificate): 17 | offset = 1 18 | certificate_header = certificate[offset : offset + certificate[offset - 1]] 19 | offset += certificate[offset - 1] + 1 20 | certificate_public_key = certificate[offset : offset + certificate[offset - 1]] 21 | offset += certificate[offset - 1] + 1 22 | certificate_signature_array = certificate[offset : offset + certificate[offset - 1]] 23 | return certificate_header, certificate_public_key, certificate_signature_array 24 | 25 | 26 | def scp_derive_key(ecdh_secret, keyindex, scpv3=False): 27 | if scpv3: 28 | mac_block = b"\x01" * 16 29 | cipher = AES.new(ecdh_secret, AES.MODE_ECB) 30 | mac_key = cipher.encrypt(mac_block) 31 | enc_block = b"\x02" * 16 32 | cipher = AES.new(ecdh_secret, AES.MODE_ECB) 33 | enc_key = cipher.encrypt(enc_block) 34 | return mac_key + enc_key 35 | retry = 0 36 | # di = sha256(i || retrycounter || ecdh secret) 37 | while True: 38 | sha256 = hashlib.new("sha256") 39 | sha256.update(struct.pack(">IB", keyindex, retry)) 40 | sha256.update(ecdh_secret) 41 | 42 | # compare di with order 43 | CURVE_SECP256K1 = Curve.get_curve("secp256k1") 44 | if int.from_bytes(sha256.digest(), "big") < CURVE_SECP256K1.order: 45 | break 46 | # regenerate a new di satisfying order upper bound 47 | retry += 1 48 | 49 | # Pi = di*G 50 | privkey = PrivateKey(bytes(sha256.digest())) 51 | pubkey = bytearray(privkey.pubkey.serialize(compressed=False)) 52 | # ki = sha256(Pi) 53 | sha256 = hashlib.new("sha256") 54 | sha256.update(pubkey) 55 | return sha256.digest() 56 | -------------------------------------------------------------------------------- /ledgerblue/recoverSetCA.py: -------------------------------------------------------------------------------- 1 | from ledgerblue.ecWrapper import PrivateKey 2 | from ledgerblue.comm import getDongle 3 | from ledgerblue.hexLoader import HexLoader 4 | from ledgerblue.recoverMutualAuth import SCPv3 5 | import binascii 6 | import argparse 7 | 8 | 9 | def get_argparser(): 10 | parser = argparse.ArgumentParser( 11 | description="Set a custom Certificate Authority to backup/restore a seed." 12 | ) 13 | parser.add_argument( 14 | "--targetId", help="The device's target ID (default is Nano X)", type=auto_int 15 | ) 16 | parser.add_argument("--name", help="The certificate name", required=True) 17 | parser.add_argument( 18 | "--issuerPublicKey", 19 | help="The public key of the Issuer (used to verify the certificate of " 20 | "the device)", 21 | ) 22 | parser.add_argument( 23 | "--rootPrivateKey", 24 | help="The private key of the Signer used to establish a secure channel " 25 | "(otherwise a random one will be generated)", 26 | ) 27 | parser.add_argument( 28 | "--caPublicKey", 29 | help="The Custom CA's public key to be enrolled (hex encoded)", 30 | required=True, 31 | ) 32 | return parser 33 | 34 | 35 | def auto_int(x): 36 | return int(x, 0) 37 | 38 | 39 | if __name__ == "__main__": 40 | args = get_argparser().parse_args() 41 | 42 | if args.targetId is None: 43 | args.targetId = 0x33000004 44 | if args.name is None: 45 | raise Exception("Missing certificate's name") 46 | if args.issuerPublicKey is None: 47 | args.issuerPublicKey = ( 48 | "0490f5c9d15a0134bb019d2afd0bf297149738459706e7ac5be4abc350a1f81805" 49 | "7224fce12ec9a65de18ec34d6e8c24db927835ea1692b14c32e9836a75dad609" 50 | ) 51 | if args.rootPrivateKey is None: 52 | privateKey = PrivateKey() 53 | publicKey = binascii.hexlify(privateKey.pubkey.serialize(compressed=False)) 54 | print("Generated random root public key : %s" % publicKey) 55 | args.rootPrivateKey = privateKey.serialize() 56 | if args.caPublicKey is None: 57 | raise Exception("Missing CA's public key") 58 | 59 | publicKey = bytearray.fromhex(args.caPublicKey) 60 | dongle = getDongle(True) 61 | 62 | # Execute secure channel protocol (new version) 63 | secret, devicePublicKey = SCPv3( 64 | dongle, 65 | bytearray.fromhex(args.issuerPublicKey), 66 | args.targetId, 67 | None, 68 | bytearray.fromhex(args.rootPrivateKey), 69 | user_mode=True, 70 | ) 71 | loader = HexLoader(dongle, 0xE0, True, secret, scpv3=True) 72 | 73 | # Load the Certificate Authority's public key 74 | loader.recoverSetCA(args.name, publicKey) 75 | -------------------------------------------------------------------------------- /ledgerblue/recoverUtil.py: -------------------------------------------------------------------------------- 1 | from ecpy.curves import Curve, Point 2 | from Crypto.Cipher import AES 3 | from ledgerblue.ecWrapper import PublicKey 4 | from ledgerblue.vss import PedersenVSS 5 | from hashlib import sha256 6 | import os 7 | import struct 8 | 9 | FIRST_NAME_TAG = 0x20 10 | NAME_TAG = 0x21 11 | DATE_OF_BIRTH_TAG = 0x22 12 | PLACE_OF_BIRTH_TAG = 0x23 13 | BACKUP_FLOW = 0x01 14 | RESTORE_FLOW = 0x10 15 | DELETE_FLOW = 0x11 16 | 17 | 18 | class Recover: 19 | def __init__(self, conf): 20 | self.sharedKey = bytes() 21 | self.backupId = bytearray.fromhex(conf["backup_info"]["backup_id"]) 22 | self.backupName = conf["backup_info"]["backup_name"] 23 | user = conf["user_info"] 24 | self.firstName = user["first_name"] 25 | self.lastName = user["last_name"] 26 | self.birthDate = user["birth"] 27 | self.birthPlace = user["city"] 28 | self.userInfo = ( 29 | self.firstName + self.lastName + self.birthDate + self.birthPlace 30 | ) 31 | self.f_tag = FIRST_NAME_TAG 32 | self.n_tag = NAME_TAG 33 | self.d_tag = DATE_OF_BIRTH_TAG 34 | self.c_tag = PLACE_OF_BIRTH_TAG 35 | self.VSS = PedersenVSS(Curve.get_curve("secp384r1")) 36 | 37 | def recoverRestoreSeed(self, loader, share, wordsNumber): 38 | cipher = AES.new(self.sharedKey, AES.MODE_SIV) 39 | ciphertext, tag = cipher.encrypt_and_digest(share) 40 | loader.recoverRestoreSeed(tag, ciphertext, wordsNumber) 41 | 42 | def recoverValidateCommit(self, loader, commits, shareCommit): 43 | dataToHash = bytes(commits + shareCommit) 44 | h = sha256() 45 | h.update(dataToHash) 46 | dataHash = h.digest() 47 | cipher = AES.new(self.sharedKey, AES.MODE_SIV) 48 | ciphertext, tag = cipher.encrypt_and_digest(dataHash) 49 | loader.recoverValidateCommit(0x2, commits) 50 | loader.recoverValidateCommit(0x4, shareCommit) 51 | loader.recoverValidateCommit(0x3, None, tag, ciphertext) 52 | 53 | def recoverShareCommit(self, point, share): 54 | Q = Point( 55 | int.from_bytes(point[: self.VSS.domain_len], "big"), 56 | int.from_bytes(point[self.VSS.domain_len : 2 * self.VSS.domain_len], "big"), 57 | self.VSS.curve, 58 | ) 59 | P = self.VSS.pedersen_share_commit(Q, share) 60 | return bytearray( 61 | P.x.to_bytes(self.VSS.domain_len, "big") 62 | + P.y.to_bytes(self.VSS.domain_len, "big") 63 | ) 64 | 65 | def recoverValidateShareCommit(self, loader, shareCommit): 66 | dataToHash = bytes(shareCommit) 67 | h = sha256() 68 | h.update(dataToHash) 69 | dataHash = h.digest() 70 | cipher = AES.new(self.sharedKey, AES.MODE_SIV) 71 | ciphertext, tag = cipher.encrypt_and_digest(dataHash) 72 | loader.recoverValidateCommit(0x4, shareCommit) 73 | loader.recoverValidateCommit(0x3, None, tag, ciphertext) 74 | 75 | def recoverVerifyCommitments(self, share, idx, commitments, point): 76 | point_len = 2 * self.VSS.domain_len 77 | commitsPoints = [ 78 | Point( 79 | int.from_bytes( 80 | commitments[i * point_len : i * point_len + self.VSS.domain_len], 81 | "big", 82 | ), 83 | int.from_bytes( 84 | commitments[ 85 | i * point_len + self.VSS.domain_len : i * point_len 86 | + 2 * self.VSS.domain_len 87 | ], 88 | "big", 89 | ), 90 | self.VSS.curve, 91 | ) 92 | for i in range(2) 93 | ] 94 | Q = Point( 95 | int.from_bytes(point[: self.VSS.domain_len], "big"), 96 | int.from_bytes(point[self.VSS.domain_len : 2 * self.VSS.domain_len], "big"), 97 | self.VSS.curve, 98 | ) 99 | result, shareCommitPoint = self.VSS.pedersen_verify_commit( 100 | Q, share, idx, commitsPoints 101 | ) 102 | shareCommit = bytearray( 103 | shareCommitPoint.x.to_bytes(self.VSS.domain_len, "big") 104 | + shareCommitPoint.y.to_bytes(self.VSS.domain_len, "big") 105 | ) 106 | return result, shareCommit 107 | 108 | def recoverPrepareDataHash(self, publicKey): 109 | backupDataToHash = bytes(self.backupName.encode() + self.userInfo.encode()) 110 | h1 = sha256() 111 | h1.update(backupDataToHash) 112 | backupDataHash = h1.digest() 113 | dataToHash = bytes(publicKey + self.backupId + backupDataHash) 114 | h2 = sha256() 115 | h2.update(dataToHash) 116 | dataHash = h2.digest() 117 | 118 | return dataHash 119 | 120 | def recoverBackupProviderDecrypt(self, encryptedData): 121 | cipher = AES.new(self.sharedKey, AES.MODE_SIV) 122 | plaintext = cipher.decrypt_and_verify(encryptedData[16:], encryptedData[:16]) 123 | 124 | share = plaintext[:96] 125 | idx = int.from_bytes(plaintext[96:100], "little") 126 | deletePublicKey = plaintext[100:165] 127 | commitHash = plaintext[165:] 128 | 129 | return share, idx, deletePublicKey, commitHash 130 | 131 | def recoverDeleteBackup(self, loader, backupPublicKey): 132 | nonce = os.urandom(16) 133 | cipher = AES.new(self.sharedKey, AES.MODE_SIV) 134 | ciphertext, tag = cipher.encrypt_and_digest(nonce) 135 | encryptedSignature = loader.recoverDeleteBackup(tag, ciphertext) 136 | cipher = AES.new(self.sharedKey, AES.MODE_SIV) 137 | signature = cipher.decrypt_and_verify( 138 | encryptedSignature[16:], encryptedSignature[:16] 139 | ) 140 | verifyKey = PublicKey(bytes(backupPublicKey), raw=True) 141 | signature = verifyKey.ecdsa_deserialize(signature) 142 | if not verifyKey.ecdsa_verify(nonce, signature): 143 | raise Exception("Invalid signature") 144 | 145 | def recoverPrepareDataIdv(self, delete=False): 146 | identifiers = [ 147 | (self.backupName, None), 148 | (self.firstName, self.f_tag), 149 | (self.lastName, self.n_tag), 150 | (self.birthDate, self.d_tag), 151 | (self.birthPlace, self.c_tag), 152 | ] 153 | flow = b"\x01" if delete else b"\x00" 154 | 155 | def pack(tup): 156 | identifier, tag = tup 157 | data = struct.pack(">B", tag) if tag is not None else b"" 158 | return ( 159 | data + struct.pack(">B", len(identifier.encode())) + identifier.encode() 160 | ) 161 | 162 | return self.backupId + b"".join(map(pack, identifiers)) + flow 163 | -------------------------------------------------------------------------------- /ledgerblue/resetCustomCA.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import argparse 21 | 22 | 23 | def get_argparser(): 24 | parser = argparse.ArgumentParser( 25 | description="""Remove all Custom CA public keys previously enrolled onto the 26 | device.""" 27 | ) 28 | parser.add_argument( 29 | "--targetId", 30 | help="The device's target ID (default is Ledger Blue)", 31 | type=auto_int, 32 | default=0x31000002, 33 | ) 34 | parser.add_argument("--apdu", help="Display APDU log", action="store_true") 35 | parser.add_argument( 36 | "--rootPrivateKey", 37 | help="""The Signer private key used to establish a Secure Channel (otherwise 38 | a random one will be generated)""", 39 | ) 40 | return parser 41 | 42 | 43 | def auto_int(x): 44 | return int(x, 0) 45 | 46 | 47 | if __name__ == "__main__": 48 | import binascii 49 | 50 | from .comm import getDongle 51 | from .deployed import getDeployedSecretV2 52 | from .ecWrapper import PrivateKey 53 | from .hexLoader import HexLoader 54 | 55 | args = get_argparser().parse_args() 56 | 57 | if args.rootPrivateKey is None: 58 | privateKey = PrivateKey() 59 | publicKey = binascii.hexlify(privateKey.pubkey.serialize(compressed=False)) 60 | print("Generated random root public key : %s" % publicKey) 61 | args.rootPrivateKey = privateKey.serialize() 62 | 63 | dongle = getDongle(args.apdu) 64 | 65 | secret = getDeployedSecretV2( 66 | dongle, bytearray.fromhex(args.rootPrivateKey), args.targetId 67 | ) 68 | loader = HexLoader(dongle, 0xE0, True, secret) 69 | 70 | loader.resetCustomCA() 71 | 72 | dongle.close() 73 | -------------------------------------------------------------------------------- /ledgerblue/runApp.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import argparse 21 | 22 | 23 | def get_argparser(): 24 | parser = argparse.ArgumentParser("Run an application on the device.") 25 | parser.add_argument( 26 | "--targetId", 27 | help="The device's target ID (default is Ledger Blue)", 28 | type=auto_int, 29 | default=0x31000002, 30 | ) 31 | parser.add_argument("--apdu", help="Display APDU log", action="store_true") 32 | parser.add_argument( 33 | "--rootPrivateKey", 34 | help="""The Signer private key used to establish a Secure Channel (otherwise 35 | a random one will be generated)""", 36 | ) 37 | parser.add_argument( 38 | "--appName", help="The name of the application to run", required=True 39 | ) 40 | return parser 41 | 42 | 43 | def auto_int(x): 44 | return int(x, 0) 45 | 46 | 47 | if __name__ == "__main__": 48 | from .ecWrapper import PrivateKey 49 | from .comm import getDongle 50 | from .hexLoader import HexLoader 51 | import binascii 52 | 53 | args = get_argparser().parse_args() 54 | 55 | if args.rootPrivateKey is None: 56 | privateKey = PrivateKey() 57 | publicKey = binascii.hexlify(privateKey.pubkey.serialize(compressed=False)) 58 | print("Generated random root public key : %s" % publicKey) 59 | args.rootPrivateKey = privateKey.serialize() 60 | 61 | dongle = getDongle(args.apdu) 62 | 63 | loader = HexLoader(dongle, 0xE0) 64 | 65 | loader.runApp(args.appName.encode()) 66 | 67 | dongle.close() 68 | -------------------------------------------------------------------------------- /ledgerblue/runScript.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import argparse 21 | 22 | 23 | def get_argparser(): 24 | parser = argparse.ArgumentParser( 25 | description="""Read a sequence of command APDUs from a file and send them to the 26 | device. The file must be formatted as hex, with one CAPDU per line.""" 27 | ) 28 | parser.add_argument("--fileName", help="The name of the APDU script to load") 29 | parser.add_argument("--apdu", help="Display APDU log", action="store_true") 30 | parser.add_argument( 31 | "--scp", help="Open a Secure Channel to exchange APDU", action="store_true" 32 | ) 33 | parser.add_argument( 34 | "--targetId", 35 | help="The device's target ID (default is Ledger Nano S). If --elfFile is used, the targetId from the ELF file will be used instead.", 36 | type=auto_int, 37 | default=0x31100002, 38 | ) 39 | parser.add_argument( 40 | "--elfFile", 41 | help="ELF file from which the target ID is fetched. Overrides '--targetId'", 42 | ) 43 | parser.add_argument( 44 | "--rootPrivateKey", 45 | help="""The Signer private key used to establish a Secure Channel (otherwise 46 | a random one will be generated)""", 47 | ) 48 | return parser 49 | 50 | 51 | def auto_int(x): 52 | return int(x, 0) 53 | 54 | 55 | if __name__ == "__main__": 56 | import binascii 57 | import sys 58 | 59 | from .comm import getDongle 60 | from .deployed import getDeployedSecretV2 61 | from .ecWrapper import PrivateKey 62 | from .hexLoader import HexLoader 63 | from .readElfMetadata import get_target_id_from_elf 64 | 65 | args = get_argparser().parse_args() 66 | 67 | if not args.fileName: 68 | # raise Exception("Missing fileName") 69 | file = sys.stdin 70 | else: 71 | file = open(args.fileName, "r") 72 | 73 | class SCP: 74 | def __init__(self, dongle, targetId, rootPrivateKey): 75 | secret = getDeployedSecretV2(dongle, rootPrivateKey, targetId) 76 | self.loader = HexLoader(dongle, 0xE0, True, secret) 77 | 78 | def encryptAES(self, data): 79 | return self.loader.scpWrap(data) 80 | 81 | def decryptAES(self, data): 82 | return self.loader.scpUnwrap(data) 83 | 84 | dongle = getDongle(args.apdu) 85 | 86 | targetId = args.targetId 87 | 88 | if args.elfFile: 89 | targetId = auto_int(get_target_id_from_elf(args.elfFile)) 90 | 91 | if args.scp: 92 | if args.rootPrivateKey is None: 93 | privateKey = PrivateKey() 94 | publicKey = binascii.hexlify(privateKey.pubkey.serialize(compressed=False)) 95 | print("Generated random root public key : %s" % publicKey) 96 | args.rootPrivateKey = privateKey.serialize() 97 | scp = SCP(dongle, targetId, bytearray.fromhex(args.rootPrivateKey)) 98 | 99 | for data in file: 100 | data = binascii.unhexlify(data.replace("\n", "")) 101 | if len(data) < 5: 102 | continue 103 | if args.scp: 104 | apduData = data[5:] 105 | apduData = scp.encryptAES(bytes(apduData)) 106 | apdu = bytearray( 107 | [data[0], data[1], data[2], data[3], len(apduData)] 108 | ) + bytearray(apduData) 109 | result = dongle.exchange(apdu) 110 | result = scp.decryptAES(result) 111 | else: 112 | result = dongle.exchange(bytearray(data)) 113 | if args.apdu: 114 | print("<= Clear " + str(result)) 115 | 116 | dongle.close() 117 | -------------------------------------------------------------------------------- /ledgerblue/setupCustomCA.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import argparse 21 | 22 | 23 | def get_argparser(): 24 | parser = argparse.ArgumentParser( 25 | description="Enroll a Custom CA public key onto the device." 26 | ) 27 | parser.add_argument( 28 | "--targetId", 29 | help="The device's target ID (default is Ledger Blue)", 30 | type=auto_int, 31 | default=0x31000002, 32 | ) 33 | parser.add_argument("--apdu", help="Display APDU log", action="store_true") 34 | parser.add_argument( 35 | "--rootPrivateKey", 36 | help="""The Signer private key used to establish a Secure Channel (otherwise 37 | a random one will be generated)""", 38 | ) 39 | parser.add_argument( 40 | "--public", 41 | help="The Custom CA public key to be enrolled (hex encoded)", 42 | required=True, 43 | ) 44 | parser.add_argument( 45 | "--name", 46 | help="""The name to assign to the Custom CA (this will be displayed on screen upon 47 | auth requests)""", 48 | required=True, 49 | ) 50 | return parser 51 | 52 | 53 | def auto_int(x): 54 | return int(x, 0) 55 | 56 | 57 | if __name__ == "__main__": 58 | import binascii 59 | 60 | from .comm import getDongle 61 | from .deployed import getDeployedSecretV2 62 | from .ecWrapper import PrivateKey 63 | from .hexLoader import HexLoader 64 | 65 | args = get_argparser().parse_args() 66 | 67 | if args.rootPrivateKey is None: 68 | privateKey = PrivateKey() 69 | publicKey = binascii.hexlify(privateKey.pubkey.serialize(compressed=False)) 70 | print("Generated random root public key : %s" % publicKey) 71 | args.rootPrivateKey = privateKey.serialize() 72 | 73 | public = bytearray.fromhex(args.public) 74 | 75 | dongle = getDongle(args.apdu) 76 | 77 | secret = getDeployedSecretV2( 78 | dongle, bytearray.fromhex(args.rootPrivateKey), args.targetId 79 | ) 80 | loader = HexLoader(dongle, 0xE0, True, secret) 81 | 82 | loader.setupCustomCA(args.name, public) 83 | 84 | dongle.close() 85 | -------------------------------------------------------------------------------- /ledgerblue/signApp.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | print("Use loadApp with --offline --signApp --signPrivateKey key (hex encoded) instead") 21 | -------------------------------------------------------------------------------- /ledgerblue/updateFirmware.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import argparse 21 | import ssl 22 | 23 | 24 | def get_argparser(): 25 | parser = argparse.ArgumentParser( 26 | "Update the firmware by using Ledger to open a Secure Channel." 27 | ) 28 | parser.add_argument( 29 | "--url", 30 | help="Server URL", 31 | default="https://hsmprod.hardwarewallet.com/hsm/process", 32 | ) 33 | parser.add_argument( 34 | "--bypass-ssl-check", 35 | help="Keep going even if remote certificate verification fails", 36 | action="store_true", 37 | default=False, 38 | ) 39 | parser.add_argument("--apdu", help="Display APDU log", action="store_true") 40 | parser.add_argument( 41 | "--perso", 42 | help="""A reference to the personalization key; this is a reference to the specific 43 | Issuer keypair used by Ledger to sign the device's Issuer Certificate""", 44 | default="perso_11", 45 | ) 46 | parser.add_argument( 47 | "--firmware", help="A reference to the firmware to load", required=True 48 | ) 49 | parser.add_argument( 50 | "--targetId", 51 | help="The device's target ID (default is Ledger Blue)", 52 | type=auto_int, 53 | default=0x31000002, 54 | ) 55 | parser.add_argument( 56 | "--firmwareKey", help="A reference to the firmware key to use", required=True 57 | ) 58 | return parser 59 | 60 | 61 | def auto_int(x): 62 | return int(x, 0) 63 | 64 | 65 | def serverQuery(request, url): 66 | data = request.SerializeToString() 67 | urll = urlparse.urlparse(args.url) 68 | req = urllib2.Request(args.url, data, {"Content-type": "application/octet-stream"}) 69 | if args.bypass_ssl_check: 70 | res = urllib2.urlopen(req, context=ssl._create_unverified_context()) 71 | else: 72 | res = urllib2.urlopen(req) 73 | data = res.read() 74 | response = Response() 75 | response.ParseFromString(data) 76 | if len(response.exception) != 0: 77 | raise Exception(response.exception) 78 | return response 79 | 80 | 81 | if __name__ == "__main__": 82 | import struct 83 | import urllib.request as urllib2 84 | import urllib.parse as urlparse 85 | from .BlueHSMServer_pb2 import Request, Response 86 | from .comm import getDongle 87 | 88 | args = get_argparser().parse_args() 89 | 90 | dongle = getDongle(args.apdu) 91 | 92 | # Identify 93 | 94 | targetid = bytearray(struct.pack(">I", args.targetId)) 95 | apdu = bytearray([0xE0, 0x04, 0x00, 0x00]) + bytearray([len(targetid)]) + targetid 96 | dongle.exchange(apdu) 97 | 98 | # Get nonce and ephemeral key 99 | 100 | request = Request() 101 | request.reference = "distributeFirmware11_scan" 102 | parameter = request.remote_parameters.add() 103 | parameter.local = False 104 | parameter.alias = "persoKey" 105 | parameter.name = args.perso 106 | if args.targetId & 0xF >= 0x3: 107 | parameter = request.remote_parameters.add() 108 | parameter.local = False 109 | parameter.alias = "scpv2" 110 | parameter.name = "dummy" 111 | request.largeStack = True 112 | 113 | response = serverQuery(request, args.url) 114 | 115 | offset = 0 116 | 117 | remotePublicKey = response.response[offset : offset + 65] 118 | offset += 65 119 | nonce = response.response[offset : offset + 8] 120 | if args.targetId & 0xF >= 0x3: 121 | offset += 8 122 | masterPublicKey = response.response[offset : offset + 65] 123 | offset += 65 124 | masterPublicKeySignatureLength = response.response[offset + 1] + 2 125 | masterPublicKeySignature = response.response[ 126 | offset : offset + masterPublicKeySignatureLength 127 | ] 128 | 129 | # Initialize chain 130 | 131 | apdu = bytearray([0xE0, 0x50, 0x00, 0x00, 0x08]) + nonce 132 | deviceInit = dongle.exchange(apdu) 133 | deviceNonce = deviceInit[4 : 4 + 8] 134 | 135 | # Get remote certificate 136 | 137 | request = Request() 138 | request.reference = "distributeFirmware11_scan" 139 | request.id = response.id 140 | parameter = request.remote_parameters.add() 141 | parameter.local = False 142 | parameter.alias = "persoKey" 143 | parameter.name = args.perso 144 | request.parameters = bytes(deviceNonce) 145 | request.largeStack = True 146 | 147 | response = serverQuery(request, args.url) 148 | 149 | offset = 0 150 | 151 | responseLength = response.response[offset + 1] 152 | remotePublicKeySignatureLength = responseLength + 2 153 | remotePublicKeySignature = response.response[ 154 | offset : offset + remotePublicKeySignatureLength 155 | ] 156 | 157 | certificate = ( 158 | bytearray([len(remotePublicKey)]) 159 | + remotePublicKey 160 | + bytearray([len(remotePublicKeySignature)]) 161 | + remotePublicKeySignature 162 | ) 163 | apdu = ( 164 | bytearray([0xE0, 0x51, 0x80, 0x00]) 165 | + bytearray([len(certificate)]) 166 | + certificate 167 | ) 168 | dongle.exchange(apdu) 169 | 170 | # Walk the chain 171 | 172 | index = 0 173 | while True: 174 | if index == 0: 175 | certificate = bytearray(dongle.exchange(bytearray.fromhex("E052000000"))) 176 | elif index == 1: 177 | certificate = bytearray(dongle.exchange(bytearray.fromhex("E052800000"))) 178 | else: 179 | break 180 | if len(certificate) == 0: 181 | break 182 | request = Request() 183 | request.reference = "distributeFirmware11_scan" 184 | request.id = response.id 185 | request.parameters = bytes(certificate) 186 | request.largeStack = True 187 | serverQuery(request, args.url) 188 | index += 1 189 | 190 | # Commit agreement and send firmware 191 | 192 | request = Request() 193 | request.reference = "distributeFirmware11_scan" 194 | if args.targetId & 0xF >= 0x3: 195 | parameter = request.remote_parameters.add() 196 | parameter.local = False 197 | parameter.alias = "scpv2" 198 | parameter.name = "dummy" 199 | request.id = response.id 200 | request.largeStack = True 201 | 202 | response = serverQuery(request, args.url) 203 | responseData = bytearray(response.response) 204 | 205 | dongle.exchange(bytearray.fromhex("E053000000")) 206 | 207 | for i in range(100): 208 | if len(responseData) == 0: 209 | break 210 | if bytes(responseData[0:4]) == b"SECU": 211 | raise Exception("Security exception " + chr(responseData[4])) 212 | 213 | responseData = dongle.exchange(responseData) 214 | 215 | request = Request() 216 | request.reference = "distributeFirmware11_scan" 217 | request.parameters = b"\xff" + b"\xff" + bytes(responseData) 218 | request.id = response.id 219 | request.largeStack = True 220 | 221 | response = serverQuery(request, args.url) 222 | responseData = bytearray(response.response) 223 | 224 | request = Request() 225 | request.reference = "distributeFirmware11_scan" 226 | parameter = request.remote_parameters.add() 227 | parameter.local = False 228 | parameter.alias = "firmware" 229 | parameter.name = args.firmware 230 | parameter = request.remote_parameters.add() 231 | parameter.local = False 232 | parameter.alias = "firmwareKey" 233 | parameter.name = args.firmwareKey 234 | request.id = response.id 235 | request.largeStack = True 236 | 237 | response = serverQuery(request, args.url) 238 | responseData = bytearray(response.response) 239 | 240 | offset = 0 241 | while offset < len(responseData): 242 | apdu = responseData[offset : offset + 5 + responseData[offset + 4]] 243 | dongle.exchange(apdu) 244 | offset += 5 + responseData[offset + 4] 245 | 246 | dongle.close() 247 | -------------------------------------------------------------------------------- /ledgerblue/updateFirmware2.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import argparse 21 | 22 | 23 | def get_argparser(): 24 | parser = argparse.ArgumentParser( 25 | "Update the firmware by using Ledger to open a Secure Channel." 26 | ) 27 | parser.add_argument( 28 | "--url", 29 | help="Websocket URL", 30 | default="wss://scriptrunner.api.live.ledger.com/update/install", 31 | ) 32 | parser.add_argument( 33 | "--bypass-ssl-check", 34 | help="Keep going even if remote certificate verification fails", 35 | action="store_true", 36 | default=False, 37 | ) 38 | parser.add_argument("--apdu", help="Display APDU log", action="store_true") 39 | parser.add_argument( 40 | "--perso", 41 | help="""A reference to the personalization key; this is a reference to the specific 42 | Issuer keypair used by Ledger to sign the device's Issuer Certificate""", 43 | default="perso_11", 44 | ) 45 | parser.add_argument( 46 | "--firmware", help="A reference to the firmware to load", required=True 47 | ) 48 | parser.add_argument( 49 | "--targetId", 50 | help="The device's target ID (default is Ledger Blue)", 51 | type=auto_int, 52 | default=0x31000002, 53 | ) 54 | parser.add_argument( 55 | "--firmwareKey", help="A reference to the firmware key to use", required=True 56 | ) 57 | return parser 58 | 59 | 60 | def auto_int(x): 61 | return int(x, 0) 62 | 63 | 64 | def process(dongle, request): 65 | response = {} 66 | apdusList = [] 67 | try: 68 | response["nonce"] = request["nonce"] 69 | if request["query"] == "exchange": 70 | apdusList.append(binascii.unhexlify(request["data"])) 71 | elif request["query"] == "bulk": 72 | for apdu in request["data"]: 73 | apdusList.append(binascii.unhexlify(apdu)) 74 | else: 75 | response["response"] = "unsupported" 76 | except: 77 | response["response"] = "parse error" 78 | 79 | if len(apdusList) != 0: 80 | try: 81 | for apdu in apdusList: 82 | response["data"] = dongle.exchange(apdu).hex() 83 | response["response"] = "success" 84 | except: 85 | response["response"] = "I/O" # or error, and SW in data 86 | 87 | return response 88 | 89 | 90 | if __name__ == "__main__": 91 | import urllib.parse as urlparse 92 | from .comm import getDongle 93 | from websocket import create_connection 94 | import json 95 | import binascii 96 | import ssl 97 | 98 | args = get_argparser().parse_args() 99 | 100 | dongle = getDongle(args.apdu) 101 | 102 | url = args.url 103 | queryParameters = {} 104 | queryParameters["targetId"] = args.targetId 105 | queryParameters["firmware"] = args.firmware 106 | queryParameters["firmwareKey"] = args.firmwareKey 107 | queryParameters["perso"] = args.perso 108 | queryString = urlparse.urlencode(queryParameters) 109 | if args.bypass_ssl_check: 110 | # SEE: https://docs.python.org/3/library/ssl.html#ssl.CERT_NONE 111 | # According to the documentation: 112 | # > With client-side sockets, just about any cert is accepted. Validation errors, such 113 | # > as untrusted or expired cert, are ignored and do not abort the TLS/SSL handshake. 114 | sslopt = {"cert_reqs": ssl.CERT_NONE} 115 | else: 116 | sslopt = {} 117 | ws = create_connection(args.url + "?" + queryString, sslopt=sslopt) 118 | while True: 119 | result = json.loads(ws.recv()) 120 | if result["query"] == "success": 121 | break 122 | if result["query"] == "error": 123 | raise Exception( 124 | result["data"] + " on " + result["uuid"] + "/" + result["session"] 125 | ) 126 | response = process(dongle, result) 127 | ws.send(json.dumps(response)) 128 | ws.close() 129 | 130 | print("Script executed successfully") 131 | 132 | dongle.close() 133 | -------------------------------------------------------------------------------- /ledgerblue/verifyApp.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import argparse 21 | 22 | 23 | def get_argparser(): 24 | parser = argparse.ArgumentParser("""Verify that the provided signature is a valid signature of the provided 25 | application.""") 26 | parser.add_argument( 27 | "--hex", help="The hex file of the signed application", required=True 28 | ) 29 | parser.add_argument( 30 | "--key", 31 | help="The Custom CA public key with which to verify the signature (hex encoded)", 32 | required=True, 33 | ) 34 | parser.add_argument( 35 | "--signature", help="The signature to be verified (hex encoded)", required=True 36 | ) 37 | return parser 38 | 39 | 40 | def auto_int(x): 41 | return int(x, 0) 42 | 43 | 44 | if __name__ == "__main__": 45 | from .hexParser import IntelHexParser 46 | from .ecWrapper import PublicKey 47 | import hashlib 48 | 49 | args = get_argparser().parse_args() 50 | 51 | # parse 52 | parser = IntelHexParser(args.hex) 53 | 54 | # prepare data 55 | m = hashlib.sha256() 56 | # consider areas are ordered by ascending address and non-overlaped 57 | for a in parser.getAreas(): 58 | m.update(a.data) 59 | dataToSign = m.digest() 60 | 61 | publicKey = PublicKey(bytes(bytearray.fromhex(args.key)), raw=True) 62 | signature = publicKey.ecdsa_deserialize(bytes(bytearray.fromhex(args.signature))) 63 | if not publicKey.ecdsa_verify(bytes(dataToSign), signature, raw=True): 64 | raise Exception("Signature not verified") 65 | 66 | print("Signature verified") 67 | -------------------------------------------------------------------------------- /ledgerblue/verifyEndorsement1.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import argparse 21 | 22 | 23 | def get_argparser(): 24 | parser = argparse.ArgumentParser( 25 | description="Verify a message signature created with Endorsement Scheme #1." 26 | ) 27 | parser.add_argument( 28 | "--key", 29 | help="The endorsement public key with which to verify the signature (hex encoded)", 30 | required=True, 31 | ) 32 | parser.add_argument( 33 | "--codehash", 34 | help="The hash of the app associated with the endorsement request (hex encoded)", 35 | required=True, 36 | ) 37 | parser.add_argument( 38 | "--message", 39 | help="The message associated to the endorsement request (hex encoded)", 40 | required=True, 41 | ) 42 | parser.add_argument( 43 | "--signature", help="The signature to be verified (hex encoded)", required=True 44 | ) 45 | return parser 46 | 47 | 48 | if __name__ == "__main__": 49 | import hashlib 50 | 51 | from .ecWrapper import PublicKey 52 | 53 | args = get_argparser().parse_args() 54 | 55 | # prepare data 56 | m = hashlib.sha256() 57 | m.update(bytes(bytearray.fromhex(args.message))) 58 | m.update(bytes(bytearray.fromhex(args.codehash))) 59 | digest = m.digest() 60 | 61 | publicKey = PublicKey(bytes(bytearray.fromhex(args.key)), raw=True) 62 | signature = publicKey.ecdsa_deserialize(bytes(bytearray.fromhex(args.signature))) 63 | if not publicKey.ecdsa_verify(bytes(digest), signature, raw=True): 64 | raise Exception("Endorsement not verified") 65 | 66 | print("Endorsement verified") 67 | -------------------------------------------------------------------------------- /ledgerblue/verifyEndorsement2.py: -------------------------------------------------------------------------------- 1 | """ 2 | ******************************************************************************* 3 | * Ledger Blue 4 | * (c) 2016 Ledger 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | ******************************************************************************** 18 | """ 19 | 20 | import argparse 21 | 22 | 23 | def get_argparser(): 24 | parser = argparse.ArgumentParser( 25 | description="Verify a message signature created with Endorsement Scheme #2." 26 | ) 27 | parser.add_argument( 28 | "--key", 29 | help="The endorsement public key with which to verify the signature (hex encoded)", 30 | required=True, 31 | ) 32 | parser.add_argument( 33 | "--codehash", 34 | help="The hash of the app associated with the endorsement request (hex encoded)", 35 | required=True, 36 | ) 37 | parser.add_argument( 38 | "--message", 39 | help="The message associated to the endorsement request (hex encoded)", 40 | required=True, 41 | ) 42 | parser.add_argument( 43 | "--signature", help="The signature to be verified (hex encoded)", required=True 44 | ) 45 | return parser 46 | 47 | 48 | if __name__ == "__main__": 49 | import hashlib 50 | import hmac 51 | 52 | from .ecWrapper import PublicKey 53 | 54 | args = get_argparser().parse_args() 55 | 56 | # prepare data 57 | tweak = hmac.new( 58 | bytes(bytearray.fromhex(args.codehash)), 59 | bytes(bytearray.fromhex(args.key)), 60 | hashlib.sha256, 61 | ).digest() 62 | m = hashlib.sha256() 63 | m.update(bytes(bytearray.fromhex(args.message))) 64 | digest = m.digest() 65 | 66 | publicKey = PublicKey(bytes(bytearray.fromhex(args.key)), raw=True) 67 | publicKey.tweak_add(bytes(tweak)) 68 | signature = publicKey.ecdsa_deserialize(bytes(bytearray.fromhex(args.signature))) 69 | if not publicKey.ecdsa_verify(bytes(digest), signature, raw=True): 70 | raise Exception("Endorsement not verified") 71 | 72 | print("Endorsement verified") 73 | -------------------------------------------------------------------------------- /ledgerblue/vss.py: -------------------------------------------------------------------------------- 1 | from ecpy.curves import Curve, Point 2 | 3 | 4 | class PedersenVSS: 5 | def __init__(self, curve: Curve): 6 | self.curve = curve 7 | self.P = Point(curve.generator.x, curve.generator.y, curve) 8 | self.domain_len = curve.generator.x.bit_length() // 8 9 | 10 | def pedersen_commit(self, Q: Point, a: int, b: int) -> Point: 11 | point1 = self.curve.mul_point(a, self.P) 12 | point2 = self.curve.mul_point(b, Q) 13 | 14 | return self.curve.add_point(point1, point2) 15 | 16 | def pedersen_share_commit(self, Q: Point, share: bytes) -> Point: 17 | a = int.from_bytes(share[: self.domain_len], "big") 18 | b = int.from_bytes(share[self.domain_len :], "big") 19 | return self.pedersen_commit(Q, a, b) 20 | 21 | def pedersen_verify_commit(self, Q: Point, share: bytes, index: int, commits: list): 22 | s_point = self.pedersen_share_commit(Q, share) 23 | 24 | r_point = commits[0] 25 | 26 | for i in range(1, len(commits)): 27 | r = self.curve.mul_point(index**i, commits[i]) 28 | r_point = self.curve.add_point(r_point, r) 29 | 30 | return s_point == r_point, s_point 31 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = [ 3 | "setuptools>=75", 4 | "setuptools_scm[toml]>=6.2", 5 | "wheel" 6 | ] 7 | build-backend = "setuptools.build_meta" 8 | 9 | [project] 10 | name = "ledgerblue" 11 | authors = [ 12 | { name = "Ledger", email = "hello@ledger.fr" } 13 | ] 14 | description = "Python library to communicate with Ledger devices" 15 | readme = { file = "README.md", content-type = "text/markdown" } 16 | license = { file = "LICENSE" } 17 | classifiers = [ 18 | "License :: OSI Approved :: Apache Software License", 19 | "Operating System :: POSIX :: Linux", 20 | "Operating System :: Microsoft :: Windows", 21 | "Operating System :: MacOS :: MacOS X", 22 | "Programming Language :: Python :: 3", 23 | "Programming Language :: Python :: 3 :: Only", 24 | "Programming Language :: Python :: 3.8", 25 | "Programming Language :: Python :: 3.9", 26 | "Programming Language :: Python :: 3.10", 27 | "Programming Language :: Python :: 3.11", 28 | "Programming Language :: Python :: 3.12", 29 | "Programming Language :: Python :: 3.13", 30 | ] 31 | dynamic = [ "version" ] 32 | requires-python = ">=3.8" 33 | dependencies = [ 34 | "pyelftools>=0.29,<1.0", 35 | "hidapi>=0.7.99", 36 | "protobuf >=5", 37 | "pycryptodomex>=3.6.1", 38 | "future", 39 | "ecpy>=0.9.0", 40 | "pillow>=3.4.0", 41 | "python-u2flib-host>=3.0.2", 42 | "websocket_client>=0.56.0", 43 | "nfcpy>=1.0.4", 44 | "bleak>=0.20.1", 45 | "pycryptodome>=3.18.0", 46 | "python-gnupg>=0.5.0" 47 | ] 48 | 49 | [tool.setuptools] 50 | packages = ["ledgerblue"] 51 | include-package-data = false 52 | 53 | [project.urls] 54 | Home = "https://github.com/LedgerHQ/blue-loader-python" 55 | 56 | [project.optional-dependencies] 57 | smartcard = [ 58 | "python-pyscard>=1.6.12" 59 | ] 60 | doc = [ 61 | "sphinx", 62 | "sphinx_rtd_theme", 63 | "sphinx_argparse" 64 | ] 65 | dev = [ 66 | "pre-commit==3.2.0", 67 | "ruff==0.3.7" 68 | ] 69 | 70 | [tool.setuptools_scm] 71 | write_to = "ledgerblue/__version__.py" 72 | local_scheme = "no-local-version" 73 | fallback_version = "0.0.0" 74 | -------------------------------------------------------------------------------- /ruff.toml: -------------------------------------------------------------------------------- 1 | [lint] 2 | # Using rules from: pycodestyle, Pyflake and isort 3 | # INP001 __init__ files check on package 4 | select = [ "E", "F", "I", "INP001"] 5 | 6 | 7 | [lint.per-file-ignores] 8 | "!ledgerblue/*" = ["INP001"] 9 | --------------------------------------------------------------------------------