diff --git a/.cargo/config b/.cargo/config index c91c3f3..7ce14af 100644 --- a/.cargo/config +++ b/.cargo/config @@ -1,2 +1,5 @@ +# Copyright (C) 2022 Nicolas Stalder +# SPDX-License-Identifier: Apache-2.0 OR MIT + [net] git-fetch-with-cli = true diff --git a/.gitignore b/.gitignore index 96ef6c0..ecd7ce7 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,7 @@ +# Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +# SPDX-License-Identifier: Apache-2.0 OR MIT + /target Cargo.lock +tarpaulin-report.html +cobertura.xml diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml new file mode 100644 index 0000000..2d18f2f --- /dev/null +++ b/.gitlab-ci.yml @@ -0,0 +1,50 @@ +# Copyright (C) 2022 Nitrokey GmbH +# SPDX-License-Identifier: CC0-1.0 + +include: 'https://raw.githubusercontent.com/Nitrokey/common-ci-jobs/master/common_jobs.yml' + +stages: + - pull-github + - build + - deploy + +variables: + GIT_STRATEGY: clone + GIT_DEPTH: 0 + GIT_SUBMODULE_STRATEGY: recursive + REPO_NAME: piv-authenticator + MAIN_BRANCH: initial-refacto + COMMON_PULL: "true" + COMMON_UPLOAD_NIGHTLY: "false" + COMMON_GITHUB_RELEASE: "false" + COMMON_UPLOAD_FILES: "false" + +build: + image: registry.git.nitrokey.com/nitrokey/piv-authenticator/piv-authenticator-build:latest + rules: + - if: '$CI_PIPELINE_SHOULD_NOT_BUILD == "true"' + when: never + - if: '$CI_PIPELINE_SOURCE == "push"' + - if: '$CI_PIPELINE_SOURCE == "web"' + - if: '$CI_PIPELINE_SOURCE == "schedule"' + tags: + - docker + stage: build + before_script: + - cargo --version + script: + - make ci + after_script: + - wget $icon_server/checkmark/$CI_COMMIT_REF_NAME/$CI_COMMIT_SHA/$CI_JOB_NAME/$CI_JOB_STATUS/${CI_JOB_URL#*/*/*/} + - cp /app/.cache/scdaemon.log scdaemon.log + coverage: '/^\d+.\d+% coverage/' + artifacts: + when: always + paths: + - "scdaemon.log" + - "cobertura.xml" + - "tarpaulin-report.html" + reports: + coverage_report: + coverage_format: cobertura + path: cobertura.xml diff --git a/Cargo.toml b/Cargo.toml index fd7d994..8261708 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,34 +1,56 @@ +# Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +# SPDX-License-Identifier: Apache-2.0 OR MIT + [package] name = "piv-authenticator" version = "0.0.0-unreleased" -authors = ["Nicolas Stalder "] -edition = "2018" -license = "Apache-2.0 OR MIT" +authors = ["Nicolas Stalder ", "Nitrokey GmbH"] +edition = "2021" +license = "LGPL-3.0-only" repository = "https://github.com/solokeys/piv-authenticator" documentation = "https://docs.rs/piv-authenticator" -# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html +[[example]] +name = "virtual" +required-features = ["virtual"] [dependencies] apdu-dispatch = { version = "0.1", optional = true } -delog = "0.1.0" +delog = { version = "0.1.5", optional = true } flexiber = { version = "0.1", features = ["derive", "heapless"] } heapless = "0.7" hex-literal = "0.3" -interchange = "0.2.0" +interchange = "0.2.2" iso7816 = "0.1" -serde = { version = "1", default-features = false } -trussed = { git = "https://github.com/trussed-dev/trussed" } -# trussed = { path = "../../../trussed" } -untrusted = "0.7" +serde = { version = "1", default-features = false, features = ["derive"] } +trussed = "0.1" +untrusted = "0.9" +vpicc = { version = "0.1.0", optional = true } +log = "0.4" +heapless-bytes = "0.3.0" +subtle = "2" [dev-dependencies] -littlefs2 = "0.3.1" +littlefs2 = "0.3.2" rand_core = { version = "0.6", features = ["getrandom"] } +trussed = { version = "0.1.0", features = ["virt"] } +env_logger = "0.9" +serde = { version = "1", features = ["derive"] } +serde_cbor = { version = "0.11", features = ["std"] } +hex = "0.4" +test-log = "0.2" +ron = "0.8" +des = "0.8" +aes = "0.8.2" +stoppable_thread = "0.2.1" +expectrl = "0.6.0" + [features] default = [] strict-pin = [] +std = [] +virtual = ["std", "vpicc","trussed/virt"] log-all = [] log-none = [] @@ -36,3 +58,6 @@ log-info = [] log-debug = [] log-warn = [] log-error = [] + +[patch.crates-io] +trussed = { git = "https://github.com/Nitrokey/trussed", tag = "v0.1.0-nitrokey-3"} diff --git a/LICENSE-APACHE b/LICENSES/Apache-2.0.txt similarity index 100% rename from LICENSE-APACHE rename to LICENSES/Apache-2.0.txt diff --git a/LICENSES/CC0-1.0.txt b/LICENSES/CC0-1.0.txt new file mode 100644 index 0000000..0e259d4 --- /dev/null +++ b/LICENSES/CC0-1.0.txt @@ -0,0 +1,121 @@ +Creative Commons Legal Code + +CC0 1.0 Universal + + CREATIVE COMMONS CORPORATION IS NOT A LAW FIRM AND DOES NOT PROVIDE + LEGAL SERVICES. DISTRIBUTION OF THIS DOCUMENT DOES NOT CREATE AN + ATTORNEY-CLIENT RELATIONSHIP. CREATIVE COMMONS PROVIDES THIS + INFORMATION ON AN "AS-IS" BASIS. CREATIVE COMMONS MAKES NO WARRANTIES + REGARDING THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS + PROVIDED HEREUNDER, AND DISCLAIMS LIABILITY FOR DAMAGES RESULTING FROM + THE USE OF THIS DOCUMENT OR THE INFORMATION OR WORKS PROVIDED + HEREUNDER. + +Statement of Purpose + +The laws of most jurisdictions throughout the world automatically confer +exclusive Copyright and Related Rights (defined below) upon the creator +and subsequent owner(s) (each and all, an "owner") of an original work of +authorship and/or a database (each, a "Work"). + +Certain owners wish to permanently relinquish those rights to a Work for +the purpose of contributing to a commons of creative, cultural and +scientific works ("Commons") that the public can reliably and without fear +of later claims of infringement build upon, modify, incorporate in other +works, reuse and redistribute as freely as possible in any form whatsoever +and for any purposes, including without limitation commercial purposes. +These owners may contribute to the Commons to promote the ideal of a free +culture and the further production of creative, cultural and scientific +works, or to gain reputation or greater distribution for their Work in +part through the use and efforts of others. + +For these and/or other purposes and motivations, and without any +expectation of additional consideration or compensation, the person +associating CC0 with a Work (the "Affirmer"), to the extent that he or she +is an owner of Copyright and Related Rights in the Work, voluntarily +elects to apply CC0 to the Work and publicly distribute the Work under its +terms, with knowledge of his or her Copyright and Related Rights in the +Work and the meaning and intended legal effect of CC0 on those rights. + +1. Copyright and Related Rights. A Work made available under CC0 may be +protected by copyright and related or neighboring rights ("Copyright and +Related Rights"). Copyright and Related Rights include, but are not +limited to, the following: + + i. the right to reproduce, adapt, distribute, perform, display, + communicate, and translate a Work; + ii. moral rights retained by the original author(s) and/or performer(s); +iii. publicity and privacy rights pertaining to a person's image or + likeness depicted in a Work; + iv. rights protecting against unfair competition in regards to a Work, + subject to the limitations in paragraph 4(a), below; + v. rights protecting the extraction, dissemination, use and reuse of data + in a Work; + vi. database rights (such as those arising under Directive 96/9/EC of the + European Parliament and of the Council of 11 March 1996 on the legal + protection of databases, and under any national implementation + thereof, including any amended or successor version of such + directive); and +vii. other similar, equivalent or corresponding rights throughout the + world based on applicable law or treaty, and any national + implementations thereof. + +2. Waiver. To the greatest extent permitted by, but not in contravention +of, applicable law, Affirmer hereby overtly, fully, permanently, +irrevocably and unconditionally waives, abandons, and surrenders all of +Affirmer's Copyright and Related Rights and associated claims and causes +of action, whether now known or unknown (including existing as well as +future claims and causes of action), in the Work (i) in all territories +worldwide, (ii) for the maximum duration provided by applicable law or +treaty (including future time extensions), (iii) in any current or future +medium and for any number of copies, and (iv) for any purpose whatsoever, +including without limitation commercial, advertising or promotional +purposes (the "Waiver"). Affirmer makes the Waiver for the benefit of each +member of the public at large and to the detriment of Affirmer's heirs and +successors, fully intending that such Waiver shall not be subject to +revocation, rescission, cancellation, termination, or any other legal or +equitable action to disrupt the quiet enjoyment of the Work by the public +as contemplated by Affirmer's express Statement of Purpose. + +3. Public License Fallback. Should any part of the Waiver for any reason +be judged legally invalid or ineffective under applicable law, then the +Waiver shall be preserved to the maximum extent permitted taking into +account Affirmer's express Statement of Purpose. In addition, to the +extent the Waiver is so judged Affirmer hereby grants to each affected +person a royalty-free, non transferable, non sublicensable, non exclusive, +irrevocable and unconditional license to exercise Affirmer's Copyright and +Related Rights in the Work (i) in all territories worldwide, (ii) for the +maximum duration provided by applicable law or treaty (including future +time extensions), (iii) in any current or future medium and for any number +of copies, and (iv) for any purpose whatsoever, including without +limitation commercial, advertising or promotional purposes (the +"License"). The License shall be deemed effective as of the date CC0 was +applied by Affirmer to the Work. Should any part of the License for any +reason be judged legally invalid or ineffective under applicable law, such +partial invalidity or ineffectiveness shall not invalidate the remainder +of the License, and in such case Affirmer hereby affirms that he or she +will not (i) exercise any of his or her remaining Copyright and Related +Rights in the Work or (ii) assert any associated claims and causes of +action with respect to the Work, in either case contrary to Affirmer's +express Statement of Purpose. + +4. Limitations and Disclaimers. + + a. No trademark or patent rights held by Affirmer are waived, abandoned, + surrendered, licensed or otherwise affected by this document. + b. Affirmer offers the Work as-is and makes no representations or + warranties of any kind concerning the Work, express, implied, + statutory or otherwise, including without limitation warranties of + title, merchantability, fitness for a particular purpose, non + infringement, or the absence of latent or other defects, accuracy, or + the present or absence of errors, whether or not discoverable, all to + the greatest extent permissible under applicable law. + c. Affirmer disclaims responsibility for clearing rights of other persons + that may apply to the Work or any use thereof, including without + limitation any person's Copyright and Related Rights in the Work. + Further, Affirmer disclaims responsibility for obtaining any necessary + consents, permissions or other rights required for any use of the + Work. + d. Affirmer understands and acknowledges that Creative Commons is not a + party to this document and has no duty or obligation with respect to + this CC0 or use of the Work. diff --git a/LICENSES/LGPL-3.0-only.txt b/LICENSES/LGPL-3.0-only.txt new file mode 100644 index 0000000..513d1c0 --- /dev/null +++ b/LICENSES/LGPL-3.0-only.txt @@ -0,0 +1,304 @@ +GNU LESSER GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright (C) 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. + +0. Additional Definitions. + +As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. + +"The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. + +An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. + +A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". + +The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. + +The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. + +1. Exception to Section 3 of the GNU GPL. +You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. + +2. Conveying Modified Versions. +If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: + + a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or + + b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. + +3. Object Code Incorporating Material from Library Header Files. +The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: + + a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. + + b) Accompany the object code with a copy of the GNU GPL and this license document. + +4. Combined Works. +You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: + + a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. + + b) Accompany the Combined Work with a copy of the GNU GPL and this license document. + + c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. + + d) Do one of the following: + + 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. + + 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. + + e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) + +5. Combined Libraries. +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 that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: + + a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. + + b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. + +6. Revised Versions of the GNU Lesser General Public License. +The Free Software Foundation may publish revised and/or new versions of the GNU Lesser 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 as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. + +If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall +apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. + +GNU GENERAL PUBLIC LICENSE +Version 3, 29 June 2007 + +Copyright © 2007 Free Software Foundation, Inc. + +Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. + +Preamble + +The GNU General Public License is a free, copyleft license for software and other kinds of works. + +The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, 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 them 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 prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. + +For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. + +Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. + +For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. + +Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. + +Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. + +The precise terms and conditions for copying, distribution and modification follow. + +TERMS AND CONDITIONS + +0. Definitions. + +“This License” refers to version 3 of the GNU General Public License. + +“Copyright” also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. + +“The Program” refers to any copyrightable work licensed under this License. Each licensee is addressed as “you”. “Licensees” and “recipients” may be individuals or organizations. + +To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work. + +A “covered work” means either the unmodified Program or a work based on the Program. + +To “propagate” a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. + +To “convey” a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. + +An interactive user interface displays “Appropriate Legal Notices” to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. + +1. Source Code. +The “source code” for a work means the preferred form of the work for making modifications to it. “Object code” means any non-source form of a work. + +A “Standard Interface” means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. + +The “System Libraries” of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A “Major Component”, in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. + +The “Corresponding Source” for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. + +The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. + +The Corresponding Source for a work in source code form is that same work. + +2. Basic Permissions. +All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. + +You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. + +Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. + +3. Protecting Users' Legal Rights From Anti-Circumvention Law. +No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. + +When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. + +4. Conveying Verbatim Copies. +You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. + +You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. + +5. Conveying Modified Source Versions. +You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to “keep intact all notices”. + + c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. + +A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an “aggregate” if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. + +6. Conveying Non-Source Forms. +You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: + + a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. + + d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. + +A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. + +A “User Product” is either (1) a “consumer product”, which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, “normally used” refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. + +“Installation Information” for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. + +If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). + +The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. + +Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. + +7. Additional Terms. +“Additional permissions” are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. + +When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. + +Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or authors of the material; or + + e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. + +All other non-permissive additional terms are considered “further restrictions” within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. + +If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. + +Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. + +8. Termination. +You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). + +However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. + +Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. + +Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. + +9. Acceptance Not Required for Having Copies. +You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. + +10. Automatic Licensing of Downstream Recipients. +Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. + +An “entity transaction” is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. + +You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. + +11. Patents. +A “contributor” is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's “contributor version”. + +A contributor's “essential patent claims” are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, “control” includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. + +Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. + +In the following three paragraphs, a “patent license” is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To “grant” such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. + +If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. “Knowingly relying” means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. + +If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. + +A patent license is “discriminatory” if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. + +Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. + +12. No Surrender of Others' Freedom. +If 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 convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. + +13. Use with the GNU Affero General Public License. +Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. + +14. Revised Versions of this License. +The Free Software Foundation may publish revised and/or new versions of the GNU 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 Program specifies that a certain numbered version of the GNU General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. + +If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. + +Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. + +15. Disclaimer of Warranty. +THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM “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 PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + +16. Limitation of Liability. +IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +17. Interpretation of Sections 15 and 16. +If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. + +END OF TERMS AND CONDITIONS + +How to Apply These Terms to Your New Programs + +If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. + +To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state 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 program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. + + This program 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, see . + +Also add information on how to contact you by electronic and paper mail. + +If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an “about box”. + +You should also get your employer (if you work as a programmer) or school, if any, to sign a “copyright disclaimer” for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . + +The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . diff --git a/LICENSE-MIT b/LICENSES/MIT.txt similarity index 100% rename from LICENSE-MIT rename to LICENSES/MIT.txt diff --git a/Makefile b/Makefile index 031929b..ac78149 100644 --- a/Makefile +++ b/Makefile @@ -1,2 +1,34 @@ +# Copyright (C) 2022 Nitrokey GmbH +# SPDX-License-Identifier: CC0-1.0 + +.NOTPARALLEL: + +export RUST_LOG ?= info,cargo_tarpaulin=off + +.PHONY: build-cortex-m4 build-cortex-m4: cargo build --target thumbv7em-none-eabi + +.PHONY: test +test: + cargo test --features virtual + +.PHONY: check +check: + cargo fmt --check + cargo check --all-targets --all-features + cargo clippy --all-targets --all-features -- -Dwarnings + RUSTDOCFLAGS='-Dwarnings' cargo doc --all-features + reuse lint + +.PHONY: tarpaulin +tarpaulin: + cargo tarpaulin --features virtual -o Html -o Xml + +.PHONY: example +example: + cargo run --example virtual --features virtual + +.PHONY: ci +ci: check tarpaulin + diff --git a/README.md b/README.md new file mode 100644 index 0000000..c41c050 --- /dev/null +++ b/README.md @@ -0,0 +1,35 @@ + + +PIV-Authenticator +================= + +`piv-authenticator` is a Rust implematation of the [Personnal Identity Verification](https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf) smartcard. + +Supported features +------------------ + +`piv-authenticator` is still under heavy development and currently doesn't support most of PIV's features. +See the [tracking issue for command support](https://github.com/Nitrokey/piv-authenticator/issues/1) for more information. + +License +------- + +This project is licensed under the [GNU Lesser General Public License (LGPL) +version 3][LGPL-3.0]. Configuration files and examples are licensed under the +[CC0 1.0 license][CC0-1.0]. The [original work][original] by [Solokeys][solokeys] from which this repository is forked from is licensed under [Apache-2.0][Apache-2.0] OR [MIT][MIT] For more information, see the license header in +each file. You can find a copy of the license texts in the +[`LICENSES`](./LICENSES) directory. + +[LGPL-3.0]: https://opensource.org/licenses/LGPL-3.0 +[CC0-1.0]: https://creativecommons.org/publicdomain/zero/1.0/ +[Apache-2.0]: https://www.apache.org/licenses/LICENSE-2.0.html +[MIT]: https://en.wikipedia.org/wiki/MIT_License +[solokeys]: https://solokeys.com/ +[original]: https://github.com/solokeys/piv-authenticator + +This project complies with [version 3.0 of the REUSE specification][reuse]. + +[reuse]: https://reuse.software/practices/3.0/ diff --git a/bacon.toml b/bacon.toml index 346112d..7642144 100644 --- a/bacon.toml +++ b/bacon.toml @@ -1,3 +1,5 @@ +# Copyright (C) 2022 Nicolas Stalder +# SPDX-License-Identifier: Apache-2.0 OR MIT # This is a configuration file for the bacon tool # More info at https://github.com/Canop/bacon diff --git a/ci/Dockerfile b/ci/Dockerfile new file mode 100644 index 0000000..7896c87 --- /dev/null +++ b/ci/Dockerfile @@ -0,0 +1,30 @@ +# Copyright (C) 2022 Nitrokey GmbH +# SPDX-License-Identifier: CC0-1.0 + +FROM docker.io/rust:latest + +RUN apt update && apt install --yes libpcsclite-dev \ + && wget https://github.com/arekinath/pivy/releases/download/v0.10.0/pivy-0.10.0-src.tar.gz \ + && tar xvf pivy-0.10.0-src.tar.gz \ + && cd pivy-0.10.0 \ + && make pivy-tool + +FROM docker.io/rust:latest + +RUN apt update && apt install --yes scdaemon libclang-dev llvm python3-pip vsmartcard-vpcd pkg-config nettle-dev libpcsclite-dev opensc + +RUN python3 -m pip install reuse + +RUN rustup component add clippy rustfmt && rustup target add thumbv7em-none-eabi +RUN cargo install cargo-tarpaulin --profile release && rm -rf "$CARGO_HOME"/registry +# initialize cargo cache +RUN cargo search + +ENV CARGO_HOME=/app/.cache/cargo + +COPY --from=0 pivy-0.10.0/pivy-tool /bin/pivy-tool + +WORKDIR /app + +COPY entrypoint.sh /entrypoint.sh +ENTRYPOINT ["/bin/bash", "/entrypoint.sh"] diff --git a/ci/Makefile b/ci/Makefile new file mode 100644 index 0000000..28ae5e9 --- /dev/null +++ b/ci/Makefile @@ -0,0 +1,29 @@ +# Copyright (C) 2022 Nitrokey GmbH +# SPDX-License-Identifier: CC0-1.0 + +-include config.mk + +TAG := registry.git.nitrokey.com/nitrokey/piv-authenticator/piv-authenticator-build +DOCKER ?= docker +FUZZ_JOBS?=$(shell nproc) +FUZZ_DURATION?="0" + +.PHONY: build +build: + $(DOCKER) build . --tag $(TAG) + +.PHONY: push +push: + $(DOCKER) push $(TAG) + +.PHONY: run +run: + $(DOCKER) run --interactive --rm --volume "$(PWD)/..:/app" --env RUST_LOG $(TAG) make ci + +.PHONY: test +test: + $(DOCKER) run --interactive --rm --volume "$(PWD)/..:/app" --env RUST_LOG $(TAG) make test + +.PHONY: fuzz +fuzz: + $(DOCKER) run --interactive --rm --volume "$(PWD)/..:/app" --env RUST_LOG $(TAG) make fuzz FUZZ_JOBS=${FUZZ_JOBS} FUZZ_DURATION=${FUZZ_DURATION} diff --git a/ci/entrypoint.sh b/ci/entrypoint.sh new file mode 100644 index 0000000..4c27a27 --- /dev/null +++ b/ci/entrypoint.sh @@ -0,0 +1,12 @@ +#!/bin/sh +# Copyright (C) 2022 Nitrokey GmbH +# SPDX-License-Identifier: CC0-1.0 + +set -e +mkdir -p /app/.cache +if [ ! -e "$CARGO_HOME" ] +then + cp -r /usr/local/cargo $CARGO_HOME +fi +pcscd +exec "$@" diff --git a/examples/virtual.rs b/examples/virtual.rs new file mode 100644 index 0000000..b5cd4f7 --- /dev/null +++ b/examples/virtual.rs @@ -0,0 +1,25 @@ +// Copyright (C) 2022 Nitrokey GmbH +// SPDX-License-Identifier: CC0-1.0 + +// To use this, make sure that you have vpcd from vsmartcard installed and configured (e. g. +// install vsmartcard-vpcd on Debian). You might have to restart your pcscd, e. g. +// `systemctl restart pcscd pcscd.socket`. +// +// Now you should be able to see the card in `pcsc_scan` and talk to it with `piv-tool`r +// +// Set `RUST_LOG=piv_authenticator::card=info` to see the executed commands. + +// TODO: add CLI + +fn main() { + env_logger::init(); + + trussed::virt::with_ram_client("piv-authenticator", |client| { + let card = piv_authenticator::Authenticator::new(client); + let mut virtual_card = piv_authenticator::vpicc::VirtualCard::new(card); + let vpicc = vpicc::connect().expect("failed to connect to vpicc"); + vpicc + .run(&mut virtual_card) + .expect("failed to run virtual smartcard"); + }); +} diff --git a/src/commands.rs b/src/commands.rs index 09965d4..0b8cdde 100644 --- a/src/commands.rs +++ b/src/commands.rs @@ -1,3 +1,6 @@ +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + //! Parsed PIV commands. //! //! The types here should enforce all restrictions in the spec (such as padded_piv_pin.len() == 8), @@ -8,7 +11,27 @@ use core::convert::{TryFrom, TryInto}; // use flexiber::Decodable; use iso7816::{Instruction, Status}; -pub use crate::{container as containers, piv_types, Pin, Puk}; +use crate::state::TouchPolicy; +pub use crate::{ + container::{ + self as containers, AttestKeyReference, AuthenticateKeyReference, + ChangeReferenceKeyReference, GenerateAsymmetricKeyReference, VerifyKeyReference, + }, + piv_types, Pin, Puk, +}; + +// https://developers.yubico.com/PIV/Introduction/Yubico_extensions.html +#[derive(Copy, Clone, Debug, Eq, PartialEq)] +pub enum YubicoPivExtension { + SetManagementKey(TouchPolicy), + ImportAsymmetricKey, + GetVersion, + Reset, + SetPinRetries, + Attest(AttestKeyReference), + GetSerial, // also used via 0x01 + GetMetadata, +} #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum Command<'l> { @@ -32,10 +55,19 @@ pub enum Command<'l> { /// The most general purpose method, performing actual cryptographic operations /// /// In particular, this can also decrypt or similar. - Authenticate(Authenticate), + GeneralAuthenticate(GeneralAuthenticate), /// Store a data object / container. PutData(PutData), - GenerateAsymmetric(GenerateAsymmetric), + GenerateAsymmetric(GenerateAsymmetricKeyReference), + + /* Yubico commands */ + YkExtension(YubicoPivExtension), +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +pub struct GeneralAuthenticate { + pub algorithm: piv_types::Algorithms, + key_reference: AuthenticateKeyReference, } impl<'l> Command<'l> { @@ -66,7 +98,6 @@ impl<'l> TryFrom<&'l [u8]> for Select<'l> { } } - #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct GetData(containers::Container); @@ -74,7 +105,9 @@ impl TryFrom<&[u8]> for GetData { type Error = Status; fn try_from(data: &[u8]) -> Result { let mut decoder = flexiber::Decoder::new(data); - let tagged_slice: flexiber::TaggedSlice = decoder.decode().map_err(|_| Status::IncorrectDataParameter)?; + let tagged_slice: flexiber::TaggedSlice = decoder + .decode() + .map_err(|_| Status::IncorrectDataParameter)?; if tagged_slice.tag() != flexiber::Tag::application(0x1C) { return Err(Status::IncorrectDataParameter); } @@ -82,41 +115,11 @@ impl TryFrom<&[u8]> for GetData { .try_into() .map_err(|_| Status::IncorrectDataParameter)?; - info_now!("request to GetData for container {:?}", container); + info!("request to GetData for container {:?}", container); Ok(Self(container)) } } -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -#[repr(u8)] -pub enum VerifyKeyReference { - GlobalPin = 0x00, - PivPin = 0x80, - PrimaryFingerOcc = 0x96, - SecondaryFingerOcc = 0x97, - PairingCode = 0x98, -} - -impl TryFrom for VerifyKeyReference { - type Error = Status; - fn try_from(p2: u8) -> Result { - // If the PIV Card Application does not contain the Discovery Object as described in Part 1, - // then no other key reference shall be able to be verified by the PIV Card Application VERIFY command. - match p2 { - 0x00 => Ok(Self::GlobalPin), - // 0x00 => Err(Status::FunctionNotSupported), - 0x80 => Ok(Self::PivPin), - 0x96 => Ok(Self::PrimaryFingerOcc), - 0x97 => Ok(Self::SecondaryFingerOcc), - 0x98 => Ok(Self::PairingCode), - // 0x96 => Err(Status::FunctionNotSupported), - // 0x97 => Err(Status::FunctionNotSupported), - // 0x98 => Err(Status::FunctionNotSupported), - _ => Err(Status::KeyReferenceNotFound), - } - } -} - #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct VerifyLogout(bool); @@ -130,7 +133,6 @@ impl TryFrom for VerifyLogout { } } } - #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct VerifyArguments<'l> { pub key_reference: VerifyKeyReference, @@ -155,13 +157,20 @@ pub enum Verify { impl TryFrom> for Verify { type Error = Status; fn try_from(arguments: VerifyArguments<'_>) -> Result { - let VerifyArguments { key_reference, logout, data } = arguments; - if key_reference != VerifyKeyReference::PivPin { + let VerifyArguments { + key_reference, + logout, + data, + } = arguments; + if key_reference != VerifyKeyReference::ApplicationPin { return Err(Status::FunctionNotSupported); } Ok(match (logout.0, data.len()) { (false, 0) => Verify::Status(key_reference), - (false, 8) => Verify::Login(VerifyLogin::PivPin(data.try_into().map_err(|_| Status::IncorrectDataParameter)?)), + (false, 8) => Verify::Login(VerifyLogin::PivPin( + data.try_into() + .map_err(|_| Status::IncorrectDataParameter)?, + )), (false, _) => return Err(Status::IncorrectDataParameter), (true, 0) => Verify::Logout(key_reference), (true, _) => return Err(Status::IncorrectDataParameter), @@ -169,26 +178,6 @@ impl TryFrom> for Verify { } } -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -#[repr(u8)] -pub enum ChangeReferenceKeyReference { - GlobalPin = 0x00, - PivPin = 0x80, - Puk = 0x81, -} - -impl TryFrom for ChangeReferenceKeyReference { - type Error = Status; - fn try_from(p2: u8) -> Result { - match p2 { - 0x00 => Ok(Self::GlobalPin), - 0x80 => Ok(Self::PivPin), - 0x81 => Ok(Self::Puk), - _ => Err(Status::KeyReferenceNotFound), - } - } -} - #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct ChangeReferenceArguments<'l> { pub key_reference: ChangeReferenceKeyReference, @@ -204,24 +193,26 @@ pub enum ChangeReference { impl TryFrom> for ChangeReference { type Error = Status; fn try_from(arguments: ChangeReferenceArguments<'_>) -> Result { - let ChangeReferenceArguments { key_reference, data } = arguments; + let ChangeReferenceArguments { + key_reference, + data, + } = arguments; use ChangeReferenceKeyReference::*; Ok(match (key_reference, data) { (GlobalPin, _) => return Err(Status::FunctionNotSupported), - (PivPin, data) => { - ChangeReference::ChangePin { - old_pin: Pin::try_from(&data[..8]).map_err(|_| Status::IncorrectDataParameter)?, - new_pin: Pin::try_from(&data[8..]).map_err(|_| Status::IncorrectDataParameter)?, - } - } - (Puk, data) => { - use crate::commands::Puk; - ChangeReference::ChangePuk { - old_puk: Puk(data[..8].try_into().map_err(|_| Status::IncorrectDataParameter)?), - new_puk: Puk(data[8..].try_into().map_err(|_| Status::IncorrectDataParameter)?), - } - } + (ApplicationPin, data) => ChangeReference::ChangePin { + old_pin: Pin::try_from(&data[..8]).map_err(|_| Status::IncorrectDataParameter)?, + new_pin: Pin::try_from(&data[8..]).map_err(|_| Status::IncorrectDataParameter)?, + }, + (PinUnblockingKey, data) => ChangeReference::ChangePuk { + old_puk: Puk(data[..8] + .try_into() + .map_err(|_| Status::IncorrectDataParameter)?), + new_puk: Puk(data[8..] + .try_into() + .map_err(|_| Status::IncorrectDataParameter)?), + }, }) } } @@ -229,7 +220,7 @@ impl TryFrom> for ChangeReference { #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct ResetPinRetries { pub padded_pin: [u8; 8], - pub puk: [u8; 8], + pub puk: [u8; 8], } impl TryFrom<&[u8]> for ResetPinRetries { @@ -245,72 +236,6 @@ impl TryFrom<&[u8]> for ResetPinRetries { } } -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -#[repr(u8)] -pub enum AuthenticateKeyReference { - SecureMessaging = 0x04, - Authentication = 0x9a, - Administration = 0x9b, - Signature = 0x9c, - Management = 0x9d, - CardAuthentication = 0x9e, - Retired01 = 0x82, - Retired02 = 0x83, - Retired03 = 0x84, - Retired04 = 0x85, - Retired05 = 0x86, - Retired06 = 0x87, - Retired07 = 0x88, - Retired08 = 0x89, - Retired09 = 0x8A, - Retired10 = 0x8B, - Retired11 = 0x8C, - Retired12 = 0x8D, - Retired13 = 0x8E, - Retired14 = 0x8F, - Retired15 = 0x90, - Retired16 = 0x91, - Retired17 = 0x92, - Retired18 = 0x93, - Retired19 = 0x94, - Retired20 = 0x95, -} - -impl TryFrom for AuthenticateKeyReference { - type Error = Status; - fn try_from(p2: u8) -> Result { - match p2 { - 0x04 => Ok(Self::SecureMessaging), - 0x9a => Ok(Self::Authentication), - 0x9b => Ok(Self::Administration), - 0x9c => Ok(Self::Signature), - 0x9d => Ok(Self::Management), - 0x9e => Ok(Self::CardAuthentication), - 0x82 => Ok(Self::Retired01), - 0x83 => Ok(Self::Retired02), - 0x84 => Ok(Self::Retired03), - 0x85 => Ok(Self::Retired04), - 0x86 => Ok(Self::Retired05), - 0x87 => Ok(Self::Retired06), - 0x88 => Ok(Self::Retired07), - 0x89 => Ok(Self::Retired08), - 0x8A => Ok(Self::Retired09), - 0x8B => Ok(Self::Retired10), - 0x8C => Ok(Self::Retired11), - 0x8D => Ok(Self::Retired12), - 0x8E => Ok(Self::Retired13), - 0x8F => Ok(Self::Retired14), - 0x90 => Ok(Self::Retired15), - 0x91 => Ok(Self::Retired16), - 0x92 => Ok(Self::Retired17), - 0x93 => Ok(Self::Retired18), - 0x94 => Ok(Self::Retired19), - 0x95 => Ok(Self::Retired20), - _ => Err(Status::KeyReferenceNotFound), - } - } -} - #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct AuthenticateArguments<'l> { /// To allow the authenticator to have additional algorithms beyond NIST SP 800-78-4, @@ -321,19 +246,7 @@ pub struct AuthenticateArguments<'l> { } #[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum Authenticate { -} - -impl TryFrom> for Authenticate { - type Error = Status; - fn try_from(_arguments: AuthenticateArguments<'_>) -> Result { - todo!(); - } -} - -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub struct PutData { -} +pub struct PutData {} impl TryFrom<&[u8]> for PutData { type Error = Status; @@ -342,47 +255,6 @@ impl TryFrom<&[u8]> for PutData { } } -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -#[repr(u8)] -pub enum GenerateAsymmetricKeyReference { - SecureMessaging = 0x04, - Authentication = 0x9a, - Signature = 0x9c, - Management = 0x9d, - CardAuthentication = 0x9e, -} - -impl TryFrom for GenerateAsymmetricKeyReference { - type Error = Status; - fn try_from(p2: u8) -> Result { - match p2 { - 0x04 => Err(Status::FunctionNotSupported), - 0x9a => Ok(Self::Authentication), - 0x9c => Ok(Self::Signature), - 0x9d => Ok(Self::Management), - 0x9e => Ok(Self::CardAuthentication), - _ => Err(Status::KeyReferenceNotFound), - } - } -} - -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub struct GenerateAsymmetricArguments<'l> { - pub key_reference: GenerateAsymmetricKeyReference, - pub data: &'l [u8], -} - -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum GenerateAsymmetric { -} - -impl TryFrom> for GenerateAsymmetric { - type Error = Status; - fn try_from(_arguments: GenerateAsymmetricArguments<'_>) -> Result { - todo!(); - } -} - impl<'l, const C: usize> TryFrom<&'l iso7816::Command> for Command<'l> { type Error = Status; /// The first layer of unraveling the iso7816::Command onion. @@ -392,7 +264,12 @@ impl<'l, const C: usize> TryFrom<&'l iso7816::Command> for Command<'l> { /// /// The individual piv::Command TryFroms then further interpret these validated parameters. fn try_from(command: &'l iso7816::Command) -> Result { - let (class, instruction, p1, p2) = (command.class(), command.instruction(), command.p1, command.p2); + let (class, instruction, p1, p2) = ( + command.class(), + command.instruction(), + command.p1, + command.p2, + ); let data = command.data(); if !class.secure_messaging().none() { @@ -406,7 +283,6 @@ impl<'l, const C: usize> TryFrom<&'l iso7816::Command> for Command<'l> { // TODO: should we check `command.expected() == 0`, where specified? Ok(match (class.into_inner(), instruction, p1, p2) { - (0x00, Instruction::Select, 0x04, 0x00) => { Self::Select(Select::try_from(data.as_slice())?) } @@ -418,12 +294,19 @@ impl<'l, const C: usize> TryFrom<&'l iso7816::Command> for Command<'l> { (0x00, Instruction::Verify, p1, p2) => { let logout = VerifyLogout::try_from(p1)?; let key_reference = VerifyKeyReference::try_from(p2)?; - Self::Verify(Verify::try_from(VerifyArguments { key_reference, logout, data })?) + Self::Verify(Verify::try_from(VerifyArguments { + key_reference, + logout, + data, + })?) } (0x00, Instruction::ChangeReferenceData, 0x00, p2) => { let key_reference = ChangeReferenceKeyReference::try_from(p2)?; - Self::ChangeReference(ChangeReference::try_from(ChangeReferenceArguments { key_reference, data })?) + Self::ChangeReference(ChangeReference::try_from(ChangeReferenceArguments { + key_reference, + data, + })?) } (0x00, Instruction::ResetRetryCounter, 0x00, 0x80) => { @@ -431,9 +314,12 @@ impl<'l, const C: usize> TryFrom<&'l iso7816::Command> for Command<'l> { } (0x00, Instruction::GeneralAuthenticate, p1, p2) => { - let unparsed_algorithm = p1; + let algorithm = p1.try_into()?; let key_reference = AuthenticateKeyReference::try_from(p2)?; - Self::Authenticate(Authenticate::try_from(AuthenticateArguments { unparsed_algorithm, key_reference, data })?) + Self::GeneralAuthenticate(GeneralAuthenticate { + algorithm, + key_reference, + }) } (0x00, Instruction::PutData, 0x3F, 0xFF) => { @@ -441,8 +327,40 @@ impl<'l, const C: usize> TryFrom<&'l iso7816::Command> for Command<'l> { } (0x00, Instruction::GenerateAsymmetricKeyPair, 0x00, p2) => { - let key_reference = GenerateAsymmetricKeyReference::try_from(p2)?; - Self::GenerateAsymmetric(GenerateAsymmetric::try_from(GenerateAsymmetricArguments { key_reference, data })?) + Self::GenerateAsymmetric(GenerateAsymmetricKeyReference::try_from(p2)?) + } + // (0x00, 0x01, 0x10, 0x00) + (0x00, Instruction::Unknown(0x01), 0x00, 0x00) => { + Self::YkExtension(YubicoPivExtension::GetSerial) + } + (0x00, Instruction::Unknown(0xff), 0xFF, 0xFE) => { + Self::YkExtension(YubicoPivExtension::SetManagementKey(TouchPolicy::Never)) + } + (0x00, Instruction::Unknown(0xff), 0xFF, 0xFF) => { + Self::YkExtension(YubicoPivExtension::SetManagementKey(TouchPolicy::Always)) + } + (0x00, Instruction::Unknown(0xfe), 0x00, 0x00) => { + Self::YkExtension(YubicoPivExtension::ImportAsymmetricKey) + } + (0x00, Instruction::Unknown(0xfd), 0x00, 0x00) => { + Self::YkExtension(YubicoPivExtension::GetVersion) + } + (0x00, Instruction::Unknown(0xfb), 0x00, 0x00) => { + Self::YkExtension(YubicoPivExtension::Reset) + } + (0x00, Instruction::Unknown(0xfa), 0x00, 0x00) => { + Self::YkExtension(YubicoPivExtension::SetPinRetries) + } + // (0x00, 0xf9, 0x9a, 0x00) + (0x00, Instruction::Unknown(0xf9), _, 0x00) => Self::YkExtension( + YubicoPivExtension::Attest(AttestKeyReference::try_from(p1)?), + ), + // (0x00, 0xf8, 0x00, 0x00) + (0x00, Instruction::Unknown(0xf8), _, _) => { + Self::YkExtension(YubicoPivExtension::GetSerial) + } + (0x00, Instruction::Unknown(0xf7), _, _) => { + Self::YkExtension(YubicoPivExtension::GetMetadata) } _ => return Err(Status::FunctionNotSupported), diff --git a/src/constants.rs b/src/constants.rs index 0a14aba..264b282 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -1,5 +1,12 @@ +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + // https://developers.yubico.com/PIV/Introduction/Yubico_extensions.html +use hex_literal::hex; + +use crate::state::ManagementAlgorithm; + pub const RID_LENGTH: usize = 5; // top nibble of first byte is "category", here "A" = International @@ -19,7 +26,8 @@ pub const DERIVED_PIV_PIX: [u8; 6] = hex!("0000 2000 0100"); pub const PIV_TRUNCATED_AID: [u8; 9] = hex!("A000000308 00001000"); // pub const PIV_AID: &[u8] = &hex!("A000000308 00001000 0100"); -pub const PIV_AID: iso7816::Aid = iso7816::Aid::new_truncatable(&hex!("A000000308 00001000 0100"), 9); +pub const PIV_AID: iso7816::Aid = + iso7816::Aid::new_truncatable(&hex!("A000000308 00001000 0100"), 9); pub const DERIVED_PIV_AID: [u8; 11] = hex!("A000000308 00002000 0100"); @@ -27,7 +35,6 @@ pub const APPLICATION_LABEL: &[u8] = b"SoloKeys PIV"; pub const APPLICATION_URL: &[u8] = b"https://github.com/solokeys/piv-authenticator"; // pub const APPLICATION_URL: &[u8] = b"https://piv.is/SoloKeys/PIV/1.0.0-alpha1"; - // https://git.io/JfWuD pub const YUBICO_OTP_PIX: [u8; 3] = hex!("200101"); pub const YUBICO_OTP_AID: iso7816::Aid = iso7816::Aid::new(&hex!("A000000527 200101")); @@ -84,7 +91,7 @@ pub const SELECT: (u8, u8, u8, u8) = ( // p2: i think this is dummy here 0x00, // b2, b1 zero means "file occurence": first/only occurence, // b4, b3 zero means "file control information": return FCI template - // 256, + // 256, ); // @@ -101,149 +108,14 @@ pub const SELECT: (u8, u8, u8, u8) = ( pub const GET_DATA: (u8, u8, u8, u8) = ( 0x00, // as before, would be 0x0C for secure messaging 0xCB, // GET DATA. There's also `CA`, setting bit 1 here - // means (7816-4, sec. 5.1.2): use BER-TLV, as opposed - // to "no indication provided". + // means (7816-4, sec. 5.1.2): use BER-TLV, as opposed + // to "no indication provided". // P1, P2: 7816-4, sec. 7.4.1: bit 1 of INS set => P1,P2 identifies // a file. And 0x3FFF identifies current DF - 0x3F, - 0xFF, + 0x3F, 0xFF, // 256, ); -// SW (SP 800-73 Part 1, Table 6) -// == == == == == == == == == == == -// 61, xx success, more response data bytes -// -// 63, 00 verification failed -// 63, Cx verification failed, x furtehr retries or resets -// -// 68, 82 secure messaging not supported -// -// 69, 82 security status not satisfied -// 69, 83 authn method blocked -// : (more secure messaging stuff) -// - -//// ISO/IEC 7816-4, 5.1.3 "Status bytes" -//#[derive(Copy, Clone, Debug, Eq, PartialEq)] -//pub enum StatusWord { - -//////////////////////////////// -//// Normal processing (90, 61) -//////////////////////////////// - -// // 9000 -// Success, - -// // 61XX -// MoreAvailable(u8), - -///////////////////////////////// -//// Warning processing (62, 63) -///////////////////////////////// - -// // 62XX: state of non-volatile memory unchanged (cf. SW2) - -// // 63XX: state of non-volatile memory changed (cf. SW2) -// VerificationFailed, -// FailedRetries(u8), - -////////////////////////////////// -//// Execution error (64, 65, 66) -////////////////////////////////// - -// // 64XX: persistent memory unchanged (cf. SW2) -// // 65XX: persistent memory changed (cf. SW2) -// // 66XX: security related issues - -///////////////////////////////// -//// Checking error (67 - 6F) -///////////////////////////////// - -// // 6700: wrong length, no further indication - -// // 68XX: functions in CLA not supported (cf. SW2) -// SecureMessagingNotSupported, -// CommandChainingNotSupported, - -// // 69xx: command not allowed (cf. SW2) -// SecurityStatusNotSatisfied, -// OperationBlocked, - -// // 6Axx: wrong parameters P1-P2 (cf. SW2) -// IncorrectDataParameter, -// FunctionNotSupported, -// NotFound, -// NotEnoughMemory, -// IncorrectP1OrP2Parameter, -// KeyReferenceNotFound, - -// // 6BXX: wrong parameters P1-P2 - -// // 6CXX: wrong Le field, SW2 encodes available bytes - -// // 6D00: instruction code not supported or invalid -// InstructionNotSupportedOrInvalid, - -// // 6E00: class not supported -// ClassNotSupported, - -// // 6F00: no precise diagnosis -// UnspecifiedCheckingError, -//} - -//impl Into for StatusWord { -// #[inline] -// fn into(self) -> u16 { -// match self { -// Self::VerificationFailed => 0x6300, -// Self::FailedRetries(x) => { -// assert!(x < 16); -// u16::from_be_bytes([0x63, 0xc0 + x]) -// } - -// Self::SecureMessagingNotSupported => 0x6882, -// Self::CommandChainingNotSupported => 0x6884, - -// Self::SecurityStatusNotSatisfied => 0x6982, -// Self::OperationBlocked => 0x6983, - -// Self::IncorrectDataParameter => 0x6a80, -// Self::FunctionNotSupported => 0x6a81, -// Self::NotFound => 0x6a82, -// Self::NotEnoughMemory => 0x6a84, -// Self::IncorrectP1OrP2Parameter => 0x6a86, -// Self::KeyReferenceNotFound => 0x6a88, - -// Self::InstructionNotSupportedOrInvalid => 0x6d00, -// Self::ClassNotSupported => 0x6e00, -// Self::UnspecifiedCheckingError => 0x6f00, - -// Self::Success => 0x9000, -// Self::MoreAvailable(x) => u16::from_be_bytes([0x61, x]), -// } -// } -//} - -//impl Into<[u8; 2]> for StatusWord { -// #[inline] -// fn into(self) -> [u8; 2] { -// let sw: u16 = self.into(); -// sw.to_be_bytes() -// } -//} - - -// 6A, 80 incorrect parameter in command data field -// 6A, 81 function not supported -// 6A, 82 data object not found ( = NOT FOUND for files, e.g. certificate, e.g. after GET-DATA) -// 6A, 84 not enough memory -// 6A, 86 incorrect parameter in P1/P2 -// 6A, 88 reference(d) data not found ( = NOT FOUND for keys, e.g. global PIN, e.g. after VERIFY) -// -// 90, 00 SUCCESS! -// == == == == == == == == == == == - // #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub struct DataObjects {} #[allow(non_upper_case_globals)] @@ -265,168 +137,142 @@ impl DataObjects { pub struct YubicoObjects {} #[allow(non_upper_case_globals)] impl YubicoObjects { - pub const AttestationCertificate: &'static [u8] = b"\x5f\xff\x01"; + pub const AttestationCertificate: &'static [u8] = &hex!("5fff01"); } -// https://developers.yubico.com/PIV/Introduction/Yubico_extensions.html -#[repr(u8)] -#[derive(Copy, Clone, Debug, Eq, PartialEq)] -pub enum YubicoPivExtension { - SetManagementKey = 0xff, - ImportAsymmetricKey = 0xfe, - GetVersion = 0xfd, - Reset = 0xfb, - SetPinRetries = 0xfa, - Attest = 0xf9, - GetSerial = 0xf8, // also used via 0x01 - GetMetadata = 0xf7, -} +pub const YUBICO_PIV_AUTHENTICATION_CERTIFICATE: &[u8; 351] = &hex!( + " + 5382 015b 7082 0152 3082 014e 3081 f5a0 + 0302 0102 0211 008e 4632 d8f0 c1f7 c14d + 67d1 4bfd e364 8e30 0a06 082a 8648 ce3d + 0403 0230 2a31 1630 1406 0355 040a 130d + 7975 6269 6b65 792d 6167 656e 7431 1030 + 0e06 0355 040b 1307 2864 6576 656c 2930 + 2017 0d32 3030 3530 3931 3230 3034 395a + 180f 3230 3632 3035 3039 3133 3030 3439 + 5a30 1231 1030 0e06 0355 0403 1307 5353 + 4820 6b65 7930 5930 1306 072a 8648 ce3d + 0201 0608 2a86 48ce 3d03 0107 0342 0004 + 832a 9247 8b4e b57a 461b 2a5e 0e44 2503 + 9bfb 2794 5678 ed48 2b1c f221 616d dabd + 3d8f b62b 75c6 ac3f 834a 594e 5adf ede7 + 3ae4 991a e733 2f61 2bcf 6c0e d678 72eb + a312 3010 300e 0603 551d 0f01 01ff 0404 + 0302 0388 300a 0608 2a86 48ce 3d04 0302 + 0348 0030 4502 2003 09e2 8447 dcb7 c532 + ee97 5b9e 44fa 4206 f226 67c1 a6c6 4adc + 6a0b 5da9 8763 8b02 2100 bb4e cb18 72cc + 1239 d3d4 1836 1418 e4a9 f383 814b 740f + 9333 b847 a973 c282 923e 7101 00fe 00 +" +); -impl core::convert::TryFrom for YubicoPivExtension { - type Error = (); - fn try_from(ins: u8) -> core::result::Result { - Ok(match ins { - // (0x00, 0x01, 0x10, 0x00) - 0x01 => YubicoPivExtension::GetSerial, - 0xff => YubicoPivExtension::SetManagementKey, - 0xfe => YubicoPivExtension::ImportAsymmetricKey, - 0xfd => YubicoPivExtension::GetVersion, - 0xfb => YubicoPivExtension::Reset, - 0xfa => YubicoPivExtension::SetPinRetries, - // (0x00, 0xf9, 0x9a, 0x00) - 0xf9 => YubicoPivExtension::Attest, - // (0x00, 0xf8, 0x00, 0x00) - 0xf8 => YubicoPivExtension::GetSerial, - 0xf7 => YubicoPivExtension::GetMetadata, - _ => return Err(()), - }) - } -} +pub const YUBICO_ATTESTATION_CERTIFICATE: &[u8; 754] = &hex!( + " + 5382 02ee 7082 02ea 3082 02e6 3082 01ce + a003 0201 0202 0900 a485 22aa 34af ae4f + 300d 0609 2a86 4886 f70d 0101 0b05 0030 + 2b31 2930 2706 0355 0403 0c20 5975 6269 + 636f 2050 4956 2052 6f6f 7420 4341 2053 + 6572 6961 6c20 3236 3337 3531 3020 170d + 3136 3033 3134 3030 3030 3030 5a18 0f32 + 3035 3230 3431 3730 3030 3030 305a 3021 + 311f 301d 0603 5504 030c 1659 7562 6963 + 6f20 5049 5620 4174 7465 7374 6174 696f + 6e30 8201 2230 0d06 092a 8648 86f7 0d01 + 0101 0500 0382 010f 0030 8201 0a02 8201 + 0100 aba9 0b16 9bef 31cc 3eac 185a 2d45 + 8075 70c7 58b0 6c3f 1b59 0d49 b989 e86f + cebb 276f d83c 603a 8500 ef5c bc40 993d + 41ee eac0 817f 7648 e4a9 4cbc d56b e11f + 0a60 93c6 feaa d28d 8ee2 b7cd 8b2b f79b + dd5a ab2f cfb9 0e54 ceec 8df5 5ed7 7b91 + c3a7 569c dcc1 0686 7636 4453 fb08 25d8 + 06b9 068c 81fd 6367 ca3c a8b8 ea1c a6ca + db44 7b12 cab2 3401 7e73 e436 83df ebf9 + 2300 0701 6a07 198a 6456 9d10 8ac5 7302 + 3d18 6eaf 3fc3 02a7 c0f7 a2fd 6d5a 4276 + 4ed6 c01e d6c0 c6aa 5da7 1a9f 10db 3057 + 185c b5b5 fd0c be49 2422 af1e 564a 3444 + d4aa d4e1 ae95 4c75 c088 61f4 8c7e 54f3 + 13eb 0fe5 2b52 605a 6eba d7e5 8c63 da51 + 1abb 225c 372b d7d1 7057 4c2e dc35 3c22 + 989b 0203 0100 01a3 1530 1330 1106 0a2b + 0601 0401 82c4 0a03 0304 0304 0303 300d + 0609 2a86 4886 f70d 0101 0b05 0003 8201 + 0100 5280 5a6d c39e df47 a8f1 b2a5 9ca3 + 8081 3b1d 6aeb 6a12 624b 11fd 8d30 f17b + fc71 10c9 b208 fcd1 4e35 7f45 f210 a252 + b9d4 b302 1a01 5607 6bfa 64a7 08f0 03fb + 27a9 608d 0dd3 ac5a 10cf 2096 4e82 bc9d + e337 dac1 4c50 e13d 16b4 caf4 1bff 0864 + c974 4f2a 3a43 e0de 4279 f213 ae77 a1e2 + ae6b df72 a5b6 ced7 4c90 13df dedb f28b + 3445 8b30 dc51 aba9 34f8 a9e5 0c47 29aa + 2f42 54f2 f819 5ab4 89fe 1b9f 197a 16c8 + c8ba 8f18 177a 07a9 97a1 56b9 525d a121 + c081 672d e80e a651 b908 b09d d360 1c70 + a30f fad8 62d8 792b 0ae6 42fc f82d f5e4 + cdfb 1596 23ff b6c0 a7a7 e285 83f9 70c8 + 196b f3c1 3f37 4465 27fb 6788 c883 b72f + 851f 8044 bb72 ce06 8259 2d83 00e1 948d + a085 +" +); -pub const YUBICO_PIV_AUTHENTICATION_CERTIFICATE: &'static [u8; 351] = &[ - 0x53, 0x82, 0x01, 0x5b, 0x70, 0x82, 0x01, 0x52, 0x30, 0x82, 0x01, 0x4e, 0x30, 0x81, 0xf5, 0xa0, - 0x03, 0x02, 0x01, 0x02, 0x02, 0x11, 0x00, 0x8e, 0x46, 0x32, 0xd8, 0xf0, 0xc1, 0xf7, 0xc1, 0x4d, - 0x67, 0xd1, 0x4b, 0xfd, 0xe3, 0x64, 0x8e, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, - 0x04, 0x03, 0x02, 0x30, 0x2a, 0x31, 0x16, 0x30, 0x14, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x0d, - 0x79, 0x75, 0x62, 0x69, 0x6b, 0x65, 0x79, 0x2d, 0x61, 0x67, 0x65, 0x6e, 0x74, 0x31, 0x10, 0x30, - 0x0e, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x13, 0x07, 0x28, 0x64, 0x65, 0x76, 0x65, 0x6c, 0x29, 0x30, - 0x20, 0x17, 0x0d, 0x32, 0x30, 0x30, 0x35, 0x30, 0x39, 0x31, 0x32, 0x30, 0x30, 0x34, 0x39, 0x5a, - 0x18, 0x0f, 0x32, 0x30, 0x36, 0x32, 0x30, 0x35, 0x30, 0x39, 0x31, 0x33, 0x30, 0x30, 0x34, 0x39, - 0x5a, 0x30, 0x12, 0x31, 0x10, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x07, 0x53, 0x53, - 0x48, 0x20, 0x6b, 0x65, 0x79, 0x30, 0x59, 0x30, 0x13, 0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, - 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, - 0x83, 0x2a, 0x92, 0x47, 0x8b, 0x4e, 0xb5, 0x7a, 0x46, 0x1b, 0x2a, 0x5e, 0x0e, 0x44, 0x25, 0x03, - 0x9b, 0xfb, 0x27, 0x94, 0x56, 0x78, 0xed, 0x48, 0x2b, 0x1c, 0xf2, 0x21, 0x61, 0x6d, 0xda, 0xbd, - 0x3d, 0x8f, 0xb6, 0x2b, 0x75, 0xc6, 0xac, 0x3f, 0x83, 0x4a, 0x59, 0x4e, 0x5a, 0xdf, 0xed, 0xe7, - 0x3a, 0xe4, 0x99, 0x1a, 0xe7, 0x33, 0x2f, 0x61, 0x2b, 0xcf, 0x6c, 0x0e, 0xd6, 0x78, 0x72, 0xeb, - 0xa3, 0x12, 0x30, 0x10, 0x30, 0x0e, 0x06, 0x03, 0x55, 0x1d, 0x0f, 0x01, 0x01, 0xff, 0x04, 0x04, - 0x03, 0x02, 0x03, 0x88, 0x30, 0x0a, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02, - 0x03, 0x48, 0x00, 0x30, 0x45, 0x02, 0x20, 0x03, 0x09, 0xe2, 0x84, 0x47, 0xdc, 0xb7, 0xc5, 0x32, - 0xee, 0x97, 0x5b, 0x9e, 0x44, 0xfa, 0x42, 0x06, 0xf2, 0x26, 0x67, 0xc1, 0xa6, 0xc6, 0x4a, 0xdc, - 0x6a, 0x0b, 0x5d, 0xa9, 0x87, 0x63, 0x8b, 0x02, 0x21, 0x00, 0xbb, 0x4e, 0xcb, 0x18, 0x72, 0xcc, - 0x12, 0x39, 0xd3, 0xd4, 0x18, 0x36, 0x14, 0x18, 0xe4, 0xa9, 0xf3, 0x83, 0x81, 0x4b, 0x74, 0x0f, - 0x93, 0x33, 0xb8, 0x47, 0xa9, 0x73, 0xc2, 0x82, 0x92, 0x3e, 0x71, 0x01, 0x00, 0xfe, 0x00, -]; +pub const YUBICO_ATTESTATION_CERTIFICATE_FOR_9A: &[u8; 584] = &hex!( + " + 3082 0244 3082 012c a003 0201 0202 1100 + c636 e7b3 a5a5 a498 5d13 6e43 362d 13f7 + 300d 0609 2a86 4886 f70d 0101 0b05 0030 + 2131 1f30 1d06 0355 0403 0c16 5975 6269 + 636f 2050 4956 2041 7474 6573 7461 7469 + 6f6e 3020 170d 3136 3033 3134 3030 3030 + 3030 5a18 0f32 3035 3230 3431 3730 3030 + 3030 305a 3025 3123 3021 0603 5504 030c + 1a59 7562 694b 6579 2050 4956 2041 7474 + 6573 7461 7469 6f6e 2039 6130 5930 1306 + 072a 8648 ce3d 0201 0608 2a86 48ce 3d03 + 0107 0342 0004 832a 9247 8b4e b57a 461b + 2a5e 0e44 2503 9bfb 2794 5678 ed48 2b1c + f221 616d dabd 3d8f b62b 75c6 ac3f 834a + 594e 5adf ede7 3ae4 991a e733 2f61 2bcf + 6c0e d678 72eb a33c 303a 3011 060a 2b06 + 0104 0182 c40a 0303 0403 0403 0430 1306 + 0a2b 0601 0401 82c4 0a03 0704 0502 0352 + f743 3010 060a 2b06 0104 0182 c40a 0308 + 0402 0202 300d 0609 2a86 4886 f70d 0101 + 0b05 0003 8201 0100 0217 38a8 f61d 1735 + e130 9dd2 d5c4 d4d0 0de1 9f37 9abe cf63 + 6a0e 2bd0 d7a4 045c 407d f743 9be4 ee7d + 9655 d291 dc32 8254 fe2d 9f19 2354 bbdd + 7d6b e961 2a1d c813 65e2 049f a287 de61 + 92d5 de46 d4a4 c2a6 b480 5d4a a4d1 1ba7 + 34f2 977b 7a5a ad9a a85d 2ad4 7fb1 57bf + 261d 3da6 b3ea 3d3d f794 cd16 3640 24cd + 7c8e 7adb 2df9 22da 26b3 c1c8 00a3 4797 + 5210 1273 4baf 12fe b70d 9e91 30a7 52cf + 12d8 2bdf 126a b62f 3924 c604 a26f ed70 + b5f2 0d2a 73e3 38a9 9cfe 353e dc17 4055 + d595 7f05 8e24 c2b3 b105 2d69 0ccf 5bf7 + 0640 1736 0ac3 a5db 3cda 62f8 532d f13f + 0455 700c 437b 1fa3 63b1 a05e 8928 5b4f + 76a7 05e1 4c45 5514 ff10 1089 696a 133d + 89f2 cafd 149a c4d0 +" +); -pub const YUBICO_ATTESTATION_CERTIFICATE: &'static [u8; 754] = &[ - 0x53, 0x82, 0x02, 0xee, 0x70, 0x82, 0x02, 0xea, 0x30, 0x82, 0x02, 0xe6, 0x30, 0x82, 0x01, 0xce, - 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x09, 0x00, 0xa4, 0x85, 0x22, 0xaa, 0x34, 0xaf, 0xae, 0x4f, - 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, - 0x2b, 0x31, 0x29, 0x30, 0x27, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x20, 0x59, 0x75, 0x62, 0x69, - 0x63, 0x6f, 0x20, 0x50, 0x49, 0x56, 0x20, 0x52, 0x6f, 0x6f, 0x74, 0x20, 0x43, 0x41, 0x20, 0x53, - 0x65, 0x72, 0x69, 0x61, 0x6c, 0x20, 0x32, 0x36, 0x33, 0x37, 0x35, 0x31, 0x30, 0x20, 0x17, 0x0d, - 0x31, 0x36, 0x30, 0x33, 0x31, 0x34, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x5a, 0x18, 0x0f, 0x32, - 0x30, 0x35, 0x32, 0x30, 0x34, 0x31, 0x37, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x5a, 0x30, 0x21, - 0x31, 0x1f, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x16, 0x59, 0x75, 0x62, 0x69, 0x63, - 0x6f, 0x20, 0x50, 0x49, 0x56, 0x20, 0x41, 0x74, 0x74, 0x65, 0x73, 0x74, 0x61, 0x74, 0x69, 0x6f, - 0x6e, 0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, - 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00, 0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, - 0x01, 0x00, 0xab, 0xa9, 0x0b, 0x16, 0x9b, 0xef, 0x31, 0xcc, 0x3e, 0xac, 0x18, 0x5a, 0x2d, 0x45, - 0x80, 0x75, 0x70, 0xc7, 0x58, 0xb0, 0x6c, 0x3f, 0x1b, 0x59, 0x0d, 0x49, 0xb9, 0x89, 0xe8, 0x6f, - 0xce, 0xbb, 0x27, 0x6f, 0xd8, 0x3c, 0x60, 0x3a, 0x85, 0x00, 0xef, 0x5c, 0xbc, 0x40, 0x99, 0x3d, - 0x41, 0xee, 0xea, 0xc0, 0x81, 0x7f, 0x76, 0x48, 0xe4, 0xa9, 0x4c, 0xbc, 0xd5, 0x6b, 0xe1, 0x1f, - 0x0a, 0x60, 0x93, 0xc6, 0xfe, 0xaa, 0xd2, 0x8d, 0x8e, 0xe2, 0xb7, 0xcd, 0x8b, 0x2b, 0xf7, 0x9b, - 0xdd, 0x5a, 0xab, 0x2f, 0xcf, 0xb9, 0x0e, 0x54, 0xce, 0xec, 0x8d, 0xf5, 0x5e, 0xd7, 0x7b, 0x91, - 0xc3, 0xa7, 0x56, 0x9c, 0xdc, 0xc1, 0x06, 0x86, 0x76, 0x36, 0x44, 0x53, 0xfb, 0x08, 0x25, 0xd8, - 0x06, 0xb9, 0x06, 0x8c, 0x81, 0xfd, 0x63, 0x67, 0xca, 0x3c, 0xa8, 0xb8, 0xea, 0x1c, 0xa6, 0xca, - 0xdb, 0x44, 0x7b, 0x12, 0xca, 0xb2, 0x34, 0x01, 0x7e, 0x73, 0xe4, 0x36, 0x83, 0xdf, 0xeb, 0xf9, - 0x23, 0x00, 0x07, 0x01, 0x6a, 0x07, 0x19, 0x8a, 0x64, 0x56, 0x9d, 0x10, 0x8a, 0xc5, 0x73, 0x02, - 0x3d, 0x18, 0x6e, 0xaf, 0x3f, 0xc3, 0x02, 0xa7, 0xc0, 0xf7, 0xa2, 0xfd, 0x6d, 0x5a, 0x42, 0x76, - 0x4e, 0xd6, 0xc0, 0x1e, 0xd6, 0xc0, 0xc6, 0xaa, 0x5d, 0xa7, 0x1a, 0x9f, 0x10, 0xdb, 0x30, 0x57, - 0x18, 0x5c, 0xb5, 0xb5, 0xfd, 0x0c, 0xbe, 0x49, 0x24, 0x22, 0xaf, 0x1e, 0x56, 0x4a, 0x34, 0x44, - 0xd4, 0xaa, 0xd4, 0xe1, 0xae, 0x95, 0x4c, 0x75, 0xc0, 0x88, 0x61, 0xf4, 0x8c, 0x7e, 0x54, 0xf3, - 0x13, 0xeb, 0x0f, 0xe5, 0x2b, 0x52, 0x60, 0x5a, 0x6e, 0xba, 0xd7, 0xe5, 0x8c, 0x63, 0xda, 0x51, - 0x1a, 0xbb, 0x22, 0x5c, 0x37, 0x2b, 0xd7, 0xd1, 0x70, 0x57, 0x4c, 0x2e, 0xdc, 0x35, 0x3c, 0x22, - 0x98, 0x9b, 0x02, 0x03, 0x01, 0x00, 0x01, 0xa3, 0x15, 0x30, 0x13, 0x30, 0x11, 0x06, 0x0a, 0x2b, - 0x06, 0x01, 0x04, 0x01, 0x82, 0xc4, 0x0a, 0x03, 0x03, 0x04, 0x03, 0x04, 0x03, 0x03, 0x30, 0x0d, - 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x03, 0x82, 0x01, - 0x01, 0x00, 0x52, 0x80, 0x5a, 0x6d, 0xc3, 0x9e, 0xdf, 0x47, 0xa8, 0xf1, 0xb2, 0xa5, 0x9c, 0xa3, - 0x80, 0x81, 0x3b, 0x1d, 0x6a, 0xeb, 0x6a, 0x12, 0x62, 0x4b, 0x11, 0xfd, 0x8d, 0x30, 0xf1, 0x7b, - 0xfc, 0x71, 0x10, 0xc9, 0xb2, 0x08, 0xfc, 0xd1, 0x4e, 0x35, 0x7f, 0x45, 0xf2, 0x10, 0xa2, 0x52, - 0xb9, 0xd4, 0xb3, 0x02, 0x1a, 0x01, 0x56, 0x07, 0x6b, 0xfa, 0x64, 0xa7, 0x08, 0xf0, 0x03, 0xfb, - 0x27, 0xa9, 0x60, 0x8d, 0x0d, 0xd3, 0xac, 0x5a, 0x10, 0xcf, 0x20, 0x96, 0x4e, 0x82, 0xbc, 0x9d, - 0xe3, 0x37, 0xda, 0xc1, 0x4c, 0x50, 0xe1, 0x3d, 0x16, 0xb4, 0xca, 0xf4, 0x1b, 0xff, 0x08, 0x64, - 0xc9, 0x74, 0x4f, 0x2a, 0x3a, 0x43, 0xe0, 0xde, 0x42, 0x79, 0xf2, 0x13, 0xae, 0x77, 0xa1, 0xe2, - 0xae, 0x6b, 0xdf, 0x72, 0xa5, 0xb6, 0xce, 0xd7, 0x4c, 0x90, 0x13, 0xdf, 0xde, 0xdb, 0xf2, 0x8b, - 0x34, 0x45, 0x8b, 0x30, 0xdc, 0x51, 0xab, 0xa9, 0x34, 0xf8, 0xa9, 0xe5, 0x0c, 0x47, 0x29, 0xaa, - 0x2f, 0x42, 0x54, 0xf2, 0xf8, 0x19, 0x5a, 0xb4, 0x89, 0xfe, 0x1b, 0x9f, 0x19, 0x7a, 0x16, 0xc8, - 0xc8, 0xba, 0x8f, 0x18, 0x17, 0x7a, 0x07, 0xa9, 0x97, 0xa1, 0x56, 0xb9, 0x52, 0x5d, 0xa1, 0x21, - 0xc0, 0x81, 0x67, 0x2d, 0xe8, 0x0e, 0xa6, 0x51, 0xb9, 0x08, 0xb0, 0x9d, 0xd3, 0x60, 0x1c, 0x70, - 0xa3, 0x0f, 0xfa, 0xd8, 0x62, 0xd8, 0x79, 0x2b, 0x0a, 0xe6, 0x42, 0xfc, 0xf8, 0x2d, 0xf5, 0xe4, - 0xcd, 0xfb, 0x15, 0x96, 0x23, 0xff, 0xb6, 0xc0, 0xa7, 0xa7, 0xe2, 0x85, 0x83, 0xf9, 0x70, 0xc8, - 0x19, 0x6b, 0xf3, 0xc1, 0x3f, 0x37, 0x44, 0x65, 0x27, 0xfb, 0x67, 0x88, 0xc8, 0x83, 0xb7, 0x2f, - 0x85, 0x1f, 0x80, 0x44, 0xbb, 0x72, 0xce, 0x06, 0x82, 0x59, 0x2d, 0x83, 0x00, 0xe1, 0x94, 0x8d, - 0xa0, 0x85, -]; +// pub const YUBICO_DEFAULT_MANAGEMENT_KEY: & [u8; 24] = b"123456781234567812345678"; +pub const YUBICO_DEFAULT_MANAGEMENT_KEY: &[u8; 24] = &hex!( + " + 0102030405060708 + 0102030405060708 + 0102030405060708 +" +); -pub const YUBICO_ATTESTATION_CERTIFICATE_FOR_9A: &'static [u8; 584] = &[ - 0x30, 0x82, 0x02, 0x44, 0x30, 0x82, 0x01, 0x2c, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x11, 0x00, - 0xc6, 0x36, 0xe7, 0xb3, 0xa5, 0xa5, 0xa4, 0x98, 0x5d, 0x13, 0x6e, 0x43, 0x36, 0x2d, 0x13, 0xf7, - 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x0b, 0x05, 0x00, 0x30, - 0x21, 0x31, 0x1f, 0x30, 0x1d, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, 0x16, 0x59, 0x75, 0x62, 0x69, - 0x63, 0x6f, 0x20, 0x50, 0x49, 0x56, 0x20, 0x41, 0x74, 0x74, 0x65, 0x73, 0x74, 0x61, 0x74, 0x69, - 0x6f, 0x6e, 0x30, 0x20, 0x17, 0x0d, 0x31, 0x36, 0x30, 0x33, 0x31, 0x34, 0x30, 0x30, 0x30, 0x30, - 0x30, 0x30, 0x5a, 0x18, 0x0f, 0x32, 0x30, 0x35, 0x32, 0x30, 0x34, 0x31, 0x37, 0x30, 0x30, 0x30, - 0x30, 0x30, 0x30, 0x5a, 0x30, 0x25, 0x31, 0x23, 0x30, 0x21, 0x06, 0x03, 0x55, 0x04, 0x03, 0x0c, - 0x1a, 0x59, 0x75, 0x62, 0x69, 0x4b, 0x65, 0x79, 0x20, 0x50, 0x49, 0x56, 0x20, 0x41, 0x74, 0x74, - 0x65, 0x73, 0x74, 0x61, 0x74, 0x69, 0x6f, 0x6e, 0x20, 0x39, 0x61, 0x30, 0x59, 0x30, 0x13, 0x06, - 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01, 0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x03, - 0x01, 0x07, 0x03, 0x42, 0x00, 0x04, 0x83, 0x2a, 0x92, 0x47, 0x8b, 0x4e, 0xb5, 0x7a, 0x46, 0x1b, - 0x2a, 0x5e, 0x0e, 0x44, 0x25, 0x03, 0x9b, 0xfb, 0x27, 0x94, 0x56, 0x78, 0xed, 0x48, 0x2b, 0x1c, - 0xf2, 0x21, 0x61, 0x6d, 0xda, 0xbd, 0x3d, 0x8f, 0xb6, 0x2b, 0x75, 0xc6, 0xac, 0x3f, 0x83, 0x4a, - 0x59, 0x4e, 0x5a, 0xdf, 0xed, 0xe7, 0x3a, 0xe4, 0x99, 0x1a, 0xe7, 0x33, 0x2f, 0x61, 0x2b, 0xcf, - 0x6c, 0x0e, 0xd6, 0x78, 0x72, 0xeb, 0xa3, 0x3c, 0x30, 0x3a, 0x30, 0x11, 0x06, 0x0a, 0x2b, 0x06, - 0x01, 0x04, 0x01, 0x82, 0xc4, 0x0a, 0x03, 0x03, 0x04, 0x03, 0x04, 0x03, 0x04, 0x30, 0x13, 0x06, - 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xc4, 0x0a, 0x03, 0x07, 0x04, 0x05, 0x02, 0x03, 0x52, - 0xf7, 0x43, 0x30, 0x10, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x82, 0xc4, 0x0a, 0x03, 0x08, - 0x04, 0x02, 0x02, 0x02, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, - 0x0b, 0x05, 0x00, 0x03, 0x82, 0x01, 0x01, 0x00, 0x02, 0x17, 0x38, 0xa8, 0xf6, 0x1d, 0x17, 0x35, - 0xe1, 0x30, 0x9d, 0xd2, 0xd5, 0xc4, 0xd4, 0xd0, 0x0d, 0xe1, 0x9f, 0x37, 0x9a, 0xbe, 0xcf, 0x63, - 0x6a, 0x0e, 0x2b, 0xd0, 0xd7, 0xa4, 0x04, 0x5c, 0x40, 0x7d, 0xf7, 0x43, 0x9b, 0xe4, 0xee, 0x7d, - 0x96, 0x55, 0xd2, 0x91, 0xdc, 0x32, 0x82, 0x54, 0xfe, 0x2d, 0x9f, 0x19, 0x23, 0x54, 0xbb, 0xdd, - 0x7d, 0x6b, 0xe9, 0x61, 0x2a, 0x1d, 0xc8, 0x13, 0x65, 0xe2, 0x04, 0x9f, 0xa2, 0x87, 0xde, 0x61, - 0x92, 0xd5, 0xde, 0x46, 0xd4, 0xa4, 0xc2, 0xa6, 0xb4, 0x80, 0x5d, 0x4a, 0xa4, 0xd1, 0x1b, 0xa7, - 0x34, 0xf2, 0x97, 0x7b, 0x7a, 0x5a, 0xad, 0x9a, 0xa8, 0x5d, 0x2a, 0xd4, 0x7f, 0xb1, 0x57, 0xbf, - 0x26, 0x1d, 0x3d, 0xa6, 0xb3, 0xea, 0x3d, 0x3d, 0xf7, 0x94, 0xcd, 0x16, 0x36, 0x40, 0x24, 0xcd, - 0x7c, 0x8e, 0x7a, 0xdb, 0x2d, 0xf9, 0x22, 0xda, 0x26, 0xb3, 0xc1, 0xc8, 0x00, 0xa3, 0x47, 0x97, - 0x52, 0x10, 0x12, 0x73, 0x4b, 0xaf, 0x12, 0xfe, 0xb7, 0x0d, 0x9e, 0x91, 0x30, 0xa7, 0x52, 0xcf, - 0x12, 0xd8, 0x2b, 0xdf, 0x12, 0x6a, 0xb6, 0x2f, 0x39, 0x24, 0xc6, 0x04, 0xa2, 0x6f, 0xed, 0x70, - 0xb5, 0xf2, 0x0d, 0x2a, 0x73, 0xe3, 0x38, 0xa9, 0x9c, 0xfe, 0x35, 0x3e, 0xdc, 0x17, 0x40, 0x55, - 0xd5, 0x95, 0x7f, 0x05, 0x8e, 0x24, 0xc2, 0xb3, 0xb1, 0x05, 0x2d, 0x69, 0x0c, 0xcf, 0x5b, 0xf7, - 0x06, 0x40, 0x17, 0x36, 0x0a, 0xc3, 0xa5, 0xdb, 0x3c, 0xda, 0x62, 0xf8, 0x53, 0x2d, 0xf1, 0x3f, - 0x04, 0x55, 0x70, 0x0c, 0x43, 0x7b, 0x1f, 0xa3, 0x63, 0xb1, 0xa0, 0x5e, 0x89, 0x28, 0x5b, 0x4f, - 0x76, 0xa7, 0x05, 0xe1, 0x4c, 0x45, 0x55, 0x14, 0xff, 0x10, 0x10, 0x89, 0x69, 0x6a, 0x13, 0x3d, - 0x89, 0xf2, 0xca, 0xfd, 0x14, 0x9a, 0xc4, 0xd0, -]; -// pub const YUBICO_DEFAULT_MANAGEMENT_KEY: &'static [u8; 24] = b"123456781234567812345678"; -pub const YUBICO_DEFAULT_MANAGEMENT_KEY: &'static [u8; 24] = &[ - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, - 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, -]; +pub const YUBICO_DEFAULT_MANAGEMENT_KEY_ALG: ManagementAlgorithm = ManagementAlgorithm::Tdes; // stolen from le yubico -pub const DISCOVERY_OBJECT: &'static [u8; 20] = b"~\x12O\x0b\xa0\x00\x00\x03\x08\x00\x00\x10\x00\x01\x00_/\x02@\x00"; - -// import secrets; secrets.token_bytes(16) -pub const GUID: &'static [u8; 16] = b"\x0c\x92\xc9\x04\xd0\xdeL\xd9\xf6\xd1\xa2\x9fE3\xca\xeb"; +pub const DISCOVERY_OBJECT: &[u8; 20] = + b"~\x12O\x0b\xa0\x00\x00\x03\x08\x00\x00\x10\x00\x01\x00_/\x02@\x00"; diff --git a/src/container.rs b/src/container.rs index 5870edb..7206a96 100644 --- a/src/container.rs +++ b/src/container.rs @@ -1,5 +1,77 @@ +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + use core::convert::TryFrom; -// use flexiber::{Decodable, Encodable}; + +use hex_literal::hex; + +macro_rules! enum_subset { + ( + $(#[$outer:meta])* + $vis:vis enum $name:ident: $sup:ident { + $($var:ident),+ + $(,)* + } + ) => { + $(#[$outer])* + #[repr(u8)] + $vis enum $name { + $( + $var, + )* + } + + impl TryFrom<$sup> for $name + { + type Error = ::iso7816::Status; + fn try_from(val: $sup) -> ::core::result::Result { + match val { + $( + $sup::$var => Ok($name::$var), + )* + _ => Err(::iso7816::Status::KeyReferenceNotFound) + } + } + } + + impl From<$name> for $sup + { + fn from(v: $name) -> $sup { + match v { + $( + $name::$var => $sup::$var, + )* + } + } + } + + impl PartialEq<$sup> for $name { + fn eq(&self, other: &$sup) -> bool { + match (self,other) { + $( + | ($name::$var, $sup::$var) + )* => true, + _ => false + } + } + } + + impl TryFrom for $name { + type Error = ::iso7816::Status; + fn try_from(tag: u8) -> ::core::result::Result { + let v: $sup = tag.try_into()?; + match v { + $( + $sup::$var => Ok($name::$var), + )* + _ => Err(::iso7816::Status::KeyReferenceNotFound) + } + } + } + } +} + +pub(crate) use enum_subset; pub struct Tag<'a>(&'a [u8]); impl<'a> Tag<'a> { @@ -11,46 +83,115 @@ impl<'a> Tag<'a> { #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub struct RetiredIndex(u8); -// #[repr(u8)] -#[derive(Clone, Copy, Debug, Eq, PartialEq)] -pub enum KeyReference { - GlobalPin, - ApplicationPin, - PinUnblockingKey, - PrimaryFinger, - SecondaryFinger, - PairingCode, +crate::enum_u8! { + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + pub enum KeyReference { + GlobalPin = 0x00, + SecureMessaging = 0x04, + ApplicationPin = 0x80, + PinUnblockingKey = 0x81, + PrimaryFinger = 0x96, + SecondaryFinger = 0x97, + PairingCode = 0x98, - PivAuthentication, - PivCardApplicationAdministration, - DigitalSignature, - KeyManagement, - CardAuthentication, + PivAuthentication = 0x9A, + PivCardApplicationAdministration = 0x9B, + DigitalSignature = 0x9C, + KeyManagement = 0x9D, + CardAuthentication = 0x9E, - // 20x - RetiredKeyManagement(RetiredIndex), + Retired01 = 0x82, + Retired02 = 0x83, + Retired03 = 0x84, + Retired04 = 0x85, + Retired05 = 0x86, + Retired06 = 0x87, + Retired07 = 0x88, + Retired08 = 0x89, + Retired09 = 0x8A, + Retired10 = 0x8B, + Retired11 = 0x8C, + Retired12 = 0x8D, + Retired13 = 0x8E, + Retired14 = 0x8F, + Retired15 = 0x90, + Retired16 = 0x91, + Retired17 = 0x92, + Retired18 = 0x93, + Retired19 = 0x94, + Retired20 = 0x95, + } +} +enum_subset! { + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + pub enum AttestKeyReference: KeyReference { + PivAuthentication, + } } -impl From for u8 { - fn from(reference: KeyReference) -> Self { - use KeyReference::*; - match reference { - GlobalPin => 0x00, - ApplicationPin => 0x80, - PinUnblockingKey => 0x81, - PrimaryFinger => 0x96, - SecondaryFinger => 0x97, - PairingCode => 0x98, +enum_subset! { + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + pub enum GenerateAsymmetricKeyReference: KeyReference { + SecureMessaging, + PivAuthentication, + DigitalSignature, + KeyManagement, + CardAuthentication, + } +} - PivAuthentication => 0x9A, - PivCardApplicationAdministration => 0x9B, - DigitalSignature => 0x9C, - KeyManagement => 0x9D, - CardAuthentication => 0x9E, +enum_subset! { + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + pub enum ChangeReferenceKeyReference: KeyReference { + GlobalPin, + ApplicationPin, + PinUnblockingKey, + } +} + +enum_subset! { + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + pub enum VerifyKeyReference: KeyReference { + GlobalPin, + ApplicationPin, + PrimaryFinger, + SecondaryFinger, + PairingCode, - RetiredKeyManagement(RetiredIndex(i)) => (0x82 - 1) + i, - } + } +} + +enum_subset! { + + #[derive(Clone, Copy, Debug, Eq, PartialEq)] + pub enum AuthenticateKeyReference: KeyReference { + SecureMessaging, + PivAuthentication, + PivCardApplicationAdministration, + DigitalSignature, + KeyManagement, + CardAuthentication, + Retired01, + Retired02, + Retired03, + Retired04, + Retired05, + Retired06, + Retired07, + Retired08, + Retired09, + Retired10, + Retired11, + Retired12, + Retired13, + Retired14, + Retired15, + Retired16, + Retired17, + Retired18, + Retired19, + Retired20, } } @@ -85,7 +226,7 @@ impl From for ContainerId { use Container::*; Self(match container { CardCapabilityContainer => 0xDB00, - CardHolderUniqueIdentifier =>0x3000, + CardHolderUniqueIdentifier => 0x3000, X509CertificateFor9A => 0x0101, CardholderFingerprints => 0x6010, SecurityObject => 0x9000, @@ -193,65 +334,3 @@ impl TryFrom> for Container { }) } } - - - // #[derive(Clone, Copy, PartialEq)] - // pub struct CertInfo { - // compressed: bool, - // } - - // impl From for u8 { - // fn from(cert_info: CertInfo) -> Self { - // cert_info.compressed as u8 - // } - // } - - // impl Encodable for CertInfo { - // fn encoded_len(&self) -> der::Result { - // Length::from(1) - // } - - // fn encode(&self, encoder: &mut Encoder<'_>) -> der::Result<()> { - // encoder.encode(der::Any::new(0x71, &[u8::from(self)])) - // } - // } - - // pub struct Certificate<'a> { - // // max bytes: 1856 - // certificate: &'a [u8], // tag: 0x70 - // // 1B - // cert_info: CertInfo, // tag: 0x71 - // // 38 - // // mscuid: ?, // tag: 0x72 - // error_detection_code: [u8; 0], // tag: 0xFE - // } - - // impl Encodable for CertInfo { - // fn encoded_len(&self) -> der::Result { - // Length::from(1) - // } - - // fn encode(&self, encoder: &mut Encoder<'_>) -> der::Result<()> { - // encoder.encode(der::Any::new(0x71, &[u8::from(self)])) - // } - // } - - // #[derive(Encodable)] - // pub struct DiscoveryObject<'a> { - // #[tlv(tag = "0x4F")] - // piv_card_application_aid: &'a [u8; 11], // tag: 0x4F, max bytes = 12, - // #[tlv(tag = 0x5F2f)] - // pin_usage_policy: [u8; 2], // tag: 0x5F2F, max bytes = 2, - // } - - // impl Encodable for CertInfo { - // fn encoded_len(&self) -> der::Result { - // Length::from(1) - // } - - // fn encode(&self, encoder: &mut Encoder<'_>) -> der::Result<()> { - // encoder.encode(der::Any::new(0x71, &[u8::from(self)])) - // } - // } - -// } diff --git a/src/derp.rs b/src/derp.rs index 0ece355..daa4cc5 100644 --- a/src/derp.rs +++ b/src/derp.rs @@ -1,3 +1,6 @@ +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + pub use untrusted::{Input, Reader}; #[derive(Copy, Clone, Debug, Eq, PartialEq)] diff --git a/src/dispatch.rs b/src/dispatch.rs index 77c6d13..fe03113 100644 --- a/src/dispatch.rs +++ b/src/dispatch.rs @@ -1,20 +1,30 @@ +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + use crate::{Authenticator, /*constants::PIV_AID,*/ Result}; -use apdu_dispatch::{app::App, command, Command, response}; +use apdu_dispatch::{app::App, command, response, Command}; use trussed::client; #[cfg(feature = "apdu-dispatch")] -impl App<{command::SIZE}, {response::SIZE}> for Authenticator +impl App<{ command::SIZE }, { response::SIZE }> for Authenticator where - T: client::Client + client::Ed255 + client::Tdes + T: client::Client + client::Ed255 + client::Tdes, { - fn select(&mut self, apdu: &Command, reply: &mut response::Data) -> Result { - self.select(apdu, reply) + fn select(&mut self, _apdu: &Command, reply: &mut response::Data) -> Result { + self.select(reply) } - fn deselect(&mut self) { self.deselect() } + fn deselect(&mut self) { + self.deselect() + } - fn call(&mut self, _: iso7816::Interface, apdu: &Command, reply: &mut response::Data) -> Result { + fn call( + &mut self, + _: iso7816::Interface, + apdu: &Command, + reply: &mut response::Data, + ) -> Result { self.respond(apdu, reply) } } diff --git a/src/error.rs b/src/error.rs deleted file mode 100644 index 4131ea0..0000000 --- a/src/error.rs +++ /dev/null @@ -1,110 +0,0 @@ -pub enum Error { - VerificationFailed { remaining: u8 }, // 63 00 or 63 CX - SecureMessagingNotSupported, // 68 82 - SecurityStatusNotSatisfied, // 69 82 - AuthenticationMethodBlocked, // 69 83 - // ExpectedSecureMessagingDataObjectsMissing, // 69 87 - // SecureMessagingDataObjectsIncorrect, // 69 88 - IncorrectParameterInCommandDataField, // 6A 80 - FunctionNotSupported, // 6A 81 - DataObjectOrApplicationNotFound, // 6A 82 - NotEnoughMemory, // 6A 84 - IncorrecParameterInP1OrP2, // 6A 86 - ReferencedDataOrReferenceDataNotFound, // 6A 88 -} - -pub enum Success { - Success, // 61 xx - SuccessResponseDataStillAvailable(u8), // 90 00 -} - -pub type Result = core::result::Result; - -// macro_rules! status_word { -// ($($Name:ident: [$sw1:expr, $sw2:tt],)*) => { -// $( -// // pub struct $Name {} - -// status_word! ($Name, $sw1, $sw2); -// )* - -// pub enum StatusWord { -// $($Name($Name),)* -// } -// }; - -// ($Name:ident, $sw1:expr, XX) => { -// pub struct $Name { -// sw2: u8, -// } - -// impl $Name { -// const SW1: u8 = $sw1; - -// pub fn new(sw2: u8) -> Self { -// Self { sw2 } -// } - -// pub fn as_bytes(&self) -> [u8; 2] { -// [Self::SW1, self.sw2] -// } - -// } - -// // impl core::ops::Deref for $Name { -// // type Target = [u8; 2]; -// // fn deref(&self) -> &Self::Target { -// // &[Self::SW1, self.sw2] -// // } -// // } - -// }; - -// ($Name:ident, $sw1:expr, $sw2:expr) => { -// #[derive(Default)] -// pub struct $Name {} - -// impl $Name { -// const SW1: u8 = $sw1; -// const SW2: u8 = $sw2; - -// pub fn new() -> Self { -// Default::default() -// } - -// pub fn as_bytes(&self) -> [u8; 2] { -// [Self::SW1, Self::SW2] -// } -// } -// }; -// } - -// status_word! { -// SecurityStatusNotSatisfied: [0x69, 0x82], -// NotFound: [0x6a, 0x82], -// Success: [0x90, 0x00], - -// SuccessBytesRemaining: [0x61, XX ], -// } - -// pub trait StatusWordTrait { -// fn sw1(&self) -> u8; -// fn sw2(&self) -> u8; -// -// fn sw(&self) -> [u8; 2] { -// [self.sw1(), self.sw2()] -// } -// } - -// #[cfg(test)] -// mod tests { -// use super::*; - -// #[test] -// fn deref() { -// let sw = SuccessBytesRemaining::new(42); -// println!("SW: {:?}", &sw.as_bytes()); -// } - -// } - diff --git a/src/lib.rs b/src/lib.rs index 373faf7..be0e796 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,27 +1,37 @@ -#![cfg_attr(not(test), no_std)] +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only +#![cfg_attr(not(any(test, feature = "std")), no_std)] + +#[cfg(not(feature = "delog"))] #[macro_use] -extern crate delog; -generate_macros!(); +extern crate log; -#[macro_use(hex)] -extern crate hex_literal; +#[cfg(feature = "delog")] +delog::generate_macros!(); pub mod commands; -pub use commands::Command; +use commands::containers::KeyReference; +use commands::GeneralAuthenticate; +pub use commands::{Command, YubicoPivExtension}; pub mod constants; pub mod container; +use container::AttestKeyReference; +pub mod derp; #[cfg(feature = "apdu-dispatch")] mod dispatch; -pub mod state; -pub mod derp; pub mod piv_types; +pub mod state; + pub use piv_types::{Pin, Puk}; +#[cfg(feature = "virtual")] +pub mod vpicc; use core::convert::TryInto; use flexiber::EncodableHeapless; +use heapless_bytes::Bytes; use iso7816::{Data, Status}; use trussed::client; use trussed::{syscall, try_syscall}; @@ -29,34 +39,36 @@ use trussed::{syscall, try_syscall}; use constants::*; pub type Result = iso7816::Result<()>; +use state::{CommandCache, LoadedState, ManagementAlgorithm, State, TouchPolicy}; + +use crate::piv_types::DynamicAuthenticationTemplate; /// PIV authenticator Trussed app. /// /// The `C` parameter is necessary, as PIV includes command sequences, /// where we need to store the previous command, so we need to know how /// much space to allocate. -pub struct Authenticator -{ - state: state::State, +pub struct Authenticator { + state: State, trussed: T, } -impl iso7816::App for Authenticator -{ +struct LoadedAuthenticator<'a, T> { + state: LoadedState<'a>, + trussed: &'a mut T, +} + +impl iso7816::App for Authenticator { fn aid(&self) -> iso7816::Aid { crate::constants::PIV_AID } } -impl Authenticator +impl Authenticator where T: client::Client + client::Ed255 + client::Tdes, { - pub fn new( - trussed: T, - ) - -> Self - { + pub fn new(trussed: T) -> Self { // seems like RefCell is not the right thing, we want something like `Rc` instead, // which can be cloned and injected into other parts of the App that use Trussed. // let trussed = RefCell::new(trussed); @@ -67,96 +79,273 @@ where } } + fn load(&mut self) -> core::result::Result, Status> { + Ok(LoadedAuthenticator { + state: self.state.load(&mut self.trussed)?, + trussed: &mut self.trussed, + }) + } + // TODO: we'd like to listen on multiple AIDs. // The way apdu-dispatch currently works, this would deselect, resetting security indicators. - pub fn deselect(&mut self) { - } + pub fn deselect(&mut self) {} - pub fn select(&mut self, _apdu: &iso7816::Command, reply: &mut Data) -> Result - { + pub fn select(&mut self, reply: &mut Data) -> Result { use piv_types::Algorithms::*; - info_now!("selecting PIV maybe"); + info!("selecting PIV maybe"); let application_property_template = piv_types::ApplicationPropertyTemplate::default() .with_application_label(APPLICATION_LABEL) .with_application_url(APPLICATION_URL) - .with_supported_cryptographic_algorithms(&[ - Tdes, - Aes256, - P256, - Ed255, - X255, - ]); + .with_supported_cryptographic_algorithms(&[Tdes, Aes256, P256, Ed25519, X25519]); application_property_template .encode_to_heapless_vec(reply) .unwrap(); - info_now!("returning: {}", hex_str!(reply)); + info!("returning: {:02X?}", reply); Ok(()) } - pub fn respond(&mut self, command: &iso7816::Command, reply: &mut Data) -> Result - { - // need to implement Debug on iso7816::Command - // info_now!("PIV responding to {:?}", command); - let last_or_only = command.class().chain().last_or_only(); - - // TODO: avoid owned copy? - let entire_command = match self.state.runtime.chained_command.as_mut() { - Some(command_so_far) => { - // TODO: make sure the header matches, e.g. '00 DB 3F FF' - command_so_far.data_mut().extend_from_slice(command.data()).unwrap(); - - if last_or_only { - let entire_command = command_so_far.clone(); - self.state.runtime.chained_command = None; - entire_command - } else { - return Ok(Default::default()); - } + pub fn respond( + &mut self, + command: &iso7816::Command, + reply: &mut Data, + ) -> Result { + info!("PIV responding to {:?}", command); + let parsed_command: Command = command.try_into()?; + info!("parsed: {:?}", &parsed_command); + + match parsed_command { + Command::Verify(verify) => self.load()?.verify(verify), + Command::ChangeReference(change_reference) => { + self.load()?.change_reference(change_reference) + } + Command::GetData(container) => self.get_data(container, reply), + Command::Select(_aid) => self.select(reply), + Command::GeneralAuthenticate(authenticate) => { + self.load()? + .general_authenticate(authenticate, command.data(), reply) + } + Command::YkExtension(yk_command) => { + self.yubico_piv_extension(command.data(), yk_command, reply) + } + _ => todo!(), + } + } + + fn get_data( + &mut self, + container: container::Container, + reply: &mut Data, + ) -> Result { + // TODO: check security status, else return Status::SecurityStatusNotSatisfied + + // Table 3, Part 1, SP 800-73-4 + // https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf#page=30 + use crate::container::Container; + match container { + Container::DiscoveryObject => { + // Err(Status::InstructionNotSupportedOrInvalid) + reply.extend_from_slice(DISCOVERY_OBJECT).ok(); + // todo!("discovery object"), } - None => { - if last_or_only { - // iso7816::Command - command.clone() - } else { - self.state.runtime.chained_command = Some(command.clone()); - return Ok(Default::default()); - } + Container::BiometricInformationTemplatesGroupTemplate => { + return Err(Status::InstructionNotSupportedOrInvalid); + // todo!("biometric information template"), + } + + // '5FC1 07' (351B) + Container::CardCapabilityContainer => { + piv_types::CardCapabilityContainer::default() + .encode_to_heapless_vec(reply) + .unwrap(); + info!("returning CCC {:02X?}", reply); + } + + // '5FC1 02' (351B) + Container::CardHolderUniqueIdentifier => { + let guid = self.state.persistent(&mut self.trussed)?.guid(); + piv_types::CardHolderUniqueIdentifier::default() + .with_guid(guid) + .encode_to_heapless_vec(reply) + .unwrap(); + info!("returning CHUID {:02X?}", reply); + } + + // // '5FC1 05' (351B) + // Container::X509CertificateForPivAuthentication => { + // // return Err(Status::NotFound); + + // // info!("loading 9a cert"); + // // it seems like fetching this certificate is the way Filo's agent decides + // // whether the key is "already setup": + // // https://github.com/FiloSottile/yubikey-agent/blob/8781bc0082db5d35712a2244e3ab3086f415dd59/setup.go#L69-L70 + // let data = try_syscall!(self.trussed.read_file( + // trussed::types::Location::Internal, + // trussed::types::PathBuf::from(b"authentication-key.x5c"), + // )).map_err(|_| { + // // info!("error loading: {:?}", &e); + // Status::NotFound + // } )?.data; + + // // todo: cleanup + // let tag = flexiber::Tag::application(0x13); // 0x53 + // flexiber::TaggedSlice::from(tag, &data) + // .unwrap() + // .encode_to_heapless_vec(reply) + // .unwrap(); + // } + + // // '5F FF01' (754B) + // YubicoObjects::AttestationCertificate => { + // let data = Data::from_slice(YUBICO_ATTESTATION_CERTIFICATE).unwrap(); + // reply.extend_from_slice(&data).ok(); + // } + _ => { + warn!("Unimplemented GET DATA object: {container:?}"); + return Err(Status::FunctionNotSupported); } + } + Ok(()) + } + + pub fn yubico_piv_extension( + &mut self, + data: &[u8], + instruction: YubicoPivExtension, + reply: &mut Data, + ) -> Result { + info!("yubico extension: {:?}", &instruction); + match instruction { + YubicoPivExtension::GetSerial => { + // make up a 4-byte serial + reply.extend_from_slice(&[0x00, 0x52, 0xf7, 0x43]).ok(); + } + + YubicoPivExtension::GetVersion => { + // make up a version, be >= 5.0.0 + reply.extend_from_slice(&[0x06, 0x06, 0x06]).ok(); + } + + YubicoPivExtension::Attest(slot) => { + match slot { + AttestKeyReference::PivAuthentication => reply + .extend_from_slice(YUBICO_ATTESTATION_CERTIFICATE_FOR_9A) + .ok(), + }; + } + + YubicoPivExtension::Reset => { + let persistent_state = self.state.persistent(&mut self.trussed)?; + + // TODO: find out what all needs resetting :) + persistent_state.reset_pin(&mut self.trussed); + persistent_state.reset_puk(&mut self.trussed); + persistent_state.reset_management_key(&mut self.trussed); + self.state.runtime.app_security_status.pin_verified = false; + self.state.runtime.app_security_status.puk_verified = false; + self.state.runtime.app_security_status.management_verified = false; + + try_syscall!(self.trussed.remove_file( + trussed::types::Location::Internal, + trussed::types::PathBuf::from(b"printed-information"), + )) + .ok(); + + try_syscall!(self.trussed.remove_file( + trussed::types::Location::Internal, + trussed::types::PathBuf::from(b"authentication-key.x5c"), + )) + .ok(); + } + + YubicoPivExtension::SetManagementKey(touch_policy) => { + self.load()? + .yubico_set_management_key(data, touch_policy, reply)?; + } + + _ => return Err(Status::FunctionNotSupported), + } + Ok(()) + } +} + +impl<'a, T: trussed::Client + trussed::client::Ed255> LoadedAuthenticator<'a, T> { + pub fn yubico_set_management_key( + &mut self, + data: &[u8], + _touch_policy: TouchPolicy, + _reply: &mut Data, + ) -> Result { + // cmd := apdu{ + // instruction: insSetMGMKey, + // param1: 0xff, + // param2: 0xff, + // data: append([]byte{ + // alg3DES, keyCardManagement, 24, + // }, key[:]...), + // } + + // TODO _touch_policy + + if !self.state.runtime.app_security_status.management_verified { + return Err(Status::SecurityStatusNotSatisfied); + } + + // example: 03 9B 18 + // B0 20 7A 20 DC 39 0B 1B A5 56 CC EB 8D CE 7A 8A C8 23 E6 F5 0D 89 17 AA + if data.len() < 4 { + warn!("Set management key with incorrect data"); + return Err(Status::IncorrectDataParameter); + } + + let key_data = &data[3..]; + + let Ok(alg) = ManagementAlgorithm::try_from(data[0]) else { + warn!("Set management key with incorrect alg: {:x}", data[0]); + return Err(Status::IncorrectDataParameter); }; - // parse Iso7816Command as PivCommand - let command: Command = (&entire_command).try_into()?; - info_now!("parsed: {:?}", &command); + if KeyReference::PivCardApplicationAdministration != data[1] { + warn!( + "Set management key with incorrect reference: {:x}, expected: {:x}", + data[1], + KeyReference::PivCardApplicationAdministration as u8 + ); + return Err(Status::IncorrectDataParameter); + } - match command { - Command::Verify(verify) => self.verify(verify), - Command::ChangeReference(change_reference) => self.change_reference(change_reference), - Command::GetData(container) => self.get_data(container, reply), - _ => todo!(), + if data[2] as usize != key_data.len() || alg.key_len() != key_data.len() { + warn!("Set management key with incorrect data length: claimed: {}, required by algorithm: {}, real: {}", data[2], alg.key_len(), key_data.len()); + return Err(Status::IncorrectDataParameter); } + + self.state + .persistent + .set_management_key(key_data, alg, self.trussed); + Ok(()) } // maybe reserve this for the case VerifyLogin::PivPin? pub fn login(&mut self, login: commands::VerifyLogin) -> Result { if let commands::VerifyLogin::PivPin(pin) = login { - // the actual PIN verification - let mut persistent_state = self.state.persistent(&mut self.trussed); - - if persistent_state.remaining_pin_retries() == 0 { + if self.state.persistent.remaining_pin_retries() == 0 { return Err(Status::OperationBlocked); } - if persistent_state.verify_pin(&pin) { - persistent_state.reset_consecutive_pin_mismatches(); + if self.state.persistent.verify_pin(&pin) { + self.state + .persistent + .reset_consecutive_pin_mismatches(self.trussed); self.state.runtime.app_security_status.pin_verified = true; Ok(()) - } else { - let remaining = persistent_state.increment_consecutive_pin_mismatches(); + let remaining = self + .state + .persistent + .increment_consecutive_pin_mismatches(self.trussed); // should we logout here? self.state.runtime.app_security_status.pin_verified = false; Err(Status::RemainingRetries(remaining)) @@ -177,14 +366,14 @@ where } Verify::Status(key_reference) => { - if key_reference != commands::VerifyKeyReference::PivPin { + if key_reference != commands::VerifyKeyReference::ApplicationPin { return Err(Status::FunctionNotSupported); } if self.state.runtime.app_security_status.pin_verified { - return Ok(()) + Ok(()) } else { - let retries = self.state.persistent(&mut self.trussed).remaining_pin_retries(); - return Err(Status::RemainingRetries(retries)); + let retries = self.state.persistent.remaining_pin_retries(); + Err(Status::RemainingRetries(retries)) } } } @@ -199,122 +388,49 @@ where } pub fn change_pin(&mut self, old_pin: commands::Pin, new_pin: commands::Pin) -> Result { - let mut persistent_state = self.state.persistent(&mut self.trussed); - if persistent_state.remaining_pin_retries() == 0 { + if self.state.persistent.remaining_pin_retries() == 0 { return Err(Status::OperationBlocked); } - if !persistent_state.verify_pin(&old_pin) { - let remaining = persistent_state.increment_consecutive_pin_mismatches(); + if !self.state.persistent.verify_pin(&old_pin) { + let remaining = self + .state + .persistent + .increment_consecutive_pin_mismatches(self.trussed); self.state.runtime.app_security_status.pin_verified = false; return Err(Status::RemainingRetries(remaining)); } - persistent_state.reset_consecutive_pin_mismatches(); - persistent_state.set_pin(new_pin); + self.state + .persistent + .reset_consecutive_pin_mismatches(self.trussed); + self.state.persistent.set_pin(new_pin, self.trussed); self.state.runtime.app_security_status.pin_verified = true; - return Ok(Default::default()); + Ok(()) } pub fn change_puk(&mut self, old_puk: commands::Puk, new_puk: commands::Puk) -> Result { - let mut persistent_state = self.state.persistent(&mut self.trussed); - if persistent_state.remaining_puk_retries() == 0 { + if self.state.persistent.remaining_puk_retries() == 0 { return Err(Status::OperationBlocked); } - if !persistent_state.verify_puk(&old_puk) { - let remaining = persistent_state.increment_consecutive_puk_mismatches(); + if !self.state.persistent.verify_puk(&old_puk) { + let remaining = self + .state + .persistent + .increment_consecutive_puk_mismatches(self.trussed); self.state.runtime.app_security_status.puk_verified = false; return Err(Status::RemainingRetries(remaining)); } - persistent_state.reset_consecutive_puk_mismatches(); - persistent_state.set_puk(new_puk); + self.state + .persistent + .reset_consecutive_puk_mismatches(self.trussed); + self.state.persistent.set_puk(new_puk, self.trussed); self.state.runtime.app_security_status.puk_verified = true; - return Ok(Default::default()); + Ok(()) } - // pub fn old_respond(&mut self, command: &iso7816::Command, reply: &mut Data) -> Result { - - // // TEMP - // // blocking::dbg!(self.state.persistent(&mut self.trussed).timestamp(&mut self.trussed)); - - // // handle CLA - // // - command chaining not supported - // // - secure messaging not supported - // // - only channel zero supported - // // - ensure INS known to us - - // let last_or_only = command.class().chain().last_or_only(); - - // // TODO: avoid owned copy? - // let owned_command = match self.state.runtime.chained_command.as_mut() { - // Some(command_so_far) => { - // // TODO: make sure the prefix matches, e.g. '00 DB 3F FF' - // command_so_far.data_mut().extend_from_slice(command.data()).unwrap(); - - // if last_or_only { - // let total_command = command_so_far.clone(); - // self.state.runtime.chained_command = None; - // total_command - // } else { - // return Ok(Default::default()); - // } - // } - - // None => { - // if last_or_only { - // // iso7816::Command - // command.clone() - // } else { - // self.state.runtime.chained_command = Some(command.clone()); - // return Ok(Default::default()); - // } - // } - // }; - - // let command = &owned_command; - - // let class = command.class(); - - // if !class.secure_messaging().none() { - // return Err(Status::SecureMessagingNotSupported); - // } - - // if class.channel() != Some(0) { - // return Err(Status::LogicalChannelNotSupported); - // } - - // // info_now!("CLA = {:?}", &command.class()); - // info_now!("INS = {:?}, P1 = {:X}, P2 = {:X}", - // &command.instruction(), - // command.p1, command.p2, - // ); - // // info_now!("extended = {:?}", command.extended); - - // // info_now!("INS = {:?}" &command.instruction()); - // match command.instruction() { - // Instruction::GetData => self.get_data(command, reply), - // Instruction::PutData => self.put_data(command), - // Instruction::Verify => panic!(),//self.old_verify(command), - // Instruction::ChangeReferenceData => panic!(),//self.change_reference_data(command), - // Instruction::GeneralAuthenticate => self.general_authenticate(command, reply), - // Instruction::GenerateAsymmetricKeyPair => self.generate_asymmetric_keypair(command, reply), - - // Instruction::Unknown(ins) => { - - // // see if it's a Yubico thing - // if let Ok(instruction) = YubicoPivExtension::try_from(ins) { - // self.yubico_piv_extension(command, instruction, reply) - // } else { - // Err(Status::FunctionNotSupported) - // } - // } - - // _ => Err(Status::FunctionNotSupported), - // } - // } - // SP 800-73-4, Part 2, Section 3.2.4 // https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf#page=92 // @@ -343,9 +459,12 @@ where // - 9000, 61XX for success // - 6982 security status // - 6A80, 6A86 for data, P1/P2 issue - pub fn general_authenticate(&mut self, command: &iso7816::Command, reply: &mut Data) -> Result - { - + pub fn general_authenticate( + &mut self, + auth: GeneralAuthenticate, + data: &[u8], + reply: &mut Data, + ) -> Result { // For "SSH", we need implement A.4.2 in SP-800-73-4 Part 2, ECDSA signatures // // ins = 87 = general authenticate @@ -363,340 +482,129 @@ where // // expected response: "7C L1 82 L2 SEQ(INT r, INT s)" - let _alg = command.p1; - let _slot = command.p2; - let mut data = command.data().as_slice(); - // refine as we gain more capability - if data.len() < 2 { - return Err(Status::IncorrectDataParameter); - } + let input = derp::Input::from(data); - let tag = data[0]; - if tag != 0x7c { - return Err(Status::IncorrectDataParameter); - } - - if data[1] > 0x81 { - panic!("unhandled >1B lengths"); - } - if data[1] == 0x81 { - data[2] as usize; - data = &data[3..]; - } else { - data[1] as usize; // ~158 for ssh ed25519 signatures (which have a ~150B commitment) - data = &data[2..]; - }; - - // step 1 of piv-go/ykAuthenticate - // https://github.com/go-piv/piv-go/blob/d5ec95eb3bec9c20d60611fb77b7caeed7d886b6/piv/piv.go#L359-L384 - if data.starts_with(&[0x80, 0x00]) { - // "request for witness" - // hint that this is an attempt to SetManagementKey - data = &data[2..]; - return self.request_for_witness(command, data, reply); - } - - // step 2 of piv-go/ykAuthenticate - // https://github.com/go-piv/piv-go/blob/d5ec95eb3bec9c20d60611fb77b7caeed7d886b6/piv/piv.go#L415-L420 - if data.starts_with(&[0x80, 0x08]) { - data = &data[2..]; - return self.request_for_challenge(command, data, reply); - } - - // expect '82 00' - if !data.starts_with(&[0x82, 0x00]) { - return Err(Status::IncorrectDataParameter); - } - data = &data[2..]; - - // // expect '81 20' - // if !data.starts_with(&[0x81, 0x20]) { - // return Err(Status::IncorrectDataParameter); - // } - // data = &data[2..]; + let (tag, input) = input + .read_all(derp::Error::UnexpectedEnd, |r| { + derp::expect_tag_and_get_value(r, 0x7C) + }) + .and_then(|input| { + input.read_all(derp::Error::UnexpectedEnd, derp::read_tag_and_get_value) + }) + .map_err(|_err| { + warn!("Bad data: {_err:?}"); + Status::IncorrectDataParameter + })?; - // expect '81 81 96' - // if !data.starts_with(&[0x81, 0x81, 0x96]) { - if !data.starts_with(&[0x81, 0x81]) { - return Err(Status::IncorrectDataParameter); + // part 2 table 7 + match tag { + 0x80 => self.request_for_witness(auth, input, reply), + 0x81 => self.request_for_challenge(auth, input, reply), + 0x82 => self.request_for_response(auth, input, reply), + 0x85 => self.request_for_exponentiation(auth, input, reply), + _ => Err(Status::IncorrectDataParameter), } - let len = data[2] as usize; - data = &data[3..]; + } - // if data.len() != 32 { - // return Err(Status::IncorrectDataParameter); - // } - if data.len() != len { + pub fn request_for_response( + &mut self, + auth: GeneralAuthenticate, + data: derp::Input<'_>, + _reply: &mut Data, + ) -> Result { + info!("Request for response"); + let alg = self.state.persistent.keys.management_key.alg; + if data.len() != alg.challenge_length() { + warn!("Bad response length"); return Err(Status::IncorrectDataParameter); } - - info_now!("looking for keyreference"); - let key_handle = match self.state.persistent(&mut self.trussed).state.keys.authentication_key { - Some(key) => key, - None => return Err(Status::KeyReferenceNotFound), - }; - - let commitment = data; // 32B of data // 150B for ed25519 - let signature = try_syscall!(self.trussed.sign_ed255(key_handle, commitment)) - .map_err(|_error| { - // NoSuchKey - debug_now!("{:?}", &_error); - Status::UnspecifiedNonpersistentExecutionError } - )? - .signature; - - piv_types::DynamicAuthenticationTemplate::with_response(&signature) - .encode_to_heapless_vec(reply) - // todo: come up with error handling (in this case, shouldn't fail) - .unwrap(); - - Ok(()) - } - - pub fn request_for_challenge(&mut self, command: &iso7816::Command, remaining_data: &[u8], reply: &mut Data) -> Result - { - // - data is of the form - // 00 87 03 9B 16 7C 14 80 08 99 6D 71 40 E7 05 DF 7F 81 08 6E EF 9C 02 00 69 73 E8 - // - remaining data contains 81 08 - // - we must a) verify the decrypted challenge, b) decrypt the counter challenge - - if command.p1 != 0x03 || command.p2 != 0x9b { + if alg != auth.algorithm { + warn!("Bad algorithm"); return Err(Status::IncorrectP1OrP2Parameter); } - if remaining_data.len() != 8 + 2 + 8 { - return Err(Status::IncorrectDataParameter); - } - - // A) verify decrypted challenge - let (response, data) = remaining_data.split_at(8); - - use state::{AuthenticateManagement, CommandCache}; - let our_challenge = match self.state.runtime.command_cache { - Some(CommandCache::AuthenticateManagement(AuthenticateManagement { challenge } )) - => challenge, - _ => { return Err(Status::InstructionNotSupportedOrInvalid); } + let Some(CommandCache::AuthenticateChallenge(plaintext)) = self.state.runtime.command_cache.take() else { + warn!("Request for response without cached challenge"); + return Err(Status::ConditionsOfUseNotSatisfied); }; - // no retries ;) - self.state.runtime.command_cache = None; - - if &our_challenge != response { - debug_now!("{:?}", &our_challenge); - debug_now!("{:?}", &response); - return Err(Status::IncorrectDataParameter); + let ciphertext = syscall!(self.trussed.encrypt( + alg.mechanism(), + self.state.persistent.keys.management_key.id, + &plaintext, + &[], + None + )) + .ciphertext; + + use subtle::ConstantTimeEq; + if data.as_slice_less_safe().ct_eq(&ciphertext).into() { + self.state.runtime.app_security_status.management_verified = true; + Ok(()) + } else { + Err(Status::SecurityStatusNotSatisfied) } + } - self.state.runtime.app_security_status.management_verified = true; + pub fn request_for_exponentiation( + &mut self, + _auth: GeneralAuthenticate, + _data: derp::Input<'_>, + _reply: &mut Data, + ) -> Result { + info!("Request for exponentiation"); + todo!() + } - // B) encrypt their challenge - let (header, challenge) = data.split_at(2); - if header != &[0x81, 0x08] { + pub fn request_for_challenge( + &mut self, + auth: GeneralAuthenticate, + data: derp::Input<'_>, + reply: &mut Data, + ) -> Result { + let alg = self.state.persistent.keys.management_key.alg; + if !data.is_empty() { + warn!("Request for challenge with non empty data"); return Err(Status::IncorrectDataParameter); } - - let key = self.state.persistent(&mut self.trussed).state.keys.management_key; - - let encrypted_challenge = syscall!(self.trussed.encrypt_tdes(key, challenge)).ciphertext; - - piv_types::DynamicAuthenticationTemplate::with_response(&encrypted_challenge) - .encode_to_heapless_vec(reply) - .unwrap(); - - Ok(()) - } - - pub fn request_for_witness(&mut self, command: &iso7816::Command, remaining_data: &[u8], reply: &mut Data) -> Result - { - // invariants: parsed data was '7C L1 80 00' + remaining_data - - if command.p1 != 0x03 || command.p2 != 0x9b { + if alg != auth.algorithm { + warn!("Bad algorithm"); return Err(Status::IncorrectP1OrP2Parameter); } + info!("Request for challenge "); + let challenge = syscall!(self.trussed.random_bytes(alg.challenge_length())).bytes; + self.state.runtime.command_cache = Some(CommandCache::AuthenticateChallenge( + Bytes::from_slice(&challenge).unwrap(), + )); + let resp = DynamicAuthenticationTemplate::with_challenge(&challenge); + resp.encode_to_heapless_vec(reply) + .map_err(|_err| { + error!("Failed to encode challenge: {_err:?}"); + Status::UnspecifiedNonpersistentExecutionError + }) + .map(drop) + } - if !remaining_data.is_empty() { - return Err(Status::IncorrectDataParameter); - } - - let key = self.state.persistent(&mut self.trussed).state.keys.management_key; - - let challenge = syscall!(self.trussed.random_bytes(8)).bytes; - let command_cache = state::AuthenticateManagement { challenge: challenge[..].try_into().unwrap() }; - self.state.runtime.command_cache = Some(state::CommandCache::AuthenticateManagement(command_cache)); - - let encrypted_challenge = syscall!(self.trussed.encrypt_tdes(key, &challenge)).ciphertext; - - piv_types::DynamicAuthenticationTemplate::with_witness(&encrypted_challenge) - .encode_to_heapless_vec(reply) - .unwrap(); - - Ok(()) - + pub fn request_for_witness( + &mut self, + _auth: GeneralAuthenticate, + _data: derp::Input<'_>, + _reply: &mut Data, + ) -> Result { + info!("Request for witness"); + todo!() } - //fn change_reference_data(&mut self, command: &Command) -> Result { - // // The way `piv-go` blocks PUK (which it needs to do because Yubikeys only - // // allow their Reset if PIN+PUK are blocked) is that it sends "change PUK" - // // with random (i.e. incorrect) PUK listed as both old and new PUK. - // // - // // 00 24 00 81 10 - // // 32 38 36 34 31 39 30 36 32 38 36 34 31 39 30 36 - // // - // // For now, we don't support PUK, so we can just return "Blocked" directly - // // if the key reference in P2 is '81' = PUK - - // // application PIN - // if command.p2 == 0x80 { - // let remaining_retries = self.state.persistent(&mut self.trussed).remaining_pin_retries(); - - // if remaining_retries == 0 { - // return Err(Status::OperationBlocked); - // } - - // if command.data().len() != 16 { - // return Err(Status::IncorrectDataParameter); - // } - - // let (old_pin, new_pin) = command.data().split_at(8); - - // let old_pin = match state::Pin::try_new(old_pin) { - // Ok(pin) => pin, - // _ => return Err(Status::IncorrectDataParameter), - // }; - - // let new_pin = match state::Pin::try_new(new_pin) { - // Ok(pin) => pin, - // _ => return Err(Status::IncorrectDataParameter), - // }; - - // if !self.state.persistent(&mut self.trussed).verify_pin(&old_pin) { - // let remaining = self.state.persistent(&mut self.trussed).increment_consecutive_pin_mismatches(&mut self.trussed); - // self.state.runtime.app_security_status.pin_verified = false; - // return Err(Status::RemainingRetries(remaining)); - // } - - // self.state.persistent(&mut self.trussed).reset_consecutive_pin_mismatches(&mut self.trussed); - // self.state.persistent(&mut self.trussed).set_pin(&mut self.trussed, new_pin); - // self.state.runtime.app_security_status.pin_verified = true; - // return Ok(()); - // } - - // // PUK - // if command.p2 == 0x81 { - // let remaining_retries = self.state.persistent(&mut self.trussed).remaining_puk_retries(); - - // if remaining_retries == 0 { - // return Err(Status::OperationBlocked); - // } - - // if command.data().len() != 16 { - // return Err(Status::IncorrectDataParameter); - // } - - // let (old_puk, new_puk) = command.data().split_at(8); - - // let old_puk = match state::Pin::try_new(old_puk) { - // Ok(puk) => puk, - // _ => return Err(Status::IncorrectDataParameter), - // }; - - // let new_puk = match state::Pin::try_new(new_puk) { - // Ok(puk) => puk, - // _ => return Err(Status::IncorrectDataParameter), - // }; - - // if !self.state.persistent(&mut self.trussed).verify_puk(&old_puk) { - // let remaining = self.state.persistent(&mut self.trussed).increment_consecutive_puk_mismatches(&mut self.trussed); - // self.state.runtime.app_security_status.puk_verified = false; - // return Err(Status::RemainingRetries(remaining)); - // } - - // self.state.persistent(&mut self.trussed).reset_consecutive_puk_mismatches(&mut self.trussed); - // self.state.persistent(&mut self.trussed).set_puk(&mut self.trussed, new_puk); - // self.state.runtime.app_security_status.puk_verified = true; - // return Ok(()); - // } - - - // Err(Status::KeyReferenceNotFound) - //} - - //fn old_verify(&mut self, command: &Command) -> Result { - // // we only implement our own PIN, not global Pin, not OCC data, not pairing code - // if command.p2 != 0x80 { - // return Err(Status::KeyReferenceNotFound); - // } - - // let p1 = command.p1; - // if p1 != 0x00 && p1 != 0xFF { - // return Err(Status::IncorrectP1OrP2Parameter); - // } - - // // all above failures shall not change security status or retry counter - - // // 1) If p1 is FF, "log out" of PIN - // if p1 == 0xFF { - // if command.data().len() != 0 { - // return Err(Status::IncorrectDataParameter); - // } else { - // self.state.runtime.app_security_status.pin_verified = false; - // return Ok(()); - // } - // } - - // // 2) Get retries (or whether verification is even needed) by passing no data - // if p1 == 0x00 && command.data().len() == 0 { - // if self.state.runtime.app_security_status.pin_verified { - // return Ok(()); - // } else { - // let retries = self.state.persistent(&mut self.trussed).remaining_pin_retries(); - // return Err(Status::RemainingRetries(retries)); - // } - // } - - // // if malformed PIN is sent, no security implication - // if command.data().len() != 8 { - // return Err(Status::IncorrectDataParameter); - // } - - // let sent_pin = match state::Pin::try_new(&command.data()) { - // Ok(pin) => pin, - // _ => return Err(Status::IncorrectDataParameter), - // }; - - // // 3) Verify le PIN! - // let remaining_retries = self.state.persistent(&mut self.trussed).remaining_pin_retries(); - // if remaining_retries == 0 { - // return Err(Status::OperationBlocked); - // } - - // if self.state.persistent(&mut self.trussed).verify_pin(&sent_pin) { - // self.state.persistent(&mut self.trussed).reset_consecutive_pin_mismatches(&mut self.trussed); - // self.state.runtime.app_security_status.pin_verified = true; - // Ok(()) - - // } else { - // let remaining = self.state.persistent(&mut self.trussed).increment_consecutive_pin_mismatches(&mut self.trussed); - // self.state.runtime.app_security_status.pin_verified = false; - // Err(Status::RemainingRetries(remaining)) - // } - //} - - pub fn generate_asymmetric_keypair(&mut self, command: &iso7816::Command, reply: &mut Data) -> Result - { + #[allow(unused)] + pub fn generate_asymmetric_keypair( + &mut self, + data: &[u8], + reply: &mut Data, + ) -> Result { if !self.state.runtime.app_security_status.management_verified { return Err(Status::SecurityStatusNotSatisfied); } - if command.p1 != 0x00 { - return Err(Status::IncorrectP1OrP2Parameter); - } - - if command.p2 != 0x9a { - // TODO: make more general - return Err(Status::FunctionNotSupported); - } - // example: 00 47 00 9A 0B // AC 09 // # P256 @@ -719,44 +627,46 @@ where // } // TODO: iterate on this, don't expect tags.. - let input = derp::Input::from(&command.data()); + let input = derp::Input::from(data); // let (mechanism, parameter) = input.read_all(derp::Error::Read, |input| { - let (mechanism, _pin_policy, _touch_policy) = input.read_all(derp::Error::Read, |input| { - derp::nested(input, 0xac, |input| { - let mechanism = derp::expect_tag_and_get_value(input, 0x80)?; - // let parameter = derp::expect_tag_and_get_value(input, 0x81)?; - let pin_policy = derp::expect_tag_and_get_value(input, 0xaa)?; - let touch_policy = derp::expect_tag_and_get_value(input, 0xab)?; - // Ok((mechanism.as_slice_less_safe(), parameter.as_slice_less_safe())) - Ok(( - mechanism.as_slice_less_safe(), - pin_policy.as_slice_less_safe(), - touch_policy.as_slice_less_safe(), - )) + let (mechanism, _pin_policy, _touch_policy) = input + .read_all(derp::Error::Read, |input| { + derp::nested(input, 0xac, |input| { + let mechanism = derp::expect_tag_and_get_value(input, 0x80)?; + // let parameter = derp::expect_tag_and_get_value(input, 0x81)?; + let pin_policy = derp::expect_tag_and_get_value(input, 0xaa)?; + let touch_policy = derp::expect_tag_and_get_value(input, 0xab)?; + // Ok((mechanism.as_slice_less_safe(), parameter.as_slice_less_safe())) + Ok(( + mechanism.as_slice_less_safe(), + pin_policy.as_slice_less_safe(), + touch_policy.as_slice_less_safe(), + )) + }) }) - }).map_err(|_e| { - info_now!("error parsing GenerateAsymmetricKeypair: {:?}", &_e); + .map_err(|_e| { + info!("error parsing GenerateAsymmetricKeypair: {:?}", &_e); Status::IncorrectDataParameter - })?; + })?; // if mechanism != &[0x11] { // HA! patch in Ed255 - if mechanism != &[0x22] { + if mechanism != [0x22] { return Err(Status::InstructionNotSupportedOrInvalid); } // ble policy - if let Some(key) = self.state.persistent(&mut self.trussed).state.keys.authentication_key { + if let Some(key) = self.state.persistent.keys.authentication_key { syscall!(self.trussed.delete(key)); } // let key = syscall!(self.trussed.generate_p256_private_key( // let key = syscall!(self.trussed.generate_p256_private_key( - let key = syscall!(self.trussed.generate_ed255_private_key( - trussed::types::Location::Internal, - )).key; - + let key = syscall!(self + .trussed + .generate_ed255_private_key(trussed::types::Location::Internal,)) + .key; // // TEMP // let mechanism = trussed::types::Mechanism::P256Prehashed; @@ -776,41 +686,41 @@ where // )? // .signature; // blocking::dbg!(&signature); - - self.state.persistent(&mut self.trussed).state.keys.authentication_key = Some(key); - self.state.persistent(&mut self.trussed).save(); + self.state.persistent.keys.authentication_key = Some(key); + self.state.persistent.save(self.trussed); // let public_key = syscall!(self.trussed.derive_p256_public_key( - let public_key = syscall!(self.trussed.derive_ed255_public_key( - key, - trussed::types::Location::Volatile, - )).key; + let public_key = syscall!(self + .trussed + .derive_ed255_public_key(key, trussed::types::Location::Volatile,)) + .key; let serialized_public_key = syscall!(self.trussed.serialize_key( // trussed::types::Mechanism::P256, trussed::types::Mechanism::Ed255, - public_key.clone(), + public_key, trussed::types::KeySerialization::Raw, - )).serialized_key; + )) + .serialized_key; - // info_now!("supposed SEC1 pubkey, len {}: {:X?}", serialized_public_key.len(), &serialized_public_key); + // info!("supposed SEC1 pubkey, len {}: {:X?}", serialized_public_key.len(), &serialized_public_key); // P256 SEC1 has 65 bytes, Ed255 pubkeys have 32 // let l2 = 65; let l2 = 32; let l1 = l2 + 2; - reply.extend_from_slice(&[0x7f, 0x49, l1, 0x86, l2]).unwrap(); + reply + .extend_from_slice(&[0x7f, 0x49, l1, 0x86, l2]) + .unwrap(); reply.extend_from_slice(&serialized_public_key).unwrap(); Ok(()) } - pub fn put_data(&mut self, command: &iso7816::Command) -> Result { - info_now!("PutData"); - if command.p1 != 0x3f || command.p2 != 0xff { - return Err(Status::IncorrectP1OrP2Parameter); - } + #[allow(unused)] + pub fn put_data(&mut self, data: &[u8]) -> Result { + info!("PutData"); // if !self.state.runtime.app_security_status.management_verified { // return Err(Status::SecurityStatusNotSatisfied); @@ -826,20 +736,22 @@ where // 88 1A 89 18 AA 81 D5 48 A5 EC 26 01 60 BA 06 F6 EC 3B B6 05 00 2E B6 3D 4B 28 7F 86 // - let input = derp::Input::from(&command.data()); - let (data_object, data) = input.read_all(derp::Error::Read, |input| { - let data_object = derp::expect_tag_and_get_value(input, 0x5c)?; - let data = derp::expect_tag_and_get_value(input, 0x53)?; - Ok((data_object.as_slice_less_safe(), data.as_slice_less_safe())) - // }).unwrap(); - }).map_err(|_e| { - info_now!("error parsing PutData: {:?}", &_e); + let input = derp::Input::from(data); + let (data_object, data) = input + .read_all(derp::Error::Read, |input| { + let data_object = derp::expect_tag_and_get_value(input, 0x5c)?; + let data = derp::expect_tag_and_get_value(input, 0x53)?; + Ok((data_object.as_slice_less_safe(), data.as_slice_less_safe())) + // }).unwrap(); + }) + .map_err(|_e| { + info!("error parsing PutData: {:?}", &_e); Status::IncorrectDataParameter - })?; + })?; - // info_now!("PutData in {:?}: {:?}", data_object, data); + // info!("PutData in {:?}: {:?}", data_object, data); - if data_object == &[0x5f, 0xc1, 0x09] { + if data_object == [0x5f, 0xc1, 0x09] { // "Printed Information", supposedly // Yubico uses this to store its "Metadata" // @@ -858,12 +770,13 @@ where trussed::types::PathBuf::from(b"printed-information"), trussed::types::Message::from_slice(data).unwrap(), None, - )).map_err(|_| Status::NotEnoughMemory)?; + )) + .map_err(|_| Status::NotEnoughMemory)?; return Ok(()); } - if data_object == &[0x5f, 0xc1, 0x05] { + if data_object == [0x5f, 0xc1, 0x05] { // "X.509 Certificate for PIV Authentication", supposedly // IOW, the cert for "authentication key" // Yubico uses this to store its "Metadata" @@ -883,187 +796,20 @@ where trussed::types::PathBuf::from(b"authentication-key.x5c"), trussed::types::Message::from_slice(data).unwrap(), None, - )).map_err(|_| Status::NotEnoughMemory)?; + )) + .map_err(|_| Status::NotEnoughMemory)?; - return Ok(Default::default()); + return Ok(()); } Err(Status::IncorrectDataParameter) } - - // match container { - // containers::Container::CardHolderUniqueIdentifier => - // piv_types::CardHolderUniqueIdentifier::default() - // .encode - // _ => todo!(), - // } - // todo!(); - - fn get_data(&mut self, container: container::Container, reply: &mut Data) -> Result - { - - // TODO: check security status, else return Status::SecurityStatusNotSatisfied - - // Table 3, Part 1, SP 800-73-4 - // https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-73-4.pdf#page=30 - use crate::container::Container; - match container { - Container::DiscoveryObject => { - // Err(Status::InstructionNotSupportedOrInvalid) - reply.extend_from_slice(DISCOVERY_OBJECT).ok(); - // todo!("discovery object"), - } - - Container::BiometricInformationTemplatesGroupTemplate => { - return Err(Status::InstructionNotSupportedOrInvalid) - // todo!("biometric information template"), - } - - // '5FC1 07' (351B) - Container::CardCapabilityContainer => { - piv_types::CardCapabilityContainer::default() - .encode_to_heapless_vec(reply) - .unwrap(); - info_now!("returning CCC {}", hex_str!(reply)); - } - - // '5FC1 02' (351B) - Container::CardHolderUniqueIdentifier => { - let guid = self.state.persistent(&mut self.trussed).guid(); - piv_types::CardHolderUniqueIdentifier::default() - .with_guid(guid) - .encode_to_heapless_vec(reply) - .unwrap(); - info_now!("returning CHUID {}", hex_str!(reply)); - } - - // // '5FC1 05' (351B) - // Container::X509CertificateForPivAuthentication => { - // // return Err(Status::NotFound); - - // // info_now!("loading 9a cert"); - // // it seems like fetching this certificate is the way Filo's agent decides - // // whether the key is "already setup": - // // https://github.com/FiloSottile/yubikey-agent/blob/8781bc0082db5d35712a2244e3ab3086f415dd59/setup.go#L69-L70 - // let data = try_syscall!(self.trussed.read_file( - // trussed::types::Location::Internal, - // trussed::types::PathBuf::from(b"authentication-key.x5c"), - // )).map_err(|_| { - // // info_now!("error loading: {:?}", &e); - // Status::NotFound - // } )?.data; - - // // todo: cleanup - // let tag = flexiber::Tag::application(0x13); // 0x53 - // flexiber::TaggedSlice::from(tag, &data) - // .unwrap() - // .encode_to_heapless_vec(reply) - // .unwrap(); - // } - - // // '5F FF01' (754B) - // YubicoObjects::AttestationCertificate => { - // let data = Data::from_slice(YUBICO_ATTESTATION_CERTIFICATE).unwrap(); - // reply.extend_from_slice(&data).ok(); - // } - - _ => return Err(Status::NotFound), - } - Ok(()) - } - - pub fn yubico_piv_extension(&mut self, command: &iso7816::Command, instruction: YubicoPivExtension, reply: &mut Data) -> Result - { - info_now!("yubico extension: {:?}", &instruction); - match instruction { - YubicoPivExtension::GetSerial => { - // make up a 4-byte serial - reply.extend_from_slice( - &[0x00, 0x52, 0xf7, 0x43]).ok(); - } - - YubicoPivExtension::GetVersion => { - // make up a version, be >= 5.0.0 - reply.extend_from_slice( - &[0x06, 0x06, 0x06]).ok(); - } - - YubicoPivExtension::Attest => { - if command.p2 != 0x00 { - return Err(Status::IncorrectP1OrP2Parameter); - } - - let slot = command.p1; - - if slot == 0x9a { - reply.extend_from_slice(YUBICO_ATTESTATION_CERTIFICATE_FOR_9A).ok(); - } else { - - return Err(Status::FunctionNotSupported) - } - } - - YubicoPivExtension::Reset => { - if command.p1 != 0x00 || command.p2 != 0x00 { - return Err(Status::IncorrectP1OrP2Parameter); - } - - // TODO: find out what all needs resetting :) - self.state.persistent(&mut self.trussed).reset_pin(); - self.state.persistent(&mut self.trussed).reset_puk(); - self.state.persistent(&mut self.trussed).reset_management_key(); - self.state.runtime.app_security_status.pin_verified = false; - self.state.runtime.app_security_status.puk_verified = false; - self.state.runtime.app_security_status.management_verified = false; - - try_syscall!(self.trussed.remove_file( - trussed::types::Location::Internal, - trussed::types::PathBuf::from(b"printed-information"), - )).ok(); - - try_syscall!(self.trussed.remove_file( - trussed::types::Location::Internal, - trussed::types::PathBuf::from(b"authentication-key.x5c"), - )).ok(); - - } - - YubicoPivExtension::SetManagementKey => { - // cmd := apdu{ - // instruction: insSetMGMKey, - // param1: 0xff, - // param2: 0xff, - // data: append([]byte{ - // alg3DES, keyCardManagement, 24, - // }, key[:]...), - // } - // TODO check we are authenticated with old management key - if command.p1 != 0xff || (command.p2 != 0xff && command.p2 != 0xfe) { - return Err(Status::IncorrectP1OrP2Parameter); - } - - let data = &command.data(); - - // example: 03 9B 18 - // B0 20 7A 20 DC 39 0B 1B A5 56 CC EB 8D CE 7A 8A C8 23 E6 F5 0D 89 17 AA - if data.len() != 3 + 24 { - return Err(Status::IncorrectDataParameter); - } - let (prefix, new_management_key) = data.split_at(3); - if prefix != &[0x03, 0x9b, 0x18] { - return Err(Status::IncorrectDataParameter); - } - let new_management_key: [u8; 24] = new_management_key.try_into().unwrap(); - self.state.persistent(&mut self.trussed).set_management_key(&new_management_key); - - } - - _ => return Err(Status::FunctionNotSupported), - } - Ok(()) - } - + // match container { + // containers::Container::CardHolderUniqueIdentifier => + // piv_types::CardHolderUniqueIdentifier::default() + // .encode + // _ => todo!(), + // } + // todo!(); } - - diff --git a/src/piv_types.rs b/src/piv_types.rs index 11194a9..7b3c76d 100644 --- a/src/piv_types.rs +++ b/src/piv_types.rs @@ -1,8 +1,49 @@ +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + use core::convert::{TryFrom, TryInto}; use flexiber::Encodable; +use hex_literal::hex; use serde::{Deserialize, Serialize}; +#[macro_export] +macro_rules! enum_u8 { + ( + $(#[$outer:meta])* + $vis:vis enum $name:ident { + $($var:ident = $num:expr),+ + $(,)* + } + ) => { + $(#[$outer])* + #[repr(u8)] + $vis enum $name { + $( + $var = $num, + )* + } + + impl TryFrom for $name { + type Error = ::iso7816::Status; + fn try_from(val: u8) -> Result { + match val { + $( + $num => Ok($name::$var), + )* + _ => Err(::iso7816::Status::KeyReferenceNotFound) + } + } + } + + impl PartialEq for $name { + fn eq(&self, other: &u8) -> bool { + *self as u8 == *other + } + } + } +} + /// According to spec, a PIN must be 6-8 digits, padded to 8 bytes with 0xFF. /// /// We are more lenient, and allow ASCII 0x20..=0x7E. @@ -24,9 +65,9 @@ impl TryFrom<&[u8]> for Pin { match unpadded_pin.len() { len @ 6..=8 => { let verifier = if cfg!(feature = "strict-pin") { - |&byte| byte >= b'0' && byte <= b'9' + |&byte| (b'0'..=b'9').contains(&byte) } else { - |&byte| byte >= 32 && byte <= 127 + |&byte| (32..=127).contains(&byte) }; if unpadded_pin.iter().all(verifier) { Ok(Pin { padded_pin, len }) @@ -34,7 +75,7 @@ impl TryFrom<&[u8]> for Pin { Err(()) } } - _ => Err(()) + _ => Err(()), } } } @@ -50,44 +91,44 @@ impl TryFrom<&[u8]> for Puk { } } -#[repr(u8)] -#[derive(Clone, Copy, Eq, PartialEq)] -// As additional reference, see: -// https://globalplatform.org/wp-content/uploads/2014/03/GPC_ISO_Framework_v1.0.pdf#page=15 -// -// This GP ISO standard contains PIV types as subset (although SM is not quite clear), -// references Opacity ZKM. -pub enum Algorithms { - Tdes = 0x3, - Rsa1k = 0x6, - Rsa2k = 0x7, - Aes128 = 0x8, - Aes192 = 0xA, - Aes256 = 0xC, - P256 = 0x11, - P384 = 0x14, - - // // non-standard! in piv-go though! - // Ed255_prev = 0x22, - +enum_u8! { + #[derive(Clone, Copy, Eq, PartialEq, Debug)] + // As additional reference, see: // https://globalplatform.org/wp-content/uploads/2014/03/GPC_ISO_Framework_v1.0.pdf#page=15 - P521 = 0x15, - // non-standard! - Rsa3k = 0xE0, - Rsa4k = 0xE1, - Ed255 = 0xE2, - X255 = 0xE3, - Ed448 = 0xE4, - X448 = 0xE5, - - // non-standard! picked by Alex, but maybe due for removal - P256Sha1 = 0xF0, - P256Sha256 = 0xF1, - P384Sha1 = 0xF2, - P384Sha256 = 0xF3, - P384Sha384 = 0xF4, + // + // This GP ISO standard contains PIV types as subset (although SM is not quite clear), + // references Opacity ZKM. + pub enum Algorithms { + Tdes = 0x3, + Rsa1024 = 0x6, + Rsa2048 = 0x7, + Aes128 = 0x8, + Aes192 = 0xA, + Aes256 = 0xC, + P256 = 0x11, + P384 = 0x14, + + // // non-standard! in piv-go though! + // Ed255_prev = 0x22, + + // https://globalplatform.org/wp-content/uploads/2014/03/GPC_ISO_Framework_v1.0.pdf#page=15 + P521 = 0x15, + // non-standard! + Rsa3072 = 0xE0, + Rsa4096 = 0xE1, + Ed25519 = 0xE2, + X25519 = 0xE3, + Ed448 = 0xE4, + X448 = 0xE5, + + // non-standard! picked by Alex, but maybe due for removal + P256Sha1 = 0xF0, + P256Sha256 = 0xF1, + P384Sha1 = 0xF2, + P384Sha256 = 0xF3, + P384Sha384 = 0xF4, + } } - /// TODO: #[derive(Clone, Copy, Default, Eq, PartialEq)] pub struct CryptographicAlgorithmTemplate<'a> { @@ -103,45 +144,53 @@ impl Encodable for CryptographicAlgorithmTemplate<'_> { // '80' let cryptographic_algorithm_identifier_tag = flexiber::Tag::context(0); for alg in self.algorithms.iter() { - encoder.encode(&flexiber::TaggedSlice::from(cryptographic_algorithm_identifier_tag, &[*alg as _])?)?; + encoder.encode(&flexiber::TaggedSlice::from( + cryptographic_algorithm_identifier_tag, + &[*alg as _], + )?)?; } // '06' let object_identifier_tag = flexiber::Tag::universal(6); - encoder.encode(&flexiber::TaggedSlice::from(object_identifier_tag, &[0x00])?) + encoder.encode(&flexiber::TaggedSlice::from( + object_identifier_tag, + &[0x00], + )?) } } #[derive(Clone, Copy, Encodable, Eq, PartialEq)] pub struct CoexistentTagAllocationAuthorityTemplate<'l> { - #[tlv(application, primitive, number = "0xF")] // = 0x4F + #[tlv(application, primitive, number = "0xF")] // = 0x4F pub application_identifier: &'l [u8], } impl Default for CoexistentTagAllocationAuthorityTemplate<'static> { fn default() -> Self { - Self { application_identifier: crate::constants::NIST_RID } + Self { + application_identifier: crate::constants::NIST_RID, + } } } #[derive(Clone, Copy, Encodable, Eq, PartialEq)] -#[tlv(application, constructed, number = "0x1")] // = 0x61 +#[tlv(application, constructed, number = "0x1")] // = 0x61 pub struct ApplicationPropertyTemplate<'l> { /// Application identifier of application: PIX (without RID, with version) - #[tlv(application, primitive, number = "0xF")] // = 0x4F - aid: &'l[u8], + #[tlv(application, primitive, number = "0xF")] // = 0x4F + aid: &'l [u8], /// Text describing the application; e.g., for use on a man-machine interface. - #[tlv(application, primitive, number = "0x10")] // = 0x50 + #[tlv(application, primitive, number = "0x10")] // = 0x50 application_label: &'l [u8], /// Reference to the specification describing the application. - #[tlv(application, primitive, number = "0x50")] // = 0x5F50 + #[tlv(application, primitive, number = "0x50")] // = 0x5F50 application_url: &'l [u8], - #[tlv(context, constructed, number = "0xC")] // = 0xAC + #[tlv(context, constructed, number = "0xC")] // = 0xAC supported_cryptographic_algorithms: CryptographicAlgorithmTemplate<'l>, - #[tlv(application, constructed, number = "0x19")] // = 0x79 + #[tlv(application, constructed, number = "0x19")] // = 0x79 coexistent_tag_allocation_authority: CoexistentTagAllocationAuthorityTemplate<'l>, } @@ -158,7 +207,6 @@ impl Default for ApplicationPropertyTemplate<'static> { } impl<'a> ApplicationPropertyTemplate<'a> { - pub const fn with_application_label(self, application_label: &'a [u8]) -> Self { Self { aid: self.aid, @@ -179,18 +227,22 @@ impl<'a> ApplicationPropertyTemplate<'a> { } } - pub const fn with_supported_cryptographic_algorithms(self, supported_cryptographic_algorithms: &'a [Algorithms]) -> Self { + pub const fn with_supported_cryptographic_algorithms( + self, + supported_cryptographic_algorithms: &'a [Algorithms], + ) -> Self { Self { aid: self.aid, application_label: self.application_label, application_url: self.application_url, - supported_cryptographic_algorithms: CryptographicAlgorithmTemplate { algorithms: supported_cryptographic_algorithms}, + supported_cryptographic_algorithms: CryptographicAlgorithmTemplate { + algorithms: supported_cryptographic_algorithms, + }, coexistent_tag_allocation_authority: self.coexistent_tag_allocation_authority, } } } - /// TODO: This should be an enum of sorts, maybe. /// /// The data objects that appear in the dynamic authentication template (tag '7C') in the data field @@ -198,43 +250,55 @@ impl<'a> ApplicationPropertyTemplate<'a> { /// /// Note that the empty tags (i.e., tags with no data) return the same tag with content /// (they can be seen as “requests for requests”): -/// - '80 00' Returns '80 TL ' (as per definition) -/// - '81 00' Returns '81 TL ' (as per external authenticate example) +/// - '80 00' Returns '80 TL \' (as per definition) +/// - '81 00' Returns '81 TL \' (as per external authenticate example) #[derive(Clone, Copy, Default, Encodable, Eq, PartialEq)] -#[tlv(application, constructed, number = "0x1C")] // = 0x7C +#[tlv(application, constructed, number = "0x1C")] // = 0x7C pub struct DynamicAuthenticationTemplate<'l> { /// The Witness (tag '80') contains encrypted data (unrevealed fact). /// This data is decrypted by the card. #[tlv(simple = "0x80")] - witness: Option<&'l[u8]>, + witness: Option<&'l [u8]>, /// The Challenge (tag '81') contains clear data (byte sequence), /// which is encrypted by the card. #[tlv(simple = "0x81")] - challenge: Option<&'l[u8]>, + challenge: Option<&'l [u8]>, /// The Response (tag '82') contains either the decrypted data from tag '80' /// or the encrypted data from tag '81'. #[tlv(simple = "0x82")] - response: Option<&'l[u8]>, + response: Option<&'l [u8]>, /// Not documented in SP-800-73-4 #[tlv(simple = "0x85")] - exponentiation: Option<&'l[u8]>, + exponentiation: Option<&'l [u8]>, } impl<'a> DynamicAuthenticationTemplate<'a> { pub fn with_challenge(challenge: &'a [u8]) -> Self { - Self { challenge: Some(challenge), ..Default::default() } + Self { + challenge: Some(challenge), + ..Default::default() + } } pub fn with_exponentiation(exponentiation: &'a [u8]) -> Self { - Self { exponentiation: Some(exponentiation), ..Default::default() } + Self { + exponentiation: Some(exponentiation), + ..Default::default() + } } pub fn with_response(response: &'a [u8]) -> Self { - Self { response: Some(response), ..Default::default() } + Self { + response: Some(response), + ..Default::default() + } } pub fn with_witness(witness: &'a [u8]) -> Self { - Self { witness: Some(witness), ..Default::default() } + Self { + witness: Some(witness), + ..Default::default() + } } } @@ -244,12 +308,13 @@ impl<'a> DynamicAuthenticationTemplate<'a> { /// /// We remove the deprecated data elements. // pivy: https://git.io/JfzBo -// https://www.idmanagement.gov/wp-content/uploads/sites/1171/uploads/TIG_SCEPACS_v2.3.pdf +// https://www.idmanagement.gov/wp-content/uploads/sites/1171/uploads/TIG_SCEPACS_v2.3.pdf FIXME: dead link #[derive(Clone, Copy, Encodable, Eq, PartialEq)] -#[tlv(application, primitive, number = "0x13")] // = 0x53 +#[tlv(application, primitive, number = "0x13")] // = 0x53 pub struct CardHolderUniqueIdentifier<'l> { #[tlv(simple = "0x30")] // pivy: 26B, TIG: 25B + // https://www.idmanagement.gov/docs/pacs-tig-scepacs.pdf fasc_n: &'l [u8], #[tlv(simple = "0x34")] @@ -269,7 +334,6 @@ pub struct CardHolderUniqueIdentifier<'l> { // #[tlv(simple = "0x36")] // // 16B, like guid // cardholder_uuid: Option<&'l [u8]>, - #[tlv(simple = "0x3E")] issuer_asymmetric_signature: &'l [u8], @@ -281,33 +345,29 @@ pub struct CardHolderUniqueIdentifier<'l> { error_detection_code: [u8; 0], } -// #[derive(Decodable, Encodable)] -// #[tlv(application, number = "0x13")] -// pub struct CardHolderUniqueIdentifier { -// #[tlv(slice, simple = "0x30")] -// fasc_n: [u8; 25], -// // #[tlv(slice, simple = "0x33")] -// // duns: [u8; 9], -// #[tlv(slice, simple = "0x34")] -// guid: [u8; 16], -// #[tlv(slice, simple = "0x35")] -// expiration_date: [u8; 8], // YYYYMMDD -// #[tlv(slice, simple = "0x3E")] -// issuer_asymmetric_signature: [u8; 1], -// #[tlv(slice, simple = "0xFE")] -// error_detection_code: [u8; 0], -// } +/// Corresponds to bit string in CBD (see https://www.idmanagement.gov/docs/pacs-tig-scepacs.pdf) +/// 11010_10011_10011_10011_10011_10110_00001_00001_00001_00001 +/// 10110_00001_00001_00001_00001_00001_00001_10110_00001_10110 +/// 00001_10110_00001_00001_00001_00001_00001_00001_00001_00001 +/// 00001_00001_10000_00001_00001_00001_00001_10000_11111_10011 +/// AGENCY CODE = 9999 (non federal) +/// SYSTEM CODE = 0000 +/// CREDENTIAL# = 000000 +/// CS = 0 +/// ICI = 0 +/// PI = 0000000000 +/// OC= 1 +/// OI=0000 +/// POA=1 +const DEFAULT_FASC_N: &[u8] = &hex!("D4E739D821086C1084210D8360D8210842108421804210C3F3"); impl Default for CardHolderUniqueIdentifier<'static> { fn default() -> Self { Self { - // 9999 = non-federal - fasc_n: &[0x99, 0x99], + fasc_n: DEFAULT_FASC_N, guid: hex!("00000000000040008000000000000000"), expiration_date: *b"99991231", - // cardholder_uuid: None, - // at least pivy only checks for non-empty entry - issuer_asymmetric_signature: b" ", + issuer_asymmetric_signature: b"", error_detection_code: [0u8; 0], } } @@ -384,4 +444,3 @@ pub struct DiscoveryObject { #[tlv(slice, application, number = "0x2f")] pin_usage_policy: [u8; 2], // tag: 0x5F2F, max bytes = 2, } - diff --git a/src/state.rs b/src/state.rs index 4ca3974..e6de4d7 100644 --- a/src/state.rs +++ b/src/state.rs @@ -1,28 +1,34 @@ +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + use core::convert::{TryFrom, TryInto}; +use heapless_bytes::Bytes; +use iso7816::Status; use trussed::{ - block, - Client as TrussedClient, + api::reply::Metadata, + config::MAX_MESSAGE_LENGTH, syscall, try_syscall, - types::{KeyId, PathBuf, Location}, + types::{KeyId, KeySerialization, Location, Mechanism, PathBuf}, }; use crate::constants::*; +use crate::piv_types::Algorithms; use crate::{Pin, Puk}; -pub type Result = core::result::Result; - pub enum Key { - Ed255(KeyId), + Ed25519(KeyId), P256(KeyId), - X255(KeyId), + X25519(KeyId), } pub enum PinPolicy { Never, Once, Always, } + +#[derive(PartialEq, Eq, Copy, Clone, Debug)] pub enum TouchPolicy { Never, Always, @@ -37,7 +43,10 @@ pub struct Slot { impl Default for Slot { fn default() -> Self { - Self { key: None, pin_policy: PinPolicy::Once, /*touch_policy: TouchPolicy::Never*/ } + Self { + key: None, + pin_policy: PinPolicy::Once, /*touch_policy: TouchPolicy::Never*/ + } } } @@ -46,10 +55,15 @@ impl Slot { use SlotName::*; match name { // Management => Slot { pin_policy: PinPolicy::Never, ..Default::default() }, - Signature => Slot { pin_policy: PinPolicy::Always, ..Default::default() }, - Pinless => Slot { pin_policy: PinPolicy::Never, ..Default::default() }, + Signature => Slot { + pin_policy: PinPolicy::Always, + ..Default::default() + }, + Pinless => Slot { + pin_policy: PinPolicy::Never, + ..Default::default() + }, _ => Default::default(), - } } } @@ -59,7 +73,7 @@ pub struct RetiredSlotIndex(u8); impl core::convert::TryFrom for RetiredSlotIndex { type Error = u8; fn try_from(i: u8) -> core::result::Result { - if 1 <= i && i <= 20 { + if (1..=20).contains(&i) { Ok(Self(i)) } else { Err(i) @@ -68,9 +82,9 @@ impl core::convert::TryFrom for RetiredSlotIndex { } pub enum SlotName { Identity, - Management, // Personalization? Administration? + Management, // Personalization? Administration? Signature, - Decryption, // Management after all? + Decryption, // Management after all? Pinless, Retired(RetiredSlotIndex), Attestation, @@ -78,8 +92,8 @@ pub enum SlotName { impl SlotName { pub fn default_pin_policy(&self) -> PinPolicy { - use SlotName::*; use PinPolicy::*; + use SlotName::*; match *self { Signature => Always, Pinless | Management | Attestation => Never, @@ -88,7 +102,10 @@ impl SlotName { } pub fn default_slot(&self) -> Slot { - Slot { key: None, pin_policy: self.default_pin_policy() } + Slot { + key: None, + pin_policy: self.default_pin_policy(), + } } pub fn reference(&self) -> u8 { @@ -117,13 +134,50 @@ impl SlotName { } } +crate::container::enum_subset! { + #[derive(Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] + pub enum ManagementAlgorithm: Algorithms { + Tdes, + Aes256 + } +} + +impl ManagementAlgorithm { + pub fn challenge_length(self) -> usize { + match self { + Self::Tdes => 8, + Self::Aes256 => 16, + } + } + + pub fn mechanism(self) -> Mechanism { + match self { + Self::Tdes => Mechanism::Tdes, + Self::Aes256 => Mechanism::Aes256Cbc, + } + } + + pub fn key_len(self) -> usize { + match self { + Self::Tdes => 24, + Self::Aes256 => 32, + } + } +} + +#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] +pub struct ManagementKey { + pub id: KeyId, + pub alg: ManagementAlgorithm, +} + #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct Keys { // 9a "PIV Authentication Key" (YK: PIV Authentication) #[serde(skip_serializing_if = "Option::is_none")] pub authentication_key: Option, // 9b "PIV Card Application Administration Key" (YK: PIV Management) - pub management_key: KeyId, + pub management_key: ManagementKey, // 9c "Digital Signature Key" (YK: Digital Signature) #[serde(skip_serializing_if = "Option::is_none")] pub signature_key: Option, @@ -137,74 +191,43 @@ pub struct Keys { pub retired_keys: [Option; 20], } - -#[derive(Clone, Debug, Default, Eq, PartialEq)] -pub struct State { - pub runtime: Runtime, - // temporary "state", to be removed again - // pub hack: Hack, - // trussed: RefCell>, +#[derive(Debug, Default, Eq, PartialEq)] +pub struct State { + pub runtime: Runtime, + pub persistent: Option, } -impl State { - pub fn new() -> Self { - Default::default() +impl State { + pub fn load(&mut self, client: &mut impl trussed::Client) -> Result, Status> { + if self.persistent.is_none() { + self.persistent = Some(Persistent::load_or_initialize(client)?); + } + Ok(LoadedState { + runtime: &mut self.runtime, + persistent: self.persistent.as_mut().unwrap(), + }) } - // it would be nicer to do this during "board bringup", by using TrussedService as Syscall - // - // TODO: it is really not good to overwrite user data on failure to decode old state. - // To fix this, need a flag to detect if we're "fresh", and/or initialize state in factory. - pub fn persistent<'t, T>(&mut self, trussed: &'t mut T) -> Persistent<'t, T> - where T: TrussedClient - + trussed::client::Tdes - { - Persistent::load_or_initialize(trussed) + pub fn persistent( + &mut self, + client: &mut impl trussed::Client, + ) -> Result<&mut Persistent, Status> { + Ok(self.load(client)?.persistent) } -} - -// #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] -// pub struct Pin { -// // padded_pin: [u8; 8] -// pin: heapless_bytes::Bytes, -// } -// impl Default for Pin { -// /// Default is "202020" -// /// But right now we have to use "123456" cause.. Filo -// fn default() -> Self { -// // Self::try_new(b"202020\xff\xff").unwrap() -// Self::try_new(b"123456\xff\xff").unwrap() -// } -// } + pub fn new() -> Self { + Default::default() + } +} -// impl Pin { -// pub fn try_new(padded_pin: &[u8]) -> Result { -// if padded_pin.len() != 8 { -// return Err(()); -// } -// let first_pad_byte = padded_pin.iter().position(|&b| b == 0xff); -// let unpadded_pin = match first_pad_byte { -// Some(l) => &padded_pin[..l], -// None => padded_pin, -// }; -// if unpadded_pin.len() < 6 { -// return Err(()); -// } -// let valid_bytes = unpadded_pin.iter().all(|&b| b >= b'0' && b <= b'9'); -// if valid_bytes { -// Ok(Self { -// // padded_pin: padded_pin.try_into().unwrap(), -// pin: Bytes::from_slice(padded_pin).unwrap(),//padded_pin.try_into().unwrap(), -// }) -// } else { -// Err(()) -// } -// } -// } +#[derive(Debug, Eq, PartialEq)] +pub struct LoadedState<'t> { + pub runtime: &'t mut Runtime, + pub persistent: &'t mut Persistent, +} #[derive(Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] -pub struct PersistentState { +pub struct Persistent { pub keys: Keys, consecutive_pin_mismatches: u8, consecutive_puk_mismatches: u8, @@ -221,28 +244,14 @@ pub struct PersistentState { guid: [u8; 16], } -#[derive(Debug, Eq, PartialEq)] -pub struct Persistent<'t, Trussed> { - trussed: &'t mut Trussed, - pub(crate) state: PersistentState, -} - -impl AsRef for Persistent<'_, T> { - fn as_ref(&self) -> &PersistentState { - &self.state - } -} - #[derive(Clone, Debug, Default, Eq, PartialEq)] -pub struct Runtime { +pub struct Runtime { // aid: Option< // consecutive_pin_mismatches: u8, - pub global_security_status: GlobalSecurityStatus, // pub currently_selected_application: SelectableAid, pub app_security_status: AppSecurityStatus, pub command_cache: Option, - pub chained_command: Option>, } // pub trait Aid { @@ -299,8 +308,7 @@ pub struct Runtime { // } #[derive(Clone, Debug, Default, Eq, PartialEq)] -pub struct GlobalSecurityStatus { -} +pub struct GlobalSecurityStatus {} #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub enum SecurityStatus { @@ -325,24 +333,13 @@ pub struct AppSecurityStatus { #[derive(Clone, Debug, Eq, PartialEq)] pub enum CommandCache { GetData(GetData), - AuthenticateManagement(AuthenticateManagement), + AuthenticateChallenge(Bytes<16>), } - #[derive(Clone, Debug, Eq, PartialEq)] -pub struct GetData { -} - -#[derive(Clone, Debug, Eq, PartialEq)] -pub struct AuthenticateManagement { - pub challenge: [u8; 8], -} - -impl<'t, T> Persistent<'t, T> -where - T: TrussedClient + trussed::client::Tdes, -{ +pub struct GetData {} +impl Persistent { pub const PIN_RETRIES_DEFAULT: u8 = 3; // hmm...! pub const PUK_RETRIES_DEFAULT: u8 = 5; @@ -351,117 +348,143 @@ where const DEFAULT_PUK: &'static [u8] = b"12345678"; pub fn guid(&self) -> [u8; 16] { - self.state.guid + self.guid } pub fn remaining_pin_retries(&self) -> u8 { - if self.state.consecutive_pin_mismatches >= Self::PIN_RETRIES_DEFAULT { + if self.consecutive_pin_mismatches >= Self::PIN_RETRIES_DEFAULT { 0 } else { - Self::PIN_RETRIES_DEFAULT - self.state.consecutive_pin_mismatches + Self::PIN_RETRIES_DEFAULT - self.consecutive_pin_mismatches } } pub fn remaining_puk_retries(&self) -> u8 { - if self.state.consecutive_puk_mismatches >= Self::PUK_RETRIES_DEFAULT { + if self.consecutive_puk_mismatches >= Self::PUK_RETRIES_DEFAULT { 0 } else { - Self::PUK_RETRIES_DEFAULT - self.state.consecutive_puk_mismatches + Self::PUK_RETRIES_DEFAULT - self.consecutive_puk_mismatches } } + // FIXME: revisit with trussed pin management pub fn verify_pin(&self, other_pin: &Pin) -> bool { // hprintln!("verifying pin {:?} against {:?}", other_pin, &self.pin).ok(); - self.state.pin == *other_pin + self.pin == *other_pin } + // FIXME: revisit with trussed pin management pub fn verify_puk(&self, other_puk: &Puk) -> bool { // hprintln!("verifying puk {:?} against {:?}", other_puk, &self.puk).ok(); - self.state.puk == *other_puk + self.puk == *other_puk } - pub fn set_pin(&mut self, new_pin: Pin) { - self.state.pin = new_pin; - self.save(); + pub fn set_pin(&mut self, new_pin: Pin, client: &mut impl trussed::Client) { + self.pin = new_pin; + self.save(client); } - pub fn set_puk(&mut self, new_puk: Puk) { - self.state.puk = new_puk; - self.save(); + pub fn set_puk(&mut self, new_puk: Puk, client: &mut impl trussed::Client) { + self.puk = new_puk; + self.save(client); } - pub fn reset_pin(&mut self) { - self.set_pin(Pin::try_from(Self::DEFAULT_PIN).unwrap()); - self.reset_consecutive_pin_mismatches(); + pub fn reset_pin(&mut self, client: &mut impl trussed::Client) { + self.set_pin(Pin::try_from(Self::DEFAULT_PIN).unwrap(), client); + self.reset_consecutive_pin_mismatches(client); } - pub fn reset_puk(&mut self) { - self.set_puk(Puk::try_from(Self::DEFAULT_PUK).unwrap()); - self.reset_consecutive_puk_mismatches(); + pub fn reset_puk(&mut self, client: &mut impl trussed::Client) { + self.set_puk(Puk::try_from(Self::DEFAULT_PUK).unwrap(), client); + self.reset_consecutive_puk_mismatches(client); } - pub fn increment_consecutive_pin_mismatches(&mut self) -> u8 { - if self.state.consecutive_pin_mismatches >= Self::PIN_RETRIES_DEFAULT { + pub fn increment_consecutive_pin_mismatches( + &mut self, + client: &mut impl trussed::Client, + ) -> u8 { + if self.consecutive_pin_mismatches >= Self::PIN_RETRIES_DEFAULT { return 0; } - self.state.consecutive_pin_mismatches += 1; - self.save(); - Self::PIN_RETRIES_DEFAULT - self.state.consecutive_pin_mismatches + self.consecutive_pin_mismatches += 1; + self.save(client); + Self::PIN_RETRIES_DEFAULT - self.consecutive_pin_mismatches } - pub fn increment_consecutive_puk_mismatches(&mut self) -> u8 { - if self.state.consecutive_puk_mismatches >= Self::PUK_RETRIES_DEFAULT { + pub fn increment_consecutive_puk_mismatches( + &mut self, + client: &mut impl trussed::Client, + ) -> u8 { + if self.consecutive_puk_mismatches >= Self::PUK_RETRIES_DEFAULT { return 0; } - self.state.consecutive_puk_mismatches += 1; - self.save(); - Self::PUK_RETRIES_DEFAULT - self.state.consecutive_puk_mismatches + self.consecutive_puk_mismatches += 1; + self.save(client); + Self::PUK_RETRIES_DEFAULT - self.consecutive_puk_mismatches } - pub fn reset_consecutive_pin_mismatches(&mut self) -> u8 { - if self.state.consecutive_pin_mismatches != 0 { - self.state.consecutive_pin_mismatches = 0; - self.save(); + pub fn reset_consecutive_pin_mismatches(&mut self, client: &mut impl trussed::Client) -> u8 { + if self.consecutive_pin_mismatches != 0 { + self.consecutive_pin_mismatches = 0; + self.save(client); } Self::PIN_RETRIES_DEFAULT } - pub fn reset_consecutive_puk_mismatches(&mut self) -> u8 { - if self.state.consecutive_puk_mismatches != 0 { - self.state.consecutive_puk_mismatches = 0; - self.save(); + pub fn reset_consecutive_puk_mismatches(&mut self, client: &mut impl trussed::Client) -> u8 { + if self.consecutive_puk_mismatches != 0 { + self.consecutive_puk_mismatches = 0; + self.save(client); } Self::PUK_RETRIES_DEFAULT } - pub fn reset_management_key(&mut self) { - self.set_management_key(YUBICO_DEFAULT_MANAGEMENT_KEY); + pub fn reset_management_key(&mut self, client: &mut impl trussed::Client) { + self.set_management_key( + YUBICO_DEFAULT_MANAGEMENT_KEY, + YUBICO_DEFAULT_MANAGEMENT_KEY_ALG, + client, + ); } - pub fn set_management_key(&mut self, management_key: &[u8; 24]) { + pub fn set_management_key( + &mut self, + management_key: &[u8], + alg: ManagementAlgorithm, + client: &mut impl trussed::Client, + ) { // let new_management_key = syscall!(self.trussed.unsafe_inject_tdes_key( - let new_management_key = syscall!(self.trussed.unsafe_inject_shared_key( + let id = syscall!(client.unsafe_inject_key( + alg.mechanism(), management_key, trussed::types::Location::Internal, - )).key; - let old_management_key = self.state.keys.management_key; - self.state.keys.management_key = new_management_key; - self.save(); - syscall!(self.trussed.delete(old_management_key)); + KeySerialization::Raw + )) + .key; + let old_management_key = self.keys.management_key.id; + self.keys.management_key = ManagementKey { id, alg }; + self.save(client); + syscall!(client.delete(old_management_key)); } - pub fn initialize(trussed: &'t mut T) -> Self { - info_now!("initializing PIV state"); - let management_key = syscall!(trussed.unsafe_inject_shared_key( - YUBICO_DEFAULT_MANAGEMENT_KEY, - trussed::types::Location::Internal, - )).key; + pub fn initialize(client: &mut impl trussed::Client) -> Self { + info!("initializing PIV state"); + let management_key = ManagementKey { + id: syscall!(client.unsafe_inject_key( + YUBICO_DEFAULT_MANAGEMENT_KEY_ALG.mechanism(), + YUBICO_DEFAULT_MANAGEMENT_KEY, + trussed::types::Location::Internal, + KeySerialization::Raw + )) + .key, + alg: YUBICO_DEFAULT_MANAGEMENT_KEY_ALG, + }; - let mut guid: [u8; 16] = syscall!(trussed.random_bytes(16)) + let mut guid: [u8; 16] = syscall!(client.random_bytes(16)) .bytes .as_ref() .try_into() @@ -472,7 +495,7 @@ where let keys = Keys { authentication_key: None, - management_key: management_key, + management_key, signature_key: None, encryption_key: None, pinless_authentication_key: None, @@ -480,62 +503,36 @@ where }; let mut state = Self { - trussed, - state: PersistentState { - keys, - consecutive_pin_mismatches: 0, - consecutive_puk_mismatches: 0, - pin: Pin::try_from(Self::DEFAULT_PIN).unwrap(), - puk: Puk::try_from(Self::DEFAULT_PUK).unwrap(), - timestamp: 0, - guid, - } + keys, + consecutive_pin_mismatches: 0, + consecutive_puk_mismatches: 0, + pin: Pin::try_from(Self::DEFAULT_PIN).unwrap(), + puk: Puk::try_from(Self::DEFAULT_PUK).unwrap(), + timestamp: 0, + guid, }; - state.save(); + state.save(client); state } - pub fn load(trussed: &'t mut T) -> Result { - let data = block!(trussed.read_file( - Location::Internal, - PathBuf::from(Self::FILENAME), - ).unwrap() - ).map_err(|e| { - info!("loading error: {:?}", &e); - drop(e) - })?.data; - - let previous_state: PersistentState = trussed::cbor_deserialize(&data).map_err(|e| { - info!("cbor deser error: {:?}", e); - info!("data: {:X?}", &data); - drop(e) - })?; - // horrible deser bug to forget Ok here :) - Ok(Self { trussed, state: previous_state }) - } - - pub fn load_or_initialize(trussed: &'t mut T) -> Self { + pub fn load_or_initialize(client: &mut impl trussed::Client) -> Result { // todo: can't seem to combine load + initialize without code repetition - let data = try_syscall!(trussed.read_file(Location::Internal, PathBuf::from(Self::FILENAME))); - if let Ok(data) = data { - let previous_state = trussed::cbor_deserialize(&data.data).map_err(|e| { - info!("cbor deser error: {:?}", e); - info!("data: {:X?}", &data); - drop(e) - }); - if let Ok(state) = previous_state { - // horrible deser bug to forget Ok here :) - return Self { trussed, state } - } - } + let data = load_if_exists(client, Location::Internal, &PathBuf::from(Self::FILENAME))?; + let Some(bytes) = data else { + return Ok( Self::initialize(client)); + }; - Self::initialize(trussed) + let parsed = trussed::cbor_deserialize(&bytes).map_err(|_err| { + error!("{_err:?}"); + Status::UnspecifiedPersistentExecutionError + })?; + Ok(parsed) } - pub fn save(&mut self) { - let data: trussed::types::Message = trussed::cbor_serialize_bytes(self.as_ref()).unwrap(); + pub fn save(&mut self, client: &mut impl trussed::Client) { + let data: trussed::types::Message = trussed::cbor_serialize_bytes(&self).unwrap(); - syscall!(self.trussed.write_file( + syscall!(client.write_file( Location::Internal, PathBuf::from(Self::FILENAME), data, @@ -543,11 +540,32 @@ where )); } - pub fn timestamp(&mut self) -> u32 { - self.state.timestamp += 1; - self.save(); - self.state.timestamp + pub fn timestamp(&mut self, client: &mut impl trussed::Client) -> u32 { + self.timestamp += 1; + self.save(client); + self.timestamp } - } +fn load_if_exists( + client: &mut impl trussed::Client, + location: Location, + path: &PathBuf, +) -> Result>, Status> { + match try_syscall!(client.read_file(location, path.clone())) { + Ok(r) => Ok(Some(r.data)), + Err(_) => match try_syscall!(client.entry_metadata(location, path.clone())) { + Ok(Metadata { metadata: None }) => Ok(None), + Ok(Metadata { + metadata: Some(_metadata), + }) => { + error!("File {path} exists but couldn't be read: {_metadata:?}"); + Err(Status::UnspecifiedPersistentExecutionError) + } + Err(_err) => { + error!("File {path} couldn't be read: {_err:?}"); + Err(Status::UnspecifiedPersistentExecutionError) + } + }, + } +} diff --git a/src/vpicc.rs b/src/vpicc.rs new file mode 100644 index 0000000..989a18d --- /dev/null +++ b/src/vpicc.rs @@ -0,0 +1,154 @@ +// Copyright (C) 2022 Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + +use iso7816::{command::FromSliceError, Command, Status}; +use trussed::virt::{Client, Ram}; + +use std::convert::{TryFrom, TryInto}; + +use crate::Authenticator; + +const REQUEST_LEN: usize = 7609; +const RESPONSE_LEN: usize = 7609; + +/// Virtual PIV smartcard implementation. +/// +/// This struct provides a virtual PIV smart card implementation that can be used with +/// `vpicc-rs` and [`vsmartcard`](https://frankmorgner.github.io/vsmartcard/) to emulate the card. +pub struct VirtualCard { + request_buffer: RequestBuffer, + response_buffer: ResponseBuffer, + card: Authenticator>, +} + +impl VirtualCard { + /// Creates a new virtual smart card from the given card. + pub fn new(card: Authenticator>) -> Self { + Self { + request_buffer: Default::default(), + response_buffer: Default::default(), + card, + } + } + + fn handle(&mut self, request: &[u8]) -> (&[u8], Status) { + parse_command(request) + .and_then(|command| self.request_buffer.handle(command)) + .map(|command| { + command + .map(|command| { + self.response_buffer + .handle(&command, |c, b| self.card.respond(c, b)) + }) + .unwrap_or_default() + }) + .unwrap_or_else(|status| (&[], status)) + } +} + +impl vpicc::VSmartCard for VirtualCard { + fn power_on(&mut self) {} + + fn power_off(&mut self) { + self.card.deselect(); + } + + fn reset(&mut self) { + self.card.deselect(); + } + + fn execute(&mut self, request: &[u8]) -> Vec { + trace!("Received request {:x?}", request); + let (data, status) = self.handle(request); + let response = make_response(data, status); + trace!("Sending response {:x?}", response); + response + } +} + +fn parse_command(data: &[u8]) -> Result, Status> { + data.try_into().map_err(|err| { + warn!("Failed to parse command: {err:?}"); + match err { + FromSliceError::InvalidSliceLength + | FromSliceError::TooShort + | FromSliceError::TooLong => Status::WrongLength, + FromSliceError::InvalidClass => Status::ClassNotSupported, + FromSliceError::InvalidFirstBodyByteForExtended => Status::UnspecifiedCheckingError, + } + }) +} + +fn make_response(data: &[u8], status: Status) -> Vec { + let status: [u8; 2] = status.into(); + let mut response = Vec::with_capacity(data.len() + 2); + response.extend_from_slice(data); + response.extend_from_slice(&status); + response +} + +#[derive(Clone, Debug, Default)] +struct RequestBuffer { + command: Option>, +} + +impl RequestBuffer { + pub fn handle(&mut self, command: Command) -> Result>, Status> { + if let Some(buffer) = &mut self.command { + buffer + .extend_from_command(&command) + .map_err(|_| Status::WrongLength)?; + } + if command.class().chain().last_or_only() { + if let Some(buffer) = self.command.take() { + Ok(Some(buffer)) + } else { + Ok(Some(command)) + } + } else { + if self.command.is_none() { + self.command = Some(command); + } + Ok(None) + } + } +} + +#[derive(Clone, Debug, Default)] +struct ResponseBuffer { + buffer: heapless::Vec, + offset: usize, +} + +impl ResponseBuffer { + pub fn handle< + const C: usize, + F: FnOnce(&Command, &mut heapless::Vec) -> Result<(), Status>, + >( + &mut self, + command: &Command, + exec: F, + ) -> (&[u8], Status) { + if command.instruction() != iso7816::Instruction::GetResponse { + self.buffer.clear(); + self.offset = 0; + if let Err(status) = exec(command, &mut self.buffer) { + return (&[], status); + } + } + self.response(command.expected()) + } + + fn response(&mut self, n: usize) -> (&[u8], Status) { + let n = n.min(self.buffer.len() - self.offset); + let data = &self.buffer[self.offset..][..n]; + self.offset += n; + let status = if self.offset >= self.buffer.len() { + Status::Success + } else { + let rest = self.buffer.len() - self.offset; + Status::MoreAvailable(u8::try_from(rest).unwrap_or(u8::MAX)) + }; + (data, status) + } +} diff --git a/tests/card/mod.rs b/tests/card/mod.rs new file mode 100644 index 0000000..2ef9c46 --- /dev/null +++ b/tests/card/mod.rs @@ -0,0 +1,40 @@ +// Copyright (C) 2022 Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + +use piv_authenticator::{vpicc::VirtualCard, Authenticator}; + +use std::{sync::mpsc, thread::sleep, time::Duration}; +use stoppable_thread::spawn; + +pub fn with_vsc R, R>(f: F) -> R { + let mut vpicc = vpicc::connect().expect("failed to connect to vpcd"); + + let (tx, rx) = mpsc::channel(); + let handle = spawn(move |stopped| { + trussed::virt::with_ram_client("opcard", |client| { + let card = Authenticator::new(client); + let mut virtual_card = VirtualCard::new(card); + let mut result = Ok(()); + while !stopped.get() && result.is_ok() { + result = vpicc.poll(&mut virtual_card); + if result.is_ok() { + tx.send(()).expect("failed to send message"); + } + } + result + }) + }); + + rx.recv().expect("failed to read message"); + + sleep(Duration::from_millis(200)); + + let result = f(); + + handle + .stop() + .join() + .expect("failed to join vpicc thread") + .expect("failed to run virtual smartcard"); + result +} diff --git a/tests/command_response.ron b/tests/command_response.ron new file mode 100644 index 0000000..2b74bad --- /dev/null +++ b/tests/command_response.ron @@ -0,0 +1,72 @@ +// Copyright (C) 2022 Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + +[ + IoTest( + name: "Verify", + cmd_resp: [ + VerifyDefaultApplicationPin(), + VerifyDefaultGlobalPin(expected_status: FunctionNotSupported) + ] + ), + IoTest( + name: "Select", + cmd_resp: [ + Select + ] + ), + IoTest( + name: "Default management key", + cmd_resp: [ + AuthenticateManagement( + key: ( + algorithm: Tdes, + key: "0102030405060708 0102030405060708 0102030405060708" + ) + ) + ] + ), + IoTest( + name: "Aes management key", + cmd_resp: [ + AuthenticateManagement( + key: ( + algorithm: Tdes, + key: "0102030405060708 0102030405060708 0102030405060708" + ) + ), + SetManagementKey( + key: ( + algorithm: Aes256, + key: "0102030405060708 0102030405060708 0102030405060708 0102030405060708" + ) + ), + AuthenticateManagement( + key: ( + algorithm: Aes256, + key: "0102030405060708 0102030405060708 0102030405060708 0102030405060708" + ) + ) + ] + ), + IoTest( + name: "unauthenticated set management key", + cmd_resp: [ + SetManagementKey( + key: ( + algorithm: Aes256, + key: "0102030405060708 0102030405060708 0102030405060708 0102030405060708" + ), + expected_status: SecurityStatusNotSatisfied, + ), + AuthenticateManagement( + key: ( + algorithm: Aes256, + key: "0102030405060708 0102030405060708 0102030405060708 0102030405060708" + ), + expected_status_challenge: IncorrectP1OrP2Parameter, + expected_status_response: IncorrectDataParameter, + ) + ] + ), +] diff --git a/tests/command_response.rs b/tests/command_response.rs new file mode 100644 index 0000000..ea4f0aa --- /dev/null +++ b/tests/command_response.rs @@ -0,0 +1,469 @@ +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only +#![cfg(feature = "virtual")] + +mod setup; + +use std::borrow::Cow; + +use aes::Aes256Enc; +use hex_literal::hex; +use serde::Deserialize; +use trussed::types::GenericArray; + +// iso7816::Status doesn't support serde +#[derive(Deserialize, Debug, PartialEq, Clone, Copy)] +enum Status { + Success, + MoreAvailable(u8), + VerificationFailed, + RemainingRetries(u8), + UnspecifiedNonpersistentExecutionError, + UnspecifiedPersistentExecutionError, + WrongLength, + LogicalChannelNotSupported, + SecureMessagingNotSupported, + CommandChainingNotSupported, + SecurityStatusNotSatisfied, + ConditionsOfUseNotSatisfied, + OperationBlocked, + IncorrectDataParameter, + FunctionNotSupported, + NotFound, + NotEnoughMemory, + IncorrectP1OrP2Parameter, + KeyReferenceNotFound, + InstructionNotSupportedOrInvalid, + ClassNotSupported, + UnspecifiedCheckingError, +} + +#[derive(Clone, Copy, Eq, PartialEq, Debug, Deserialize)] +pub enum Algorithm { + Tdes = 0x3, + Rsa1024 = 0x6, + Rsa2048 = 0x7, + Aes128 = 0x8, + Aes192 = 0xA, + Aes256 = 0xC, + P256 = 0x11, + P384 = 0x14, + + P521 = 0x15, + // non-standard! + Rsa3072 = 0xE0, + Rsa4096 = 0xE1, + Ed25519 = 0xE2, + X25519 = 0xE3, + Ed448 = 0xE4, + X448 = 0xE5, + + // non-standard! picked by Alex, but maybe due for removal + P256Sha1 = 0xF0, + P256Sha256 = 0xF1, + P384Sha1 = 0xF2, + P384Sha256 = 0xF3, + P384Sha384 = 0xF4, +} +impl Algorithm { + pub fn challenge_len(self) -> usize { + match self { + Self::Tdes => 8, + Self::Aes256 => 16, + _ => panic!(), + } + } + + pub fn key_len(self) -> usize { + match self { + Self::Tdes => 24, + Self::Aes256 => 32, + _ => panic!(), + } + } +} + +fn serialize_len(len: usize) -> heapless::Vec { + let mut buf = heapless::Vec::new(); + if let Ok(len) = u8::try_from(len) { + if len <= 0x7f { + buf.extend_from_slice(&[len]).ok(); + } else { + buf.extend_from_slice(&[0x81, len]).ok(); + } + } else if let Ok(len) = u16::try_from(len) { + let arr = len.to_be_bytes(); + buf.extend_from_slice(&[0x82, arr[0], arr[1]]).ok(); + } else { + } + buf +} + +fn tlv(tag: &[u8], data: &[u8]) -> Vec { + let mut buf = Vec::from(tag); + buf.extend_from_slice(&serialize_len(data.len())); + buf.extend_from_slice(data); + buf +} + +fn build_command(cla: u8, ins: u8, p1: u8, p2: u8, data: &[u8], le: u16) -> Vec { + let mut res = vec![cla, ins, p1, p2]; + let lc = data.len(); + let extended = if lc == 0 { + false + } else if let Ok(len) = lc.try_into() { + res.push(len); + false + } else { + let len: u16 = lc.try_into().unwrap(); + res.push(0); + res.extend_from_slice(&len.to_be_bytes()); + true + }; + + res.extend_from_slice(data); + + if le == 0 { + return res; + } + + if let Ok(len) = (le - 1).try_into() { + let _: u8 = len; + res.push(len.wrapping_add(1)); + } else if extended { + res.extend_from_slice(&le.to_be_bytes()); + } else { + res.push(0); + res.extend_from_slice(&le.to_be_bytes()); + } + + res +} + +impl TryFrom for Status { + type Error = u16; + fn try_from(sw: u16) -> Result { + Ok(match sw { + 0x6300 => Self::VerificationFailed, + sw @ 0x63c0..=0x63cf => Self::RemainingRetries((sw as u8) & 0xf), + + 0x6400 => Self::UnspecifiedNonpersistentExecutionError, + 0x6500 => Self::UnspecifiedPersistentExecutionError, + + 0x6700 => Self::WrongLength, + + 0x6881 => Self::LogicalChannelNotSupported, + 0x6882 => Self::SecureMessagingNotSupported, + 0x6884 => Self::CommandChainingNotSupported, + + 0x6982 => Self::SecurityStatusNotSatisfied, + 0x6985 => Self::ConditionsOfUseNotSatisfied, + 0x6983 => Self::OperationBlocked, + + 0x6a80 => Self::IncorrectDataParameter, + 0x6a81 => Self::FunctionNotSupported, + 0x6a82 => Self::NotFound, + 0x6a84 => Self::NotEnoughMemory, + 0x6a86 => Self::IncorrectP1OrP2Parameter, + 0x6a88 => Self::KeyReferenceNotFound, + + 0x6d00 => Self::InstructionNotSupportedOrInvalid, + 0x6e00 => Self::ClassNotSupported, + 0x6f00 => Self::UnspecifiedCheckingError, + + 0x9000 => Self::Success, + sw @ 0x6100..=0x61FF => Self::MoreAvailable(sw as u8), + other => return Err(other), + }) + } +} + +impl Default for Status { + fn default() -> Status { + Status::Success + } +} + +#[derive(Deserialize, Debug)] +#[serde(deny_unknown_fields)] +struct IoTest { + name: String, + cmd_resp: Vec, +} + +#[derive(Debug, Clone, Deserialize)] +#[serde(deny_unknown_fields)] +enum OutputMatcher { + Len(usize), + // The () at the end are here to workaround a compiler bug. See: + // https://github.com/rust-lang/rust/issues/89940#issuecomment-1282321806 + And(Cow<'static, [OutputMatcher]>, #[serde(default)] ()), + Or(Cow<'static, [OutputMatcher]>, #[serde(default)] ()), + /// HEX data + Data(Cow<'static, str>), + Bytes(Cow<'static, [u8]>), + NonZero, +} + +impl Default for OutputMatcher { + fn default() -> Self { + MATCH_EMPTY + } +} + +fn parse_hex(data: &str) -> Vec { + let tmp: String = data.split_whitespace().collect(); + hex::decode(tmp).unwrap() +} + +impl OutputMatcher { + fn validate(&self, data: &[u8]) -> bool { + match self { + Self::NonZero => data.iter().max() != Some(&0), + Self::Data(expected) => { + println!("Validating output with {expected}"); + data == parse_hex(expected) + } + Self::Bytes(expected) => { + println!("Validating output with {expected:x?}"); + data == &**expected + } + Self::Len(len) => data.len() == *len, + Self::And(matchers, _) => matchers.iter().filter(|m| !m.validate(data)).count() == 0, + Self::Or(matchers, _) => matchers.iter().filter(|m| m.validate(data)).count() != 0, + } + } +} + +#[derive(Deserialize, Debug)] +#[serde(deny_unknown_fields)] +struct ManagementKey { + algorithm: Algorithm, + key: String, +} + +#[derive(Deserialize, Debug)] +#[serde(deny_unknown_fields)] +enum IoCmd { + IoData { + input: String, + #[serde(default)] + output: OutputMatcher, + #[serde(default)] + expected_status: Status, + }, + VerifyDefaultApplicationPin { + #[serde(default)] + expected_status: Status, + }, + VerifyDefaultGlobalPin { + #[serde(default)] + expected_status: Status, + }, + SetManagementKey { + key: ManagementKey, + #[serde(default)] + expected_status: Status, + }, + AuthenticateManagement { + key: ManagementKey, + #[serde(default)] + expected_status_challenge: Status, + #[serde(default)] + expected_status_response: Status, + }, + Select, +} + +const MATCH_EMPTY: OutputMatcher = OutputMatcher::Len(0); +const MATCH_ANY: OutputMatcher = OutputMatcher::And(Cow::Borrowed(&[]), ()); + +impl IoCmd { + fn run(&self, card: &mut setup::Piv) { + match self { + Self::IoData { + input, + output, + expected_status, + } => Self::run_iodata(input, output, *expected_status, card), + Self::VerifyDefaultApplicationPin { expected_status } => { + Self::run_verify_default_application_pin(*expected_status, card) + } + Self::VerifyDefaultGlobalPin { expected_status } => { + Self::run_verify_default_global_pin(*expected_status, card) + } + Self::AuthenticateManagement { + key, + expected_status_challenge, + expected_status_response, + } => Self::run_authenticate_management( + key.algorithm, + &key.key, + *expected_status_challenge, + *expected_status_response, + card, + ), + Self::SetManagementKey { + key, + expected_status, + } => Self::run_set_management_key(key.algorithm, &key.key, *expected_status, card), + Self::Select => Self::run_select(card), + } + } + + fn run_set_management_key( + alg: Algorithm, + key: &str, + expected_status: Status, + card: &mut setup::Piv, + ) { + let mut key_data = parse_hex(key); + let mut data = vec![alg as u8, 0x9b, key_data.len() as u8]; + data.append(&mut key_data); + + Self::run_bytes( + &build_command(0x00, 0xff, 0xff, 0xff, &data, 0), + &MATCH_ANY, + expected_status, + card, + ); + } + + fn run_bytes( + input: &[u8], + output: &OutputMatcher, + expected_status: Status, + card: &mut setup::Piv, + ) -> heapless::Vec { + println!("Command: {:x?}", input); + let mut rep: heapless::Vec = heapless::Vec::new(); + let cmd: iso7816::Command<{ setup::COMMAND_SIZE }> = iso7816::Command::try_from(input) + .unwrap_or_else(|err| { + panic!("Bad command: {err:?}, for command: {}", hex::encode(input)) + }); + let status: Status = card + .respond(&cmd, &mut rep) + .err() + .map(|s| TryFrom::::try_from(s.into()).unwrap()) + .unwrap_or_default(); + + println!("Output: {:?}\nStatus: {status:?}", hex::encode(&rep)); + + if !output.validate(&rep) { + panic!("Bad output. Expected {:?}", output); + } + if status != expected_status { + panic!("Bad status. Expected {:?}", expected_status); + } + rep + } + + fn run_iodata( + input: &str, + output: &OutputMatcher, + expected_status: Status, + card: &mut setup::Piv, + ) { + Self::run_bytes(&parse_hex(input), output, expected_status, card); + } + + fn run_authenticate_management( + alg: Algorithm, + key: &str, + expected_status_challenge: Status, + expected_status_response: Status, + card: &mut setup::Piv, + ) { + use des::{ + cipher::{BlockEncrypt, KeyInit}, + TdesEde3, + }; + let command = build_command(0x00, 0x87, alg as u8, 0x9B, &hex!("7C 02 81 00"), 0); + let mut res = Self::run_bytes(&command, &MATCH_ANY, expected_status_challenge, card); + let key = parse_hex(key); + if expected_status_challenge != Status::Success && res.is_empty() { + res = heapless::Vec::from_slice(&vec![0; alg.challenge_len() + 6]).unwrap(); + } + + // Remove header + let challenge = &mut res[6..][..alg.challenge_len()]; + match alg { + Algorithm::Tdes => { + let cipher = TdesEde3::new(GenericArray::from_slice(&key)); + cipher.encrypt_block(GenericArray::from_mut_slice(challenge)); + } + Algorithm::Aes256 => { + let cipher = Aes256Enc::new(GenericArray::from_slice(&key)); + cipher.encrypt_block(GenericArray::from_mut_slice(challenge)); + } + _ => panic!(), + } + let second_data = tlv(&[0x7C], &tlv(&[0x82], challenge)); + let command = build_command(0x00, 0x87, alg as u8, 0x9B, &second_data, 0); + Self::run_bytes(&command, &MATCH_ANY, expected_status_response, card); + } + + fn run_verify_default_global_pin(expected_status: Status, card: &mut setup::Piv) { + Self::run_bytes( + &hex!("00 20 00 00 08 313233343536FFFF"), + &MATCH_EMPTY, + expected_status, + card, + ); + } + + fn run_verify_default_application_pin(expected_status: Status, card: &mut setup::Piv) { + Self::run_bytes( + &hex!("00 20 00 80 08 313233343536FFFF"), + &MATCH_EMPTY, + expected_status, + card, + ); + } + + fn run_select(card: &mut setup::Piv) { + let matcher = OutputMatcher::Bytes(Cow::Borrowed(&hex!( + " + 61 63 // Card application property template + 4f 06 000010000100 // Application identifier + 50 0c 536f6c6f4b65797320504956 // Application label = b\"Solokeys PIV\" + + // URL = b\"https://github.com/solokeys/piv-authenticator\" + 5f50 2d 68747470733a2f2f6769746875622e636f6d2f736f6c6f6b6579732f7069762d61757468656e74696361746f72 + + // Cryptographic Algorithm Identifier Template + ac 12 + 80 01 03 // TDES - ECB + 80 01 0c // AES256 - ECB + 80 01 11 // P-256 + 80 01 e2 // Ed25519 + 80 01 e3 // X25519 + 06 01 00 + // Coexistent Tag Allocation Authority Template + 79 07 + 4f 05 a000000308 + " + ))); + Self::run_bytes( + &hex!("00 A4 04 00 0C A000000308000010000100 00"), + &matcher, + Status::Success, + card, + ); + } +} + +#[test_log::test] +fn command_response() { + let data = std::fs::read_to_string("tests/command_response.ron").unwrap(); + let tests: Vec = ron::from_str(&data).unwrap(); + for t in tests { + println!("\n\n===========================================================",); + println!("Running {}", t.name); + setup::piv(|card| { + for io in t.cmd_resp { + io.run(card); + } + }); + } +} diff --git a/tests/generate_asymmetric_keypair.rs b/tests/generate_asymmetric_keypair.rs index bfd8817..8f787f2 100644 --- a/tests/generate_asymmetric_keypair.rs +++ b/tests/generate_asymmetric_keypair.rs @@ -1,6 +1,7 @@ -mod setup; +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only -use iso7816::Status::*; +mod setup; // example: 00 47 00 9A 0B // AC 09 @@ -13,10 +14,10 @@ use iso7816::Status::*; #[test] fn gen_keypair() { - let cmd = cmd!("00 47 00 9A 0B AC 09 80 01 11 AA 01 02 AB 01 02"); + let _cmd = cmd!("00 47 00 9A 0B AC 09 80 01 11 AA 01 02 AB 01 02"); // without PIN, no key generation - setup::piv(|piv| { + setup::piv(|_piv| { // not currently implemented // // let mut response = iso7816::Data::<16>::default(); diff --git a/tests/get_data.rs b/tests/get_data.rs index cbdd046..2b94b0a 100644 --- a/tests/get_data.rs +++ b/tests/get_data.rs @@ -1,3 +1,6 @@ +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + mod setup; // use delog::hex_str; @@ -9,8 +12,8 @@ fn get_data() { // let cmd = cmd!("00 47 00 9A 0B AC 09 80 01 11 AA 01 02 AB 01 02"); // let cmd = cmd!("00 f8 00 00"); -// // without PIN, no key generation - setup::piv(|piv| { + // // without PIN, no key generation + setup::piv(|_piv| { // ykGetSerial // println!("{}", hex_str!(&piv.respond(&cmd!("00 f8 00 00")).unwrap())); diff --git a/tests/pivy.rs b/tests/pivy.rs new file mode 100644 index 0000000..c5dc1fa --- /dev/null +++ b/tests/pivy.rs @@ -0,0 +1,24 @@ +// Copyright (C) 2022 Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + +#![cfg(feature = "virtual")] + +mod card; + +use card::with_vsc; + +use expectrl::{spawn, Eof, Regex, WaitStatus}; + +#[test] +fn list() { + with_vsc(|| { + let mut p = spawn("pivy-tool list").unwrap(); + p.check(Regex("card: [0-9A-Z]*")).unwrap(); + p.check("device: Virtual PCD 00 00").unwrap(); + p.check("chuid: ok").unwrap(); + p.check(Regex("guid: [0-9A-Z]*")).unwrap(); + p.check("algos: 3DES AES256 ECCP256 (null) (null)").unwrap(); + p.check(Eof).unwrap(); + assert_eq!(p.wait().unwrap(), WaitStatus::Exited(p.pid(), 0)); + }); +} diff --git a/tests/put_data.rs b/tests/put_data.rs index ee6e034..a92e501 100644 --- a/tests/put_data.rs +++ b/tests/put_data.rs @@ -1,3 +1,6 @@ +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only + mod setup; // use apdu_dispatch::dispatch::Interface::Contact; @@ -16,7 +19,7 @@ mod setup; #[test] fn put_data() { - setup::piv(|piv| { + setup::piv(|_piv| { // let mut response = iso7816::Data::<16>::default(); // piv.respond(&cmd!( diff --git a/tests/setup/mod.rs b/tests/setup/mod.rs index 293c9cf..91b9391 100644 --- a/tests/setup/mod.rs +++ b/tests/setup/mod.rs @@ -1,70 +1,23 @@ -trussed::platform!(Platform, - R: rand_core::OsRng,//chacha20::ChaCha8Rng, - S: store::Store, - UI: ui::UserInterface, -); +// Copyright (C) 2022 Nicolas Stalder AND Nitrokey GmbH +// SPDX-License-Identifier: LGPL-3.0-only -const COMMAND_SIZE: usize = 3072; +#[allow(unused)] +pub const COMMAND_SIZE: usize = 3072; #[macro_export] macro_rules! cmd { - ($tt:tt) => { iso7816::Command::<3072>::try_from(&hex_literal::hex!($tt)).unwrap() } + ($tt:tt) => { + iso7816::Command::<3072>::try_from(&hex_literal::hex!($tt)).unwrap() + }; } -pub type Piv<'service> = piv_authenticator::Authenticator< - trussed::ClientImplementation<&'service mut trussed::service::Service>, COMMAND_SIZE>; +use trussed::virt::{Client, Ram}; -pub fn piv(test: impl FnOnce(&mut Piv) -> R) -> R { - use trussed::Interchange as _; - unsafe { trussed::pipe::TrussedInterchange::reset_claims(); } - let trussed_platform = init_platform(); - let mut trussed_service = trussed::service::Service::new(trussed_platform); - let client_id = "test"; - let trussed_client = trussed_service.try_as_new_client(client_id).unwrap(); - let mut piv_app = piv_authenticator::Authenticator::new(trussed_client); - test(&mut piv_app) -} - -pub fn init_platform() -> Platform { - let rng = rand_core::OsRng; - let store = store::Store::format( - store::InternalStorage::new(), - store::ExternalStorage::new(), - store::VolatileStorage::new(), - ); - let ui = ui::UserInterface::new(); - - let platform = Platform::new(rng, store, ui); - - platform -} - -pub mod ui { - use trussed::platform::{consent, reboot, ui}; - pub struct UserInterface { start_time: std::time::Instant } +pub type Piv = piv_authenticator::Authenticator>; - impl UserInterface { pub fn new() -> Self { Self { start_time: std::time::Instant::now() } } } - - impl trussed::platform::UserInterface for UserInterface { - fn check_user_presence(&mut self) -> consent::Level { consent::Level::Normal } - fn set_status(&mut self, _status: ui::Status) {} - fn refresh(&mut self) {} - fn uptime(&mut self) -> core::time::Duration { self.start_time.elapsed() } - fn reboot(&mut self, _to: reboot::To) -> ! { loop { continue; } } - } -} - -pub mod store { - use littlefs2::{const_ram_storage, consts, fs::{Allocation, Filesystem}}; - use trussed::types::{LfsResult, LfsStorage}; - - const_ram_storage!(InternalStorage, 8192); - const_ram_storage!(ExternalStorage, 8192); - const_ram_storage!(VolatileStorage, 8192); - - trussed::store!(Store, - Internal: InternalStorage, - External: ExternalStorage, - Volatile: VolatileStorage - ); +pub fn piv(test: impl FnOnce(&mut Piv) -> R) -> R { + trussed::virt::with_ram_client("test", |client| { + let mut piv_app = piv_authenticator::Authenticator::new(client); + test(&mut piv_app) + }) }