sequoia-tpm-0.1.1/.cargo_vcs_info.json0000644000000001360000000000100132770ustar { "git": { "sha1": "410c483ec90e78903b56db827cb5809ee047f44d" }, "path_in_vcs": "" }sequoia-tpm-0.1.1/.dockerignore000064400000000000000000000001211046102023000145350ustar 00000000000000target NVChip # YML are key formats, don't send them to avoid dirty builds *.yml sequoia-tpm-0.1.1/.gitignore000064400000000000000000000000621046102023000140550ustar 00000000000000.dir-locals* /target NVChip .#* \#* README.sh keyssequoia-tpm-0.1.1/.gitlab-ci.yml000064400000000000000000000022251046102023000145240ustar 00000000000000image: "rust@sha256:86bb2e39e20f602b169ade0bc5cff7460a49af2f60b9aefc390db48eb888d20a" build: image: docker:stable # When using dind, it's wise to use the overlayfs driver for # improved performance. variables: DOCKER_DRIVER: overlay2 services: - docker:dind before_script: - docker info script: - docker build . pages: script: - apt-get update -yqq - apt-get install -yqq --no-install-recommends emacs org-mode texlive-latex-extra texlive-latex-base texlive-generic-recommended texlive-fonts-recommended - emacs -Q --batch README.org -f org-latex-export-to-pdf - curl -o /etc/emacs/htmlize.el https://raw.githubusercontent.com/hniksic/emacs-htmlize/master/htmlize.el - emacs -Q --batch README.org --eval "(load \"/etc/emacs/htmlize.el\")" -f org-html-export-to-html - emacs -Q --batch CONTRIBUTING.org --eval "(load \"/etc/emacs/htmlize.el\")" -f org-html-export-to-html - mkdir public - mv README.html public/index.html - mv README.pdf public - mv CONTRIBUTING.html public/contributing.html artifacts: paths: - README.pdf - public rules: - if: '$CI_COMMIT_BRANCH == "main"' sequoia-tpm-0.1.1/CONTRIBUTING.org000064400000000000000000000025021046102023000145060ustar 00000000000000#+TITLE: Contributing #+HTML_HEAD: * Contributing :PROPERTIES: :CUSTOM_ID: contributing :END: Thank you for considering a contribution to this project! All changes will need to: - build successfully with =docker build .=, - be signed-off, - have good commit messages. Additionally changes that are not backwards-compatible (for example changing or removing API) need to first be discussed using issues. ** Build :PROPERTIES: :CUSTOM_ID: build :END: =docker build .= will perform all necessary checks including lints and integration tests ** Commit messages :PROPERTIES: :CUSTOM_ID: commit-messages :END: Commit messages should be self-contained and describe the motivation for a change. The subject line should be short, with any elaborations in the body. If the commit closes an issue, write =Closes #issuenumber= at the end of the body. Keep in mind [[https://chris.beams.io/posts/git-commit/][the seven rules of a great Git commit message]]: 1. Separate subject from body with a blank line 2. Limit the subject line to 50 characters 3. Capitalize the subject line 4. Do not end the subject line with a period 5. Use the imperative mood in the subject line 6. Wrap the body at 72 characters 7. Use the body to explain what and why vs. how sequoia-tpm-0.1.1/Cargo.toml0000644000000026450000000000100113040ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" rust-version = "1.77" name = "sequoia-tpm" version = "0.1.1" authors = [ "Neal H. Walfield ", "Wiktor Kwapisiewicz ", ] build = false autobins = false autoexamples = false autotests = false autobenches = false description = "Machinery for working with TPM from Sequoia" homepage = "https://sequoia-pgp.org/" documentation = "https://docs.rs/sequoia-tpm" readme = "README.org" keywords = [ "cryptography", "openpgp", "pgp", "tpm", ] categories = ["cryptography"] license = "LGPL-2.0-or-later AND Apache-2.0" repository = "https://gitlab.com/sequoia-pgp/sequoia-tpm" [lib] name = "sequoia_tpm" path = "src/lib.rs" [dependencies.hex] version = "0.4.3" [dependencies.serde] version = "1" [dependencies.tss-esapi] version = "7" [dependencies.tss-esapi-sys] version = "0.5" [badges.gitlab] repository = "sequoia-pgp/sequoia-tpm" [badges.maintenance] status = "actively-developed" sequoia-tpm-0.1.1/Cargo.toml.orig000064400000000000000000000014111046102023000147530ustar 00000000000000[workspace] members = ["tools"] [package] name = "sequoia-tpm" description = "Machinery for working with TPM from Sequoia" version = "0.1.1" authors = [ "Neal H. Walfield ", "Wiktor Kwapisiewicz ", ] documentation = "https://docs.rs/sequoia-tpm" homepage = "https://sequoia-pgp.org/" repository = "https://gitlab.com/sequoia-pgp/sequoia-tpm" readme = "README.org" keywords = ["cryptography", "openpgp", "pgp", "tpm"] categories = ["cryptography" ] license = "LGPL-2.0-or-later AND Apache-2.0" edition = "2018" rust-version = "1.77" [badges] gitlab = { repository = "sequoia-pgp/sequoia-tpm" } maintenance = { status = "actively-developed" } [dependencies] tss-esapi = "7" tss-esapi-sys = "0.5" serde = "1" hex = "0.4.3" sequoia-tpm-0.1.1/Dockerfile000064400000000000000000000021531046102023000140620ustar 00000000000000FROM ghcr.io/tpm2-software/ubuntu-22.04:latest # Install Rust toolchain RUN curl https://sh.rustup.rs -sSf | bash -s -- -y ENV PATH="/root/.cargo/bin:${PATH}" RUN apt-get update -y -qq && \ apt-get install --assume-yes --no-install-recommends \ ca-certificates \ clang \ emacs \ libclang-dev \ libsofthsm2 \ libsqlite3-dev \ libssl-dev \ nettle-dev \ make \ org-mode \ pkg-config \ libtss2-dev \ tpm2-tools \ && \ apt-get clean COPY Cargo.toml Cargo.lock /app/ COPY tools /app/tools WORKDIR /app RUN mkdir .cargo RUN mkdir src RUN touch src/main.rs RUN cargo vendor > .cargo/config COPY src /app/src RUN rm src/main.rs RUN cargo build -p sequoia-tpm-tools COPY README.org /app/ RUN emacs -Q --batch --eval " \ (progn \ (require 'ob-tangle) \ (dolist (file command-line-args-left) \ (with-current-buffer (find-file-noselect file) \ (org-babel-tangle))))" README.org RUN /bin/bash -x ./README.sh RUN cargo test RUN cargo clippy -- -A clippy::style -A clippy::complexity sequoia-tpm-0.1.1/LICENSE-APACHE000064400000000000000000000261361046102023000140230ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. sequoia-tpm-0.1.1/LICENSE-LGPL2000064400000000000000000000627341046102023000137260ustar 00000000000000Sequoia PGP is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. Sequoia PGP is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. --- GNU LIBRARY GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1991 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the library GPL. It is numbered 2 because it goes with version 2 of the ordinary GPL.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Library General Public License, applies to some specially designated Free Software Foundation software, and to any other libraries whose authors decide to use it. You can use it for your libraries, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library, or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link a program with the library, you must provide complete object files to the recipients so that they can relink them with the library, after making changes to the library and recompiling it. And you must show them these terms so they know their rights. Our method of protecting your rights has two steps: (1) copyright the library, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the library. Also, for each distributor's protection, we want to make certain that everyone understands that there is no warranty for this free library. If the library is modified by someone else and passed on, we want its recipients to know that what they have is not the original version, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that companies distributing free software will individually obtain patent licenses, thus in effect transforming the program into proprietary software. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License, which was designed for utility programs. This license, the GNU Library General Public License, applies to certain designated libraries. This license is quite different from the ordinary one; be sure to read it in full, and don't assume that anything in it is the same as in the ordinary license. The reason we have a separate public license for some libraries is that they blur the distinction we usually make between modifying or adding to a program and simply using it. Linking a program with a library, without changing the library, is in some sense simply using the library, and is analogous to running a utility program or application program. However, in a textual and legal sense, the linked executable is a combined work, a derivative of the original library, and the ordinary General Public License treats it as such. Because of this blurred distinction, using the ordinary General Public License for libraries did not effectively promote software sharing, because most developers did not use the libraries. We concluded that weaker conditions might promote sharing better. However, unrestricted linking of non-free programs would deprive the users of those programs of all benefit from the free status of the libraries themselves. This Library General Public License is intended to permit developers of non-free programs to use free libraries, while preserving your freedom as a user of such programs to change the free libraries that are incorporated in them. (We have not seen how to achieve this as regards changes in header files, but we have achieved it as regards changes in the actual functions of the Library.) The hope is that this will lead to faster development of free libraries. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, while the latter only works together with the library. Note that it is possible for a library to be covered by the ordinary General Public License rather than by this special one. GNU LIBRARY GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Library General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also compile or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. c) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. d) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Library General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! sequoia-tpm-0.1.1/README.org000064400000000000000000000754261046102023000135530ustar 00000000000000#+TITLE: TPM for OpenPGP #+HTML_HEAD: #+PROPERTY: header-args :tangle yes :exports both This crate implements bindings so that TPM chips can be used with OpenPGP applications. * Basic key usage First, we assume that we'll use TPM 2 simulator package. If you want to test on real device set ~TCTI~ to ~device:/dev/tpmrm0~. #+begin_src sh set -e set -o pipefail tpm_server & sleep 5 tpm2_startup -c -T mssim TCTI=mssim: PATH=$PATH:./target/debug # Increase verbosity of commands export RUST_LOG=info #+end_src To generate a number of random bytes using the specified TPM: #+begin_src sh :var TCTI="device:/dev/tpmrm0" PATH="./target/debug" :exports both draw-bytes --tcti $TCTI #+end_src #+RESULTS: : 46d2f84712cefc51c8bc124354f7daa0fecd2f6066963ab15b6b50a63248dd90 ** Creating persistent keys This crate uses descriptive documents for configuring key properties. *** RSA The following configuration creates RSA-2048 signing key and persists it at the handle ~0x01000027~. ~123~ is used as a sample auth value (PIN). #+BEGIN_SRC yaml :tangle key.yml spec: provider: tpm: tcti: "mssim:" handle: 0x81000027 algo: RSA: bits: 2048 capabilities: - sign auth: 123 #+END_SRC The key description (~key.yml~) is being read by the ~create-key~ binary that persists that key: #+BEGIN_SRC sh create-key -f key.yml #+END_SRC Presence of the key can be checked by using ~tpm2_getcap handles-persistent~ command from TSS suite of tools. And the same file is used to retrieve it again using ~get-key~ binary: #+BEGIN_SRC sh get-key -f key.yml #+END_SRC #+RESULTS: : public_key: : RSA: : bytes: a6235b59c325e5f92752bf9e30b2b2f4cedab2ed43375e0be4fb0904775d0ef77f8385d338ded56ed4fbfae4edeb17cd56b81db28683a515aef7004a5f39dfe3c2c13d604f93c6345ab209efdb1b6ad1a5949b1d8d195b2854e1c2ee7d975bc5616b98913630c2915ed0a8574e86082deb960fa20f623155fd9c78c4ecb84c70dd05b60900c57397ab77c36fddb83870a65ea3e31d539cf9b9ca82ac6def43e9508e0ff4ecaf6a186974fd226b6d0af3eae2b91330cdc27303dbbca38ecb73b7844ee42c3994b854e6dcfe30a1c433cb5c432a9f261999ff0cffaa38b068c0c1110ad97a99042f6cea0d65c43ff684b7ba45e95ddbb05110b8c9d560cd7f5331 : manu: 1229081888 : name: 000b6c69b7da1d7391d0046fa805915520adb39bb419554c881cfdfee56b69d6d68d We can turn this into a not quite valid OpenPGP certificate using the ~get-openpgp-key~ binary: #+BEGIN_SRC sh get-openpgp-key -f key.yml #+END_SRC #+RESULTS: : -----BEGIN PGP PUBLIC KEY BLOCK----- : : xsBNBAAAAAABCADYAHeYhUkqnjcSiAu67+NINl7/ObsPq/kiYuAbPZbvxyOrae7i : 4yoMpGh+BWIYL/Q0PL063lCRvLTiIMAsx0HDl2Xlo4SQxp3ae/rYrgsbUh7Efzf6 : +zsFcGGBVUQe1RbWseDAmpcGWAClTZg3/Eqe87nVaLTvac5Ns2CXwxs1d150PEP+ : 8ZWR8M9ERRH1Yess7MPF88GJEuoGBQACbDOFSGgs6JQxPlSEbg5LPkISUMmoROZ8 : 5HDpCfS3ofBluDw5EWRSj9EuCkWBNAUA4saGM0IwS161bfCecIPAqCaFPD7PQ2KU : 4sBq1wkOdLpveOdFDGAC2A7hXn6h82S8OfBxABEBAAE= : =bZUC : -----END PGP PUBLIC KEY BLOCK----- Creating decryption key is just as strightforward: #+BEGIN_SRC yaml :tangle decryption.yml spec: provider: tpm: tcti: "mssim:" handle: 0x81000018 algo: RSA: bits: 2048 capabilities: - decrypt auth: 123 #+END_SRC #+BEGIN_SRC sh create-key -f decryption.yml #+END_SRC *** EC: NIST-P256 The following configuration creates NIST-P256 signing key and persists it at the handle ~0x01000127~. ~123~ is used as a sample auth value (PIN). #+BEGIN_SRC yaml :tangle key-nist-p256.yml spec: provider: tpm: tcti: "mssim:" handle: 0x81000127 algo: EC: curve: NIST-P256 capabilities: - sign auth: 123 #+END_SRC The key description (~key-nist-p256.yml~) is being read by the ~create-key~ binary that persists that key: #+BEGIN_SRC sh create-key -f key-nist-p256.yml #+END_SRC Presence of the key can be checked by using ~tpm2_getcap handles-persistent~ command from TSS suite of tools. And the same file is used to retrieve it again using ~get-key~ binary: #+BEGIN_SRC sh get-key -f key-nist-p256.yml #+END_SRC #+RESULTS: : public_key: : EC: : x: b998133e8339fc3680808ef64c41fdceb791ccc0c4e1906b99bfd134e59be38c : y: 830dc6c759441d30c843f1d5e27d5afa65dd6190359498bd57d3b5c984704ae9 : manu: 1229081888 : name: 000b064deda7eaebd1f0ca982fc4adcc20d6c90d64d72de5277f072ba3633de848ba Creating decryption key is just as strightforward: #+BEGIN_SRC yaml :tangle decryption-nist-p256.yml spec: provider: tpm: tcti: "mssim:" handle: 0x81000118 algo: EC: curve: NIST-P256 capabilities: - decrypt auth: 123 #+END_SRC #+BEGIN_SRC sh create-key -f decryption-nist-p256.yml #+END_SRC *** EC: NIST-P384 The following configuration creates NIST-P384 signing key and persists it at the handle ~0x01000227~. ~123~ is used as a sample auth value (PIN). #+BEGIN_SRC yaml :tangle key-nist-p384.yml spec: provider: tpm: tcti: "mssim:" handle: 0x81000227 algo: EC: curve: NIST-P384 capabilities: - sign auth: 123 #+END_SRC The key description (~key-nist-p384.yml~) is being read by the ~create-key~ binary that persists that key: #+BEGIN_SRC sh create-key -f key-nist-p384.yml #+END_SRC Presence of the key can be checked by using ~tpm2_getcap handles-persistent~ command from TSS suite of tools. And the same file is used to retrieve it again using ~get-key~ binary: #+BEGIN_SRC sh get-key -f key-nist-p384.yml #+END_SRC #+RESULTS: : public_key: : EC: : x: b5d6885b6774c8a1a944b4559f26b931df031c893bc05139fc54c876b01401253ecea26ea17fa70c017bb5b4d6bb5885 : y: d29cda6bc9742e49b030db3ec9004217ba8fd052b7d26fc7bddbbe7cb9854fabf7cdc5978ebb8fed9383d387a07bcdf9 : manu: 1229081888 : name: 000b8e28e3d95570efc686bb21f5329a658fe09321d38b496fe02749251e28a07ef5 Creating decryption key is just as strightforward: #+BEGIN_SRC yaml :tangle decryption-nist-p384.yml spec: provider: tpm: tcti: "mssim:" handle: 0x81000218 algo: EC: curve: NIST-P384 capabilities: - decrypt auth: 123 #+END_SRC #+BEGIN_SRC sh create-key -f decryption-nist-p384.yml #+END_SRC ** Creating non-persistent keys Non persistent keys allow using unlimited number of keys that never use up TPM memory. *** RSA Keys need to be wrapped using a key parent that itself needs to be persistent: #+BEGIN_SRC yaml :tangle parent.yml spec: provider: tpm: tcti: "mssim:" handle: 0x81000028 algo: RSA: bits: 2048 capabilities: - decrypt - restrict auth: 123 #+END_SRC #+BEGIN_SRC sh create-key -f parent.yml #+END_SRC Then, we can create non-persistent key: #+BEGIN_SRC yaml :tangle child.yml spec: provider: tpm: tcti: "mssim:" parent: 0x81000028 algo: RSA: bits: 2048 capabilities: - sign auth: 123 #+END_SRC #+BEGIN_SRC sh create-key -f child.yml | tee child-full.yml #+END_SRC Inspecting ~child-full.yml~ reveals that the ~tpm~ section has been extended with two new properties: ~private~ and ~unique~. This is the private key wrapped (encrypted) using the parent key: #+BEGIN_SRC yaml spec: provider: tpm: tcti: "mssim:" parent: 0x81000028 private: 002035531cd18d59c7e358b63b1f89ed3b2fdd12176ed5c02f5d68dfbf7f872c65ae00107170ee9bc217b4a7ed59ad11a1387aef195031690b01d6d3acd6b4f63d16006bb33737392dd1ba9753bcf81227e3dffecddc082821994e41c047e325d82ee2c3106e94d5f5bbcd935e6f80e2321f24012a24be73f231c9f6606d927016b3afd73b96df2e3f5a181cfbe436da9cf9bcefa1a1513cb63e8021fb9ad2cc81bce55d9651aa7ed8aeaccba7ba98834d759e9f3b30e21953e65a12742bc253dfbef1e8e158fcc9755acd08e3f4af4183b7b008c4ec0865b48315d346be unique: RSA: bytes: aa79ea1d9800af8b6556562c27dca2be827d7ca1facfd056c4effe79dca366e948e4b0f5253392ce4ea274c84f609e57edfd4848cf10e87e19b22e4bf27fc3560a8e6405a1a339969ce6d00bc4b32e1398be63f59af4c7337b4079817fd231d379dd437cb35910ce13337a6af0877c88ac2f8bc86dd902de3ffd10bdc6c5f284063f95c2c2487942472f34551691fdf8ae0f30a7a188bc73ecb776bef2a959be2cc89b425247030e2a921d505bb71e19100b17028b74e39e673dd1d35603fea424d44913e84c7744128ec2d82853d34062ea9476557a4458c70c05d7efd205ee6b89aa7b0b84daaecbf4075db8fcee2ed622dca2ee8e391e457cc88f3ac39b7d algo: RSA: bits: 2048 capabilities: - sign auth: 123 #+END_SRC Except for the different configuration this key is perfectly usable in all operations: #+BEGIN_SRC sh get-key -f child-full.yml #+END_SRC #+RESULTS: : public_key: : RSA: : bytes: c4c1c097f96afae8de9c3a3ece841f510acca20ed417c890e9626205672fbceaf21bb92ff680897aeb4418c52c146c5f7bab0f44762e64bea6228f7617d493b3399110339da3513f3864acf7f977b092e63200da83a31d8640a6cb50761bf90c868b35240097d85053a55e25043fcab4367c4881050aa7b52c71d2dc0155afbfd3ab50c6223e8dd119d6c7270b0d5e5c672fa8d809a38d53c98b2d126927ad6f29f243247ff56ffe0378a6fcfc09a5ef998e9b31158ae68aa323b4f6f3650c17e5ea82e131f533d3c88c6241421b0998e63e60cec498a150db07f4969430d04700ad41172b3ebc74854223128821cc16d7f7e019269909418cf4a2eff93bc92d : manu: 1398033696 : name: 000bc287d88098837a6fa7732ac5f1735996a4b5e7827fb0e82177b763b31654c77c *** EC: NIST-P256 Keys need to be wrapped using a key parent that itself needs to be persistent: #+BEGIN_SRC yaml :tangle parent-nist-p256.yml spec: provider: tpm: tcti: "mssim:" handle: 0x81000328 algo: EC: curve: NIST-P256 capabilities: - decrypt - restrict auth: 123 #+END_SRC #+BEGIN_SRC sh create-key -f parent-nist-p256.yml #+END_SRC Then, we can create non-persistent key: #+BEGIN_SRC yaml :tangle child-nist-p256.yml spec: provider: tpm: tcti: "mssim:" parent: 0x81000328 algo: EC: curve: NIST-P256 capabilities: - sign auth: 123 #+END_SRC #+BEGIN_SRC sh create-key -f child-nist-p256.yml | tee child-nist-p256-complete.yml #+END_SRC Inspecting ~child-nist-p256-complete.yml~ reveals that the ~tpm~ section has been extended with two new properties: ~private~ and ~unique~. This is the private key wrapped (encrypted) using the parent key: #+BEGIN_SRC yaml spec: provider: tpm: tcti: "mssim:" parent: 0x81000328 private: 0020f02ddfa535dfae96031629c001868c0c28358df4d8d8784536a22faa7fea90020010a27a2d5a839d5bece4c50110e189dbf67d76f6f7f68a71301791fe0db8c187b1495621d1b4776fdc2f8b184451d16fd1aacc8261005df7c86058a7fa1609dce2e5a8ec7c631398b2e57e288dbe99059de30cfabdbcd057c53763 unique: EC: x: 1f93e6eb830bfb22b6ac482f3c41770a65ab6478c5c0c4d0758b250289defc0b y: c211a231b6d5313a8a78af4a621ce7766ca1c000c59e904ed3f1fa38ff54cb72 algo: EC: curve: NIST-P256 capabilities: - sign auth: 123 #+END_SRC Except for the different configuration this key is perfectly usable in all operations: #+BEGIN_SRC sh get-key -f child-nist-p256-complete.yml #+END_SRC #+RESULTS: : public_key: : EC: : x: 1f93e6eb830bfb22b6ac482f3c41770a65ab6478c5c0c4d0758b250289defc0b : y: c211a231b6d5313a8a78af4a621ce7766ca1c000c59e904ed3f1fa38ff54cb72 : manu: 1398033696 : name: 000b1a7ea2e65a4c70d21c2af706ed370b20a56b28f644d19b7501345910a3a3e7cd *** EC: NIST-P384 Keys need to be wrapped using a key parent that itself needs to be persistent: #+BEGIN_SRC yaml :tangle parent-nist-p384.yml spec: provider: tpm: tcti: "mssim:" handle: 0x81000428 algo: EC: curve: NIST-P384 capabilities: - decrypt - restrict auth: 123 #+END_SRC #+BEGIN_SRC sh create-key -f parent-nist-p384.yml #+END_SRC Then, we can create non-persistent key: #+BEGIN_SRC yaml :tangle child-nist-p384.yml spec: provider: tpm: tcti: "mssim:" parent: 0x81000428 algo: EC: curve: NIST-P384 capabilities: - sign auth: 123 #+END_SRC #+BEGIN_SRC sh create-key -f child-nist-p384.yml | tee child-nist-p384-complete.yml #+END_SRC Inspecting ~child-nist-p384-complete.yml~ reveals that the ~tpm~ section has been extended with two new properties: ~private~ and ~unique~. This is the private key wrapped (encrypted) using the parent key: #+BEGIN_SRC yaml spec: provider: tpm: tcti: "mssim:" parent: 0x81000428 private: 0020fb1df208021cab7898d4edba2e87966a62e4e95820ad695b8d5af40351361f9100102e21b1075be238d84a9b98471879ec2cc415b4b0309edf82dd6b5a00fa557b9dc06ea752ea36fb4dea4f9a47c5884e1d43e0fcbd40db477e4147264f202145e1c995f411406c82d444a91d67edf69c824737e32057728d9f04193b469b3759bbb033673fafec5db9fa86 unique: EC: x: cf159a49527490e60ba5cede361ca82a43d41e6754e8ddea1f57fdba9e05bd49ed62bb982994407801f95c366f85ef43 y: 322ee52ffde0fe5f85367f801a0cbc5f05a772e6ac86027eed64a02303683b2caa1adb0674645533cb578284ee86eaab algo: EC: curve: NIST-P384 capabilities: - sign auth: 123 #+END_SRC Except for the different configuration this key is perfectly usable in all operations: #+BEGIN_SRC sh get-key -f child-nist-p384-complete.yml #+END_SRC #+RESULTS: : public_key: : EC: : x: cf159a49527490e60ba5cede361ca82a43d41e6754e8ddea1f57fdba9e05bd49ed62bb982994407801f95c366f85ef43 : y: 322ee52ffde0fe5f85367f801a0cbc5f05a772e6ac86027eed64a02303683b2caa1adb0674645533cb578284ee86eaab : manu: 1398033696 : name: 000b1a7ea2e65a4c70d21c2af706ed370b20a56b28f644d19b7501345910a3a3e7cd ** Importing private keys It is also possible to import already existing private keys into the TPM. *** RSA #+BEGIN_SRC yaml :tangle private-key.yml spec: provider: tpm: tcti: "mssim:" algo: RSA: bits: 1024 private: rsa: prime: f69495352f2ab58db89a0a6ddb060ca0baa5ec190d1d61f0fae32cdfb7516fc9e4968b5c494c057f35dfe69136fe35434f0a3b8979551347c47a357abad0ad0b modulus: bytes: cd1abae5d734341ad373bae4f9ef46b1cf699d4054c859b9c0f0c811ca4d7b1cb03c66ea655156639b78c5db2c2fea42430f417ab3d4aee5f63b881dd106a3c60105bc46bb18c7a794a17f50392405551f77287e61b5f784354cd351021e1853b0cfd3470d4cc9bd9e39836b83c1be6bb200fef56786406e8cd45f73e4a9f523 exponent: 65537 capabilities: - sign auth: 123 #+END_SRC Using these keys is the same as for any other type of key: #+BEGIN_SRC sh :results verbatim get-key -f private-key.yml #+END_SRC #+RESULTS: : --- : public_key: : RSA: : bytes: cd1abae5d734341ad373bae4f9ef46b1cf699d4054c859b9c0f0c811ca4d7b1cb03c66ea655156639b78c5db2c2fea42430f417ab3d4aee5f63b881dd106a3c60105bc46bb18c7a794a17f50392405551f77287e61b5f784354cd351021e1853b0cfd3470d4cc9bd9e39836b83c1be6bb200fef56786406e8cd45f73e4a9f523 : manu: 1398033696 : name: 000bb0369f40552df81f3bda82053e1974ffb5e2ca32999c602ee67428703e8211ad : *** EC: NIST-P256 To generate a new P-256 key use the following openssl command: #+BEGIN_SRC sh :results verbatim openssl ecparam -name secp256r1 -genkey -noout | openssl ec -in - -inform engine -text -noout -conv_form uncompressed #+END_SRC #+RESULTS: #+begin_example Private-Key: (256 bit) priv: 98:20:9e:ea:87:b0:63:ec:a8:51:09:ef:1b:8a:46: c0:97:ab:25:2c:59:fb:a1:2f:38:99:e3:8f:e5:4e: d4:1b pub: 04:12:b2:a3:f6:de:b2:74:df:7d:fa:6a:9e:6e:13: de:a9:b9:51:5d:59:0a:66:69:66:de:fe:f5:f8:6d: 1e:ca:df:47:95:cf:10:a8:94:22:6f:17:78:dc:d4: 18:5d:b5:c4:d4:2a:9c:10:59:1a:22:11:81:2e:f5: b6:54:09:4f:81 ASN1 OID: prime256v1 NIST CURVE: P-256 #+end_example The =ec.parameter= value should reflect the =priv= field with all bytes concatenated. The public part: =ec.points= would be two halves of the =pub= openssl value (omitting first =04= byte). #+BEGIN_SRC yaml :tangle private-key-nist-p256.yml spec: provider: tpm: tcti: "mssim:" algo: EC: curve: NIST-P256 private: ec: parameter: 98209eea87b063eca85109ef1b8a46c097ab252c59fba12f3899e38fe54ed41b points: x: 12b2a3f6deb274df7dfa6a9e6e13dea9b9515d590a666966defef5f86d1ecadf y: 4795cf10a894226f1778dcd4185db5c4d42a9c10591a2211812ef5b654094f81 capabilities: - sign auth: 123 #+END_SRC Using these keys is the same as for any other type of key: #+BEGIN_SRC sh get-key -f private-key-nist-p256.yml #+END_SRC #+RESULTS: : public_key: : EC: : x: 12b2a3f6deb274df7dfa6a9e6e13dea9b9515d590a666966defef5f86d1ecadf : y: 4795cf10a894226f1778dcd4185db5c4d42a9c10591a2211812ef5b654094f81 : manu: 1229081888 : name: 000b23684f8b125caad589545052d8779253a6ef854f9290f7c8b670cb2c4165aa18 *** EC: NIST-P384 To generate a new P-384 key use the following openssl command: #+BEGIN_SRC sh :results verbatim openssl ecparam -name secp384r1 -genkey -noout | openssl ec -in - -inform engine -text -noout -conv_form uncompressed #+END_SRC #+RESULTS: #+begin_example Private-Key: (384 bit) priv: a1:79:12:49:9c:40:12:98:ed:ec:db:89:f7:a3:08: 75:74:6f:0e:fc:44:3e:be:d1:3a:05:3f:1a:2f:c6: 45:97:3d:d3:5a:93:27:1c:6d:7f:25:79:36:95:bd: 1c:4f:be pub: 04:e1:d7:38:d7:54:2b:83:b2:e8:bd:4d:cd:03:6f: f8:1c:a2:ed:08:30:1c:26:34:d2:c4:24:6c:3e:79: ae:e9:90:36:7c:f7:3b:c2:2c:29:50:da:e9:98:d7: 97:a3:95:75:5e:cc:c5:61:a0:38:fd:76:ce:60:2a: 7a:6c:0e:f4:51:db:3f:75:21:ac:ab:96:50:f7:77: 09:b5:32:69:2d:93:23:98:e2:aa:09:ae:18:e4:20: db:16:56:57:12:c3:6f ASN1 OID: secp384r1 NIST CURVE: P-384 #+end_example The =ec.parameter= value should reflect the =priv= field with all bytes concatenated. The public part: =ec.points= would be two halves of the =pub= openssl value (omitting first =04= byte). #+BEGIN_SRC yaml :tangle private-key-nist-p384.yml spec: provider: tpm: tcti: "mssim:" algo: EC: curve: NIST-P384 private: ec: parameter: 595e7774730018cc3942e4b713c2a288b8dbcec147ede1ed3c3760553bc39a7a092db968df4da71267c9586e69e6ffc7 points: x: 88eae33668dfc22f1bec8ca87bef7dab67562b1b1bf10101b5a655212b31356d46963624e11f0b30ffb7bc60f315fb09 y: 5c1ec2296140c2404a605e6c65b85c10d3e5807feb4d15f674e4318c7887e03408e98a348c413b16ad615484ed84cf2f capabilities: - sign auth: 123 #+END_SRC Using these keys is the same as for any other type of key: #+BEGIN_SRC sh get-key -f private-key-nist-p384.yml #+END_SRC #+RESULTS: : public_key: : EC: : x: 88eae33668dfc22f1bec8ca87bef7dab67562b1b1bf10101b5a655212b31356d46963624e11f0b30ffb7bc60f315fb09 : y: 5c1ec2296140c2404a605e6c65b85c10d3e5807feb4d15f674e4318c7887e03408e98a348c413b16ad615484ed84cf2f : manu: 1398033696 : name: 000b4c2c9cf06ff4af433703b1459bf1529311fcc7a24c6e407594ba071a7bc82060 ** Signing digests *** RSA Signing uses raw RSA keys and produces raw PKCS1.5 signatures for now. Ultimately these raw objects can be wrapped with protocol-specific structures e.g. certificates (for raw RSA keys) or OpenPGP signatures (for raw signatures). Signing can use any key that has been defined previously: #+BEGIN_SRC sh :results output echo -n foo | openssl dgst -binary -sha256 | sign-digest -f key.yml | xxd #+END_SRC #+RESULTS: #+begin_example 00000000: a2a7 066e 813b 0ae9 a978 2f78 dbb1 c25d ...n.;...x/x...] 00000010: 3402 fca2 106e 4052 ef3f e370 399d e95f 4....n@R.?.p9.._ 00000020: 45d3 5f56 f915 5f81 c9e9 6b4b ff27 9529 E._V.._...kK.'.) 00000030: 591c 0cf2 6a19 18d5 af6a e2e1 161b b950 Y...j....j.....P 00000040: cbfe 715b 201c e1dc 6691 f862 9e1b ca87 ..q[ ...f..b.... 00000050: 2313 f774 f689 dd5b e28f 9c9b 275c 6432 #..t...[....'\d2 00000060: e491 533a 5509 bd9b 5ddf 8403 81cb e341 ..S:U...]......A 00000070: 2fc7 23e9 9c93 4170 48e7 cdda 3c07 0151 /.#...ApH...<..Q 00000080: dafd 00bb 352e dacc 33a9 a087 9a9d 93cf ....5...3....... 00000090: 4dff d59d 7f19 ca68 3d6e e3e7 26f5 17d4 M......h=n..&... 000000a0: c683 677e c039 dd4e 27ff f2db f354 9fe1 ..g~.9.N'....T.. 000000b0: 6e7a 1ea5 c215 ba4d 44c1 5f72 0bce 1fe9 nz.....MD._r.... 000000c0: 53c2 3cbf 8412 d610 784d 6cf5 aa56 2c87 S.<.....xMl..V,. 000000d0: 48a2 dbdf 3944 9ae3 94ae 2a57 98bb 420c H...9D....*W..B. 000000e0: 842e 2aa6 7dd2 1842 7ef4 5208 3b47 d410 ..*.}..B~.R.;G.. 000000f0: 137f 9292 8d94 d5e3 64c0 2a2b e4e8 4342 ........d.*+..CB #+end_example *** EC: NIST-P256 Signing uses raw elliptic curve keys and produces a concatenation of R and S values. Ultimately these raw objects can be wrapped with protocol-specific structures e.g. certificates (for raw RSA keys) or OpenPGP signatures (for raw signatures). Signing can use any key that has been defined previously: #+BEGIN_SRC sh :results output echo -n foo | openssl dgst -binary -sha256 | sign-digest -f key-nist-p256.yml | xxd #+END_SRC #+RESULTS: : 00000000: 2b10 9aca a8ec 800c 4b50 b35a a62e 6f52 +.......KP.Z..oR : 00000010: 5bc3 a3c9 5c68 bd2a 4588 b7e8 94f6 2923 [...\h.*E.....)# : 00000020: f3e4 b073 82a1 42b4 1139 e5d0 d7a3 996d ...s..B..9.....m : 00000030: 8893 a60a 6171 ddc1 ecb6 2992 8382 d8d2 ....aq....)..... *** EC: NIST-P384 Signing uses raw elliptic curve keys and produces a concatenation of R and S values. Ultimately these raw objects can be wrapped with protocol-specific structures e.g. certificates (for raw RSA keys) or OpenPGP signatures (for raw signatures). Signing can use any key that has been defined previously: #+BEGIN_SRC sh :results output echo -n foo | openssl dgst -binary -sha256 | sign-digest -f key-nist-p384.yml | xxd #+END_SRC #+RESULTS: : 00000000: a33b 5ed4 bbbc f6bd 6297 c696 fc10 5ae4 .;^.....b.....Z. : 00000010: 4a32 d807 a065 ea75 19b9 7d2f 9f05 8e09 J2...e.u..}/.... : 00000020: a6b6 028b 2eb7 9c7f ab6e 8701 61a3 e39d .........n..a... : 00000030: 23db fc1b b859 e2dd 20e5 ebc9 3503 c671 #....Y.. ...5..q : 00000040: 00e2 057c 3b00 86fa 84e8 4152 3b9d 9e70 ...|;.....AR;..p : 00000050: 5a19 05a0 f13f 64f6 ddd7 5edd 764c 6cea Z....?d...^.vLl. ** Decryption *** RSA Encryption and decryption works similarily to signing. The plaintext is being passed as standard input to =encrypt-raw= commmand and it outputs the raw cipher text. =decrypt-raw= works in the other direction consuming the cipher text and producing the plain text. Both of these take the key defintion as a sole argument. #+BEGIN_SRC sh :results output echo this is a sample encryption message | encrypt-raw -f decryption.yml > encrypted decrypt-raw -f decryption.yml < encrypted #+END_SRC #+RESULTS: : this is a sample encryption message *** ECDH Encryption and decryption with EC keys works a little bit differently. EC key is used to generate two points: one is a public point that will be shared with the other party, the other is used as a symmetric key for encryption of the actual data. First, we need an EC key with =decrypt= capability. The key cannot be marked as =restrict= as that will prevent decryption. #+BEGIN_SRC yaml :tangle key-nist-p256-decryption.yml spec: provider: tpm: tcti: "mssim:" handle: 0x81000147 algo: EC: curve: NIST-P256 capabilities: - decrypt auth: 123 #+END_SRC Then we generate two points: public point and the shared secret: #+BEGIN_SRC sh create-key -f key-nist-p256-decryption.yml # create a shared secret and public point ecdh-key-gen -f key-nist-p256-decryption.yml --public-point public.bin > shared-secret.bin echo "Public point:" xxd public.bin echo "Shared secret:" xxd shared-secret.bin #+END_SRC And we use the shared secret to encrypt the message. Shared secret is removed as it is no longer necessary. The public point, along with the encrypted message, is transferred. #+BEGIN_SRC sh # encrypt the message using shared secret echo this is a sample encryption message | openssl aes-256-cbc -e -kfile shared-secret.bin > encrypted # remove shared secret, move public point and encrypted message to the other party rm shared-secret.bin #+END_SRC The decrypting party first recovers the shared secret using the public point. Then the shared secret is passed to symmetric algorithm as a key (here using OpenSSL): #+BEGIN_SRC sh # recover shared secret using private key and the public point ecdh-recover -f key-nist-p256-decryption.yml --public-point public.bin > shared-secret.bin # decrypt the message openssl aes-256-cbc -d -kfile shared-secret.bin -in encrypted #+END_SRC #+RESULTS: : this is a sample encryption message This concludes our basic TPM usage section. TPM will be cleared discarding all keys: #+BEGIN_SRC sh tpm2_clear #+END_SRC * Key duplication Key duplication allows secure private key material transfer from one machine (e.g. offline computer) to the other (e.g. online computer). The main benefit is that the online computer never sees private key bits in plain. They are encrypted to the storage key that is stored in the TPM chip. The encrypted private key is decrypted by the TPM during import. On online laptop, export the TPM key that will serve as parent for the imported key. This parent key needs to have =decrypt= and =restrict= capabilities. #+BEGIN_SRC yaml :tangle duplication-parent.yml spec: provider: tpm: tcti: "mssim:" handle: 0x81000027 algo: RSA: bits: 2048 capabilities: - decrypt - restrict auth: 123 #+END_SRC #+BEGIN_SRC sh create-key -f duplication-parent.yml #+END_SRC Retrieve the key's public key bits and transfer them to the offline computer: #+BEGIN_SRC sh get-key -f duplication-parent.yml | tee duplication-parent-full.yml #+END_SRC #+RESULTS: #+begin_example spec: provider: tpm: tcti: "device:/dev/tpmrm0" handle: 2164260888 parent: ~ private: ~ unique: RSA: bytes: bd1fdfb6ad445dd24bd9150886a7ea392863bf2864f8105bca870349150691309581f08271d93a7286e6d8126df38ca51b4d5366a867461743c842d0e4d6867cc81e8d8a96b6c7b01d702d1674d6432ac686d9e1d9b767b46d93d640c9ddcf952c46690231711ccd040d7b85453acb9a857040f49208823315b970e0ec3c15f31a1d6d17238a6b1e717020946ba2e8591f5aa36a3d65b4ac166755e54609355c2517dafc6c545f322093dd6ad01b33931c9f25ef3e47e61bf5d2a2b553af3fef8c2180267b76857768d38e5954b90362923df57ded9a9264cc56a120c48d2f47e6d7dc7a069f2a2c7b4d4079a599df8e672bca9540dcd024bcdd45cfc6450653 algo: RSA: bits: 2048 exponent: ~ private: ~ capabilities: - decrypt - restrict auth: "123" #+end_example Now, taking the private key and wrapping it with the parent's key: #+BEGIN_SRC sh wrap --parent duplication-parent-full.yml -f private-key.yml | tee key-to-import.yml #+END_SRC #+RESULTS: #+begin_example spec: provider: tpm: tcti: "mssim:" parent: 2164260903 unique: RSA: bytes: cd1abae5d734341ad373bae4f9ef46b1cf699d4054c859b9c0f0c811ca4d7b1cb03c66ea655156639b78c5db2c2fea42430f417ab3d4aee5f63b881dd106a3c60105bc46bb18c7a794a17f50392405551f77287e61b5f784354cd351021e1853b0cfd3470d4cc9bd9e39836b83c1be6bb200fef56786406e8cd45f73e4a9f523 wrapped: secret: 41ccb56cfbfc120d0aa54bfd01c29e827bf58f70010cbc035eac87939eb0928c40e3a38a397fd03ad7c1b105beba154e2687ed40125e77c32f2979725940619cb5f2ae0f9238f10e593baabdf86a8ab02724c45d3d32bee36f18899387b91102d92d7fcc434d3b19599ad1ba417f3be30a1e2c4a686c472b34e3052193d8b33d94ecf5b10de590b2a275c443fdc31fa65558f074320aabe9bf79c3d8db34d108b026c4803ea342f179cebff89c84cb172127b6b517c1537bbcd05d551016dc886f7115b3a74265df5332da70a49e6981ab1a441307bcac0ba54a2505e74bd6df490075795bb39f9c63abbe02c632020786d6d89a88e4dc32b8f553f5805b3e0d private: 0020dccc065f0fc4c8db35c0a26f7742df8efa0fa7dfe7964d6e5f004405aa1fff280abec442094816fc2b51f58ea277ab49b61db7ca007f4387f251a8f1db2af77cf7fdd6ded9d793d91891c9cd7e47e18bffc3b2280bbd0e3a5b8685cfe934a199d57db474592194cd29f5701f8042318062685103e987caa88b7e8ba5cc741c576f37b4d545d0d3ed2fa2 data: "" policy: 09bd2ec618ec5d4688b2861cd8aedbbce1c1dd0b9e31e4a12f837750b33831e2 algo: RSA: bits: 1024 capabilities: - sign auth: "123" #+end_example The duplicated key can then be imported: #+BEGIN_SRC sh create-key -f key-to-import.yml | tee duplicated-key.yml #+END_SRC #+RESULTS: #+begin_example spec: provider: tpm: tcti: "mssim:" parent: 2164260903 private: 00202a2ee14685008e505bf6284cd2250f4071d6cfa06e344d5e1462acb8cad0cdba0010058b8588770859c9271d31729a56b3f4d9d2b01e45e9209cbeecb7b95aa7ff86edbc8ca350abcbd28391bea433ec9eb82e8490821669d34d2362b4558c034305b5c8d51417751efad8d414e0df781785e56f8bab9395655d0a753fdf17efe0f4e6df85b8958e9df7bb29371ab22cd49e82bd1da05d4e15d971ae unique: RSA: bytes: cd1abae5d734341ad373bae4f9ef46b1cf699d4054c859b9c0f0c811ca4d7b1cb03c66ea655156639b78c5db2c2fea42430f417ab3d4aee5f63b881dd106a3c60105bc46bb18c7a794a17f50392405551f77287e61b5f784354cd351021e1853b0cfd3470d4cc9bd9e39836b83c1be6bb200fef56786406e8cd45f73e4a9f523 policy: 09bd2ec618ec5d4688b2861cd8aedbbce1c1dd0b9e31e4a12f837750b33831e2 algo: RSA: bits: 1024 capabilities: - sign auth: "123" #+end_example Note that the imported key has =wrapped= key set. Import procedure checks the integrity of the key and if the encrypted seed can be successfully imported the =wrapped= key is removed and a regular =private= value is being inserted. The duplicated key can be inspected for public key: #+BEGIN_SRC sh get-key -f duplicated-key.yml #+END_SRC It also works the same way as any other key: #+BEGIN_SRC sh echo -n foo | openssl dgst -binary -sha256 | sign-digest -f duplicated-key.yml | xxd #+END_SRC #+RESULTS: #+begin_example 00000000: ba01 7074 b3b4 07bd 9ea5 28fb a04f 1f83 ..pt......(..O.. 00000010: 8fa5 6965 e2de 71cb d320 4332 60a9 f088 ..ie..q.. C2`... 00000020: 7725 5145 5688 9a12 97fa 5ad8 7c6f 3213 w%QEV.....Z.|o2. 00000030: d21d 4c84 4888 e3f6 4eab 988c 5b72 eb65 ..L.H...N...[r.e 00000040: d88b 16b3 473b 91d8 053e 05de 5733 208e ....G;...>..W3 . 00000050: e8ad 6a3e 22eb 349d 1798 ef0e 8924 2f35 ..j>".4......$/5 00000060: 2dce 3af5 e1d3 47b9 cb9e 9ccd bc63 7e91 -.:...G......c~. 00000070: 23e6 cac0 83e9 10a8 0aaa 7a06 6579 87ee #.........z.ey.. #+end_example * Work plan Work on this project is being sponsored by NLnet. See https://nlnet.nl/project/Sequoia-TPM/ for details. ** Signing and decryption using RSA keys [5/5] - [X] Creating new RSA keys and persisting them in TPM memory - [X] Using non-persistent RSA keys (that don't use up TPM memory) - [X] Importing RSA private keys to TPM (for already existing keys) - [X] Signing using RSA keys in the TPM - [X] Decryption using RSA keys in the TPM ** Support for Elliptic Curve algorithms [5/5] - [X] Creating new EC keys and persisting them in TPM memory - [X] Using non-persistent EC keys (that don't use up TPM memory) - [X] Importing EC private keys to TPM (for already existing keys) - [X] Signing using EC keys in the TPM - [X] Decryption using EC keys in the TPM ** Key migration support [4/4] - [X] Export of TPM encryption key - [X] Wrapping user's private key using TPM encryption key - [X] Import of the wrapper private key to the TPM chip - [X] PR to the upstream rust-tss-esapi crate ** Design and implementation of private key store crate [/] - [ ] Implementation of Sequoia's Decryptor and Signer traits for TPM keys - [ ] API for managing TPM keys - [ ] API for key migration ** Test harness using a TPM simulator [/] - [ ] Integration tests for creating, importing keys - [ ] Test cases for encryption (using Sequoia) and decryption (using TPM crate) - [ ] Tests for key migration ** Extending Sequoia's CLI to support private key store [/] - [ ] Extension to the CLI to allow specifying the location of the private key store - [ ] Modification to the sourec code not to rely on software private keys ** Documentation for tools and the API [/] - [ ] Making sure all functions and items are documented - [ ] Including README and end-user documentation on how to use the project - [ ] Adding best practices document sequoia-tpm-0.1.1/src/lib.rs000064400000000000000000000655301046102023000140030ustar 00000000000000#![deny(missing_docs)] //! Declarative TPM. //! //! This crate allows operating on TPM objects using declarative descriptions of keys //! and the associated artifacts. //! //! See binaries in `bin` for examples on how are these functions defined. use serde::{Deserialize, Serialize}; use std::convert::{TryFrom, TryInto}; use std::str::FromStr; use tss_esapi::attributes::object::ObjectAttributesBuilder; use tss_esapi::attributes::session::SessionAttributesBuilder; use tss_esapi::constants::session_type::SessionType; use tss_esapi::constants::tss::*; use tss_esapi::constants::CommandCode; use tss_esapi::handles::{KeyHandle, PersistentTpmHandle, TpmHandle}; use tss_esapi::interface_types::algorithm::{ EccSchemeAlgorithm, PublicAlgorithm, RsaSchemeAlgorithm, }; use tss_esapi::interface_types::ecc::EccCurve; use tss_esapi::interface_types::key_bits::RsaKeyBits; use tss_esapi::interface_types::resource_handles::Hierarchy; use tss_esapi::interface_types::session_handles::PolicySession; use tss_esapi::structures::SymmetricDefinitionObject; use tss_esapi::structures::{ Auth, Digest, EccParameter, EccScheme, KeyDerivationFunctionScheme, Private, PublicBuilder, PublicEccParametersBuilder, PublicRsaParametersBuilder, RsaExponent, RsaScheme, Signature, SignatureScheme, }; use tss_esapi::Result; use tss_esapi::constants::tss::TPM2_ST_HASHCHECK; use tss_esapi::structures::{ Data, EccPoint, Public, PublicKeyRsa, RsaDecryptionScheme, SymmetricDefinition, }; use tss_esapi::tss2_esys::TPMT_TK_HASHCHECK; use tss_esapi::{Context, Tcti}; // Re-export as this is part of our public API. pub use tss_esapi::interface_types::algorithm::HashingAlgorithm; /// Description of a key. /// /// The details of the key are specified by the `spec` field. #[derive(Debug, Serialize, Deserialize)] pub struct Description { /// Specification of the described key. pub spec: Specification, } /// Key details specification. /// /// The specification of the contents of the key as well as by which provider it is managed. /// While this crate defines only the TPM provider other crates could define other provider /// types. #[derive(Debug, Serialize, Deserialize)] pub struct Specification { /// Provider to use for the key. pub provider: Provider, /// Algorithm used by the key. pub algo: AlgorithmSpec, /// Optional: key private bits. pub private: Option, /// List of key capabilities. pub capabilities: Vec, /// Authentication value to use the key. pub auth: String, } /// Key private material. /// /// Defines data layout and contents of the private key definitions for both RSA and EC keys. #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum PrivateKeyMaterial { /// RSA key material. Rsa(PrivateRsaKeyMaterial), /// EC key material. Ec(EcParameter), } /// RSA private key material. /// /// Defines the contents of RSA private key: `prime` and `modulus` fields. #[derive(Debug, Serialize, Deserialize)] pub struct PrivateRsaKeyMaterial { /// RSA prime factor. pub prime: String, /// RSA modulus factor. pub modulus: RsaPublic, } impl From<&PrivateRsaKeyMaterial> for tss_esapi_sys::TPM2B_PRIVATE_KEY_RSA { fn from(private_rsa: &PrivateRsaKeyMaterial) -> Self { let key_prime = hex::decode(&private_rsa.prime).unwrap(); let mut result = Self::default(); result.buffer[..key_prime.len()].clone_from_slice(&key_prime[..key_prime.len()]); result.size = key_prime.len().try_into().unwrap(); result } } /// EC private key material. /// /// Defines private key material for EC: `parameter` and both `points`. #[derive(Debug, Serialize, Deserialize)] pub struct EcParameter { /// EC parameter. pub parameter: String, /// EC point. pub points: EcPublic, } impl From<&EcParameter> for tss_esapi_sys::TPM2B_ECC_PARAMETER { fn from(param: &EcParameter) -> Self { let parameter = hex::decode(¶m.parameter).unwrap(); let mut parameter_buffer = [0u8; 128]; parameter_buffer[..parameter.len()].clone_from_slice(¶meter); Self { size: parameter.len() as u16, buffer: parameter_buffer, } } } /// Key capability. /// /// Defines for which usages is this key intended. All keys need to be either `Decrypt` or `Sign` /// keys. Some keys can also be `Restrict`ed keys. /// /// Keys that are both `Decrypt` and `Sign` are called storage keys and are used to load other /// keys in the TPM. Restricted decryption keys will not reveal the plaintext to non-TPM code. /// /// Restricted signing keys will sign only digests produced in the TPM. They are used mostly /// to sign data produced by the TPM, e.g. the attestation data. #[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum Capability { /// Allows decryption using this key. Decrypt, /// Allows signing using this key. Sign, /// This key is restricted. Restrict, /// This is an unknown, unsupported capability. #[serde(other)] Unknown, } /// Algorithm specification. /// /// If a new key is about to be created the specifics of the algorithm need to be defined. /// This object specifies details for each supported asymmetric algorithm. #[derive(Debug, Serialize, Deserialize)] pub enum AlgorithmSpec { /// RSA bits and optional exponent. #[serde(rename = "RSA")] Rsa { /// Number of bits for this key. bits: u16, /// The exponent if it's different from 0x010001. exponent: Option, }, /// EC curve. #[serde(rename = "EC")] Ec { /// Elliptic Curve to use. curve: EcCurve, }, } /// EC curve. /// /// EC curve that is supported by this library. #[derive(Debug, Serialize, Deserialize, Eq, PartialEq)] pub enum EcCurve { /// NIST P-256 curve. #[serde(rename = "NIST-P256")] NistP256, /// NIST P-384 curve. #[serde(rename = "NIST-P384")] NistP384, } impl From<&EcCurve> for EccCurve { fn from(curve: &EcCurve) -> Self { match curve { EcCurve::NistP256 => EccCurve::NistP256, EcCurve::NistP384 => EccCurve::NistP384, } } } /// Cryptographic provider. /// /// Specifies cryptographic provider that should be used for all cryptographic operations. #[derive(Debug, Serialize, Deserialize)] pub struct Provider { /// Defines details for the TPM provider. pub tpm: TpmProvider, } /// TPM cryptographic provider. /// /// Specifies details of the target TPM as well as several TPM-specific key properties. #[derive(Debug, Serialize, Deserialize)] pub struct TpmProvider { /// Connection string for the provider. E.g. `mssim:` for the simulator or /// `device:/dev/tpmrm0` for a hardware device. pub tcti: String, /// Numeric handle of the key if it is persisted. pub handle: Option, /// Numeric handle of the parent of this key if the parent is persisted. pub parent: Option, /// Wrapped private bytes of the key. pub private: Option, /// Wrapped unique/public bytes of the key. pub unique: Option, /// Key has been wrapped by [`wrap`]. pub wrapped: Option, /// Policy of key usage. pub policy: Option, } /// Key that has been wrapped. /// /// Some cryptographic providers can export a wrapped (encrypted) key. This structure /// defines details of these keys. #[derive(Debug, Serialize, Deserialize)] pub struct WrappedKey { /// Secret value that has been wrapped. pub secret: String, /// Private value that has been wrapped. pub private: String, /// Encrypted data for wrapping. pub data: String, } /// Public key bits. /// /// For export of public keys this structure is used with one variant per one supported /// asymmetric algorithm. #[derive(Debug, Serialize, Deserialize)] pub enum PublicKeyBytes { /// RSA public key details. RSA(RsaPublic), /// EC public details. EC(EcPublic), } /// RSA public key. /// /// Defines raw `bytes` of the public key of the RSA key. #[derive(Debug, Serialize, Deserialize)] pub struct RsaPublic { /// RSA raw bytes. pub bytes: String, } impl From<&RsaPublic> for PublicKeyRsa { fn from(public: &RsaPublic) -> Self { let public_modulus = hex::decode(&public.bytes).unwrap(); PublicKeyRsa::try_from(public_modulus).unwrap() } } /// EC public point. /// /// Defines the coordinates of EC's public point. #[derive(Debug, Serialize, Deserialize)] pub struct EcPublic { /// Point's `x` coordinate. pub x: String, /// Point's `y` coordinate. pub y: String, } impl From<&EcPublic> for EccPoint { fn from(public: &EcPublic) -> Self { let x = hex::decode(&public.x).unwrap(); let y = hex::decode(&public.y).unwrap(); EccPoint::new( EccParameter::try_from(x).unwrap(), EccParameter::try_from(y).unwrap(), ) } } /// Create key given by the `spec`. /// /// Creates given key and returns the `PublicBuilder` for that key. If the key was a private key import /// this function additionally returns a Sensitive value. pub fn create( spec: &Specification, ) -> Result<(PublicBuilder, Option)> { let is_fixed = spec.private.is_none() && spec.provider.tpm.wrapped.is_none() && spec.provider.tpm.policy.is_none(); let attributes = ObjectAttributesBuilder::new() .with_fixed_tpm(is_fixed) .with_fixed_parent(is_fixed) .with_sensitive_data_origin(true) .with_user_with_auth(true) .with_decrypt(spec.capabilities.contains(&Capability::Decrypt)) .with_sign_encrypt(spec.capabilities.contains(&Capability::Sign)) .with_restricted(spec.capabilities.contains(&Capability::Restrict)) .build()?; let mut builder = PublicBuilder::new() .with_name_hashing_algorithm(HashingAlgorithm::Sha256) .with_object_attributes(attributes); if let Some(policy) = &spec.provider.tpm.policy { builder = builder.with_auth_policy(Digest::try_from(hex::decode(policy).unwrap())?); } if let Some(unique) = &spec.provider.tpm.unique { builder = match unique { PublicKeyBytes::RSA(ref bytes) => builder.with_rsa_unique_identifier(bytes.into()), PublicKeyBytes::EC(ref bytes) => builder.with_ecc_unique_identifier(bytes.into()), } } else { builder = builder .with_rsa_unique_identifier(Default::default()) .with_ecc_unique_identifier(Default::default()); } builder = match &spec.algo { AlgorithmSpec::Rsa { bits, exponent } => { let mut rsa_params_builder = PublicRsaParametersBuilder::new(); if spec.capabilities.contains(&Capability::Restrict) { rsa_params_builder = rsa_params_builder.with_symmetric(SymmetricDefinitionObject::AES_256_CFB); } rsa_params_builder = rsa_params_builder .with_scheme(if spec.capabilities.contains(&Capability::Decrypt) { RsaScheme::Null } else if spec.capabilities.contains(&Capability::Sign) { RsaScheme::create(RsaSchemeAlgorithm::RsaSsa, Some(HashingAlgorithm::Sha256)) .unwrap() } else { panic!("Key needs to be for decryption or for signing") }) .with_key_bits(RsaKeyBits::try_from(*bits).unwrap()) .with_exponent(RsaExponent::try_from(exponent.unwrap_or(0)).unwrap()) .with_is_signing_key(spec.capabilities.contains(&Capability::Sign)) .with_is_decryption_key(spec.capabilities.contains(&Capability::Decrypt)) .with_restricted(spec.capabilities.contains(&Capability::Restrict)); let rsa_params = rsa_params_builder.build()?; builder .with_public_algorithm(PublicAlgorithm::Rsa) .with_rsa_parameters(rsa_params) } AlgorithmSpec::Ec { ref curve } => { let mut ecc_builder = PublicEccParametersBuilder::new() .with_ecc_scheme(if spec.capabilities.contains(&Capability::Decrypt) { EccScheme::Null } else if spec.capabilities.contains(&Capability::Sign) { EccScheme::create( EccSchemeAlgorithm::EcDsa, Some(HashingAlgorithm::Sha256), None, ) .unwrap() } else { panic!("Key needs to be for decryption or for signing") }) .with_curve(curve.into()) .with_is_signing_key(spec.capabilities.contains(&Capability::Sign)) .with_is_decryption_key(spec.capabilities.contains(&Capability::Decrypt)) .with_restricted(spec.capabilities.contains(&Capability::Restrict)) .with_key_derivation_function_scheme(KeyDerivationFunctionScheme::Null); if spec.capabilities.contains(&Capability::Restrict) { ecc_builder = ecc_builder.with_symmetric(SymmetricDefinitionObject::AES_256_CFB); } builder = builder .with_public_algorithm(PublicAlgorithm::Ecc) .with_ecc_parameters(ecc_builder.build()?); builder } }; let private = match spec.private { Some(PrivateKeyMaterial::Rsa(ref private_rsa)) => { let rsa: tss_esapi_sys::TPM2B_PRIVATE_KEY_RSA = private_rsa.into(); builder = builder.with_rsa_unique_identifier((&private_rsa.modulus).into()); Some(tss_esapi_sys::TPM2B_SENSITIVE { size: rsa.size, sensitiveArea: tss_esapi_sys::TPMT_SENSITIVE { sensitiveType: TPM2_ALG_RSA, authValue: Default::default(), seedValue: Default::default(), sensitive: tss_esapi_sys::TPMU_SENSITIVE_COMPOSITE { rsa }, }, }) } Some(PrivateKeyMaterial::Ec(ref param)) => { let ecc: tss_esapi_sys::TPM2B_ECC_PARAMETER = param.into(); builder = builder.with_ecc_unique_identifier((&(param.points)).into()); Some(tss_esapi_sys::TPM2B_SENSITIVE { size: ecc.size, sensitiveArea: tss_esapi_sys::TPMT_SENSITIVE { sensitiveType: TPM2_ALG_ECC, authValue: Default::default(), seedValue: Default::default(), sensitive: tss_esapi_sys::TPMU_SENSITIVE_COMPOSITE { ecc }, }, }) } _ => None, }; Ok((builder, private)) } /// Converts `specification` to raw key handle. /// /// TPM functions require a key handle as a key identifier. This function converts the key /// specification to the internal key handle object. pub fn convert_to_key_handle( context: &mut Context, specification: &Specification, ) -> Result { let key_handle = if let (public, Some(private)) = create(specification)? { context.load_external(private.try_into()?, public.build()?, Hierarchy::Null)? } else if let Some(handle) = specification.provider.tpm.handle { let persistent_tpm_handle = PersistentTpmHandle::new(handle)?; let handle = context.execute_without_session(|ctx| { ctx.tr_from_tpm_public(TpmHandle::Persistent(persistent_tpm_handle)) .expect("Need handle") }); handle.into() } else if let (Some(parent), Some(private)) = ( specification.provider.tpm.parent, &specification.provider.tpm.private, ) { let persistent_tpm_handle = PersistentTpmHandle::new(parent)?; let handle = context.execute_without_session(|ctx| { ctx.tr_from_tpm_public(TpmHandle::Persistent(persistent_tpm_handle)) .expect("Need handle") }); let key_handle: KeyHandle = handle.into(); context.tr_set_auth( key_handle.into(), Auth::try_from(specification.auth.as_bytes())?, )?; context.load( key_handle, Private::try_from(hex::decode(private).unwrap())?, create(specification)?.0.build()?, )? } else { panic!("Cannot load key"); }; context.tr_set_auth( key_handle.into(), Auth::try_from(specification.auth.as_bytes())?, )?; Ok(key_handle) } /// Read public key. /// /// Refreshes the key specification with data available in the cryptographic provider /// most notably the public key. pub fn read_key(spec: &mut Specification) -> Result<()> { let tcti = Tcti::from_str(&spec.provider.tpm.tcti)?; let mut context = Context::new(tcti)?; let session = context.start_auth_session( None, None, None, SessionType::Hmac, SymmetricDefinition::AES_256_CFB, HashingAlgorithm::Sha256, )?; let (session_attr, session_mask) = SessionAttributesBuilder::new() .with_decrypt(true) .with_encrypt(true) .build(); context .tr_sess_set_attributes(session.unwrap(), session_attr, session_mask) .unwrap(); context.set_sessions((session, None, None)); let key_handle = convert_to_key_handle(&mut context, spec)?; let (public, _, _) = context.read_public(key_handle)?; let public_key = match &public { Public::Rsa { unique, .. } => PublicKeyBytes::RSA(RsaPublic { bytes: hex::encode(unique.value()), }), Public::Ecc { unique, .. } => PublicKeyBytes::EC(EcPublic { x: hex::encode(unique.x().value()), y: hex::encode(unique.y().value()), }), _ => panic!("Unsupported key type."), }; spec.provider.tpm.unique = Some(public_key); spec.provider.tpm.policy = hex::encode( match &public { tss_esapi::structures::Public::Rsa { auth_policy, .. } => auth_policy, tss_esapi::structures::Public::Ecc { auth_policy, .. } => auth_policy, _ => panic!("Unsupported key type."), } .value(), ) .into(); Ok(()) } /// Decrypt a buffer of data. /// /// Use RSA decrypt function to decrypt a piece of `ciphertext` into a vector /// of bytes. /// /// *Note*: for EC keys use [`derive`]. pub fn decrypt(spec: &Specification, ciphertext: &[u8]) -> Result> { let tcti = Tcti::from_str(&spec.provider.tpm.tcti)?; let mut context = Context::new(tcti)?; let session = context.start_auth_session( None, None, None, SessionType::Hmac, SymmetricDefinition::AES_256_CFB, HashingAlgorithm::Sha256, )?; let (session_attr, session_mask) = SessionAttributesBuilder::new() .with_decrypt(true) .with_encrypt(true) .build(); context .tr_sess_set_attributes(session.unwrap(), session_attr, session_mask) .unwrap(); context.set_sessions((session, None, None)); let key_handle = convert_to_key_handle(&mut context, spec)?; let cipher_text = PublicKeyRsa::try_from(ciphertext)?; let plain_text = context.rsa_decrypt( key_handle, cipher_text, RsaDecryptionScheme::RsaEs, Data::default(), )?; Ok(plain_text.to_vec()) } /// Derives a common point. /// /// Use EC algorithm to derive a common point on a curve for both the key /// defined by `spec` and the public Z point defined in `data`. pub fn derive(spec: &Specification, data: &[u8]) -> Result<(Vec, Vec)> { let tcti = Tcti::from_str(&spec.provider.tpm.tcti)?; let mut context = Context::new(tcti)?; let session = context.start_auth_session( None, None, None, SessionType::Hmac, SymmetricDefinition::AES_256_CFB, HashingAlgorithm::Sha256, )?; let (session_attr, session_mask) = SessionAttributesBuilder::new() .with_decrypt(true) .with_encrypt(true) .build(); context .tr_sess_set_attributes(session.unwrap(), session_attr, session_mask) .unwrap(); context.set_sessions((session, None, None)); let key_handle = convert_to_key_handle(&mut context, spec)?; let size = data.len() / 2; let z_point = context.ecdh_z_gen( key_handle, EccPoint::new( EccParameter::try_from(&data[..size])?, EccParameter::try_from(&data[size..])?, ), )?; Ok((z_point.x().value().to_vec(), z_point.y().value().to_vec())) } /// Sign a hash of data. /// /// Uses key defined by `spec` to sign a digest specified by `hash` and returns raw /// signatures bytes as a vector. For RSA the vector specifies raw signature values. /// For EC the vector is a concatenation of signature's R and S values. /// /// Note: most TPMs only support SHA256. pub fn sign(spec: &Specification, hash_algo: HashingAlgorithm, hash: &[u8]) -> Result> { let tcti = Tcti::from_str(&spec.provider.tpm.tcti)?; let mut context = Context::new(tcti)?; let session = context.start_auth_session( None, None, None, SessionType::Hmac, SymmetricDefinition::AES_256_CFB, hash_algo, )?; let (session_attr, session_mask) = SessionAttributesBuilder::new() .with_decrypt(true) .with_encrypt(true) .build(); context .tr_sess_set_attributes(session.unwrap(), session_attr, session_mask) .unwrap(); context.set_sessions((session, None, None)); let key_handle = convert_to_key_handle(&mut context, spec)?; let scheme = SignatureScheme::Null; let validation = TPMT_TK_HASHCHECK { tag: TPM2_ST_HASHCHECK, hierarchy: TPM2_RH_NULL, digest: Default::default(), } .try_into()?; let digest = Digest::try_from(hash)?; let signature = context.sign(key_handle, digest, scheme, validation)?; Ok(match signature { Signature::RsaSsa(ref signature) => Vec::from(signature.signature().value()), Signature::EcDsa(signature) => { let mut sig = vec![]; sig.extend(signature.signature_r().value()); sig.extend(signature.signature_s().value()); sig } _ => panic!("Unsupported signature scheme."), }) } /// Wrap (encrypt) a key. /// /// Wraps the key specified by `spec` with the key specified by `parent`. Effectively this /// encrypts the private portion of the `spec` key with public key of the `parent` key. /// The `spec` key needs to allow wrapping (e.g. using PolicyDuplicationSelect) and the `parent` /// key needs to support import of wrapped keys (e.g. using Decrypt+Restricted capabilities). pub fn wrap(spec: &mut Specification, parent: &Specification) -> Result<()> { let tcti = Tcti::from_str(&spec.provider.tpm.tcti)?; let mut context = Context::new(tcti)?; // create a policy digest that allows key duplication let trial_session = context .start_auth_session( None, None, None, SessionType::Trial, SymmetricDefinition::AES_256_CFB, HashingAlgorithm::Sha256, )? .expect("Start auth session returned a NONE handle"); let (policy_auth_session_attributes, policy_auth_session_attributes_mask) = SessionAttributesBuilder::new() .with_decrypt(true) .with_encrypt(true) .build(); context.tr_sess_set_attributes( trial_session, policy_auth_session_attributes, policy_auth_session_attributes_mask, )?; let policy_session = PolicySession::try_from(trial_session)?; context.policy_auth_value(policy_session)?; context.policy_command_code(policy_session, CommandCode::Duplicate)?; let digest = context.policy_get_digest(policy_session)?; // end of: create policy digest let session = context.start_auth_session( None, None, None, SessionType::Hmac, SymmetricDefinition::AES_256_CFB, HashingAlgorithm::Sha256, )?; let (session_attr, session_mask) = SessionAttributesBuilder::new() .with_decrypt(true) .with_encrypt(true) .build(); context.tr_sess_set_attributes(session.unwrap(), session_attr, session_mask)?; context.set_sessions((session, None, None)); let key_handle = if let (public, Some(private)) = create(spec)? { context.load_external( private.try_into()?, public.with_auth_policy(digest).build()?, Hierarchy::Null, )? } else { panic!("Can import only private keys"); }; let parent_handle = context.load_external_public(create(parent)?.0.build()?, Hierarchy::Null)?; let (public, _, _) = context.read_public(key_handle)?; let public_key = match &public { Public::Rsa { unique, .. } => PublicKeyBytes::RSA(RsaPublic { bytes: hex::encode(unique.value()), }), Public::Ecc { unique, .. } => PublicKeyBytes::EC(EcPublic { x: hex::encode(unique.x().value()), y: hex::encode(unique.y().value()), }), _ => panic!("Unsupported key type."), }; let auth_policy = match &public { tss_esapi::structures::Public::Rsa { auth_policy, .. } => auth_policy, tss_esapi::structures::Public::Ecc { auth_policy, .. } => auth_policy, _ => panic!("Unsupported key type."), } .value(); spec.provider.tpm.unique = Some(public_key); spec.private = None; context.set_sessions((None, None, None)); let policy_auth_session = context .start_auth_session( None, None, None, SessionType::Policy, SymmetricDefinition::AES_256_CFB, HashingAlgorithm::Sha256, )? .expect("Start auth session returned a NONE handle"); let (policy_auth_session_attributes, policy_auth_session_attributes_mask) = SessionAttributesBuilder::new() .with_decrypt(true) .with_encrypt(true) .build(); context.tr_sess_set_attributes( policy_auth_session, policy_auth_session_attributes, policy_auth_session_attributes_mask, )?; let policy_session = PolicySession::try_from(policy_auth_session)?; context.policy_auth_value(policy_session)?; context.policy_command_code(policy_session, CommandCode::Duplicate)?; context.set_sessions((Some(policy_auth_session), None, None)); let (data, private, secret) = context.duplicate( key_handle.into(), parent_handle.into(), None, SymmetricDefinitionObject::Null, )?; spec.provider.tpm.wrapped = Some(WrappedKey { private: hex::encode(private.value()), secret: hex::encode(secret.value()), data: hex::encode(data.value()), }); spec.provider.tpm.policy = Some(hex::encode(auth_policy)); spec.provider.tpm.parent = parent.provider.tpm.handle; Ok(()) }