Repository: gl-sergei/u2f-token Branch: master Commit: 2c19a75c3109 Files: 68 Total size: 251.1 KB Directory structure: gitextract_1ksv5dfj/ ├── .github/ │ └── workflows/ │ └── c-cpp.yml ├── .gitignore ├── .gitmodules ├── .travis.yml ├── COPYING ├── README.md ├── requirements.txt └── src/ ├── .gitignore ├── Makefile ├── affine.h ├── bn-thumb1.h ├── bn.c ├── bn.h ├── call-ec.c ├── call-ec_p256r1.c ├── cert/ │ ├── attestation.der │ ├── attestation.pem │ ├── attestation_key.der │ ├── attestation_key.pem │ ├── certtool │ ├── csr.csr │ ├── dump-der.py │ └── gen.sh ├── csn.c ├── csn.h ├── dbug.c ├── dbug.h ├── ec_p256r1.c ├── ec_p256r1.h ├── ecc.c ├── ecc.h ├── efm32hg.ld ├── empty-attestation-cert.c ├── field-group-select.h ├── gdb.commands ├── hmac.c ├── hmac.h ├── inject_key.py ├── inject_key_bin.py ├── jpc-ac_p256r1.h ├── jpc.c ├── jpc_p256r1.c ├── mod.c ├── mod.h ├── modp256r1.c ├── modp256r1.h ├── muladd_256.h ├── neug.c ├── neug.h ├── pbt.c ├── pbt.h ├── platform.c ├── platform.h ├── random.c ├── random.h ├── sha256.c ├── sha256.h ├── stm32f103.ld ├── toboot.h ├── u2f-apdu.c ├── u2f-apdu.h ├── u2f-hid.c ├── u2f-hid.h ├── u2f.c ├── usb-hid.c ├── usb-hid.h ├── uvoid.c └── uvoid.h ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/c-cpp.yml ================================================ name: C/C++ CI on: push: branches: [ "master" ] pull_request: branches: [ "master" ] jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 with: submodules: recursive - name: instal deps run: | pip install -r requirements.txt --user sudo apt-get update sudo apt-get -yy install python-pip openssl gcc-arm-none-eabi binutils-arm-none-eabi - name: make run: | set -e mkdir artifacts cd src for ENFORCE_DEBUG_LOCK in 1 0 ; do for CUSTOM_ATTESTATION_CERT in 1 0 ; do for TARGET in TOMU MAPLE_MINI BLUE_PILL BLACK_PILL ST_DONGLE ST_DONGLE_NO_PUSH ; do make TARGET=${TARGET} CUSTOM_ATTESTATION_CERT=${CUSTOM_ATTESTATION_CERT} ENFORCE_DEBUG_LOCK=${ENFORCE_DEBUG_LOCK} -j4 if [ "${CUSTOM_ATTESTATION_CERT}" = 0 ] && [ "${ENFORCE_DEBUG_LOCK}" = 1 ] ; then cp build/u2f.bin ../artifacts/u2f-${TARGET}.bin fi openssl ecparam -name prime256v1 -genkey -noout -outform der -out key.der ./inject_key.py --key key.der --ctr 1001 make clean distclean certclean done done done cd .. ================================================ FILE: .gitignore ================================================ */build */.dep doc/chopstx.info .vs/ ================================================ FILE: .gitmodules ================================================ [submodule "chopstx"] path = chopstx url = https://github.com/gl-sergei/chopstx.git ================================================ FILE: .travis.yml ================================================ language: c sudo: required dist: trusty addons: apt: packages: - python-pip - openssl install: - pip install -r requirements.txt --user - sudo apt-add-repository -y ppa:team-gcc-arm-embedded/ppa - sudo apt-get update - sudo apt-get install -yy gcc-arm-embedded script: - | set -e mkdir artefacts cd src for ENFORCE_DEBUG_LOCK in 1 0 ; do for CUSTOM_ATTESTATION_CERT in 1 0 ; do for TARGET in TOMU MAPLE_MINI BLUE_PILL BLACK_PILL ST_DONGLE ST_DONGLE_NO_PUSH ; do make TARGET=${TARGET} CUSTOM_ATTESTATION_CERT=${CUSTOM_ATTESTATION_CERT} ENFORCE_DEBUG_LOCK=${ENFORCE_DEBUG_LOCK} -j4 if [ "${CUSTOM_ATTESTATION_CERT}" = 0 ] && [ "${ENFORCE_DEBUG_LOCK}" = 1 ] ; then cp build/u2f.bin ../artefacts/u2f-${TARGET}.bin fi openssl ecparam -name prime256v1 -genkey -noout -outform der -out key.der ./inject_key.py --key key.der --ctr 1001 make clean distclean certclean done done done cd .. deploy: provider: releases api_key: secure: L44PBDcHxpeG/HN2rIkAycRfRV0uiuyHIAxk/VWGyg7K/COMDl4Nhwjg2a+G/vMtH3CIgih+dxlG6auVI1kFJNgpQOsuhn8obl+QrF1+Vw+8zHIHVPCVook30Ar5ovYjV9EXHpA6lHucFOrNFrJ4BeT6NdDYjWVq+c7+9jgjtk3Hdoz1OfYbVLhbNRVwv/SqC8tyo0EjOqG0Fe13XXYDjUzNsFYZOP9Xu0Y94O64i8akrfNzwC4xZHFLpH5MHoF6nd/LJXxixsJ2C2OYJAcjI6ju8qwjGPWvIbIV52xyrXyM/nswGo/B7s7w/B4o2cqciJEll8fRqtJKeE3AWPc5L3hWz1ii6fb+5dAbgW+triwpNjLnX5PzJSsH1no6+3eXW5GmQnvS3cf/ht22JUvy5XnSnn3AHgJTuvmKXJfvE48ZWDaM4US+4z+dLLNRtxEEsTDHRNa96inkLVI60ZHIwACw90z0avnr0rvUdEYsx56oksCN1HcRr0tK3x2iBpqzBPGOYcTBENMnhMevRie88hjidj/ePRem4yxHHswZKmEwu5kL65atjTWN6ZrQQOqO9BH0NiFXfk9gOoWwRLhF090qoMI8n8u5R5iXz8wAMbQzH7/rntoCoNUy9bxLcclmzrk9lsxlhDp46xYfOHH/R9BRcOFKAEymt6B1k41chkE= file_glob: true file: artefacts/* skip_cleanup: true draft: true on: repo: gl-sergei/u2f-token tags: true ================================================ FILE: COPYING ================================================ GNU 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. 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 . ================================================ FILE: README.md ================================================ ![GitHub Workflow Status (with event)](https://img.shields.io/github/actions/workflow/status/gl-sergei/u2f-token/.github%2Fworkflows%2Fc-cpp.yml) ![GitHub all releases](https://img.shields.io/github/downloads/gl-sergei/u2f-token/total) [![Latest Release](https://img.shields.io/github/release/gl-sergei/u2f-token.svg)](https://github.com/gl-sergei/u2f-token/releases/latest) [![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0) # U2F-TOKEN firmware for STM32F103 and EFM32HG boards Turns your cheap STM32F103 or EFM32HG board into U2F token. ## Supported boards U2F-TOKEN is known to work on: - [Tomu board](https://tomu.im/) (EFM32HG) is an excellent device to use for U2F as it can sit entirely inside of your USB port (and it is opensource) - Blue pill (STM32F103) as well as Black pill - Countless ST32F103 based Chinese St-Link V2 clones can be turned into U2F devices with U2F-TOKEN - Variety of Maple Mini clones which can be found on Aliexpress ## Udev rules On Linux you need to add the following rules to be able to use your device as non root user. Create the file `/etc/udev/rules.d/10-u2f-token.rules` (as root) and paste in the following lines: ``` text ACTION=="add|change", KERNEL=="hidraw*", SUBSYSTEM=="hidraw", ATTRS{idVendor}=="16d0", ATTRS{idProduct}=="0e90", TAG+="uaccess" ACTION=="add|change", SUBSYSTEM=="usb", ATTRS{idVendor}=="16d0", ATTRS{idProduct}=="0e90", TAG+="uaccess" ``` ### Using webauthn from snap packages Snap has additional security measures so that you will need to add a tag to the hidraw rule for each snap app that you want to have access to the token. For Chromium and Firefox (snap since ubuntu 21.10) this then reads: ``` text ACTION=="add|change", KERNEL=="hidraw*", SUBSYSTEM=="hidraw", ATTRS{idVendor}=="16d0", ATTRS{idProduct}=="0e90", TAG+="uaccess", TAG+="snap_firefox_firefox", TAG+="snap_chromium_chromedriver" ``` ## Installing using prebuilt release binaries ### Requirements Python 3.6 or later and pip are needed. You will also need the `hidapi` library: * To install on OS X run `brew install hidapi` * To install on Ubuntu run `sudo apt install libhidapi-hidraw0 python3-hid` * To install on Archlinux, run `pacman -Sy hidapi` If you are on Linux, you will also need to install the aforementioned Udev rules. ### Flash binary Download the binary suitable for your board at [releases page][releases]. [releases]: https://github.com/gl-sergei/u2f-token/releases Binaries for Tomu are built with bootloader support, use the following command to flash the firmware: ``` sh dfu-util -d 1209:70b1 -D u2f-TOMU.bin ``` Binaries for STM32 boards are built without bootloader support, you need to flash the firmware using SWD or JTAG interface. Example using OpenOCD and STLINK-V2: ``` sh openocd -f interface/stlink-v2.cfg -f target/stm32f1x.cfg -c 'init' -c 'halt' -c 'flash write_image erase unlock u2f-BLUE_PILL.bin 0x08000000' -c 'exit' ``` (replace BLUE_PILL with appropriate board name) ### Initialize device After flashing device with binary it requires to be initialized. Release binaries come with readout protection enabled and without attestation certificate provisioned. To initialize the device, clone this repository and run (Python 3.6+ and the hidapi library are required): ``` sh pip3 install -r requirements.txt --user cd src/cert python3 certtool init ``` You will see something similar to: ``` text Trying to initialize device HIDDevice: USB_16d0_0e90_14100000 | 16d0:e90 | unknown | U2F-token (STM32) | 1.00 release_number: 256 usage_page: 61904 usage: 1 interface_number: -1 Success ``` The above command will upload pre-generated `attestaion.der` from this repository to the device. If for whatever reason you want to use your own certificate, tweak and run `./gen.sh` to generate it. Test your key with latest Chrome or Firefox browser using [this page][yubico-test]. [yubico-test]: https://demo.yubico.com/webauthn-technical/ ## Building and flashing ### Requirements #### Build tools Install and setup Command Line tools for Xcode on macOS. Install build-essentials package on Debian/Ubuntu: ``` sh sudo apt install build-essential ``` #### GNU Toolchain for ARM Embedded Processors Installing on macOS with homebrew: ``` sh brew tap osx-cross/arm brew install arm-gcc-bin ``` Installing on Debian/Ubuntu: ``` sh sudo apt-add-repository ppa:team-gcc-arm-embedded/ppa sudo apt update sudo apt install gcc-arm-embedded ``` For Kali Linux: ``` sh apt install gcc-arm-none-eabi ``` #### OpenSSL MacOS comes with openssl/libressl installed out of the box. Installing on Debian/Ubuntu: ``` sh sudo apt install openssl ``` #### asn1crypto There is a tiny python script used to convert certificates generated by OpenSSL from DER format into C-array. It depends on asn1crypto package. To install with pip: ``` sh pip install --user --upgrade asn1crypto ``` #### OpenOCD Installing on macOS with homebrew: ``` sh brew install open-ocd ``` Installing on Debian/Ubuntu: ``` sh sudo apt install openocd ``` ### Building ``` sh git clone https://github.com/gl-sergei/u2f-token.git cd u2f-token git submodule update --init cd src ``` ``` sh make TARGET= ``` will produce firmware file `build/u2f.bin`. Supported targets are: - [TOMU](http://tomu.im/) - [MAPLE_MINI](https://wiki.stm32duino.com/index.php?title=Maple_Mini) - [BLUE_PILL](https://wiki.stm32duino.com/index.php?title=Blue_Pill) - [BLACK_PILL](https://wiki.stm32duino.com/index.php?title=Black_Pill) - [ST_DONGLE](https://wiki.stm32duino.com/index.php?title=ST-LINK_clone) - [ST_DONGLE_NO_PUSH](https://wiki.stm32duino.com/index.php?title=ST-LINK_clone) Use BLUE_PILL or BLACK_PILL for generic STM32F103 board without push button. If build was unsuccessful for whatever reason and you want to start from scratch you may want to run ``` sh make clean ``` to remove all object files, or ``` sh make certclean ``` to remove generated certificates, or ``` sh make distclean ``` to remove `board.h` symlink, or even all of the above. ### Readout protection Make sure to enable readout protection if you are going to use your device as 2FA for your accounts. Build firmware with `ENFORCE_DEBUG_LOCK=1`: ``` sh make clean make TARGET= ENFORCE_DEBUG_LOCK=1 ``` ### Injecting private key Firmware generates EC private key on its first boot and erases it when it enters the bootloader. You may want to backup your private key and make it survive firmware upgrade. To achieve this, generate the key on your host machine and inject it into the firmware binary. Generate your private key: ``` sh openssl ecparam -name prime256v1 -genkey -noout -outform der -out key.der ``` You may want to encrypt your `key.der` and back it up. Check device's authentication counter if you are going to perform the firmware upgrade. You can see it in Yubikey demo site output. For the new device, you can skip `ctr` parameter all together or set it to 1. Let's say the current counter value is 1000. Use this command to patch firmware binary: ``` sh ./inject_key.py --key key.der --ctr 1001 ``` ### Flashing #### To STMF103 board using ST-LINK/V2 and OpenOCD Start OpenOCD: ``` sh openocd -f interface/stlink-v2.cfg -f target/stm32f1x.cfg ``` On other terminal run: ``` sh telnet localhost 4444 > reset halt > stm32f1x unlock 0 > reset halt > program build/u2f.elf verify reset > shutdown ``` #### To EFM32HG (Tomu) board using DFU Providing you have Toboot installed: ``` sh dfu-util -v -d 1209:70b1 -D build/u2f.bin ``` After flashing device you still need to initialize device as described in [Initialize device](#initialize-device) ## Security considerations ### Random number generator (RNG) U2F-TOKEN is using [Neug][neug] to generate high quality random numbers. The source of entropy is built-in Analog to Digital Converter (both STM32F103 and EFM32HG have ones). 32-bit ADC output is passed through CRC32 35 times to get 1120 bit input for SHA256-based whitening element. [neug]: https://www.gniibe.org/memo/development/gnuk/rng/neug.html "Neug" I ran [this suite][rngtest] on 1.7M of raw RNG output from Tomu board. ```text SUMMARY ------- monobit_test 0.119269669219 PASS frequency_within_block_test 0.11518538339 PASS runs_test 0.0626194973829 PASS longest_run_ones_in_a_block_test 0.585067135452 PASS binary_matrix_rank_test 0.862015222632 PASS dft_test 0.965404804209 PASS non_overlapping_template_matching_test 1.00000631693 PASS overlapping_template_matching_test 0.35076924588 PASS maurers_universal_test 0.999954925686 PASS linear_complexity_test 0.906328320146 PASS serial_test 0.159775233458 PASS approximate_entropy_test 0.15960828003 PASS cumulative_sums_test 0.0774471722878 PASS random_excursion_test 0.251774950817 PASS random_excursion_variant_test 0.0871834280054 PASS ``` [rngtest]: https://github.com/dj-on-github/sp800_22_tests "SP800-22 Rev 1a PRNG test suite" ### Device Key Device key is a private key for ECDSA p256r1. Any 256 bits are valid key. It is generated using RNG on first run and stored in device's flash memory. It should not leave the device. You must protect your device's flash from readout to protect device key (see below). ### Key handles U2F protocol specifies two actions - register and authenticate. Register takes appID and challenge from the caller and returns key handle, public key corresponding to that key handle and attestation certificate. No one usually verify the validity of attestation certificate. Authenticate takes the key handle, appID and another challenge, then it signs both with the private key corresponding to the key handle. Caller then able to check if signature has been made by the same device using a public key from register step. Device in turn has to make sure to refuse signing requests for unknown key handles and don't mess private keys corresponding to different key handles. If embedded devices would have unlimited storage, the best would be to store all pairs of key handle and private key on the device. But it is not the case, so the private key actually computed based on key handle and device key. Here is how it is done by U2F-TOKEN firmware: #### Register request (`app_id` is given): 1. Generate random `nonce` (32 bytes) 2. Compute `HMAC_SHA265(app_id + nonce)` using device key. Result becomes a private key (32 bytes) 3. Compute `HMAC_SHA256(private_k + app_id) + nonce`. Result becomes a key handle (64 bytes) 4. Compute public key for the private key (it's a nice feature of ECC that public key can be easily computed for given private key, but it is not that easy to do vice versa) and hand it out to the caller along with the key handle #### Authenticate request (`app_id` and key handle are given): 1. Extract `nonce` (last 32 bytes of key handle) 2. Compute `HMAC_SHA256(app_id + nonce)` using device key. This is a private key 3. Compute `HMAC_SHA256(private_k)` and compare it to the first 32 bytes of key handle, they should match. If they don't, return key not found error. Key handle should look random for casual observer and it does. I ran the same suite on 200K of key handle data generated on Tomu board: ``` text SUMMARY ------- monobit_test 0.228183190471 PASS frequency_within_block_test 0.226128174333 PASS runs_test 0.0567490131255 PASS longest_run_ones_in_a_block_test 0.748631279961 PASS binary_matrix_rank_test 0.612219673314 PASS dft_test 0.553339041027 PASS non_overlapping_template_matching_test 1.00000008312 PASS overlapping_template_matching_test 0.932591232105 PASS maurers_universal_test 0.999315334632 PASS linear_complexity_test 0.335268833847 PASS serial_test 0.201711285468 PASS approximate_entropy_test 0.20129897411 PASS cumulative_sums_test 0.11790756896 PASS random_excursion_test 0.199118786038 PASS random_excursion_variant_test 0.157445636324 PASS ``` ### Tamper resistance STM32F103 and EFM32HG devices are not tamper resistant. Highly skilled hacker with the right equipment will be able to read the contents of device's flash and get the device key. Then he will be able to clone your device and use it as second factor to log into your account providing that he knows your passwords as well. However, they are resistant enough for daily use as *second factor* authentication device, because: 1. Firmware does not allow to read flash contents by USB, neither does it disclose device key 2. Both STM32F103 and EFM32HG have "flash readout protection" feature. Once enabled, this feature protecting flash from being read via debug interface. See [this post][p1] for EFM32, and [this question][q1] for STM32F103. See also `efm32 debuglock` and `stm32f1x lock` commands in [OpenOCD manual][openocd-flash]. [p1]: http://community.silabs.com/t5/32-bit-MCU/Read-Write-Protection-of-Flash-and-SRAM/td-p/106405 "readout protection" [q1]: https://stackoverflow.com/q/32509747 "readout protection" [openocd-flash]: http://openocd.org/doc/html/Flash-Commands.html "readout protection" ## License Chopstx is a threading library for Cortex-M0 and Cortex-M3 processors written by Niibe Yutaka. ECC is taken from Gnuk project by Niibe Yutaka. Some constants and memory layout structures were taken from EFM32 platform libraries by Silicon Laboratories. Copyright © 2017 Sergei Glushchenko 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 . As additional permission under GNU GPL version 3 section 7, you may distribute non-source form of the Program without the copy of the GNU GPL normally required by section 4, provided you inform the recipients of GNU GPL by a written offer. ================================================ FILE: requirements.txt ================================================ asn1crypto easyhid pyu2f ================================================ FILE: src/.gitignore ================================================ cert/opnssl.cnf cert/certificates.c board.h ================================================ FILE: src/Makefile ================================================ # U2F firmware PROJECT = u2f CHOPSTX = ../chopstx ifeq ($(TARGET),) TARGET=MAPLE_MINI endif ifeq ($(TARGET),MAPLE_MINI) MCU = cortex-m3 CHIP = stm32f103 DRIVERS = pbt.c DEFS = -DUSE_SYS3 -DFREE_STANDING -DHAVE_PUSH_BUTTON -DTARGET_MAPLE_MINI LDSCRIPT = stm32f103.ld BOARD = $(CHOPSTX)/board/board-maple-mini.h else ifeq ($(TARGET),ST_DONGLE) MCU = cortex-m3 CHIP = stm32f103 DRIVERS = pbt.c DEFS = -DUSE_SYS3 -DFREE_STANDING -DTARGET_ST_DONGLE -DHAVE_PUSH_BUTTON LDSCRIPT = stm32f103.ld BOARD = $(CHOPSTX)/board/board-st-dongle.h else ifeq ($(TARGET),U2F_DONGLE) MCU = cortex-m3 CHIP = stm32f103 DRIVERS = pbt.c DEFS = -DUSE_SYS3 -DFREE_STANDING -DTARGET_U2F_DONGLE -DHAVE_PUSH_BUTTON LDSCRIPT = stm32f103.ld BOARD = $(CHOPSTX)/board/board-u2f-dongle.h else ifeq ($(TARGET),ST_DONGLE_NO_PUSH) MCU = cortex-m3 CHIP = stm32f103 DRIVERS = uvoid.c DEFS = -DUSE_SYS3 -DFREE_STANDING -DTARGET_ST_DONGLE LDSCRIPT = stm32f103.ld BOARD = $(CHOPSTX)/board/board-st-dongle.h else ifeq ($(TARGET),BLUE_PILL) MCU = cortex-m3 CHIP = stm32f103 DRIVERS = uvoid.c DEFS = -DUSE_SYS3 -DFREE_STANDING -DBLUE_PILL LDSCRIPT = stm32f103.ld BOARD = $(CHOPSTX)/board/board-blue-pill.h else ifeq ($(TARGET),BLACK_PILL) MCU = cortex-m3 CHIP = stm32f103 DRIVERS = uvoid.c DEFS = -DUSE_SYS3 -DFREE_STANDING -DBLACK_PILL LDSCRIPT = stm32f103.ld BOARD = $(CHOPSTX)/board/board-black-pill.h else ifeq ($(TARGET),TOMU) MCU = cortex-m0plus CHIP = efm32hg DRIVERS = csn.c DEFS = -DMAKE_ENTRY_PUBLIC -DUSE_SYS3 -DFREE_STANDING -DMHZ=21 \ -DHAVE_CAPSENSE -DTARGET_TOMU LDSCRIPT = efm32hg.ld BOARD = $(CHOPSTX)/board/board-tomu.h endif ifeq ($(ENFORCE_DEBUG_LOCK),1) DEFS += -DENFORCE_DEBUG_LOCK endif ifeq ($(CUSTOM_ATTESTATION_CERT),1) GENCERT_CMD = cd cert && ./gen.sh && ( python dump-der.py > certificates.c || ( rm certificates.c && exit 1 ) ) && cd .. else GENCERT_CMD = cp empty-attestation-cert.c cert/certificates.c endif CSRC = u2f.c usb-hid.c dbug.c u2f-hid.c u2f-apdu.c \ sha256.c neug.c random.c ec_p256r1.c bn.c jpc_p256r1.c \ call-ec_p256r1.c modp256r1.c mod.c hmac.c platform.c $(DRIVERS) USE_SYS = yes USE_USB = yes USE_ADC = yes USE_EVENTFLAG = yes ################################### CROSS = arm-none-eabi- CC = $(CROSS)gcc LD = $(CROSS)gcc OBJCOPY = $(CROSS)objcopy CWARN = -Wall -Wextra -Wstrict-prototypes OPT = -O3 -Os -g LIBS = #################### include $(CHOPSTX)/rules.mk board.h: ln -s $(BOARD) board.h cert/certificates.c: $(GENCERT_CMD) sys.c: board.h u2f.c: board.h u2f-apdu.c: cert/certificates.c distclean: clean rm -f board.h certclean: rm -f cert/certificates.c rm -f cert/opnssl.cnf rm -f cert/*.der rm -f cert/*.pem rm -f cert/*.csr ================================================ FILE: src/affine.h ================================================ /** * @brief Affine coordinates */ typedef struct { bn256 x[1]; bn256 y[1]; } ac; ================================================ FILE: src/bn-thumb1.h ================================================ /* * bn256_mul for ARM processours without umull instruction (Cortex-M0+) * * Some parts are generated and/or copied from TomsFastMath (public domain). * MULADD is adopted from "Shades of Elliptic Curve Cryptography on Embedded * Processors" by Erich Wenger, Thomas Unterluggauer and Mario Werner * * Some numbers: * * this implementation takes 1.3120s to register / 0.6837s to authenticate * uECC implementation takes 1.2960s to register / 0.6758s to authenticate * pure C implementation takes 1.6560s to register / 0.8558s to authenticate */ #define COMBA_START #define COMBA_CLEAR \ c0 = c1 = c2 = 0; #define COMBA_FORWARD \ do { c0 = c1; c1 = c2; c2 = 0; } while (0); #define COMBA_STORE(x) \ x = c0; #define COMBA_STORE2(x) \ x = c1; #define COMBA_FINI #define MULADD(i, j) \ asm ( \ "ldr r1, %[_i] \n\t" \ "ldr r2, %[_j] \n\t" \ "uxth r6, r1 \n\t" \ "uxth r7, r2 \n\t" \ "lsr r1, r1, #16 \n\t" \ "lsr r2, r2, #16 \n\t" \ \ "mov r0, r6 \n\t" \ "mul r0, r0, r7 \n\t" \ "mul r6, r6, r2 \n\t" \ "mul r2, r2, r1 \n\t" \ "mul r1, r1, r7 \n\t" \ \ "mov r7, #0 \n\t" \ "add %0, %0, r0 \n\t" \ "adc %1, %1, r2 \n\t" \ "adc %2, %2, r7 \n\t" \ \ "lsl r0, r6, #16 \n\t" \ "lsr r2, r6, #16 \n\t" \ "add %0, %0, r0 \n\t" \ "adc %1, %1, r2 \n\t" \ "adc %2, %2, r7 \n\t" \ \ "lsl r0, r1, #16 \n\t" \ "lsr r2, r1, #16 \n\t" \ "add %0, %0, r0 \n\t" \ "adc %1, %1, r2 \n\t" \ "adc %2, %2, r7 \n\t" \ \ :"=l"(c0), "=l"(c1), "=l"(c2) \ : "0"(c0), "1"(c1), "2"(c2), [_i] "m" (i), [_j] "m" (j) \ : "r0", "r1", "r2", "r6", "r7", "cc"); static inline void bn256_mul_thumb1 (bn512 *X, const bn256 *A, const bn256 *B) { uint32_t c0, c1, c2, at[16]; memcpy(at, A->word, 8 * sizeof(uint32_t)); memcpy(at+8, B->word, 8 * sizeof(uint32_t)); COMBA_START; COMBA_CLEAR; /* 0 */ MULADD(at[0], at[8]); COMBA_STORE(X->word[0]); /* 1 */ COMBA_FORWARD; MULADD(at[0], at[9]); MULADD(at[1], at[8]); COMBA_STORE(X->word[1]); /* 2 */ COMBA_FORWARD; MULADD(at[0], at[10]); MULADD(at[1], at[9]); MULADD(at[2], at[8]); COMBA_STORE(X->word[2]); /* 3 */ COMBA_FORWARD; MULADD(at[0], at[11]); MULADD(at[1], at[10]); MULADD(at[2], at[9]); MULADD(at[3], at[8]); COMBA_STORE(X->word[3]); /* 4 */ COMBA_FORWARD; MULADD(at[0], at[12]); MULADD(at[1], at[11]); MULADD(at[2], at[10]); MULADD(at[3], at[9]); MULADD(at[4], at[8]); COMBA_STORE(X->word[4]); /* 5 */ COMBA_FORWARD; MULADD(at[0], at[13]); MULADD(at[1], at[12]); MULADD(at[2], at[11]); MULADD(at[3], at[10]); MULADD(at[4], at[9]); MULADD(at[5], at[8]); COMBA_STORE(X->word[5]); /* 6 */ COMBA_FORWARD; MULADD(at[0], at[14]); MULADD(at[1], at[13]); MULADD(at[2], at[12]); MULADD(at[3], at[11]); MULADD(at[4], at[10]); MULADD(at[5], at[9]); MULADD(at[6], at[8]); COMBA_STORE(X->word[6]); /* 7 */ COMBA_FORWARD; MULADD(at[0], at[15]); MULADD(at[1], at[14]); MULADD(at[2], at[13]); MULADD(at[3], at[12]); MULADD(at[4], at[11]); MULADD(at[5], at[10]); MULADD(at[6], at[9]); MULADD(at[7], at[8]); COMBA_STORE(X->word[7]); /* 8 */ COMBA_FORWARD; MULADD(at[1], at[15]); MULADD(at[2], at[14]); MULADD(at[3], at[13]); MULADD(at[4], at[12]); MULADD(at[5], at[11]); MULADD(at[6], at[10]); MULADD(at[7], at[9]); COMBA_STORE(X->word[8]); /* 9 */ COMBA_FORWARD; MULADD(at[2], at[15]); MULADD(at[3], at[14]); MULADD(at[4], at[13]); MULADD(at[5], at[12]); MULADD(at[6], at[11]); MULADD(at[7], at[10]); COMBA_STORE(X->word[9]); /* 10 */ COMBA_FORWARD; MULADD(at[3], at[15]); MULADD(at[4], at[14]); MULADD(at[5], at[13]); MULADD(at[6], at[12]); MULADD(at[7], at[11]); COMBA_STORE(X->word[10]); /* 11 */ COMBA_FORWARD; MULADD(at[4], at[15]); MULADD(at[5], at[14]); MULADD(at[6], at[13]); MULADD(at[7], at[12]); COMBA_STORE(X->word[11]); /* 12 */ COMBA_FORWARD; MULADD(at[5], at[15]); MULADD(at[6], at[14]); MULADD(at[7], at[13]); COMBA_STORE(X->word[12]); /* 13 */ COMBA_FORWARD; MULADD(at[6], at[15]); MULADD(at[7], at[14]); COMBA_STORE(X->word[13]); /* 14 */ COMBA_FORWARD; MULADD(at[7], at[15]); COMBA_STORE(X->word[14]); COMBA_STORE2(X->word[15]); COMBA_FINI; } ================================================ FILE: src/bn.c ================================================ /* * bn.c -- 256-bit (and 512-bit) bignum calculation * * Copyright (C) 2011, 2013, 2014 Free Software Initiative of Japan * Author: NIIBE Yutaka * * This file is a part of Gnuk, a GnuPG USB Token implementation. * * Gnuk 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. * * Gnuk 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 . * */ #include #include #ifndef BN256_NO_RANDOM #include "random.h" #endif #include "bn.h" uint32_t bn256_add (bn256 *X, const bn256 *A, const bn256 *B) { int i; uint32_t v; uint32_t carry = 0; uint32_t *px; const uint32_t *pa, *pb; px = X->word; pa = A->word; pb = B->word; for (i = 0; i < BN256_WORDS; i++) { v = *pb; *px = *pa + carry; carry = (*px < carry); *px += v; carry += (*px < v); px++; pa++; pb++; } return carry; } uint32_t bn256_sub (bn256 *X, const bn256 *A, const bn256 *B) { int i; uint32_t v; uint32_t borrow = 0; uint32_t *px; const uint32_t *pa, *pb; px = X->word; pa = A->word; pb = B->word; for (i = 0; i < BN256_WORDS; i++) { uint32_t borrow0 = (*pa < borrow); v = *pb; *px = *pa - borrow; borrow = (*px < v) + borrow0; *px -= v; px++; pa++; pb++; } return borrow; } uint32_t bn256_add_uint (bn256 *X, const bn256 *A, uint32_t w) { int i; uint32_t carry = w; uint32_t *px; const uint32_t *pa; px = X->word; pa = A->word; for (i = 0; i < BN256_WORDS; i++) { *px = *pa + carry; carry = (*px < carry); px++; pa++; } return carry; } uint32_t bn256_sub_uint (bn256 *X, const bn256 *A, uint32_t w) { int i; uint32_t borrow = w; uint32_t *px; const uint32_t *pa; px = X->word; pa = A->word; for (i = 0; i < BN256_WORDS; i++) { uint32_t borrow0 = (*pa < borrow); *px = *pa - borrow; borrow = borrow0; px++; pa++; } return borrow; } #ifndef BN256_C_IMPLEMENTATION #define ASM_IMPLEMENTATION 1 #endif #if defined(ASM_IMPLEMENTATION) && !defined(__thumb2__) && defined(__thumb__) #include "bn-thumb1.h" #endif void bn256_mul (bn512 *X, const bn256 *A, const bn256 *B) { #if defined(ASM_IMPLEMENTATION) && defined(__thumb2__) #include "muladd_256.h" const uint32_t *s; uint32_t *d; uint32_t w; uint32_t c; memset (X->word, 0, sizeof (uint32_t)*BN256_WORDS*2); s = A->word; d = &X->word[0]; w = B->word[0]; MULADD_256 (s, d, w, c); s = A->word; d = &X->word[1]; w = B->word[1]; MULADD_256 (s, d, w, c); s = A->word; d = &X->word[2]; w = B->word[2]; MULADD_256 (s, d, w, c); s = A->word; d = &X->word[3]; w = B->word[3]; MULADD_256 (s, d, w, c); s = A->word; d = &X->word[4]; w = B->word[4]; MULADD_256 (s, d, w, c); s = A->word; d = &X->word[5]; w = B->word[5]; MULADD_256 (s, d, w, c); s = A->word; d = &X->word[6]; w = B->word[6]; MULADD_256 (s, d, w, c); s = A->word; d = &X->word[7]; w = B->word[7]; MULADD_256 (s, d, w, c); #elif defined(ASM_IMPLEMENTATION) && defined(__thumb__) bn256_mul_thumb1 (X, A, B); #else int i, j, k; int i_beg, i_end; uint32_t r0, r1, r2; r0 = r1 = r2 = 0; for (k = 0; k <= (BN256_WORDS - 1)*2; k++) { if (k < BN256_WORDS) { i_beg = 0; i_end = k; } else { i_beg = k - BN256_WORDS + 1; i_end = BN256_WORDS - 1; } for (i = i_beg; i <= i_end; i++) { uint64_t uv; uint32_t u, v; uint32_t carry; j = k - i; uv = ((uint64_t )A->word[i])*((uint64_t )B->word[j]); v = uv; u = (uv >> 32); r0 += v; carry = (r0 < v); r1 += carry; carry = (r1 < carry); r1 += u; carry += (r1 < u); r2 += carry; } X->word[k] = r0; r0 = r1; r1 = r2; r2 = 0; } X->word[k] = r0; #endif } void bn256_sqr (bn512 *X, const bn256 *A) { #if defined(ASM_IMPLEMENTATION) && defined(__thumb2__) int i; memset (X->word, 0, sizeof (bn512)); for (i = 0; i < BN256_WORDS; i++) { uint32_t *wij = &X->word[i*2]; const uint32_t *xj = &A->word[i]; uint32_t x_i = *xj++; uint32_t c; asm (/* (C,R4,R5) := w_i_i + x_i*x_i; w_i_i := R5; */ "mov %[c], #0\n\t" "ldr r5, [%[wij]]\n\t" /* R5 := w_i_i; */ "mov r4, %[c]\n\t" "umlal r5, r4, %[x_i], %[x_i]\n\t" "str r5, [%[wij]], #4\n\t" "cmp %[xj], %[x_max1]\n\t" "bhi 0f\n\t" "mov r9, %[c]\n\t" /* R9 := 0, the constant ZERO from here. */ "beq 1f\n" "2:\n\t" "ldmia %[xj]!, { r7, r8 }\n\t" "ldmia %[wij], { r5, r6 }\n\t" /* (C,R4,R5) := (C,R4) + w_i_j + 2*x_i*x_j; */ "umull r7, r12, %[x_i], r7\n\t" "adds r5, r5, r4\n\t" "adc r4, %[c], r9\n\t" "adds r5, r5, r7\n\t" "adcs r4, r4, r12\n\t" "adc %[c], r9, r9\n\t" "adds r5, r5, r7\n\t" "adcs r4, r4, r12\n\t" "adc %[c], %[c], r9\n\t" /* (C,R4,R6) := (C,R4) + w_i_j + 2*x_i*x_j; */ "adds r6, r6, r4\n\t" "adc r4, %[c], r9\n\t" "umull r7, r12, %[x_i], r8\n\t" "adds r6, r6, r7\n\t" "adcs r4, r4, r12\n\t" "adc %[c], r9, r9\n\t" "adds r6, r6, r7\n\t" "adcs r4, r4, r12\n\t" "adc %[c], %[c], r9\n\t" /**/ "stmia %[wij]!, { r5, r6 }\n\t" "cmp %[xj], %[x_max1]\n\t" "bcc 2b\n\t" "bne 0f\n" "1:\n\t" /* (C,R4,R5) := (C,R4) + w_i_j + 2*x_i*x_j; */ "ldr r5, [%[wij]]\n\t" "ldr r6, [%[xj]], #4\n\t" "adds r5, r5, r4\n\t" "adc r4, %[c], r9\n\t" "umull r7, r12, %[x_i], r6\n\t" "adds r5, r5, r7\n\t" "adcs r4, r4, r12\n\t" "adc %[c], r9, r9\n\t" "adds r5, r5, r7\n\t" "adcs r4, r4, r12\n\t" "adc %[c], %[c], r9\n\t" "str r5, [%[wij]], #4\n" "0:\n\t" "ldr r5, [%[wij]]\n\t" "adds r4, r4, r5\n\t" "adc %[c], %[c], #0\n\t" "str r4, [%[wij]], #4" : [c] "=&r" (c), [wij] "=r" (wij), [xj] "=r" (xj) : [x_i] "r" (x_i), [x_max1] "r" (&A->word[BN256_WORDS-1]), "[wij]" (wij), "[xj]" (xj) : "r4", "r5", "r6", "r7", "r8", "r9", "r12", "memory", "cc"); if (i < BN256_WORDS - 1) *wij = c; } #elif defined(ASM_IMPLEMENTATION) && defined(__thumb__) bn256_mul_thumb1 (X, A, A); #else int i, j, k; int i_beg, i_end; uint32_t r0, r1, r2; r0 = r1 = r2 = 0; for (k = 0; k <= (BN256_WORDS - 1)*2; k++) { if (k < BN256_WORDS) { i_beg = 0; i_end = k/2; } else { i_beg = k - BN256_WORDS + 1; i_end = k/2; } for (i = i_beg; i <= i_end; i++) { uint64_t uv; uint32_t u, v; uint32_t carry; j = k - i; uv = ((uint64_t )A->word[i])*((uint64_t )A->word[j]); if (i < j) { r2 += ((uv >> 63) != 0); uv <<= 1; } v = uv; u = (uv >> 32); r0 += v; carry = (r0 < v); r1 += carry; carry = (r1 < carry); r1 += u; carry += (r1 < u); r2 += carry; } X->word[k] = r0; r0 = r1; r1 = r2; r2 = 0; } X->word[k] = r0; #endif } uint32_t bn256_shift (bn256 *X, const bn256 *A, int shift) { int i; uint32_t carry = 0, next_carry; if (shift > 0) { for (i = 0; i < BN256_WORDS; i++) { next_carry = A->word[i] >> (32 - shift); X->word[i] = (A->word[i] << shift) | carry; carry = next_carry; } } else { shift = -shift; for (i = BN256_WORDS - 1; i >= 0; i--) { next_carry = A->word[i] & ((1 << shift) - 1); X->word[i] = (A->word[i] >> shift) | (carry << (32 - shift)); carry = next_carry; } } return carry; } int bn256_is_zero (const bn256 *X) { int i; int r = 1; for (i = 0; i < BN256_WORDS; i++) r &= (X->word[i] == 0); return r; } int bn256_is_even (const bn256 *X) { return !(X->word[0] & 1); } int bn256_is_ge (const bn256 *A, const bn256 *B) { uint32_t borrow; bn256 tmp[1]; borrow = bn256_sub (tmp, A, B); return borrow == 0; } int bn256_cmp (const bn256 *A, const bn256 *B) { uint32_t borrow; int is_zero; bn256 tmp[1]; borrow = bn256_sub (tmp, A, B); is_zero = bn256_is_zero (tmp); return is_zero ? 0 : (borrow ? -1 : 1); } #ifndef BN256_NO_RANDOM void bn256_random (bn256 *X) { const uint8_t *rand = random_bytes_get (); X->word[7] = ((uint32_t *)rand)[7]; X->word[6] = ((uint32_t *)rand)[6]; X->word[5] = ((uint32_t *)rand)[5]; X->word[4] = ((uint32_t *)rand)[4]; X->word[3] = ((uint32_t *)rand)[3]; X->word[2] = ((uint32_t *)rand)[2]; X->word[1] = ((uint32_t *)rand)[1]; X->word[0] = ((uint32_t *)rand)[0]; random_bytes_free (rand); } #endif ================================================ FILE: src/bn.h ================================================ #define BN256_WORDS 8 typedef struct bn256 { uint32_t word[ BN256_WORDS ]; /* Little endian */ } bn256; #define BN512_WORDS 16 typedef struct bn512 { uint32_t word[ BN512_WORDS ]; /* Little endian */ } bn512; uint32_t bn256_add (bn256 *X, const bn256 *A, const bn256 *B); uint32_t bn256_sub (bn256 *X, const bn256 *A, const bn256 *B); uint32_t bn256_add_uint (bn256 *X, const bn256 *A, uint32_t w); uint32_t bn256_sub_uint (bn256 *X, const bn256 *A, uint32_t w); void bn256_mul (bn512 *X, const bn256 *A, const bn256 *B); void bn256_sqr (bn512 *X, const bn256 *A); uint32_t bn256_shift (bn256 *X, const bn256 *A, int shift); int bn256_is_zero (const bn256 *X); int bn256_is_even (const bn256 *X); int bn256_is_ge (const bn256 *A, const bn256 *B); int bn256_cmp (const bn256 *A, const bn256 *B); void bn256_random (bn256 *X); ================================================ FILE: src/call-ec.c ================================================ /* * call-ec.c - interface between Gnuk and Elliptic curve over GF(prime) * * Copyright (C) 2013, 2014 Free Software Initiative of Japan * Author: NIIBE Yutaka * * This file is a part of Gnuk, a GnuPG USB Token implementation. * * Gnuk 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. * * Gnuk 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 . * */ #include "field-group-select.h" /* We are little-endian in the computation, but the protocol is big-endian. */ #define ECDSA_BYTE_SIZE 32 #define ECDH_BYTE_SIZE 32 int FUNC(ecdsa_sign) (const uint8_t *hash, uint8_t *output, const uint8_t *key_data) { int i; bn256 r[1], s[1], z[1], d[1]; uint8_t *p; p = (uint8_t *)d; for (i = 0; i < ECDSA_BYTE_SIZE; i++) p[ECDSA_BYTE_SIZE - i - 1] = key_data[i]; p = (uint8_t *)z; for (i = 0; i < ECDSA_BYTE_SIZE; i++) p[ECDSA_BYTE_SIZE - i - 1] = hash[i]; FUNC(ecdsa) (r, s, z, d); p = (uint8_t *)r; for (i = 0; i < ECDSA_BYTE_SIZE; i++) *output++ = p[ECDSA_BYTE_SIZE - i - 1]; p = (uint8_t *)s; for (i = 0; i < ECDSA_BYTE_SIZE; i++) *output++ = p[ECDSA_BYTE_SIZE - i - 1]; return 0; } int FUNC(ecc_compute_public) (const uint8_t *key_data, uint8_t *p0) { uint8_t *p, *p1; ac q[1]; bn256 k[1]; int i; p = (uint8_t *)k; for (i = 0; i < ECDSA_BYTE_SIZE; i++) p[ECDSA_BYTE_SIZE - i - 1] = key_data[i]; if (FUNC(compute_kG) (q, k) < 0) return 1; p = p0; p1 = (uint8_t *)q->x; for (i = 0; i < ECDSA_BYTE_SIZE; i++) *p++ = p1[ECDSA_BYTE_SIZE - i - 1]; p1 = (uint8_t *)q->y; for (i = 0; i < ECDSA_BYTE_SIZE; i++) *p++ = p1[ECDSA_BYTE_SIZE - i - 1]; return 0; } int FUNC(ecdh_decrypt) (const uint8_t *input, uint8_t *output, const uint8_t *key_data) { bn256 k[1]; ac X[1], P[1]; int i; uint8_t *p0; const uint8_t *p1; int r; p0 = (uint8_t *)k; for (i = 0; i < ECDH_BYTE_SIZE; i++) p0[ECDH_BYTE_SIZE - i - 1] = key_data[i]; p1 = input+1; /* skip '04' */ p0 = (uint8_t *)P->x; for (i = 0; i < ECDH_BYTE_SIZE; i++) p0[ECDH_BYTE_SIZE - i - 1] = *p1++; p0 = (uint8_t *)P->y; for (i = 0; i < ECDH_BYTE_SIZE; i++) p0[ECDH_BYTE_SIZE - i - 1] = *p1++; r = FUNC(compute_kP) (X, k, P); if (r == 0) { p0 = output; p1 = (const uint8_t *)X->x; *p0++ = 4; for (i = 0; i < ECDH_BYTE_SIZE; i++) *p0++ = p1[ECDH_BYTE_SIZE - i - 1]; p1 = (const uint8_t *)X->y; for (i = 0; i < ECDH_BYTE_SIZE; i++) *p0++ = p1[ECDH_BYTE_SIZE - i - 1]; } return r; } /** * @brief Check if a secret d0 is valid or not * * @param D0 scalar D0: secret * @param D1 scalar D1: secret candidate N-D0 * * Return 0 on error. * Return -1 when D1 should be used as the secret * Return 1 when D0 should be used as the secret */ int FUNC(ecc_check_secret) (const uint8_t *d0, uint8_t *d1) { return FUNC(check_secret) ((const bn256 *)d0, (bn256 *)d1); } ================================================ FILE: src/call-ec_p256r1.c ================================================ /* * call-ec_p256r1.c - interface between Gnuk and Elliptic curve over * GF(p256r1) * * Copyright (C) 2014 Free Software Initiative of Japan * Author: NIIBE Yutaka * * This file is a part of Gnuk, a GnuPG USB Token implementation. * * Gnuk 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. * * Gnuk 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 . * */ #include #include #include #include "bn.h" #include "affine.h" #include "jpc-ac_p256r1.h" #include "ec_p256r1.h" #define FIELD p256r1 #include "call-ec.c" ================================================ FILE: src/cert/attestation.pem ================================================ -----BEGIN CERTIFICATE----- MIIBTzCB9qADAgECAgkAk23OEsqXqkowCgYIKoZIzj0EAwIwITELMAkGA1UEBhMC VVMxEjAQBgNVBAMMCVUyRiBUb2tlbjAeFw0xOTAzMTAxMjA2NTZaFw0yOTAzMDcx MjA2NTZaMCExCzAJBgNVBAYTAlVTMRIwEAYDVQQDDAlVMkYgVG9rZW4wWTATBgcq hkjOPQIBBggqhkjOPQMBBwNCAAQmAqzENDN9eViFl5uuJBsQWKROfrFtAN7c/wSf zwAYrQqMlqwSKPdTBq3+dcbVfETTwjBdZR/lIdAvfqHHJI//oxcwFTATBgsrBgEE AYLlHAIBAQQEAwIFIDAKBggqhkjOPQQDAgNIADBFAiB0IvcCgmbDTSYuHN4oDbc2 0pww4UyBYOeju3hkQO6+PQIhAJFLv29sWYypzdI4WyPdOpiSUWkH3Jni08FkAdJL ZZkT -----END CERTIFICATE----- ================================================ FILE: src/cert/attestation_key.pem ================================================ -----BEGIN EC PARAMETERS----- BggqhkjOPQMBBw== -----END EC PARAMETERS----- -----BEGIN EC PRIVATE KEY----- MHcCAQEEIAV6k2UmLr8tw/+bt8m+7mWdhatCToLIm/dChWIXfeswoAoGCCqGSM49 AwEHoUQDQgAEJgKsxDQzfXlYhZebriQbEFikTn6xbQDe3P8En88AGK0KjJasEij3 Uwat/nXG1XxE08IwXWUf5SHQL36hxySP/w== -----END EC PRIVATE KEY----- ================================================ FILE: src/cert/certtool ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- # # certtool - Initialize U2F-token with attestation certificate # # Copyright (C) 2019 Sergei Glushchenko # Author: Sergei Glushchenko # # This file is a part of U2F firmware for STM32 and EFM32HG # # 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 . # # As additional permission under GNU GPL version 3 section 7, you may # distribute non-source form of the Program without the copy of the # GNU GPL normally required by section 4, provided you inform the # recipients of GNU GPL by a written offer. import easyhid import struct import secrets import argparse from asn1crypto.keys import ECPrivateKey FIDO_USAGE_PAGE = 0xF1D0 U2F_USAGE = 1 HID_RPT_SIZE = 64 CMD_INIT = 0x06 CMD_MSG = 0x03 CMD_ERROR = 0x3f VID = 0x16d0 PID = 0x0e90 BROADCAST_CID = 0xffffffff def sendCommand(dev, channel, cmd, data): msg = struct.pack('>IBH', channel, cmd | 0x80, len(data)) msg += data[:HID_RPT_SIZE - 7] data = data[HID_RPT_SIZE - 7:] dev.write(msg) seq = 0 while data: msg = struct.pack('>IB', channel, seq) msg += data[:HID_RPT_SIZE - 5] data = data[HID_RPT_SIZE - 5:] dev.write(msg) seq += 1 def recvResponse(dev, channel): data = dev.read() ret_channel, cmd, len = struct.unpack(">IBH", data[:7]) if ret_channel != channel: raise Exception("Wrong channel") if cmd == CMD_ERROR | 0x80: raise Exception("HID Error: {:d}".format(data[6])) return data[7:7+len] def init(dev): dev.open() nonce = secrets.token_bytes(8) sendCommand(dev, BROADCAST_CID, CMD_INIT, nonce) data = recvResponse(dev, BROADCAST_CID) if data[:8] != nonce: raise Exception("Invalid nonce") channel, = struct.unpack(">I", data[8:8+4]) return channel def put_cert(dev, cert, key): channel = init(dev) cla, ins, p1, p2 = 0, 0x40, 0, 0 Lc = len(cert) + len(key) data = struct.pack('>BBBBBH', cla, ins, p1, p2, 0, Lc) data += key + cert sendCommand(dev, channel, CMD_MSG, data) data = recvResponse(dev, channel) if data != b'\x90\x00': raise Exception("APDU Error: " + data.hex()) def load_key(pk_der): pk = ECPrivateKey.load(pk_der) pk_hex = format(pk['private_key'].native, '064x') return bytes.fromhex(pk_hex) def command_list(args): e = easyhid.Enumeration() devices = [ dev for dev in e.find() if dev.vendor_id == VID and dev.product_id == PID ] for dev in devices: print(dev.description()) def command_init(args): e = easyhid.Enumeration() devices = [ dev for dev in e.find() if dev.vendor_id == VID and dev.product_id == PID ] if len(devices) < 1: raise Exception("No U2F devices found") with open(args.certificate, "rb") as f: cert = f.read() with open(args.key, "rb") as f: key = load_key(f.read()) for dev in devices: print("Trying to initialize device {}".format(dev.description())) try: put_cert(dev, cert, key) print('Success') except Exception as e: print(e) def main(): parser = argparse.ArgumentParser( description="Initialize U2F-token with attestation certificate") subparsers = parser.add_subparsers(help='available commands') parser_list = subparsers.add_parser('list', help='list U2F devices') parser_list.set_defaults(func=command_list) parser_init = subparsers.add_parser('init', help='init U2F devices') parser_init.add_argument("--certificate", default="attestation.der", help="attestation certificate in DER format") parser_init.add_argument("--key", default="attestation_key.der", help="attestation certificate key in DER format") parser_init.set_defaults(func=command_init) args = parser.parse_args() args.func(args) if __name__ == "__main__": main() ================================================ FILE: src/cert/csr.csr ================================================ -----BEGIN CERTIFICATE REQUEST----- MIHbMIGDAgEAMCExCzAJBgNVBAYTAlVTMRIwEAYDVQQDDAlVMkYgVG9rZW4wWTAT BgcqhkjOPQIBBggqhkjOPQMBBwNCAAQmAqzENDN9eViFl5uuJBsQWKROfrFtAN7c /wSfzwAYrQqMlqwSKPdTBq3+dcbVfETTwjBdZR/lIdAvfqHHJI//oAAwCgYIKoZI zj0EAwIDRwAwRAIgdTIhqIC351IBcpkXhZxoCa2CcFgE/YSXUJIu5Z0VU8ECIAT4 C85tQCenIO6q9dDb6lXrnAaT0xEf+sb5rkxJKjoO -----END CERTIFICATE REQUEST----- ================================================ FILE: src/cert/dump-der.py ================================================ #!/usr/bin/env python # -*- coding: utf-8 -*- # # dump-der.py - convert DER encoded certificate and EC key into C header # # Copyright (C) 2017-2019 Sergei Glushchenko # Author: Sergei Glushchenko # # This file is a part of U2F firmware for STM32 and EFM32HG # # 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 . # # As additional permission under GNU GPL version 3 section 7, you may # distribute non-source form of the Program without the copy of the # GNU GPL normally required by section 4, provided you inform the # recipients of GNU GPL by a written offer. from __future__ import print_function from asn1crypto.keys import ECPrivateKey attestation_cert_def = ''' struct attestation_cert __attribute__ ((section(".attestation.cert"))) attestation_cert = {{ .hdr = {{ .der_len = ATTESTATION_DER_LEN, .der = attestation_cert.data, .key = attestation_cert.data + ATTESTATION_DER_LEN, }}, .data = {{{}}} }};''' def pk_to_hex_bytes(name, pk_der): # parse der format pk = ECPrivateKey.load(pk_der) # extract private key pk_native = pk['private_key'].native # translate to hex string pk_hex = format(pk_native, '064x') # split by pairs of characters hex_bytes = ["0x" + pk_hex[i:i + 2] for i in range(0, len(pk_hex), 2)] return hex_bytes def cert_to_hex_bytes(name, der): if hasattr(der, 'hex'): hex_str = der.hex() else: hex_str = der.encode('hex') hex_bytes = ["0x" + hex_str[i:i + 2] for i in range(0, len(hex_str), 2)] return hex_bytes with open("attestation.der", "rb") as f: cert_bytes = cert_to_hex_bytes("attestation_der", f.read()) with open("attestation_key.der", "rb") as f: key_bytes = pk_to_hex_bytes("attestation_key", f.read()) print("#define ATTESTATION_DER_LEN {}".format(len(cert_bytes))) print(attestation_cert_def.format(", ".join(cert_bytes + key_bytes + ['0x0'] * (1024 - 12 - len(cert_bytes) - len(key_bytes))))) ================================================ FILE: src/cert/gen.sh ================================================ #!/usr/bin/env bash set -e cat > opnssl.cnf < * * This file is a part of U2F firmware for EFM32 * * 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 . * * As additional permission under GNU GPL version 3 section 7, you may * distribute non-source form of the Program without the copy of the * GNU GPL normally required by section 4, provided you inform the * recipients of GNU GPL by a written offer. * */ #include #include #include #include #include "board.h" #include "sys.h" #include #define MASKED_WRITE(reg, mask, val) { (reg) = (((reg) & ~(mask)) | (val)); } #define INTR_REQ_TIMER0 2 #define INTR_REQ_TIMER1 7 #define PRIO_CSN 8 extern uint8_t __process6_stack_base__[], __process6_stack_size__[]; #define STACK_ADDR_CSN ((uint32_t)__process6_stack_base__) #define STACK_SIZE_CSN ((uint32_t)__process6_stack_size__) static uint32_t present = 0; static uint32_t count_max[2] = {0, 0}; static chopstx_intr_t timer1_intr; static void measure_start (int ch) { /* select channel */ MASKED_WRITE(ACMP0->INPUTSEL, 0x07, ch); /* reset and start timers */ TIMER0->CNT = 0; TIMER1->CNT = 0; TIMER0->CMD = (1 << 0); /* start */ TIMER1->CMD = (1 << 0); /* start */ } static uint32_t measure_stop (void) { TIMER0->CMD = (1 << 1); /* stop */ TIMER1->CMD = (1 << 1); /* stop */ TIMER1->IFC = 1; /* clear interrupt flag */ return TIMER0->CNT; } static void * csn (void *arg) { int ch = 0; int since_last_touch = 0; (void)arg; chopstx_claim_irq (&timer1_intr, INTR_REQ_TIMER1); measure_start (ch); while (1) { uint32_t touch = 0; struct chx_poll_head *pd_array[1] = { (struct chx_poll_head *)&timer1_intr }; chopstx_poll (NULL, 1, pd_array); if (timer1_intr.ready) { uint32_t count; uint32_t threshold; count = measure_stop (); threshold = count_max[ch] - count_max[ch] / 2; if (count > 0 && count < threshold) touch |= 1 << ch; else touch &= ~(1 << ch); if (count > threshold) count_max[ch] = (count_max[ch] + count) / 2; if (present > 0) --present; if (touch) { if (since_last_touch > 10) { if (present > 0) present = 0; /* clear user presence */ else present = 500; /* set user presence for 10 seconds */ } since_last_touch = 0; } else ++since_last_touch; if (since_last_touch > 1000) since_last_touch = 1000; ch ^= 1; measure_start (ch); } } return NULL; } int user_presence_get (void) { return (present > 0); } void user_presence_reset (void) { present = 0; } void capsense_init (void) { CMU->HFPERCLKEN0 |= CMU_HFPERCLKEN0_ACMP0 | CMU_HFPERCLKEN0_TIMER0 | CMU_HFPERCLKEN0_PRS | CMU_HFPERCLKEN0_TIMER1; /* Set control register. No need to set interrupt modes */ ACMP0->CTRL = (0x0 << 31) /* FULLBIAS */ | (0x0 << 30) /* HALFBIAS */ | (0x7 << 24) /* BIASPROG */ | (0x7 << 8) /* WARMTIME */ | (0x5 << 4); /* HYSTSEL */ /* Select capacative sensing mode by selecting a resistor and enabling it */ ACMP0->INPUTSEL= (0x03 << 28) /* CSRESSEL */ | (0x01 << 24) /* CSRESEN */ | (0x00 << 16) /* LPREF */ | (0x3d << 8) /* VDDLEVEL */ | (0x0B << 4);/* NEGSEL = CAPSENSE */ /* Enable ACMP if requested. */ MASKED_WRITE(ACMP0->CTRL, 0x1, 1); MASKED_WRITE(ACMP0->INPUTSEL, 0x07, 0); while (!(ACMP0->STATUS & 0x1 /* ACMPACT */)) {}; /* Initialize TIMER0 - Prescaler 2^10, clock source CC1, top value 0xFFFF */ TIMER0->CTRL = (0xA << 24) /* PRESC = DIV1024 */ | (1 << 16); /* CLKSEL = CC1 */ TIMER0->TOP = 0xFFFF; /*Set up TIMER0 CC1 to trigger on PRS ch 0 */ TIMER0->CC[1].CTRL = (1 << 0) /* MODE = INPUTCAPTURE */ | (0 << 16) /* PRSSEL = PRSCH0 */ | (1 << 20) /* INSEL = PRS */ | (2 << 26) /* ICEVCTRL = RISING */ | (2 << 24); /* ICEDGE = BOTH */ /* Set up PRS ch 0 to trigger on ACMP0 output */ PRS->CH[0].CTRL = (1 << 24) /* EDSEL = POSEDGE */ | (2 << 16) /* SOURCESEL = ACMP0 */ | (0 << 0); /* SIGSEL = ACMP0OUT */ /* Initialize TIMER1 - Prescaler 2^10, top value 40 * MHZ, interrupt on overflow */ TIMER1->CTRL = (0xa << 24); /* PRESC_DIV1024 */ TIMER1->TOP = 40 * MHZ; TIMER1->IEN = (1 << 0); /* IEN_OF */ TIMER1->CNT = 0; chopstx_create (PRIO_CSN, STACK_ADDR_CSN, STACK_SIZE_CSN, csn, NULL); } ================================================ FILE: src/csn.h ================================================ #ifndef __U2F_CSN_H__ #define __U2F_CSN_H__ int user_presence_get (void); void user_presence_reset (void); void capsense_init (void); #endif ================================================ FILE: src/dbug.c ================================================ /* * dbug.c - debugging routines * * Copyright (C) 2017 Sergei Glushchenko * Author: Sergei Glushchenko * * This file is a part of U2F firmware for STM32 * * 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 . * * As additional permission under GNU GPL version 3 section 7, you may * distribute non-source form of the Program without the copy of the * GNU GPL normally required by section 4, provided you inform the * recipients of GNU GPL by a written offer. * */ #include #include /* some debugging routines */ void dbg_send_command (int command, void *message) { asm ("mov r0, %[cmd];" "mov r1, %[msg];" "bkpt #0xAB" : : [cmd] "r" (command), [msg] "r" (message) : "r0", "r1", "memory"); } void dbg_print(const char *text) { uint32_t msg[3]; msg[0] = 2 /*stderr*/; msg[1] = (uint32_t) text; msg[2] = strlen(text); dbg_send_command (0x05, msg); } ================================================ FILE: src/dbug.h ================================================ #ifndef __U2F_DBUG_H__ #define __U2F_DBUG_H__ void dbg_send_command (int command, void *message); void dbg_print(const char *text); #endif ================================================ FILE: src/ec_p256r1.c ================================================ /* -*- coding: utf-8 -*- * ec_p256r1.c - Elliptic curve over GF(p256r1) * * Copyright (C) 2014 Free Software Initiative of Japan * Author: NIIBE Yutaka * * This file is a part of Gnuk, a GnuPG USB Token implementation. * * Gnuk 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. * * Gnuk 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 . * */ #include #include #include "bn.h" #include "modp256r1.h" #include "affine.h" #include "jpc-ac_p256r1.h" #include "mod.h" #include "ec_p256r1.h" #define FIELD p256r1 #define COEFFICIENT_A_IS_MINUS_3 1 /* * a = -3 mod p256r1 */ static const bn256 coefficient_a[1] = { {{ 0xfffffffc, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0xffffffff }} }; static const bn256 coefficient_b[1] = { {{ 0x27d2604b, 0x3bce3c3e, 0xcc53b0f6, 0x651d06b0, 0x769886bc, 0xb3ebbd55, 0xaa3a93e7, 0x5ac635d8 }} }; static const ac precomputed_KG[15] = { { {{{ 0xd898c296, 0xf4a13945, 0x2deb33a0, 0x77037d81, 0x63a440f2, 0xf8bce6e5, 0xe12c4247, 0x6b17d1f2 }}}, {{{ 0x37bf51f5, 0xcbb64068, 0x6b315ece, 0x2bce3357, 0x7c0f9e16, 0x8ee7eb4a, 0xfe1a7f9b, 0x4fe342e2 }}} }, { {{{ 0x8e14db63, 0x90e75cb4, 0xad651f7e, 0x29493baa, 0x326e25de, 0x8492592e, 0x2811aaa5, 0x0fa822bc }}}, {{{ 0x5f462ee7, 0xe4112454, 0x50fe82f5, 0x34b1a650, 0xb3df188b, 0x6f4ad4bc, 0xf5dba80d, 0xbff44ae8 }}} }, { {{{ 0x097992af, 0x93391ce2, 0x0d35f1fa, 0xe96c98fd, 0x95e02789, 0xb257c0de, 0x89d6726f, 0x300a4bbc }}}, {{{ 0xc08127a0, 0xaa54a291, 0xa9d806a5, 0x5bb1eead, 0xff1e3c6f, 0x7f1ddb25, 0xd09b4644, 0x72aac7e0 }}} }, { {{{ 0xd789bd85, 0x57c84fc9, 0xc297eac3, 0xfc35ff7d, 0x88c6766e, 0xfb982fd5, 0xeedb5e67, 0x447d739b }}}, {{{ 0x72e25b32, 0x0c7e33c9, 0xa7fae500, 0x3d349b95, 0x3a4aaff7, 0xe12e9d95, 0x834131ee, 0x2d4825ab }}} }, { {{{ 0x2a1d367f, 0x13949c93, 0x1a0a11b7, 0xef7fbd2b, 0xb91dfc60, 0xddc6068b, 0x8a9c72ff, 0xef951932 }}}, {{{ 0x7376d8a8, 0x196035a7, 0x95ca1740, 0x23183b08, 0x022c219c, 0xc1ee9807, 0x7dbb2c9b, 0x611e9fc3 }}} }, { {{{ 0x0b57f4bc, 0xcae2b192, 0xc6c9bc36, 0x2936df5e, 0xe11238bf, 0x7dea6482, 0x7b51f5d8, 0x55066379 }}}, {{{ 0x348a964c, 0x44ffe216, 0xdbdefbe1, 0x9fb3d576, 0x8d9d50e5, 0x0afa4001, 0x8aecb851, 0x15716484 }}} }, { {{{ 0xfc5cde01, 0xe48ecaff, 0x0d715f26, 0x7ccd84e7, 0xf43e4391, 0xa2e8f483, 0xb21141ea, 0xeb5d7745 }}}, {{{ 0x731a3479, 0xcac917e2, 0x2844b645, 0x85f22cfe, 0x58006cee, 0x0990e6a1, 0xdbecc17b, 0xeafd72eb }}} }, { {{{ 0x313728be, 0x6cf20ffb, 0xa3c6b94a, 0x96439591, 0x44315fc5, 0x2736ff83, 0xa7849276, 0xa6d39677 }}}, {{{ 0xc357f5f4, 0xf2bab833, 0x2284059b, 0x824a920c, 0x2d27ecdf, 0x66b8babd, 0x9b0b8816, 0x674f8474 }}} }, { {{{ 0x677c8a3e, 0x2df48c04, 0x0203a56b, 0x74e02f08, 0xb8c7fedb, 0x31855f7d, 0x72c9ddad, 0x4e769e76 }}}, {{{ 0xb824bbb0, 0xa4c36165, 0x3b9122a5, 0xfb9ae16f, 0x06947281, 0x1ec00572, 0xde830663, 0x42b99082 }}} }, { {{{ 0xdda868b9, 0x6ef95150, 0x9c0ce131, 0xd1f89e79, 0x08a1c478, 0x7fdc1ca0, 0x1c6ce04d, 0x78878ef6 }}}, {{{ 0x1fe0d976, 0x9c62b912, 0xbde08d4f, 0x6ace570e, 0x12309def, 0xde53142c, 0x7b72c321, 0xb6cb3f5d }}} }, { {{{ 0xc31a3573, 0x7f991ed2, 0xd54fb496, 0x5b82dd5b, 0x812ffcae, 0x595c5220, 0x716b1287, 0x0c88bc4d }}}, {{{ 0x5f48aca8, 0x3a57bf63, 0xdf2564f3, 0x7c8181f4, 0x9c04e6aa, 0x18d1b5b3, 0xf3901dc6, 0xdd5ddea3 }}} }, { {{{ 0x3e72ad0c, 0xe96a79fb, 0x42ba792f, 0x43a0a28c, 0x083e49f3, 0xefe0a423, 0x6b317466, 0x68f344af }}}, {{{ 0x3fb24d4a, 0xcdfe17db, 0x71f5c626, 0x668bfc22, 0x24d67ff3, 0x604ed93c, 0xf8540a20, 0x31b9c405 }}} }, { {{{ 0xa2582e7f, 0xd36b4789, 0x4ec39c28, 0xd1a1014, 0xedbad7a0, 0x663c62c3, 0x6f461db9, 0x4052bf4b }}}, {{{ 0x188d25eb, 0x235a27c3, 0x99bfcc5b, 0xe724f339, 0x71d70cc8, 0x862be6bd, 0x90b0fc61, 0xfecf4d51 }}} }, { {{{ 0xa1d4cfac, 0x74346c10, 0x8526a7a4, 0xafdf5cc0, 0xf62bff7a, 0x123202a8, 0xc802e41a, 0x1eddbae2 }}}, {{{ 0xd603f844, 0x8fa0af2d, 0x4c701917, 0x36e06b7e, 0x73db33a0, 0x0c45f452, 0x560ebcfc, 0x43104d86 }}} }, { {{{ 0x0d1d78e5, 0x9615b511, 0x25c4744b, 0x66b0de32, 0x6aaf363a, 0x0a4a46fb, 0x84f7a21c, 0xb48e26b4 }}}, {{{ 0x21a01b2d, 0x06ebb0f6, 0x8b7b0f98, 0xc004e404, 0xfed6f668, 0x64131bcd, 0x4d4d3dab, 0xfac01540 }}} } }; static const ac precomputed_2E_KG[15] = { { {{{ 0x185a5943, 0x3a5a9e22, 0x5c65dfb6, 0x1ab91936, 0x262c71da, 0x21656b32, 0xaf22af89, 0x7fe36b40 }}}, {{{ 0x699ca101, 0xd50d152c, 0x7b8af212, 0x74b3d586, 0x07dca6f1, 0x9f09f404, 0x25b63624, 0xe697d458 }}} }, { {{{ 0x7512218e, 0xa84aa939, 0x74ca0141, 0xe9a521b0, 0x18a2e902, 0x57880b3a, 0x12a677a6, 0x4a5b5066 }}}, {{{ 0x4c4f3840, 0x0beada7a, 0x19e26d9d, 0x626db154, 0xe1627d40, 0xc42604fb, 0xeac089f1, 0xeb13461c }}} }, { {{{ 0x27a43281, 0xf9faed09, 0x4103ecbc, 0x5e52c414, 0xa815c857, 0xc342967a, 0x1c6a220a, 0x0781b829 }}}, {{{ 0xeac55f80, 0x5a8343ce, 0xe54a05e3, 0x88f80eee, 0x12916434, 0x97b2a14f, 0xf0151593, 0x690cde8d }}} }, { {{{ 0xf7f82f2a, 0xaee9c75d, 0x4afdf43a, 0x9e4c3587, 0x37371326, 0xf5622df4, 0x6ec73617, 0x8a535f56 }}}, {{{ 0x223094b7, 0xc5f9a0ac, 0x4c8c7669, 0xcde53386, 0x085a92bf, 0x37e02819, 0x68b08bd7, 0x0455c084 }}} }, { {{{ 0x9477b5d9, 0x0c0a6e2c, 0x876dc444, 0xf9a4bf62, 0xb6cdc279, 0x5050a949, 0xb77f8276, 0x06bada7a }}}, {{{ 0xea48dac9, 0xc8b4aed1, 0x7ea1070f, 0xdebd8a4b, 0x1366eb70, 0x427d4910, 0x0e6cb18a, 0x5b476dfd }}} }, { {{{ 0x278c340a, 0x7c5c3e44, 0x12d66f3b, 0x4d546068, 0xae23c5d8, 0x29a751b1, 0x8a2ec908, 0x3e29864e }}}, {{{ 0x26dbb850, 0x142d2a66, 0x765bd780, 0xad1744c4, 0xe322d1ed, 0x1f150e68, 0x3dc31e7e, 0x239b90ea }}} }, { {{{ 0x7a53322a, 0x78c41652, 0x09776f8e, 0x305dde67, 0xf8862ed4, 0xdbcab759, 0x49f72ff7, 0x820f4dd9 }}}, {{{ 0x2b5debd4, 0x6cc544a6, 0x7b4e8cc4, 0x75be5d93, 0x215c14d3, 0x1b481b1b, 0x783a05ec, 0x140406ec }}} }, { {{{ 0xe895df07, 0x6a703f10, 0x01876bd8, 0xfd75f3fa, 0x0ce08ffe, 0xeb5b06e7, 0x2783dfee, 0x68f6b854 }}}, {{{ 0x78712655, 0x90c76f8a, 0xf310bf7f, 0xcf5293d2, 0xfda45028, 0xfbc8044d, 0x92e40ce6, 0xcbe1feba }}} }, { {{{ 0x4396e4c1, 0xe998ceea, 0x6acea274, 0xfc82ef0b, 0x2250e927, 0x230f729f, 0x2f420109, 0xd0b2f94d }}}, {{{ 0xb38d4966, 0x4305addd, 0x624c3b45, 0x10b838f8, 0x58954e7a, 0x7db26366, 0x8b0719e5, 0x97145982 }}} }, { {{{ 0x23369fc9, 0x4bd6b726, 0x53d0b876, 0x57f2929e, 0xf2340687, 0xc2d5cba4, 0x4a866aba, 0x96161000 }}}, {{{ 0x2e407a5e, 0x49997bcd, 0x92ddcb24, 0x69ab197d, 0x8fe5131c, 0x2cf1f243, 0xcee75e44, 0x7acb9fad }}} }, { {{{ 0x23d2d4c0, 0x254e8394, 0x7aea685b, 0xf57f0c91, 0x6f75aaea, 0xa60d880f, 0xa333bf5b, 0x24eb9acc }}}, {{{ 0x1cda5dea, 0xe3de4ccb, 0xc51a6b4f, 0xfeef9341, 0x8bac4c4d, 0x743125f8, 0xacd079cc, 0x69f891c5 }}} }, { {{{ 0x702476b5, 0xeee44b35, 0xe45c2258, 0x7ed031a0, 0xbd6f8514, 0xb422d1e7, 0x5972a107, 0xe51f547c }}}, {{{ 0xc9cf343d, 0xa25bcd6f, 0x097c184e, 0x8ca922ee, 0xa9fe9a06, 0xa62f98b3, 0x25bb1387, 0x1c309a2b }}} }, { {{{ 0x1967c459, 0x9295dbeb, 0x3472c98e, 0xb0014883, 0x08011828, 0xc5049777, 0xa2c4e503, 0x20b87b8a }}}, {{{ 0xe057c277, 0x3063175d, 0x8fe582dd, 0x1bd53933, 0x5f69a044, 0x0d11adef, 0x919776be, 0xf5c6fa49 }}} }, { {{{ 0x0fd59e11, 0x8c944e76, 0x102fad5f, 0x3876cba1, 0xd83faa56, 0xa454c3fa, 0x332010b9, 0x1ed7d1b9 }}}, {{{ 0x0024b889, 0xa1011a27, 0xac0cd344, 0x05e4d0dc, 0xeb6a2a24, 0x52b520f0, 0x3217257a, 0x3a2b03f0 }}} }, { {{{ 0xdf1d043d, 0xf20fc2af, 0xb58d5a62, 0xf330240d, 0xa0058c3b, 0xfc7d229c, 0xc78dd9f6, 0x15fee545 }}}, {{{ 0x5bc98cda, 0x501e8288, 0xd046ac04, 0x41ef80e5, 0x461210fb, 0x557d9f49, 0xb8753f81, 0x4ab5b6b2 }}} } }; /* * N: order of G */ static const bn256 N[1] = { {{ 0xfc632551, 0xf3b9cac2, 0xa7179e84, 0xbce6faad, 0xffffffff, 0xffffffff, 0x00000000, 0xffffffff }} }; /* * MU = 2^512 / N * MU = ( (1 << 256) | MU_lower ) */ static const bn256 MU_lower[1] = { {{ 0xeedf9bfe, 0x012ffd85, 0xdf1a6c21, 0x43190552, 0xffffffff, 0xfffffffe, 0xffffffff, 0x00000000 }} }; #include "ecc.c" ================================================ FILE: src/ec_p256r1.h ================================================ int compute_kP_p256r1 (ac *X, const bn256 *K, const ac *P); int compute_kG_p256r1 (ac *X, const bn256 *K); void ecdsa_p256r1 (bn256 *r, bn256 *s, const bn256 *z, const bn256 *d); int check_secret_p256r1 (const bn256 *q, bn256 *d1); ================================================ FILE: src/ecc.c ================================================ /* -*- coding: utf-8 -*- * ecc.c - Elliptic curve over GF(prime) * * Copyright (C) 2011, 2013, 2014, 2015 * Free Software Initiative of Japan * Author: NIIBE Yutaka * * This file is a part of Gnuk, a GnuPG USB Token implementation. * * Gnuk 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. * * Gnuk 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 . * */ /* * References: * * [1] Suite B Implementer's Guide to FIPS 186-3 (ECDSA), February 3, 2010. * * [2] Michael Brown, Darrel Hankerson, Julio López, and Alfred Menezes, * Software Implementation of the NIST Elliptic Curves Over Prime Fields, * Proceedings of the 2001 Conference on Topics in Cryptology: The * Cryptographer's Track at RSA * Pages 250-265, Springer-Verlag London, UK, 2001 * ISBN:3-540-41898-9 * * [3] Mustapha Hedabou, Pierre Pinel, Lucien Bénéteau, * A comb method to render ECC resistant against Side Channel Attacks, * 2004 */ #include "field-group-select.h" /* * Coefficients */ /* * static const bn256 *coefficient_a; * static const bn256 *coefficient_b; */ /* * N: order of G */ /* * static const bn256 N[1]; */ /* * MU = 2^512 / N * MU = ( (1 << 256) | MU_lower ) */ /* * static const bn256 MU_lower[1]; */ /* * w = 4 * m = 256 * d = 64 * e = 32 */ /* * static const ac precomputed_KG[15]; * static const ac precomputed_2E_KG[15]; */ #if TEST /* * Generator of Elliptic curve over GF(p256) */ const ac *G = &precomputed_KG[0]; #endif static int get_vk (const bn256 *K, int i) { uint32_t w0, w1, w2, w3; if (i < 32) { w3 = K->word[6]; w2 = K->word[4]; w1 = K->word[2]; w0 = K->word[0]; } else { w3 = K->word[7]; w2 = K->word[5]; w1 = K->word[3]; w0 = K->word[1]; i -= 32; } w3 >>= i; w2 >>= i; w1 >>= i; w0 >>= i; return ((w3 & 1) << 3) | ((w2 & 1) << 2) | ((w1 & 1) << 1) | (w0 & 1); } /** * @brief X = k * G * * @param K scalar k * * Return -1 on error. * Return 0 on success. */ int FUNC(compute_kG) (ac *X, const bn256 *K) { uint8_t index[64]; /* Lower 4-bit for index absolute value, msb is for sign (encoded as: 0 means 1, 1 means -1). */ bn256 K_dash[1]; jpc Q[1], tmp[1], *dst; int i; int vk; uint32_t k_is_even = bn256_is_even (K); bn256_sub_uint (K_dash, K, k_is_even); /* It keeps the condition: 1 <= K' <= N - 2, and K' is odd. */ /* Fill index. */ vk = get_vk (K_dash, 0); for (i = 1; i < 64; i++) { int vk_next, is_zero; vk_next = get_vk (K_dash, i); is_zero = (vk_next == 0); index[i-1] = (vk - 1) | (is_zero << 7); vk = (is_zero ? vk : vk_next); } index[63] = vk - 1; memset (Q->z, 0, sizeof (bn256)); /* infinity */ for (i = 31; i >= 0; i--) { FUNC(jpc_double) (Q, Q); FUNC(jpc_add_ac_signed) (Q, Q, &precomputed_2E_KG[index[i+32]&0x0f], index[i+32] >> 7); FUNC(jpc_add_ac_signed) (Q, Q, &precomputed_KG[index[i]&0x0f], index[i] >> 7); } dst = k_is_even ? Q : tmp; FUNC(jpc_add_ac) (dst, Q, &precomputed_KG[0]); return FUNC(jpc_to_ac) (X, Q); } /** * check if P is on the curve. * * Return -1 on error. * Return 0 on success. */ static int point_is_on_the_curve (const ac *P) { bn256 s[1], t[1]; /* Elliptic curve: y^2 = x^3 + a*x + b */ MFNC(sqr) (s, P->x); MFNC(mul) (s, s, P->x); #ifndef COEFFICIENT_A_IS_ZERO MFNC(mul) (t, coefficient_a, P->x); MFNC(add) (s, s, t); #endif MFNC(add) (s, s, coefficient_b); MFNC(sqr) (t, P->y); if (bn256_cmp (s, t) == 0) return 0; else return -1; } static int get_vk_kP (const bn256 *K, int i) { uint32_t w; uint8_t blk = i/32; uint8_t pos = i%32; uint8_t col = 3*(pos % 11) + (pos >= 11) + (pos >= 22); uint8_t word_index = (blk * 3) + (pos / 11); w = ((K->word[word_index] >> col) & 7); if (word_index < 7 && (pos == 10 || pos == 21)) { uint8_t mask; uint8_t shift; word_index++; if (pos == 10) { shift = 2; mask = 4; } else { shift = 1; mask = 6; } w |= ((K->word[word_index] << shift) & mask); } return w; } /** * @brief X = k * P * * @param K scalar k * @param P P in affine coordiate * * Return -1 on error. * Return 0 on success. * * For the curve (cofactor is 1 and n is prime), possible error cases are: * * P is not on the curve. * P = G, k = n * Something wrong in the code. * * Mathmatically, k=1 and P=O is another possible case, but O cannot be * represented by affine coordinate. */ int FUNC(compute_kP) (ac *X, const bn256 *K, const ac *P) { uint8_t index[86]; /* Lower 2-bit for index absolute value, msb is for sign (encoded as: 0 means 1, 1 means -1). */ bn256 K_dash[1]; uint32_t k_is_even = bn256_is_even (K); jpc Q[1], tmp[1], *dst; int i; int vk; ac P3[1], P5[1], P7[1]; const ac *p_Pi[4]; if (point_is_on_the_curve (P) < 0) return -1; if (bn256_sub (K_dash, K, N) == 0) /* >= N, it's too big. */ return -1; bn256_sub_uint (K_dash, K, k_is_even); /* It keeps the condition: 1 <= K' <= N - 2, and K' is odd. */ p_Pi[0] = P; p_Pi[1] = P3; p_Pi[2] = P5; p_Pi[3] = P7; { jpc Q1[1]; memcpy (Q->x, P->x, sizeof (bn256)); memcpy (Q->y, P->y, sizeof (bn256)); memset (Q->z, 0, sizeof (bn256)); Q->z->word[0] = 1; FUNC(jpc_double) (Q, Q); FUNC(jpc_add_ac) (Q1, Q, P); if (FUNC(jpc_to_ac) (P3, Q1) < 0) /* Never occurs, except coding errors. */ return -1; FUNC(jpc_double) (Q, Q); FUNC(jpc_add_ac) (Q1, Q, P); if (FUNC(jpc_to_ac) (P5, Q1) < 0) /* Never occurs, except coding errors. */ return -1; memcpy (Q->x, P3->x, sizeof (bn256)); memcpy (Q->y, P3->y, sizeof (bn256)); memset (Q->z, 0, sizeof (bn256)); Q->z->word[0] = 1; FUNC(jpc_double) (Q, Q); FUNC(jpc_add_ac) (Q1, Q, P); if (FUNC(jpc_to_ac) (P7, Q1) < 0) /* Never occurs, except coding errors. */ return -1; } /* Fill index. */ vk = get_vk_kP (K_dash, 0); for (i = 1; i < 86; i++) { int vk_next, is_even; vk_next = get_vk_kP (K_dash, i); is_even = ((vk_next & 1) == 0); index[i-1] = (is_even << 7) | ((is_even?7-vk:vk-1) >> 1); vk = vk_next + is_even; } index[85] = ((vk - 1) >> 1); memset (Q->z, 0, sizeof (bn256)); /* infinity */ for (i = 85; i >= 0; i--) { FUNC(jpc_double) (Q, Q); FUNC(jpc_double) (Q, Q); FUNC(jpc_double) (Q, Q); FUNC(jpc_add_ac_signed) (Q, Q, p_Pi[index[i]&0x03], index[i] >> 7); } dst = k_is_even ? Q : tmp; FUNC(jpc_add_ac) (dst, Q, P); return FUNC(jpc_to_ac) (X, Q); } /** * @brief Compute signature (r,s) of hash string z with secret key d */ void FUNC(ecdsa) (bn256 *r, bn256 *s, const bn256 *z, const bn256 *d) { bn256 k[1]; ac KG[1]; bn512 tmp[1]; bn256 k_inv[1]; uint32_t carry; #define borrow carry #define tmp_k k_inv do { do { bn256_random (k); if (bn256_add_uint (k, k, 1)) continue; if (bn256_sub (tmp_k, k, N) == 0) /* >= N, it's too big. */ continue; /* 1 <= k <= N - 1 */ FUNC(compute_kG) (KG, k); borrow = bn256_sub (r, KG->x, N); if (borrow) memcpy (r, KG->x, sizeof (bn256)); else memcpy (KG->x, r, sizeof (bn256)); } while (bn256_is_zero (r)); mod_inv (k_inv, k, N); bn256_mul (tmp, r, d); mod_reduce (s, tmp, N, MU_lower); carry = bn256_add (s, s, z); if (carry) bn256_sub (s, s, N); else bn256_sub ((bn256 *)tmp, s, N); bn256_mul (tmp, s, k_inv); mod_reduce (s, tmp, N, MU_lower); } while (bn256_is_zero (s)); #undef tmp_k #undef borrow } /** * @brief Check if a secret d0 is valid or not * * @param D0 scalar D0: secret * @param D1 scalar D1: secret candidate N-D0 * * Return 0 on error. * Return -1 when D1 should be used as the secret * Return 1 when D0 should be used as the secret */ int FUNC(check_secret) (const bn256 *d0, bn256 *d1) { ac Q0[1], Q1[1]; if (bn256_is_zero (d0) || bn256_sub (d1, N, d0) != 0) /* == 0 or >= N, it's not valid. */ return 0; FUNC(compute_kG) (Q0, d0); FUNC(compute_kG) (Q1, d1); /* * Jivsov compliant key check */ return bn256_cmp (Q1[0].y, Q0[0].y); } ================================================ FILE: src/ecc.h ================================================ int ecdsa_sign_p256r1 (const uint8_t *hash, uint8_t *output, const uint8_t *key_data); uint8_t *ecc_compute_public_p256r1 (const uint8_t *key_data, uint8_t *public); int ecc_check_secret_p256r1 (const uint8_t *d0, uint8_t *d1); int ecdh_decrypt_p256r1 (const uint8_t *input, uint8_t *output, const uint8_t *key_data); ================================================ FILE: src/efm32hg.ld ================================================ /* * EFM32HG memory setup. */ __main_stack_size__ = 0x0200; /* Idle+Exception handlers */ __process0_stack_size__ = 0x0200; /* Main program */ __process1_stack_size__ = 0x0100; /* pwd */ __process2_stack_size__ = 0x0100; /* blk */ __process3_stack_size__ = 0x0200; /* usb-hid */ __process4_stack_size__ = 0x0800; /* u2f-hid */ __process5_stack_size__ = 0x0200; /* rng */ __process6_stack_size__ = 0x0100; /* pbt / csn */ MEMORY { flash : org = 0x00004000, len = 46k ram : org = 0x20000000, len = 8k flash1 : org = 0x00004000+0xb400, len = 3k } __ram_start__ = ORIGIN(ram); __ram_size__ = 8k; __ram_end__ = __ram_start__ + __ram_size__; SECTIONS { . = 0; _text = .; .text : ALIGN(16) SUBALIGN(8) { . = ALIGN(16); KEEP(*(.first_page.first_words)) . = ORIGIN(flash) + 0x90; KEEP(*(.toboot.config)) KEEP(*(.sys.vectors)) *(.text.startup.*) build/sys-*.o(.text) build/sys-*.o(.text.*) build/sys-*.o(.rodata) build/sys-*.o(.rodata.*) /* * Because of alignment requirement * of startup.vectors, align to 256. */ . = ALIGN(256); KEEP(*(.startup.vectors)) . = ALIGN(16); *(.text) *(.text.*) *(.rodata) *(.rodata.*) *(.glue_7t) *(.glue_7) *(.gcc*) . = ALIGN(8); } > flash /DISCARD/ : { *(.bss.startup.0) } .ARM.extab : {*(.ARM.extab* .gnu.linkonce.armextab.*)} > flash .ARM.exidx : { PROVIDE(__exidx_start = .); *(.ARM.exidx* .gnu.linkonce.armexidx.*) PROVIDE(__exidx_end = .); } > flash .eh_frame_hdr : {*(.eh_frame_hdr)} > flash .eh_frame : ONLY_IF_RO {*(.eh_frame)} > flash .textalign : ONLY_IF_RO { . = ALIGN(8); } > flash _etext = .; _textdata = _etext; .process_stack : { . = ALIGN(8); __process6_stack_base__ = .; . += __process6_stack_size__; . = ALIGN(8); __process6_stack_end__ = .; __process5_stack_base__ = .; . += __process5_stack_size__; . = ALIGN(8); __process5_stack_end__ = .; __process4_stack_base__ = .; . += __process4_stack_size__; . = ALIGN(8); __process4_stack_end__ = .; __process3_stack_base__ = .; . += __process3_stack_size__; . = ALIGN(8); __process3_stack_end__ = .; __process2_stack_base__ = .; . += __process2_stack_size__; . = ALIGN(8); __process2_stack_end__ = .; __process1_stack_base__ = .; . += __process1_stack_size__; . = ALIGN(8); __process1_stack_end__ = .; __process0_stack_base__ = .; . += __process0_stack_size__; . = ALIGN(8); __process0_stack_end__ = .; } > ram .main_stack : { . = ALIGN(8); __main_stack_base__ = .; . += __main_stack_size__; . = ALIGN(8); __main_stack_end__ = .; } > ram .data : { . = ALIGN(4); PROVIDE(_data = .); *(.data) . = ALIGN(4); *(.data.*) . = ALIGN(4); *(.ramtext) . = ALIGN(4); PROVIDE(_edata = .); } > ram AT > flash .bss : { . = ALIGN(4); PROVIDE(_bss_start = .); *(.bss) . = ALIGN(4); *(.bss.*) . = ALIGN(4); *(COMMON) . = ALIGN(512); __usb_bdt__ = .; . += 512; PROVIDE(_bss_end = .); } > ram .flash_storage : { . = ALIGN (1024); _attestation_cert_base = .; *(.attestation.cert); . = ALIGN (1024); _device_key_base = .; *(.device.key); . = ALIGN (1024); _auth_ctr_base = .; *(.auth.ctr); . = ALIGN (1024); } > flash1 PROVIDE(end = .); _end = .; } __heap_base__ = _end; __heap_end__ = __ram_end__; ================================================ FILE: src/empty-attestation-cert.c ================================================ struct attestation_cert __attribute__ ((section(".attestation.cert"))) attestation_cert = { .hdr = { .der_len = (uint32_t) -1, .der = NULL, .key = NULL } }; ================================================ FILE: src/field-group-select.h ================================================ #define CONCAT0(a,b) a##b #define CONCAT1(a,b) CONCAT0(a,b) #define CONCAT2(a,b,c) CONCAT1(a,b##c) #define CONCAT3(a,b,c) CONCAT2(a,b,c) #define FUNC(func) CONCAT1(func##_,FIELD) #define MFNC(func) CONCAT3(mod,FIELD,_##func) ================================================ FILE: src/gdb.commands ================================================ file build/u2f.elf target remote localhost:3333 monitor arm semihosting enable monitor reset halt load build/u2f.elf ================================================ FILE: src/hmac.c ================================================ /* * hmac.c - HMAC * * Copyright (C) 2017 Sergei Glushchenko * Author: Sergei Glushchenko * * This file is a part of U2F firmware for STM32 * * 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 . * * As additional permission under GNU GPL version 3 section 7, you may * distribute non-source form of the Program without the copy of the * GNU GPL normally required by section 4, provided you inform the * recipients of GNU GPL by a written offer. * */ #include #include "sha256.h" #include "hmac.h" static void _hmac_sha256_init (const hmac_context *ctx) { hmac_sha256_context *context = (hmac_sha256_context *)ctx; sha256_start(&context->sha_ctx); } static void _hmac_sha256_update (const hmac_context *ctx, const uint8_t *message, unsigned message_size) { hmac_sha256_context *context = (hmac_sha256_context *)ctx; sha256_update(&context->sha_ctx, message, message_size); } static void _hmac_sha256_finish (const hmac_context *ctx, uint8_t *hash_result) { hmac_sha256_context *context = (hmac_sha256_context *)ctx; sha256_finish(&context->sha_ctx, hash_result); } /* Compute an HMAC using K as a key (as in RFC 6979). Note that K is always the same size as the hash result size. */ static void hmac_init(const hmac_context *ctx, const uint8_t *K) { uint8_t *pad = ctx->tmp + 2 * ctx->result_size; unsigned i; for (i = 0; i < ctx->result_size; ++i) pad[i] = K[i] ^ 0x36; for (; i < ctx->block_size; ++i) pad[i] = 0x36; ctx->init_hash (ctx); ctx->update_hash (ctx, pad, ctx->block_size); } static void hmac_update(const hmac_context *ctx, const uint8_t *message, unsigned message_size) { ctx->update_hash (ctx, message, message_size); } static void hmac_finish(const hmac_context *ctx, const uint8_t *K, uint8_t *result) { uint8_t *pad = ctx->tmp + 2 * ctx->result_size; unsigned i; for (i = 0; i < ctx->result_size; ++i) pad[i] = K[i] ^ 0x5c; for (; i < ctx->block_size; ++i) pad[i] = 0x5c; ctx->finish_hash (ctx, result); ctx->init_hash (ctx); ctx->update_hash (ctx, pad, ctx->block_size); ctx->update_hash (ctx, result, ctx->result_size); ctx->finish_hash (ctx, result); } void hmac_sha256_init (hmac_sha256_context *ctx, const uint8_t *K) { ctx->hmac_ctx.init_hash = _hmac_sha256_init; ctx->hmac_ctx.update_hash = _hmac_sha256_update; ctx->hmac_ctx.finish_hash = _hmac_sha256_finish; ctx->hmac_ctx.block_size = 64; ctx->hmac_ctx.result_size = 32; ctx->hmac_ctx.tmp = ctx->tmp; hmac_init (&ctx->hmac_ctx, K); } void hmac_sha256_update (const hmac_sha256_context *ctx, const uint8_t *message, unsigned message_size) { hmac_update (&ctx->hmac_ctx, message, message_size); } void hmac_sha256_finish (const hmac_sha256_context *ctx, const uint8_t *K, uint8_t *hash_result) { hmac_finish (&ctx->hmac_ctx, K, hash_result); } ================================================ FILE: src/hmac.h ================================================ typedef struct hmac_context { void (*init_hash)(const struct hmac_context *context); void (*update_hash)(const struct hmac_context *context, const uint8_t *message, unsigned message_size); void (*finish_hash)(const struct hmac_context *context, uint8_t *hash_result); unsigned block_size; /* Hash function block size in bytes, eg 64 for SHA-256. */ unsigned result_size; /* Hash function result size in bytes, eg 32 for SHA-256. */ uint8_t *tmp; /* Must point to a buffer of at least (2 * result_size + block_size) bytes. */ } hmac_context; typedef struct hmac_sha256_context { hmac_context hmac_ctx; sha256_context sha_ctx; uint8_t tmp[32 * 2 + 64]; } hmac_sha256_context; void hmac_sha256_init (hmac_sha256_context *ctx, const uint8_t *K); void hmac_sha256_update (const hmac_sha256_context *ctx, const uint8_t *message, unsigned message_size); void hmac_sha256_finish (const hmac_sha256_context *ctx, const uint8_t *K, uint8_t *hash_result); ================================================ FILE: src/inject_key.py ================================================ #!/usr/bin/env python # # Use this script to inject your own private key and authentication counter # into U2F binary. Might be useful if you want keys to survive firmware updates. # # Example: # # Generate EC private key with openssl: # > openssl ecparam -name prime256v1 -genkey -noout -outform der > key.der # # Inject generated key into u2f.bin and set auth counter to 100: # > python3 inject_key.py --key key.der --ctr 100 # from __future__ import print_function from asn1crypto.keys import ECPrivateKey import hashlib import argparse import sys import struct import os import tempfile import subprocess parser = argparse.ArgumentParser() parser.add_argument("--elf", default="build/u2f.elf", help=".elf file to inject keys into") parser.add_argument("--key", help="EC private key in DER format") parser.add_argument("--ctr", default=1, type=int, help="value of auth counter") args = parser.parse_args() # load and parse private key if args.key: with open(args.key, "rb") as f: der = f.read() else: stdin = sys.stdin.buffer if hasattr(sys.stdin, "buffer") else sys.stdin der = stdin.read() key = ECPrivateKey.load(der) # convert key into raw bytes and calculate it's sha256 key_bytes = bytearray.fromhex(format(key["private_key"].native, '064x')) key_hash = hashlib.sha256(key_bytes).digest() # fill authentication counter ctr_bytes = struct.pack(" openssl ecparam -name prime256v1 -genkey -noout -outform der > key.der # # Inject generated key into u2f.bin and set auth counter to 100: # > python3 inject_key_bin.py --key key.der --ctr 100 --bin build/u2f.bin # # key will not be modified if --key parameter is not present # counter will not be modified if --ctr parameter is not present from __future__ import print_function from asn1crypto.keys import ECPrivateKey import hashlib import argparse import sys import struct import os parser = argparse.ArgumentParser() parser.add_argument("--bin", default="build/u2f.bin", help='.bin file to inject keys into. Or "stdin"') parser.add_argument("--key", help="EC private key in DER format") parser.add_argument("--ctr", default=0, type=lambda x: int(x,0), help="Value of auth counter") parser.add_argument("--offset", default=0, type=lambda x: int(x,0), help="Offset within file to patch") args = parser.parse_args() fname, fext = os.path.splitext(args.bin) assert fext == ".bin" fsize = os.path.getsize(args.bin) print("Target binary file %s, size 0x%X" % (args.bin, fsize)) if args.offset: offset = args.offset else: offset = fsize - 0x800 # load and parse private key if not args.key: print("Key not modified") else: key_offset = offset print("Injecting key from %s at 0x%0X" % (args.key, key_offset)) if args.key == "stdin": stdin = sys.stdin.buffer if hasattr(sys.stdin, "buffer") else sys.stdin der = stdin.read() else: with open(args.key, "rb") as f: der = f.read() key = ECPrivateKey.load(der) # convert key into raw bytes and calculate it's sha256 key_bytes = bytearray.fromhex(format(key["private_key"].native, '064x')) key_hash = hashlib.sha256(key_bytes).digest() # pad key to 1KiB key_blob = (key_bytes + key_hash).ljust(1024, b"\x00") assert len(key_blob) == 1024 with open(args.bin, 'r+b') as f: f.seek(key_offset) f.write(key_blob) if not args.ctr: print("Counter not modified") else: ctr_offset = offset + 0x400 print("Injecting counter %d at 0x%0X" % (args.ctr, ctr_offset)) # fill authentication counter ctr_blob = struct.pack(" * * This file is a part of Gnuk, a GnuPG USB Token implementation. * * Gnuk 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. * * Gnuk 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 . * */ #include "field-group-select.h" /** * @brief X = 2 * A * * @param X Destination JPC * @param A JPC */ void FUNC(jpc_double) (jpc *X, const jpc *A) { bn256 a[1], b[1], c[1], tmp0[1]; bn256 *d; if (bn256_is_zero (A->z)) /* A is infinite */ return; d = X->x; MFNC(sqr) (a, A->y); memcpy (b, a, sizeof (bn256)); MFNC(mul) (a, a, A->x); MFNC(shift) (a, a, 2); MFNC(sqr) (b, b); MFNC(shift) (b, b, 3); #if defined(COEFFICIENT_A_IS_MINUS_3) MFNC(sqr) (tmp0, A->z); MFNC(sub) (c, A->x, tmp0); MFNC(add) (tmp0, tmp0, A->x); MFNC(mul) (tmp0, tmp0, c); MFNC(shift) (c, tmp0, 1); MFNC(add) (c, c, tmp0); #elif defined (COEFFICIENT_A_IS_ZERO) MFNC(sqr) (tmp0, A->x); MFNC(shift) (c, tmp0, 1); MFNC(add) (c, c, tmp0); #else #error "not supported." #endif MFNC(sqr) (d, c); MFNC(shift) (tmp0, a, 1); MFNC(sub) (d, d, tmp0); MFNC(mul) (X->z, A->y, A->z); MFNC(shift) (X->z, X->z, 1); MFNC(sub) (tmp0, a, d); MFNC(mul) (tmp0, c, tmp0); MFNC(sub) (X->y, tmp0, b); } /** * @brief X = A + B * * @param X Destination JPC * @param A JPC * @param B AC * @param MINUS if 1 subtraction, addition otherwise. */ void FUNC(jpc_add_ac_signed) (jpc *X, const jpc *A, const ac *B, int minus) { bn256 a[1], b[1], c[1], d[1], tmp[1]; #define minus_B_y c #define c_sqr a #define c_cube b #define x1_c_sqr c #define x1_c_sqr_2 c #define c_cube_plus_x1_c_sqr_2 c #define x1_c_sqr_copy a #define y3_tmp c #define y1_c_cube a if (bn256_is_zero (A->z)) /* A is infinite */ { memcpy (X->x, B->x, sizeof (bn256)); if (minus) { memcpy (tmp, B->y, sizeof (bn256)); bn256_sub (X->y, CONST_P256, B->y); } else { memcpy (X->y, B->y, sizeof (bn256)); bn256_sub (tmp, CONST_P256, B->y); } memset (X->z, 0, sizeof (bn256)); X->z->word[0] = 1; return; } MFNC(sqr) (a, A->z); memcpy (b, a, sizeof (bn256)); MFNC(mul) (a, a, B->x); MFNC(mul) (b, b, A->z); if (minus) { bn256_sub (minus_B_y, CONST_P256, B->y); MFNC(mul) (b, b, minus_B_y); } else { bn256_sub (tmp, CONST_P256, B->y); MFNC(mul) (b, b, B->y); } if (bn256_cmp (A->x, a) == 0 && bn256_cmp (A->y, b) == 0) { FUNC(jpc_double) (X, A); return; } MFNC(sub) (c, a, A->x); MFNC(sub) (d, b, A->y); MFNC(mul) (X->z, A->z, c); MFNC(sqr) (c_sqr, c); MFNC(mul) (c_cube, c_sqr, c); MFNC(mul) (x1_c_sqr, A->x, c_sqr); MFNC(sqr) (X->x, d); memcpy (x1_c_sqr_copy, x1_c_sqr, sizeof (bn256)); MFNC(shift) (x1_c_sqr_2, x1_c_sqr, 1); MFNC(add) (c_cube_plus_x1_c_sqr_2, x1_c_sqr_2, c_cube); MFNC(sub) (X->x, X->x, c_cube_plus_x1_c_sqr_2); MFNC(sub) (y3_tmp, x1_c_sqr_copy, X->x); MFNC(mul) (y3_tmp, y3_tmp, d); MFNC(mul) (y1_c_cube, A->y, c_cube); MFNC(sub) (X->y, y3_tmp, y1_c_cube); } /** * @brief X = A + B * * @param X Destination JPC * @param A JPC * @param B AC */ void FUNC(jpc_add_ac) (jpc *X, const jpc *A, const ac *B) { FUNC(jpc_add_ac_signed) (X, A, B, 0); } /** * @brief X = convert A * * @param X Destination AC * @param A JPC * * Return -1 on error (infinite). * Return 0 on success. */ int FUNC(jpc_to_ac) (ac *X, const jpc *A) { bn256 z_inv[1], z_inv_sqr[1]; if (bn256_is_zero (A->z)) return -1; mod_inv (z_inv, A->z, CONST_P256); MFNC(sqr) (z_inv_sqr, z_inv); MFNC(mul) (z_inv, z_inv, z_inv_sqr); MFNC(mul) (X->x, A->x, z_inv_sqr); MFNC(mul) (X->y, A->y, z_inv); return 0; } ================================================ FILE: src/jpc_p256r1.c ================================================ /* * jpc_p256r1.c -- arithmetic on Jacobian projective coordinates for p256r1. * * Copyright (C) 2014 Free Software Initiative of Japan * Author: NIIBE Yutaka * * This file is a part of Gnuk, a GnuPG USB Token implementation. * * Gnuk 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. * * Gnuk 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 . * */ #include #include #include "bn.h" #include "mod.h" #include "modp256r1.h" #include "affine.h" #include "jpc-ac_p256r1.h" #define FIELD p256r1 #define CONST_P256 P256R1 #define COEFFICIENT_A_IS_MINUS_3 1 #include "jpc.c" ================================================ FILE: src/mod.c ================================================ /* * mod.c -- modulo arithmetic * * Copyright (C) 2011, 2014 Free Software Initiative of Japan * Author: NIIBE Yutaka * * This file is a part of Gnuk, a GnuPG USB Token implementation. * * Gnuk 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. * * Gnuk 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 . * */ #include #include #include "bn.h" /** * @brief X = A mod B (using MU=(1<<(256)+MU_lower)) (Barret reduction) * */ void mod_reduce (bn256 *X, const bn512 *A, const bn256 *B, const bn256 *MU_lower) { bn256 q[1]; bn512 q_big[1], tmp[1]; uint32_t carry; #define borrow carry uint32_t borrow_next; memset (q, 0, sizeof (bn256)); q->word[0] = A->word[15]; bn256_mul (tmp, q, MU_lower); tmp->word[8] += A->word[15]; carry = (tmp->word[8] < A->word[15]); tmp->word[9] += carry; q->word[7] = A->word[14]; q->word[6] = A->word[13]; q->word[5] = A->word[12]; q->word[4] = A->word[11]; q->word[3] = A->word[10]; q->word[2] = A->word[9]; q->word[1] = A->word[8]; q->word[0] = A->word[7]; bn256_mul (q_big, q, MU_lower); bn256_add ((bn256 *)&q_big->word[8], (bn256 *)&q_big->word[8], q); q->word[0] = q_big->word[9] + tmp->word[1]; carry = (q->word[0] < tmp->word[1]); q->word[1] = q_big->word[10] + carry; carry = (q->word[1] < carry); q->word[1] += tmp->word[2]; carry += (q->word[1] < tmp->word[2]); q->word[2] = q_big->word[11] + carry; carry = (q->word[2] < carry); q->word[2] += tmp->word[3]; carry += (q->word[2] < tmp->word[3]); q->word[3] = q_big->word[12] + carry; carry = (q->word[3] < carry); q->word[3] += tmp->word[4]; carry += (q->word[3] < tmp->word[4]); q->word[4] = q_big->word[13] + carry; carry = (q->word[4] < carry); q->word[4] += tmp->word[5]; carry += (q->word[4] < tmp->word[5]); q->word[5] = q_big->word[14] + carry; carry = (q->word[5] < carry); q->word[5] += tmp->word[6]; carry += (q->word[5] < tmp->word[6]); q->word[6] = q_big->word[15] + carry; carry = (q->word[6] < carry); q->word[6] += tmp->word[7]; carry += (q->word[6] < tmp->word[7]); q->word[7] = carry; q->word[7] += tmp->word[8]; carry = (q->word[7] < tmp->word[8]); memset (q_big, 0, sizeof (bn512)); q_big->word[8] = A->word[8]; q_big->word[7] = A->word[7]; q_big->word[6] = A->word[6]; q_big->word[5] = A->word[5]; q_big->word[4] = A->word[4]; q_big->word[3] = A->word[3]; q_big->word[2] = A->word[2]; q_big->word[1] = A->word[1]; q_big->word[0] = A->word[0]; bn256_mul (tmp, q, B); tmp->word[8] += carry * B->word[0]; tmp->word[15] = tmp->word[14] = tmp->word[13] = tmp->word[12] = tmp->word[11] = tmp->word[10] = tmp->word[9] = 0; borrow = bn256_sub (X, (bn256 *)&q_big->word[0], (bn256 *)&tmp->word[0]); borrow_next = (q_big->word[8] < borrow); q_big->word[8] -= borrow; borrow_next += (q_big->word[8] < tmp->word[8]); q_big->word[8] -= tmp->word[8]; carry = q_big->word[8]; if (carry) carry -= bn256_sub (X, X, B); else bn256_sub (q, X, B); if (carry) carry -= bn256_sub (X, X, B); else bn256_sub (q, X, B); borrow = bn256_sub (q, X, B); if (borrow) memcpy (q, X, sizeof (bn256)); else memcpy (X, q, sizeof (bn256)); #undef borrow } /* * Reference: * Donald E. Knuth, The Art of Computer Programming, Vol. 2: * Seminumerical Algorithms, 3rd ed. Reading, MA: Addison-Wesley, 1998 * * Max loop: X=0x8000...0000 and N=0xffff...ffff */ #define MAX_GCD_STEPS_BN256 (3*256-2) /** * @brief C = X^(-1) mod N * * Assume X and N are co-prime (or N is prime). * NOTE: If X==0, it return 0. * */ void mod_inv (bn256 *C, const bn256 *X, const bn256 *N) { bn256 u[1], v[1], tmp[1]; bn256 A[1] = { { { 1, 0, 0, 0, 0, 0, 0, 0 } } }; uint32_t carry; #define borrow carry int n = MAX_GCD_STEPS_BN256; memset (C, 0, sizeof (bn256)); memcpy (u, X, sizeof (bn256)); memcpy (v, N, sizeof (bn256)); while (n--) { int c = (bn256_is_even (u) << 1) + bn256_is_even (v); switch (c) { case 3: bn256_shift (u, u, -1); if (bn256_is_even (A)) { bn256_add (tmp, A, N); carry = 0; } else carry = bn256_add (A, A, N); bn256_shift (A, A, -1); A->word[7] |= carry * 0x80000000; bn256_shift (v, v, -1); if (bn256_is_even (C)) { bn256_add (tmp, C, N); carry = 0; } else carry = bn256_add (C, C, N); bn256_shift (C, C, -1); C->word[7] |= carry * 0x80000000; if (bn256_is_ge (tmp, tmp)) { bn256_sub (tmp, tmp, tmp); borrow = bn256_sub (tmp, tmp, tmp); if (borrow) bn256_add (tmp, tmp, tmp); else bn256_add (tmp, A, N); } else { bn256_sub (tmp, tmp, tmp); borrow = bn256_sub (tmp, tmp, tmp); if (borrow) bn256_add (tmp, tmp, tmp); else bn256_add (tmp, tmp, N); } break; case 1: bn256_shift (tmp, tmp, -1); if (bn256_is_even (tmp)) { bn256_add (tmp, tmp, N); carry = 0; } else carry = bn256_add (tmp, tmp, N); bn256_shift (tmp, tmp, -1); tmp->word[7] |= carry * 0x80000000; bn256_shift (v, v, -1); if (bn256_is_even (C)) { bn256_add (tmp, C, N); carry = 0; } else carry = bn256_add (C, C, N); bn256_shift (C, C, -1); C->word[7] |= carry * 0x80000000; if (bn256_is_ge (tmp, tmp)) { bn256_sub (tmp, tmp, tmp); borrow = bn256_sub (tmp, tmp, tmp); if (borrow) bn256_add (tmp, tmp, tmp); else bn256_add (tmp, A, N); } else { bn256_sub (tmp, tmp, tmp); borrow = bn256_sub (tmp, tmp, tmp); if (borrow) bn256_add (tmp, tmp, tmp); else bn256_add (tmp, tmp, N); } break; case 2: bn256_shift (u, u, -1); if (bn256_is_even (A)) { bn256_add (tmp, A, N); carry = 0; } else carry = bn256_add (A, A, N); bn256_shift (A, A, -1); A->word[7] |= carry * 0x80000000; bn256_shift (tmp, tmp, -1); if (bn256_is_even (tmp)) { bn256_add (tmp, tmp, N); carry = 0; } else carry = bn256_add (tmp, tmp, N); bn256_shift (tmp, tmp, -1); tmp->word[7] |= carry * 0x80000000; if (bn256_is_ge (tmp, tmp)) { bn256_sub (tmp, tmp, tmp); borrow = bn256_sub (tmp, tmp, tmp); if (borrow) bn256_add (tmp, tmp, tmp); else bn256_add (tmp, A, N); } else { bn256_sub (tmp, tmp, tmp); borrow = bn256_sub (tmp, tmp, tmp); if (borrow) bn256_add (tmp, tmp, tmp); else bn256_add (tmp, tmp, N); } break; case 0: bn256_shift (tmp, tmp, -1); if (bn256_is_even (tmp)) { bn256_add (tmp, tmp, N); carry = 0; } else carry = bn256_add (tmp, tmp, N); bn256_shift (tmp, tmp, -1); tmp->word[7] |= carry * 0x80000000; bn256_shift (tmp, tmp, -1); if (bn256_is_even (tmp)) { bn256_add (tmp, tmp, N); carry = 0; } else carry = bn256_add (tmp, tmp, N); bn256_shift (tmp, tmp, -1); tmp->word[7] |= carry * 0x80000000; if (bn256_is_ge (u, v)) { bn256_sub (u, u, v); borrow = bn256_sub (A, A, C); if (borrow) bn256_add (A, A, N); else bn256_add (tmp, A, N); } else { bn256_sub (v, v, u); borrow = bn256_sub (C, C, A); if (borrow) bn256_add (C, C, N); else bn256_add (tmp, C, N); } break; } } #undef borrow } ================================================ FILE: src/mod.h ================================================ void mod_reduce (bn256 *X, const bn512 *A, const bn256 *B, const bn256 *MU_lower); void mod_inv (bn256 *X, const bn256 *A, const bn256 *N); ================================================ FILE: src/modp256r1.c ================================================ /* * modp256r1.c -- modulo arithmetic for p256r1 * * Copyright (C) 2011, 2013, 2014, 2016 * Free Software Initiative of Japan * Author: NIIBE Yutaka * * This file is a part of Gnuk, a GnuPG USB Token implementation. * * Gnuk 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. * * Gnuk 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 . * */ /* * p256 = 2^256 - 2^224 + 2^192 + 2^96 - 1 */ #include #include #include "bn.h" #include "modp256r1.h" /* 256 224 192 160 128 96 64 32 0 2^256 1 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000 2^256 - 2^224 0 ffffffff 00000000 00000000 00000000 00000000 00000000 00000000 00000000 2^256 - 2^224 + 2^192 0 ffffffff 00000001 00000000 00000000 00000000 00000000 00000000 00000000 2^256 - 2^224 + 2^192 + 2^96 0 ffffffff 00000001 00000000 00000000 00000001 00000000 00000000 00000000 2^256 - 2^224 + 2^192 + 2^96 - 1 0 ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff */ const bn256 p256r1 = { {0xffffffff, 0xffffffff, 0xffffffff, 0x00000000, 0x00000000, 0x00000000, 0x00000001, 0xffffffff} }; /* * Implementation Note. * * It's always modulo p256r1. * * Once, I tried redundant representation which caused wrong * calculation. Implementation could be correct with redundant * representation, but it found that it's more expensive. * */ /** * @brief X = (A + B) mod p256r1 */ void modp256r1_add (bn256 *X, const bn256 *A, const bn256 *B) { uint32_t cond; bn256 tmp[1]; cond = (bn256_add (X, A, B) == 0); cond &= bn256_sub (tmp, X, P256R1); if (cond) /* No-carry AND borrow */ memcpy (tmp, tmp, sizeof (bn256)); else memcpy (X, tmp, sizeof (bn256)); } /** * @brief X = (A - B) mod p256r1 */ void modp256r1_sub (bn256 *X, const bn256 *A, const bn256 *B) { uint32_t borrow; bn256 tmp[1]; borrow = bn256_sub (X, A, B); bn256_add (tmp, X, P256R1); if (borrow) memcpy (X, tmp, sizeof (bn256)); else memcpy (tmp, tmp, sizeof (bn256)); } /** * @brief X = A mod p256r1 */ void modp256r1_reduce (bn256 *X, const bn512 *A) { bn256 tmp[1], tmp0[1]; uint32_t borrow; #define S1 X #define S2 tmp #define S3 tmp #define S4 tmp #define S5 tmp #define S6 tmp #define S7 tmp #define S8 tmp #define S9 tmp S1->word[7] = A->word[7]; S1->word[6] = A->word[6]; S1->word[5] = A->word[5]; S1->word[4] = A->word[4]; S1->word[3] = A->word[3]; S1->word[2] = A->word[2]; S1->word[1] = A->word[1]; S1->word[0] = A->word[0]; borrow = bn256_sub (tmp0, S1, P256R1); if (borrow) memcpy (tmp0, tmp0, sizeof (bn256)); else memcpy (S1, tmp0, sizeof (bn256)); /* X = S1 */ S2->word[7] = A->word[15]; S2->word[6] = A->word[14]; S2->word[5] = A->word[13]; S2->word[4] = A->word[12]; S2->word[3] = A->word[11]; S2->word[2] = S2->word[1] = S2->word[0] = 0; /* X += 2 * S2 */ modp256r1_add (X, X, S2); modp256r1_add (X, X, S2); S3->word[7] = 0; S3->word[6] = A->word[15]; S3->word[5] = A->word[14]; S3->word[4] = A->word[13]; S3->word[3] = A->word[12]; S3->word[2] = S3->word[1] = S3->word[0] = 0; /* X += 2 * S3 */ modp256r1_add (X, X, S3); modp256r1_add (X, X, S3); S4->word[7] = A->word[15]; S4->word[6] = A->word[14]; S4->word[5] = S4->word[4] = S4->word[3] = 0; S4->word[2] = A->word[10]; S4->word[1] = A->word[9]; S4->word[0] = A->word[8]; /* X += S4 */ modp256r1_add (X, X, S4); S5->word[7] = A->word[8]; S5->word[6] = A->word[13]; S5->word[5] = A->word[15]; S5->word[4] = A->word[14]; S5->word[3] = A->word[13]; S5->word[2] = A->word[11]; S5->word[1] = A->word[10]; S5->word[0] = A->word[9]; borrow = bn256_sub (tmp0, S5, P256R1); if (borrow) memcpy (tmp0, tmp0, sizeof (bn256)); else memcpy (S5, tmp0, sizeof (bn256)); /* X += S5 */ modp256r1_add (X, X, S5); S6->word[7] = A->word[10]; S6->word[6] = A->word[8]; S6->word[5] = S6->word[4] = S6->word[3] = 0; S6->word[2] = A->word[13]; S6->word[1] = A->word[12]; S6->word[0] = A->word[11]; borrow = bn256_sub (tmp0, S6, P256R1); if (borrow) memcpy (tmp0, tmp0, sizeof (bn256)); else memcpy (S6, tmp0, sizeof (bn256)); /* X -= S6 */ modp256r1_sub (X, X, S6); S7->word[7] = A->word[11]; S7->word[6] = A->word[9]; S7->word[5] = S7->word[4] = 0; S7->word[3] = A->word[15]; S7->word[2] = A->word[14]; S7->word[1] = A->word[13]; S7->word[0] = A->word[12]; borrow = bn256_sub (tmp0, S7, P256R1); if (borrow) memcpy (tmp0, tmp0, sizeof (bn256)); else memcpy (S7, tmp0, sizeof (bn256)); /* X -= S7 */ modp256r1_sub (X, X, S7); S8->word[7] = A->word[12]; S8->word[6] = 0; S8->word[5] = A->word[10]; S8->word[4] = A->word[9]; S8->word[3] = A->word[8]; S8->word[2] = A->word[15]; S8->word[1] = A->word[14]; S8->word[0] = A->word[13]; /* X -= S8 */ modp256r1_sub (X, X, S8); S9->word[7] = A->word[13]; S9->word[6] = 0; S9->word[5] = A->word[11]; S9->word[4] = A->word[10]; S9->word[3] = A->word[9]; S9->word[2] = 0; S9->word[1] = A->word[15]; S9->word[0] = A->word[14]; /* X -= S9 */ modp256r1_sub (X, X, S9); borrow = bn256_sub (tmp, X, P256R1); if (borrow) memcpy (tmp, X, sizeof (bn256)); else memcpy (X, tmp, sizeof (bn256)); #undef S1 #undef S2 #undef S3 #undef S4 #undef S5 #undef S6 #undef S7 #undef S8 #undef S9 } /** * @brief X = (A * B) mod p256r1 */ void modp256r1_mul (bn256 *X, const bn256 *A, const bn256 *B) { bn512 AB[1]; bn256_mul (AB, A, B); modp256r1_reduce (X, AB); } /** * @brief X = A * A mod p256r1 */ void modp256r1_sqr (bn256 *X, const bn256 *A) { bn512 AA[1]; bn256_sqr (AA, A); modp256r1_reduce (X, AA); } /** * @brief X = (A << shift) mod p256r1 * @note shift < 32 */ void modp256r1_shift (bn256 *X, const bn256 *A, int shift) { uint32_t carry; #define borrow carry bn256 tmp[1]; carry = bn256_shift (X, A, shift); if (shift < 0) return; memset (tmp, 0, sizeof (bn256)); tmp->word[7] = carry; tmp->word[0] = carry; modp256r1_add (X, X, tmp); tmp->word[7] = 0; tmp->word[0] = 0; tmp->word[6] = carry; tmp->word[3] = carry; modp256r1_sub (X, X, tmp); borrow = bn256_sub (tmp, X, P256R1); if (borrow) memcpy (tmp, X, sizeof (bn256)); else memcpy (X, tmp, sizeof (bn256)); #undef borrow } ================================================ FILE: src/modp256r1.h ================================================ extern const bn256 p256r1; #define P256R1 (&p256r1) void modp256r1_add (bn256 *X, const bn256 *A, const bn256 *B); void modp256r1_sub (bn256 *X, const bn256 *A, const bn256 *B); void modp256r1_reduce (bn256 *X, const bn512 *A); void modp256r1_mul (bn256 *X, const bn256 *A, const bn256 *B); void modp256r1_sqr (bn256 *X, const bn256 *A); void modp256r1_shift (bn256 *X, const bn256 *A, int shift); ================================================ FILE: src/muladd_256.h ================================================ #define MULADD_256_ASM(s_,d_,w_,c_) \ asm ( "ldmia %[s]!, { r8, r9, r10 } \n\t" \ "ldmia %[d], { r5, r6, r7 } \n\t" \ "umull r4, r8, %[w], r8 \n\t" \ "adds r5, r5, r4 \n\t" \ "adcs r6, r6, r8 \n\t" \ "umull r4, r8, %[w], r9 \n\t" \ "adc %[c], r8, #0 \n\t" \ "adds r6, r6, r4 \n\t" \ "adcs r7, r7, %[c] \n\t" \ "umull r4, r8, %[w], r10 \n\t" \ "adc %[c], r8, #0 \n\t" \ "adds r7, r7, r4 \n\t" \ "stmia %[d]!, { r5, r6, r7 } \n\t" \ "ldmia %[s]!, { r8, r9, r10 } \n\t" \ "ldmia %[d], { r5, r6, r7 } \n\t" \ "adcs r5, r5, %[c] \n\t" \ "umull r4, r8, %[w], r8 \n\t" \ "adc %[c], r8, #0 \n\t" \ "adds r5, r5, r4 \n\t" \ "adcs r6, r6, %[c] \n\t" \ "umull r4, r8, %[w], r9 \n\t" \ "adc %[c], r8, #0 \n\t" \ "adds r6, r6, r4 \n\t" \ "adcs r7, r7, %[c] \n\t" \ "umull r4, r8, %[w], r10 \n\t" \ "adc %[c], r8, #0 \n\t" \ "adds r7, r7, r4 \n\t" \ "stmia %[d]!, { r5, r6, r7 } \n\t" \ "ldmia %[s]!, { r8, r9 } \n\t" \ "ldmia %[d], { r5, r6 } \n\t" \ "adcs r5, r5, %[c] \n\t" \ "umull r4, r8, %[w], r8 \n\t" \ "adc %[c], r8, #0 \n\t" \ "adds r5, r5, r4 \n\t" \ "adcs r6, r6, %[c] \n\t" \ "umull r4, r8, %[w], r9 \n\t" \ "adc %[c], r8, #0 \n\t" \ "adds r6, r6, r4 \n\t" \ "adc %[c], %[c], #0 \n\t" \ "stmia %[d]!, { r5, r6 }" \ : [s] "=&r" (s_), [d] "=&r" (d_), [c] "=&r" (c_) \ : "[s]" (s_), "[d]" (d_), [w] "r" (w_) \ : "r4", "r5", "r6", "r7", "r8", "r9", "r10", \ "memory", "cc" ) #define MULADD_256(s__,d__,w__,c__) do { \ MULADD_256_ASM(s__,d__,w__,c__); \ *d__ = c__; \ } while (0) ================================================ FILE: src/neug.c ================================================ /* * neug.c - true random number generation * * Copyright (C) 2011, 2012, 2013, 2016, 2017 * Free Software Initiative of Japan * Author: NIIBE Yutaka * * This file is a part of NeuG, a True Random Number Generator * implementation based on quantization error of ADC (for STM32F103). * * NeuG 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. * * NeuG 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 . * */ #include #include #include #include "board.h" #include "sys.h" #include "neug.h" #if !defined (GNU_LINUX_EMULATION) && !defined(MCU_EFM32HG) #include "mcu/stm32f103.h" #endif #include "adc.h" #include "sha256.h" #if defined (GNU_LINUX_EMULATION) || defined(MCU_EFM32HG) static const uint32_t crc32_rv_table[256] = { 0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61, 0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, 0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75, 0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039, 0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d, 0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95, 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1, 0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072, 0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca, 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde, 0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba, 0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6, 0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a, 0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2, 0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637, 0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, 0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53, 0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff, 0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b, 0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3, 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7, 0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3, 0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c, 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8, 0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec, 0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0, 0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c, 0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4, 0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668, 0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4 }; static uint32_t crc; void crc32_rv_reset (void) { crc = 0xffffffff; } void crc32_rv_step (uint32_t v) { crc = crc32_rv_table[(crc ^ (v << 0)) >> 24] ^ (crc << 8); crc = crc32_rv_table[(crc ^ (v << 8)) >> 24] ^ (crc << 8); crc = crc32_rv_table[(crc ^ (v << 16)) >> 24] ^ (crc << 8); crc = crc32_rv_table[(crc ^ (v << 24)) >> 24] ^ (crc << 8); } uint32_t crc32_rv_get (void) { return crc; } uint32_t rbit (uint32_t v) { v = ((v >> 1) & 0x55555555) | ((v & 0x55555555) << 1); v = ((v >> 2) & 0x33333333) | ((v & 0x33333333) << 2); v = ((v >> 4) & 0x0F0F0F0F) | ((v & 0x0F0F0F0F) << 4); v = ((v >> 8) & 0x00FF00FF) | ((v & 0x00FF00FF) << 8); v = ( v >> 16 ) | ( v << 16); return v; } #else void crc32_rv_reset (void) { RCC->AHBENR |= RCC_AHBENR_CRCEN; CRC->CR = CRC_CR_RESET; } void crc32_rv_step (uint32_t v) { CRC->DR = v; } uint32_t crc32_rv_get (void) { return CRC->DR; } uint32_t rbit (uint32_t v) { uint32_t r; asm ("rbit %0, %1" : "=r" (r) : "r" (v)); return r; } #endif static chopstx_mutex_t mode_mtx; static chopstx_cond_t mode_cond; static sha256_context sha256_ctx_data; static uint32_t sha256_output[SHA256_DIGEST_SIZE/sizeof (uint32_t)]; /* * To be a full entropy source, the requirement is to have N samples * for output of 256-bit, where: * * N = (256 * 2) / * * For example, N should be more than 103 for min-entropy = 5.0. * * On the other hand, in the section 6.2 "Full Entropy Source * Requirements", it says: * * At least twice the block size of the underlying cryptographic * primitive shall be provided as input to the conditioning * function to produce full entropy output. * * For us, cryptographic primitive is SHA-256 and its blocksize is * 512-bit (64-byte), thus, N >= 128. * * We chose N=140. Note that we have "additional bits" of 16-byte for * last block (feedback from previous output of SHA-256) to feed * hash_df function of SHA-256, together with sample data of 140-byte. * * N=140 corresponds to min-entropy >= 3.68. * */ #define NUM_NOISE_INPUTS 140 #define EP_ROUND_0 0 /* initial-five-byte and 3-byte, then 56-byte-input */ #define EP_ROUND_1 1 /* 64-byte-input */ #define EP_ROUND_2 2 /* 17-byte-input */ #define EP_ROUND_RAW 3 /* 32-byte-input */ #define EP_ROUND_RAW_DATA 4 /* 32-byte-input */ #define EP_ROUND_0_INPUTS 56 #define EP_ROUND_1_INPUTS 64 #define EP_ROUND_2_INPUTS 17 #define EP_ROUND_RAW_INPUTS 32 #define EP_ROUND_RAW_DATA_INPUTS 32 static uint8_t ep_round; static void noise_source_continuous_test (uint8_t noise); static void noise_source_continuous_test_word (uint8_t b0, uint8_t b1, uint8_t b2, uint8_t b3); /* * Hash_df initial string: * * Initial five bytes are: * 1, : counter = 1 * 0, 0, 1, 0 : no_of_bits_returned (in big endian) * * Then, three-byte from noise source follows. * * One-byte was used in the previous turn, and we have three bytes in * CRC32. */ static void ep_fill_initial_string (void) { uint32_t v = crc32_rv_get (); uint8_t b1, b2, b3; b3 = v >> 24; b2 = v >> 16; b1 = v >> 8; noise_source_continuous_test (b1); noise_source_continuous_test (b2); noise_source_continuous_test (b3); adc_buf[0] = 0x01000001; adc_buf[1] = (v & 0xffffff00); } static void ep_init (int mode) { if (mode == NEUG_MODE_RAW) { ep_round = EP_ROUND_RAW; adc_start_conversion (0, EP_ROUND_RAW_INPUTS); } else if (mode == NEUG_MODE_RAW_DATA) { ep_round = EP_ROUND_RAW_DATA; adc_start_conversion (0, EP_ROUND_RAW_DATA_INPUTS / 4); } else { ep_round = EP_ROUND_0; ep_fill_initial_string (); adc_start_conversion (2, EP_ROUND_0_INPUTS); } } static void ep_fill_wbuf_v (int i, int test, uint32_t v) { if (test) { uint8_t b0, b1, b2, b3; b3 = v >> 24; b2 = v >> 16; b1 = v >> 8; b0 = v; noise_source_continuous_test_word (b0, b1, b2, b3); } sha256_ctx_data.wbuf[i] = v; } /* Here, we assume a little endian architecture. */ static int ep_process (int mode) { int i, n; uint32_t v; if (ep_round == EP_ROUND_0) { sha256_start (&sha256_ctx_data); sha256_ctx_data.wbuf[0] = adc_buf[0]; sha256_ctx_data.wbuf[1] = adc_buf[1]; for (i = 0; i < EP_ROUND_0_INPUTS / 4; i++) { crc32_rv_step (adc_buf[i*4 + 2]); crc32_rv_step (adc_buf[i*4 + 3]); crc32_rv_step (adc_buf[i*4 + 4]); crc32_rv_step (adc_buf[i*4 + 5]); v = crc32_rv_get (); ep_fill_wbuf_v (i+2, 1, v); } adc_start_conversion (0, EP_ROUND_1_INPUTS); sha256_process (&sha256_ctx_data); ep_round++; return 0; } else if (ep_round == EP_ROUND_1) { for (i = 0; i < EP_ROUND_1_INPUTS / 4; i++) { crc32_rv_step (adc_buf[i*4]); crc32_rv_step (adc_buf[i*4 + 1]); crc32_rv_step (adc_buf[i*4 + 2]); crc32_rv_step (adc_buf[i*4 + 3]); v = crc32_rv_get (); ep_fill_wbuf_v (i, 1, v); } adc_start_conversion (0, EP_ROUND_2_INPUTS + 3); sha256_process (&sha256_ctx_data); ep_round++; return 0; } else if (ep_round == EP_ROUND_2) { for (i = 0; i < EP_ROUND_2_INPUTS / 4; i++) { crc32_rv_step (adc_buf[i*4]); crc32_rv_step (adc_buf[i*4 + 1]); crc32_rv_step (adc_buf[i*4 + 2]); crc32_rv_step (adc_buf[i*4 + 3]); v = crc32_rv_get (); ep_fill_wbuf_v (i, 1, v); } crc32_rv_step (adc_buf[i*4]); crc32_rv_step (adc_buf[i*4 + 1]); crc32_rv_step (adc_buf[i*4 + 2]); crc32_rv_step (adc_buf[i*4 + 3]); v = crc32_rv_get () & 0xff; /* First byte of CRC32 is used here. */ noise_source_continuous_test (v); sha256_ctx_data.wbuf[i] = v; ep_init (NEUG_MODE_CONDITIONED); /* The rest three-byte of CRC32 is used here. */ n = SHA256_DIGEST_SIZE / 2; memcpy (((uint8_t *)sha256_ctx_data.wbuf) + EP_ROUND_2_INPUTS, sha256_output, n); sha256_ctx_data.total[0] = 5 + NUM_NOISE_INPUTS + n; sha256_finish (&sha256_ctx_data, (uint8_t *)sha256_output); return SHA256_DIGEST_SIZE / sizeof (uint32_t); } else if (ep_round == EP_ROUND_RAW) { for (i = 0; i < EP_ROUND_RAW_INPUTS / 4; i++) { crc32_rv_step (adc_buf[i*4]); crc32_rv_step (adc_buf[i*4 + 1]); crc32_rv_step (adc_buf[i*4 + 2]); crc32_rv_step (adc_buf[i*4 + 3]); v = crc32_rv_get (); ep_fill_wbuf_v (i, 1, v); } ep_init (mode); return EP_ROUND_RAW_INPUTS / 4; } else if (ep_round == EP_ROUND_RAW_DATA) { for (i = 0; i < EP_ROUND_RAW_DATA_INPUTS / 4; i++) { v = adc_buf[i]; ep_fill_wbuf_v (i, 0, v); } ep_init (mode); return EP_ROUND_RAW_DATA_INPUTS / 4; } return 0; } static const uint32_t *ep_output (int mode) { if (mode) return sha256_ctx_data.wbuf; else return sha256_output; } #define REPETITION_COUNT 1 #define ADAPTIVE_PROPORTION_64 2 #define ADAPTIVE_PROPORTION_4096 4 uint8_t neug_err_state; uint16_t neug_err_cnt; uint16_t neug_err_cnt_rc; uint16_t neug_err_cnt_p64; uint16_t neug_err_cnt_p4k; uint16_t neug_rc_max; uint16_t neug_p64_max; uint16_t neug_p4k_max; static void noise_source_cnt_max_reset (void) { neug_err_cnt = neug_err_cnt_rc = neug_err_cnt_p64 = neug_err_cnt_p4k = 0; neug_rc_max = neug_p64_max = neug_p4k_max = 0; } static void noise_source_error_reset (void) { neug_err_state = 0; } static void noise_source_error (uint32_t err) { neug_err_state |= err; neug_err_cnt++; if ((err & REPETITION_COUNT)) neug_err_cnt_rc++; if ((err & ADAPTIVE_PROPORTION_64)) neug_err_cnt_p64++; if ((err & ADAPTIVE_PROPORTION_4096)) neug_err_cnt_p4k++; } /* * For health tests, we assume that the device noise source has * min-entropy >= 4.2. Observing raw data stream (before CRC-32) has * more than 4.2 bit/byte entropy. When the data stream after CRC-32 * filter will be less than 4.2 bit/byte entropy, that must be * something wrong. Note that even we observe < 4.2, we still have * some margin, since we use NUM_NOISE_INPUTS=140. * */ /* Cuttoff = 9, when min-entropy = 4.2, W= 2^-30 */ /* ceiling of (1+30/4.2) */ #define REPITITION_COUNT_TEST_CUTOFF 9 static uint8_t rct_a; static uint8_t rct_b; static void repetition_count_test (uint8_t sample) { if (rct_a == sample) { rct_b++; if (rct_b >= REPITITION_COUNT_TEST_CUTOFF) noise_source_error (REPETITION_COUNT); if (rct_b > neug_rc_max) neug_rc_max = rct_b; } else { rct_a = sample; rct_b = 1; } } static void repetition_count_test_word (uint8_t b0, uint8_t b1, uint8_t b2, uint8_t b3) { if (rct_a == b0) rct_b++; else { rct_a = b0; rct_b = 1; } if (rct_a == b1) rct_b++; else { rct_a = b1; rct_b = 1; } if (rct_a == b2) rct_b++; else { rct_a = b2; rct_b = 1; } if (rct_a == b3) rct_b++; else { rct_a = b3; rct_b = 1; } if (rct_b >= REPITITION_COUNT_TEST_CUTOFF) noise_source_error (REPETITION_COUNT); if (rct_b > neug_rc_max) neug_rc_max = rct_b; } /* Cuttoff = 18, when min-entropy = 4.2, W= 2^-30 */ /* With R, qbinom(1-2^-30,64,2^-4.2) */ #define ADAPTIVE_PROPORTION_64_TEST_CUTOFF 18 static uint8_t ap64t_a; static uint8_t ap64t_b; static uint8_t ap64t_s; static void adaptive_proportion_64_test (uint8_t sample) { if (ap64t_s++ >= 64) { ap64t_a = sample; ap64t_s = 1; ap64t_b = 0; } else if (ap64t_a == sample) { ap64t_b++; if (ap64t_b > ADAPTIVE_PROPORTION_64_TEST_CUTOFF) noise_source_error (ADAPTIVE_PROPORTION_64); if (ap64t_b > neug_p64_max) neug_p64_max = ap64t_b; } } static void adaptive_proportion_64_test_word (uint8_t b0, uint8_t b1, uint8_t b2, uint8_t b3) { if (ap64t_s >= 64) { ap64t_a = b0; ap64t_s = 4; ap64t_b = 0; } else { ap64t_s += 4; if (ap64t_a == b0) ap64t_b++; } if (ap64t_a == b1) ap64t_b++; if (ap64t_a == b2) ap64t_b++; if (ap64t_a == b3) ap64t_b++; if (ap64t_b > ADAPTIVE_PROPORTION_64_TEST_CUTOFF) noise_source_error (ADAPTIVE_PROPORTION_64); if (ap64t_b > neug_p64_max) neug_p64_max = ap64t_b; } /* Cuttoff = 315, when min-entropy = 4.2, W= 2^-30 */ /* With R, qbinom(1-2^-30,4096,2^-4.2) */ #define ADAPTIVE_PROPORTION_4096_TEST_CUTOFF 315 static uint8_t ap4096t_a; static uint16_t ap4096t_b; static uint16_t ap4096t_s; static void adaptive_proportion_4096_test (uint8_t sample) { if (ap4096t_s++ >= 4096) { ap4096t_a = sample; ap4096t_s = 1; ap4096t_b = 0; } else if (ap4096t_a == sample) { ap4096t_b++; if (ap4096t_b > ADAPTIVE_PROPORTION_4096_TEST_CUTOFF) noise_source_error (ADAPTIVE_PROPORTION_4096); if (ap4096t_b > neug_p4k_max) neug_p4k_max = ap4096t_b; } } static void adaptive_proportion_4096_test_word (uint8_t b0, uint8_t b1, uint8_t b2, uint8_t b3) { if (ap4096t_s >= 4096) { ap4096t_a = b0; ap4096t_s = 4; ap4096t_b = 0; } else { ap4096t_s += 4; if (ap4096t_a == b0) ap4096t_b++; } if (ap4096t_a == b1) ap4096t_b++; if (ap4096t_a == b2) ap4096t_b++; if (ap4096t_a == b3) ap4096t_b++; if (ap4096t_b > ADAPTIVE_PROPORTION_4096_TEST_CUTOFF) noise_source_error (ADAPTIVE_PROPORTION_4096); if (ap4096t_b > neug_p4k_max) neug_p4k_max = ap4096t_b; } static void noise_source_continuous_test (uint8_t noise) { repetition_count_test (noise); adaptive_proportion_64_test (noise); adaptive_proportion_4096_test (noise); } static void noise_source_continuous_test_word (uint8_t b0, uint8_t b1, uint8_t b2, uint8_t b3) { repetition_count_test_word (b0, b1, b2, b3); adaptive_proportion_64_test_word (b0, b1, b2, b3); adaptive_proportion_4096_test_word (b0, b1, b2, b3); } /* * Ring buffer, filled by generator, consumed by neug_get routine. */ struct rng_rb { uint32_t *buf; chopstx_mutex_t m; chopstx_cond_t data_available; chopstx_cond_t space_available; uint8_t head, tail; uint8_t size; unsigned int full :1; unsigned int empty :1; }; static void rb_init (struct rng_rb *rb, uint32_t *p, uint8_t size) { rb->buf = p; rb->size = size; chopstx_mutex_init (&rb->m); chopstx_cond_init (&rb->data_available); chopstx_cond_init (&rb->space_available); rb->head = rb->tail = 0; rb->full = 0; rb->empty = 1; } static void rb_add (struct rng_rb *rb, uint32_t v) { rb->buf[rb->tail++] = v; if (rb->tail == rb->size) rb->tail = 0; if (rb->tail == rb->head) rb->full = 1; rb->empty = 0; } static uint32_t rb_del (struct rng_rb *rb) { uint32_t v = rb->buf[rb->head++]; if (rb->head == rb->size) rb->head = 0; if (rb->head == rb->tail) rb->empty = 1; rb->full = 0; return v; } uint8_t neug_mode; static int rng_should_terminate; static chopstx_t rng_thread; /** * @brief Random number generation thread. */ static void * rng (void *arg) { struct rng_rb *rb = (struct rng_rb *)arg; int mode = neug_mode; rng_should_terminate = 0; chopstx_mutex_init (&mode_mtx); chopstx_cond_init (&mode_cond); /* Enable ADCs */ adc_start (); ep_init (mode); while (!rng_should_terminate) { int err; int n; err = adc_wait_completion (); chopstx_mutex_lock (&mode_mtx); if (err || mode != neug_mode) { mode = neug_mode; noise_source_cnt_max_reset (); /* Discarding data available, re-initiate from the start. */ ep_init (mode); chopstx_cond_signal (&mode_cond); chopstx_mutex_unlock (&mode_mtx); continue; } else chopstx_mutex_unlock (&mode_mtx); if ((n = ep_process (mode))) { int i; const uint32_t *vp; if (neug_err_state != 0 && (mode == NEUG_MODE_CONDITIONED || mode == NEUG_MODE_RAW)) { /* Don't use the result and do it again. */ noise_source_error_reset (); continue; } vp = ep_output (mode); chopstx_mutex_lock (&rb->m); while (rb->full) chopstx_cond_wait (&rb->space_available, &rb->m); for (i = 0; i < n; i++) { rb_add (rb, *vp++); if (rb->full) break; } chopstx_cond_signal (&rb->data_available); chopstx_mutex_unlock (&rb->m); } } adc_stop (); return NULL; } static struct rng_rb the_ring_buffer; extern uint8_t __process5_stack_base__[], __process5_stack_size__[]; #define STACK_ADDR_RNG ((uint32_t)__process5_stack_base__) #define STACK_SIZE_RNG ((uint32_t)__process5_stack_size__) #define PRIO_RNG 2 /** * @brief Initialize NeuG. */ void neug_init (uint32_t *buf, uint8_t size) { const uint32_t *u = (const uint32_t *)unique_device_id (); struct rng_rb *rb = &the_ring_buffer; int i; crc32_rv_reset (); /* * This initialization ensures that it generates different sequence * even if all physical conditions are same. */ for (i = 0; i < 3; i++) crc32_rv_step (*u++); neug_mode = NEUG_MODE_CONDITIONED; rb_init (rb, buf, size); rng_thread = chopstx_create (PRIO_RNG, STACK_ADDR_RNG, STACK_SIZE_RNG, rng, rb); } /** * @breif Flush random bytes. */ void neug_flush (void) { struct rng_rb *rb = &the_ring_buffer; chopstx_mutex_lock (&rb->m); while (!rb->empty) (void)rb_del (rb); chopstx_cond_signal (&rb->space_available); chopstx_mutex_unlock (&rb->m); } /** * @brief Wakes up RNG thread to generate random numbers. */ void neug_kick_filling (void) { struct rng_rb *rb = &the_ring_buffer; chopstx_mutex_lock (&rb->m); if (!rb->full) chopstx_cond_signal (&rb->space_available); chopstx_mutex_unlock (&rb->m); } /** * @brief Get random word (32-bit) from NeuG. * @detail With NEUG_KICK_FILLING, it wakes up RNG thread. * With NEUG_NO_KICK, it doesn't wake up RNG thread automatically, * it is needed to call neug_kick_filling later. */ uint32_t neug_get (int kick) { struct rng_rb *rb = &the_ring_buffer; uint32_t v; chopstx_mutex_lock (&rb->m); while (rb->empty) chopstx_cond_wait (&rb->data_available, &rb->m); v = rb_del (rb); if (kick) chopstx_cond_signal (&rb->space_available); chopstx_mutex_unlock (&rb->m); return v; } int neug_get_nonblock (uint32_t *p) { struct rng_rb *rb = &the_ring_buffer; int r = 0; chopstx_mutex_lock (&rb->m); if (rb->empty) { r = -1; chopstx_cond_signal (&rb->space_available); } else *p = rb_del (rb); chopstx_mutex_unlock (&rb->m); return r; } int neug_consume_random (void (*proc) (uint32_t, int)) { int i = 0; struct rng_rb *rb = &the_ring_buffer; chopstx_mutex_lock (&rb->m); while (!rb->empty) { uint32_t v; v = rb_del (rb); proc (v, i); i++; } chopstx_cond_signal (&rb->space_available); chopstx_mutex_unlock (&rb->m); return i; } void neug_wait_full (void) { struct rng_rb *rb = &the_ring_buffer; chopstx_mutex_lock (&rb->m); while (!rb->full) chopstx_cond_wait (&rb->data_available, &rb->m); chopstx_mutex_unlock (&rb->m); } void neug_fini (void) { rng_should_terminate = 1; neug_get (1); chopstx_join (rng_thread, NULL); } void neug_mode_select (uint8_t mode) { if (neug_mode == mode) return; neug_wait_full (); chopstx_mutex_lock (&mode_mtx); neug_mode = mode; neug_flush (); chopstx_cond_wait (&mode_cond, &mode_mtx); chopstx_mutex_unlock (&mode_mtx); neug_wait_full (); neug_flush (); } ================================================ FILE: src/neug.h ================================================ #define NEUG_NO_KICK 0 #define NEUG_KICK_FILLING 1 #define NEUG_PRE_LOOP 32 #define NEUG_MODE_CONDITIONED 0 /* Conditioned data. */ #define NEUG_MODE_RAW 1 /* CRC-32 filtered sample data. */ #define NEUG_MODE_RAW_DATA 2 /* Sample data directly. */ extern uint8_t neug_mode; extern uint16_t neug_err_cnt; extern uint16_t neug_err_cnt_rc; extern uint16_t neug_err_cnt_p64; extern uint16_t neug_err_cnt_p4k; extern uint16_t neug_rc_max; extern uint16_t neug_p64_max; extern uint16_t neug_p4k_max; void neug_init (uint32_t *buf, uint8_t size); uint32_t neug_get (int kick); int neug_get_nonblock (uint32_t *p); void neug_kick_filling (void); void neug_flush (void); void neug_wait_full (void); void neug_fini (void); void neug_mode_select (uint8_t mode); int neug_consume_random (void (*proc) (uint32_t, int)); void crc32_rv_reset (void); void crc32_rv_step (uint32_t v); uint32_t crc32_rv_get (void); uint32_t rbit (uint32_t v); ================================================ FILE: src/pbt.c ================================================ /* * pbt.c - push button driver and user presence indicator * * Copyright (C) 2017 Sergei Glushchenko * Author: Sergei Glushchenko * * This file is a part of U2F firmware for STM32 * * 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 . * * As additional permission under GNU GPL version 3 section 7, you may * distribute non-source form of the Program without the copy of the * GNU GPL normally required by section 4, provided you inform the * recipients of GNU GPL by a written offer. * */ #include #include #include #include #include "board.h" #include "sys.h" #include #define PRIO_PBT 2 extern uint8_t __process6_stack_base__[], __process6_stack_size__[]; #define STACK_ADDR_PBT ((uint32_t)__process6_stack_base__) #define STACK_SIZE_PBT ((uint32_t)__process6_stack_size__) /* chopstx does not expose generic GPIO interface */ struct GPIO { volatile uint32_t CRL; volatile uint32_t CRH; volatile uint32_t IDR; volatile uint32_t ODR; volatile uint32_t BSRR; volatile uint32_t BRR; volatile uint32_t LCKR; }; #define GPIOA_BASE (APB2PERIPH_BASE + 0x0800) #define GPIOA ((struct GPIO *) GPIOA_BASE) #define GPIOB_BASE (APB2PERIPH_BASE + 0x0C00) #define GPIOB ((struct GPIO *) GPIOB_BASE) #define GPIOC_BASE (APB2PERIPH_BASE + 0x1000) #define GPIOC ((struct GPIO *) GPIOC_BASE) #define GPIOD_BASE (APB2PERIPH_BASE + 0x1400) #define GPIOD ((struct GPIO *) GPIOD_BASE) #define GPIOE_BASE (APB2PERIPH_BASE + 0x1800) #define GPIOE ((struct GPIO *) GPIOE_BASE) #if defined(TARGET_MAPLE_MINI) #define GPIO_PBT_RD 8 #define GPIO_PBT_BASE GPIOB_BASE #define GPIO_PBT_IS_LO 0 #elif defined(TARGET_ST_DONGLE) #define GPIO_PBT_RD 5 #define GPIO_PBT_BASE GPIOA_BASE #define GPIO_PBT_IS_LO 1 #elif defined(TARGET_U2F_DONGLE) #define GPIO_PBT_RD 14 #define GPIO_PBT_BASE GPIOC_BASE #define GPIO_PBT_IS_LO 1 #endif #ifdef GPIO_PBT_BASE static struct GPIO *const GPIO_PBT = (struct GPIO *)GPIO_PBT_BASE; #endif static int touch = 0; static int pbt_get (void) { return ((GPIO_PBT->IDR >> GPIO_PBT_RD) & 1) ^ GPIO_PBT_IS_LO; } static chopstx_intr_t intr; static void * pbt (void *arg) { (void)arg; uint32_t timeout; uint32_t count = 0; int since_last_touch = 0; while (1) { timeout = 100 * 1000; /* 0.1 sec */ struct chx_poll_head *pd_array[1] = { (struct chx_poll_head *)&intr }; chopstx_poll (&timeout, 1, pd_array); if (!intr.ready && count > 0) --count; if (pbt_get ()) { if (since_last_touch > 5) { touch ^= 1; count = 100; /* remember user presence for 10 seconds */ } since_last_touch = 0; } else ++since_last_touch; if (since_last_touch > 1000) since_last_touch = 1000; if (count == 0) touch = 0; } return NULL; } int user_presence_get (void) { return touch; } void user_presence_reset (void) { touch = 0; } void pbt_init (void) { const uint32_t line = GPIO_PBT_RD; /* EXTIx[3:0]: EXTI x configuration (x= 8) - 0001: PB[x] pin */ AFIO->EXTICR[2] |= 1; EXTI->IMR |= (1 << line); EXTI->FTSR |= (1 << line); chopstx_claim_irq (&intr, line); chopstx_create (PRIO_PBT, STACK_ADDR_PBT, STACK_SIZE_PBT, pbt, NULL); } ================================================ FILE: src/pbt.h ================================================ #ifndef __U2F_PBT_H__ #define __U2F_PBT_H__ int user_presence_get (void); void user_presence_reset (void); void pbt_init (void); #endif ================================================ FILE: src/platform.c ================================================ /* * platform.c - platform specific hacks * * Copyright (C) 2018 Sean Cross, * Sergei Glushchenko * Author: Sergei Glushchenko * * This file is a part of U2F firmware * Bootloader-spcific parts were copied ftom toboot. * * 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 . * * As additional permission under GNU GPL version 3 section 7, you may * distribute non-source form of the Program without the copy of the * GNU GPL normally required by section 4, provided you inform the * recipients of GNU GPL by a written offer. * */ #include #include #include #include "board.h" #include "sys.h" #if defined(TARGET_TOMU) #include "toboot.h" #include static struct toboot_configuration __attribute__ ((used, section(".toboot.config"))) toboot_config = { .align = 0, .magic = TOBOOT_V2_MAGIC, .reserved_gen = 0, .start = 16, .config = TOBOOT_CONFIG_FLAG_AUTORUN, .lock_entry = 0, .erase_mask_lo = 0x00000000, .erase_mask_hi = 0xe0000000, .reserved_hash = 0 }; #define LOCKBITS_BASE (0x0FE04000UL) /* Lock-bits page base address */ #define DEBUG_LOCK_WORD (LOCKBITS_BASE + (127 * 4)) const volatile uint32_t *dlw = (volatile uint32_t *) DEBUG_LOCK_WORD; #if defined(ENFORCE_DEBUG_LOCK) /* Debug lock EFM32HG device by clearing DEBUG LOCK WORD */ static void debug_lock_maybe (void) { uint8_t zero[] = { 0x0, 0x0, 0x0, 0x0 }; if (*dlw != 0) flash_write ((uintptr_t) dlw, zero, sizeof (zero)); } #endif /* ENFORCE_DEBUG_LOCK */ #else /* STM32F1x obiously */ #define OPTION_BYTES_ADDR 0x1ffff800 #if defined(ENFORCE_DEBUG_LOCK) /* Debug lock STM32F1x device */ static void debug_lock_maybe (void) { uint32_t ob_val = * (uint32_t *) (OPTION_BYTES_ADDR); if ((ob_val & 0xff) != 0xff) { flash_unlock (); flash_protect (); nvic_system_reset (); } } #endif /* ENFORCE_DEBUG_LOCK */ #endif /* TARGET_TOMU */ /* Preform platform-specific actions */ void platform_init (void) { #if defined(ENFORCE_DEBUG_LOCK) debug_lock_maybe (); #endif } ================================================ FILE: src/platform.h ================================================ #ifndef __U2F_PLATFORM_H__ #define __U2F_PLATFORM_H__ void platform_init (void); #endif /* __U2F_PLATFORM_H__ */ ================================================ FILE: src/random.c ================================================ /* * random.c -- get random bytes * * Copyright (C) 2010, 2011, 2012, 2013, 2015 * Free Software Initiative of Japan * Author: NIIBE Yutaka * * This file is a part of Gnuk, a GnuPG USB Token implementation. * * Gnuk 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. * * Gnuk 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 . * */ #include #include #include "neug.h" #define RANDOM_BYTES_LENGTH 32 static uint32_t random_word[RANDOM_BYTES_LENGTH/sizeof (uint32_t)]; void random_init (void) { int i; neug_init (random_word, RANDOM_BYTES_LENGTH/sizeof (uint32_t)); for (i = 0; i < NEUG_PRE_LOOP; i++) (void)neug_get (NEUG_KICK_FILLING); } void random_fini (void) { neug_fini (); } /* * Return pointer to random 32-byte */ const uint8_t * random_bytes_get (void) { neug_wait_full (); return (const uint8_t *)random_word; } /* * Free pointer to random 32-byte */ void random_bytes_free (const uint8_t *p) { (void)p; memset (random_word, 0, RANDOM_BYTES_LENGTH); neug_flush (); } /* * Return 4-byte salt */ void random_get_salt (uint8_t *p) { uint32_t rnd; rnd = neug_get (NEUG_KICK_FILLING); memcpy (p, &rnd, sizeof (uint32_t)); rnd = neug_get (NEUG_KICK_FILLING); memcpy (p + sizeof (uint32_t), &rnd, sizeof (uint32_t)); } /* * Random byte iterator */ int random_gen (void *arg, unsigned char *out, size_t out_len) { uint8_t *index_p = (uint8_t *)arg; uint8_t index = *index_p; size_t n; while (out_len) { neug_wait_full (); n = RANDOM_BYTES_LENGTH - index; if (n > out_len) n = out_len; memcpy (out, ((unsigned char *)random_word) + index, n); out += n; out_len -= n; index += n; if (index >= RANDOM_BYTES_LENGTH) { index = 0; neug_flush (); } } *index_p = index; return 0; } ================================================ FILE: src/random.h ================================================ void random_init (void); void random_fini (void); /* 32-byte random bytes */ const uint8_t *random_bytes_get (void); void random_bytes_free (const uint8_t *p); /* 8-byte salt */ void random_get_salt (uint8_t *p); /* iterator returning a byta at a time */ int random_gen (void *arg, unsigned char *output, size_t output_len); ================================================ FILE: src/sha256.c ================================================ /* * sha256.c -- Compute SHA-256 hash * * Just for little endian architecture. * * Code taken from: * http://gladman.plushost.co.uk/oldsite/cryptography_technology/sha/index.php * * File names are sha2.c, sha2.h, brg_types.h, brg_endian.h * in the archive sha2-07-01-07.zip. * * Code is modified in the style of PolarSSL API. * * See original copyright notice below. */ /* --------------------------------------------------------------------------- Copyright (c) 2002, Dr Brian Gladman, Worcester, UK. All rights reserved. LICENSE TERMS The free distribution and use of this software in both source and binary form is allowed (with or without changes) provided that: 1. distributions of this source code include the above copyright notice, this list of conditions and the following disclaimer; 2. distributions in binary form include the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other associated materials; 3. the copyright holder's name is not used to endorse products built using this software without specific written permission. ALTERNATIVELY, provided that this notice is retained in full, this product may be distributed under the terms of the GNU General Public License (GPL), in which case the provisions of the GPL apply INSTEAD OF those given above. DISCLAIMER This software is provided 'as is' with no explicit or implied warranties in respect of its properties, including, but not limited to, correctness and/or fitness for purpose. --------------------------------------------------------------------------- Issue Date: 01/08/2005 */ #include #include #include #include "sha256.h" #define SHA256_MASK (SHA256_BLOCK_SIZE - 1) static void memcpy_output_bswap32 (unsigned char *dst, const uint32_t *p) { int i; uint32_t q = 0; for (i = 0; i < 32; i++) { if ((i & 3) == 0) q = __builtin_bswap32 (p[i >> 2]); /* bswap32 is GCC extention */ dst[i] = q >> ((i & 3) * 8); } } #define rotr32(x,n) (((x) >> n) | ((x) << (32 - n))) #define ch(x,y,z) ((z) ^ ((x) & ((y) ^ (z)))) #define maj(x,y,z) (((x) & (y)) | ((z) & ((x) ^ (y)))) /* round transforms for SHA256 compression functions */ #define vf(n,i) v[(n - i) & 7] #define hf(i) (p[i & 15] += \ g_1(p[(i + 14) & 15]) + p[(i + 9) & 15] + g_0(p[(i + 1) & 15])) #define v_cycle0(i) \ p[i] = __builtin_bswap32 (p[i]); \ vf(7,i) += p[i] + k_0[i] \ + s_1(vf(4,i)) + ch(vf(4,i),vf(5,i),vf(6,i)); \ vf(3,i) += vf(7,i); \ vf(7,i) += s_0(vf(0,i))+ maj(vf(0,i),vf(1,i),vf(2,i)) #define v_cycle(i, j) \ vf(7,i) += hf(i) + k_0[i+j] \ + s_1(vf(4,i)) + ch(vf(4,i),vf(5,i),vf(6,i)); \ vf(3,i) += vf(7,i); \ vf(7,i) += s_0(vf(0,i))+ maj(vf(0,i),vf(1,i),vf(2,i)) #define s_0(x) (rotr32((x), 2) ^ rotr32((x), 13) ^ rotr32((x), 22)) #define s_1(x) (rotr32((x), 6) ^ rotr32((x), 11) ^ rotr32((x), 25)) #define g_0(x) (rotr32((x), 7) ^ rotr32((x), 18) ^ ((x) >> 3)) #define g_1(x) (rotr32((x), 17) ^ rotr32((x), 19) ^ ((x) >> 10)) #define k_0 k256 static const uint32_t k256[64] = { 0X428A2F98, 0X71374491, 0XB5C0FBCF, 0XE9B5DBA5, 0X3956C25B, 0X59F111F1, 0X923F82A4, 0XAB1C5ED5, 0XD807AA98, 0X12835B01, 0X243185BE, 0X550C7DC3, 0X72BE5D74, 0X80DEB1FE, 0X9BDC06A7, 0XC19BF174, 0XE49B69C1, 0XEFBE4786, 0X0FC19DC6, 0X240CA1CC, 0X2DE92C6F, 0X4A7484AA, 0X5CB0A9DC, 0X76F988DA, 0X983E5152, 0XA831C66D, 0XB00327C8, 0XBF597FC7, 0XC6E00BF3, 0XD5A79147, 0X06CA6351, 0X14292967, 0X27B70A85, 0X2E1B2138, 0X4D2C6DFC, 0X53380D13, 0X650A7354, 0X766A0ABB, 0X81C2C92E, 0X92722C85, 0XA2BFE8A1, 0XA81A664B, 0XC24B8B70, 0XC76C51A3, 0XD192E819, 0XD6990624, 0XF40E3585, 0X106AA070, 0X19A4C116, 0X1E376C08, 0X2748774C, 0X34B0BCB5, 0X391C0CB3, 0X4ED8AA4A, 0X5B9CCA4F, 0X682E6FF3, 0X748F82EE, 0X78A5636F, 0X84C87814, 0X8CC70208, 0X90BEFFFA, 0XA4506CEB, 0XBEF9A3F7, 0XC67178F2, }; void sha256_process (sha256_context *ctx) { uint32_t i; uint32_t *p = ctx->wbuf; uint32_t v[8]; memcpy (v, ctx->state, 8 * sizeof (uint32_t)); v_cycle0 ( 0); v_cycle0 ( 1); v_cycle0 ( 2); v_cycle0 ( 3); v_cycle0 ( 4); v_cycle0 ( 5); v_cycle0 ( 6); v_cycle0 ( 7); v_cycle0 ( 8); v_cycle0 ( 9); v_cycle0 (10); v_cycle0 (11); v_cycle0 (12); v_cycle0 (13); v_cycle0 (14); v_cycle0 (15); for (i = 16; i < 64; i += 16) { v_cycle ( 0, i); v_cycle ( 1, i); v_cycle ( 2, i); v_cycle ( 3, i); v_cycle ( 4, i); v_cycle ( 5, i); v_cycle ( 6, i); v_cycle ( 7, i); v_cycle ( 8, i); v_cycle ( 9, i); v_cycle (10, i); v_cycle (11, i); v_cycle (12, i); v_cycle (13, i); v_cycle (14, i); v_cycle (15, i); } ctx->state[0] += v[0]; ctx->state[1] += v[1]; ctx->state[2] += v[2]; ctx->state[3] += v[3]; ctx->state[4] += v[4]; ctx->state[5] += v[5]; ctx->state[6] += v[6]; ctx->state[7] += v[7]; } void sha256_update (sha256_context *ctx, const unsigned char *input, unsigned int ilen) { uint32_t left = (ctx->total[0] & SHA256_MASK); uint32_t fill = SHA256_BLOCK_SIZE - left; ctx->total[0] += ilen; if (ctx->total[0] < ilen) ctx->total[1]++; while (ilen >= fill) { memcpy (((unsigned char*)ctx->wbuf) + left, input, fill); sha256_process (ctx); input += fill; ilen -= fill; left = 0; fill = SHA256_BLOCK_SIZE; } memcpy (((unsigned char*)ctx->wbuf) + left, input, ilen); } void sha256_finish (sha256_context *ctx, unsigned char output[32]) { uint32_t last = (ctx->total[0] & SHA256_MASK); ctx->wbuf[last >> 2] = __builtin_bswap32 (ctx->wbuf[last >> 2]); ctx->wbuf[last >> 2] &= 0xffffff80 << (8 * (~last & 3)); ctx->wbuf[last >> 2] |= 0x00000080 << (8 * (~last & 3)); ctx->wbuf[last >> 2] = __builtin_bswap32 (ctx->wbuf[last >> 2]); if (last > SHA256_BLOCK_SIZE - 9) { if (last < 60) ctx->wbuf[15] = 0; sha256_process (ctx); last = 0; } else last = (last >> 2) + 1; while (last < 14) ctx->wbuf[last++] = 0; ctx->wbuf[14] = __builtin_bswap32 ((ctx->total[0] >> 29) | (ctx->total[1] << 3)); ctx->wbuf[15] = __builtin_bswap32 (ctx->total[0] << 3); sha256_process (ctx); memcpy_output_bswap32 (output, ctx->state); memset (ctx, 0, sizeof (sha256_context)); } static const uint32_t initial_state[8] = { 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 }; void sha256_start (sha256_context *ctx) { ctx->total[0] = ctx->total[1] = 0; memcpy (ctx->state, initial_state, 8 * sizeof(uint32_t)); } void sha256 (const unsigned char *input, unsigned int ilen, unsigned char output[32]) { sha256_context ctx; sha256_start (&ctx); sha256_update (&ctx, input, ilen); sha256_finish (&ctx, output); } ================================================ FILE: src/sha256.h ================================================ #define SHA256_DIGEST_SIZE 32 #define SHA256_BLOCK_SIZE 64 typedef struct { uint32_t total[2]; uint32_t state[8]; uint32_t wbuf[16]; } sha256_context; void sha256 (const unsigned char *input, unsigned int ilen, unsigned char output[32]); void sha256_start (sha256_context *ctx); void sha256_finish (sha256_context *ctx, unsigned char output[32]); void sha256_update (sha256_context *ctx, const unsigned char *input, unsigned int ilen); void sha256_process (sha256_context *ctx); ================================================ FILE: src/stm32f103.ld ================================================ /* * ST32F103 memory setup. */ __main_stack_size__ = 0x0100; /* Idle+Exception handlers */ __process0_stack_size__ = 0x0400; /* Main program */ __process1_stack_size__ = 0x0200; /* pwd */ __process2_stack_size__ = 0x0200; /* blk */ __process3_stack_size__ = 0x0200; /* usb-hid */ __process4_stack_size__ = 0x1000; /* u2f-hid */ __process5_stack_size__ = 0x0500; /* rng */ __process6_stack_size__ = 0x0200; /* pbt */ MEMORY { flash0 : org = 0x08000000, len = 4k flash : org = 0x08000000+0x1000, len = 58k flash1 : org = 0x08000000+0xf400, len = 3k ram : org = 0x20000000, len = 20k } __ram_start__ = ORIGIN(ram); __ram_size__ = 20k; __ram_end__ = __ram_start__ + __ram_size__; SECTIONS { . = 0; .sys : ALIGN(4) SUBALIGN(4) { _sys = .; KEEP(*(.vectors)) . = ALIGN(16); KEEP(*(.sys.version)) KEEP(*(.sys.board_id)) KEEP(*(.sys.board_name)) build/sys-*.o(.text) build/sys-*.o(.text.*) build/sys-*.o(.rodata) build/sys-*.o(.rodata.*) . = ALIGN(1024); *(.sys.0) *(.sys.1) *(.sys.2) } > flash0 _text = .; .startup : ALIGN(128) SUBALIGN(128) { KEEP(*(.startup.vectors)) . = ALIGN (16); } > flash =0xffffffff .text : ALIGN(16) SUBALIGN(16) { *(.text.startup.*) *(.text) *(.text.*) *(.rodata) *(.rodata.*) *(.glue_7t) *(.glue_7) *(.gcc*) . = ALIGN(8); } > flash .ARM.extab : {*(.ARM.extab* .gnu.linkonce.armextab.*)} > flash .ARM.exidx : { PROVIDE(__exidx_start = .); *(.ARM.exidx* .gnu.linkonce.armexidx.*) PROVIDE(__exidx_end = .); } > flash .eh_frame_hdr : {*(.eh_frame_hdr)} > flash .eh_frame : ONLY_IF_RO {*(.eh_frame)} > flash .textalign : ONLY_IF_RO { . = ALIGN(8); } > flash _etext = .; _textdata = _etext; .process_stack : { . = ALIGN(8); __process6_stack_base__ = .; . += __process6_stack_size__; . = ALIGN(8); __process6_stack_end__ = .; __process5_stack_base__ = .; . += __process5_stack_size__; . = ALIGN(8); __process5_stack_end__ = .; __process4_stack_base__ = .; . += __process4_stack_size__; . = ALIGN(8); __process4_stack_end__ = .; __process3_stack_base__ = .; . += __process3_stack_size__; . = ALIGN(8); __process3_stack_end__ = .; __process2_stack_base__ = .; . += __process2_stack_size__; . = ALIGN(8); __process2_stack_end__ = .; __process1_stack_base__ = .; . += __process1_stack_size__; . = ALIGN(8); __process1_stack_end__ = .; __process0_stack_base__ = .; . += __process0_stack_size__; . = ALIGN(8); __process0_stack_end__ = .; } > ram .main_stack : { . = ALIGN(8); __main_stack_base__ = .; . += __main_stack_size__; . = ALIGN(8); __main_stack_end__ = .; } > ram .data : { . = ALIGN(4); PROVIDE(_data = .); *(.data) . = ALIGN(4); *(.data.*) . = ALIGN(4); *(.ramtext) . = ALIGN(4); PROVIDE(_edata = .); } > ram AT > flash .bss : { . = ALIGN(4); PROVIDE(_bss_start = .); *(.bss) . = ALIGN(4); *(.bss.*) . = ALIGN(4); *(COMMON) . = ALIGN(4); PROVIDE(_bss_end = .); } > ram .flash_storage : { . = ALIGN (1024); _attestation_cert_base = .; *(.attestation.cert); . = ALIGN (1024); _device_key_base = .; *(.device.key); . = ALIGN (1024); _auth_ctr_base = .; *(.auth.ctr); . = ALIGN (1024); } > flash1 PROVIDE(end = .); _end = .; } __heap_base__ = _end; __heap_end__ = __ram_end__; ================================================ FILE: src/toboot.h ================================================ #ifndef TOBOOT_API_H_ #define TOBOOT_API_H_ #include /// Store this configuration struct at offset 0x94 from the start /// of your binary image. /// You may set all RESERVED values to 0. as they will be calculated /// when the program is written to flash. struct toboot_configuration { /// Our LD script using ALIGN(8). uint32_t align; /// Set to 0x907070b2 to indicate a valid configuration header. uint32_t magic; /// Reserved value. Used as a generational counter. Toboot will /// overwrite this value with a monotonically-increasing counter /// every time a new image is burned. This is used to determine /// which image is the newest. uint16_t reserved_gen; /// The starting page for your program in 1024-byte blocks. /// Toboot itself sets this to 0. If this is nonzero, then it /// must be located after the Toboot image. Toboot is currently /// under 5 kilobytes, so make sure this value is at least 6. uint8_t start; /// Configuration bitmask. See below for values. uint8_t config; /// Set to 0x18349420 to prevent the user from entering Toboot manually. /// Use this value with caution, as it can be used to lockout a Tomu. uint32_t lock_entry; /// A bitmask of sectors to erase when updating the program. Each "1" /// causes that sector to be erased, unless it's Toboot itself. Bit values /// determine flash blocks 0-31. uint32_t erase_mask_lo; /// A bitmask of sectors to erase when updating the program. Each "1" /// causes that sector to e erased. Use these two values to e.g. force /// private keys to be erased when updating. Bit values determine flash /// blocks 32-63. uint32_t erase_mask_hi; /// A hash of the entire header, minus this entry. Toboot calculates /// this when it programs the first block. A Toboot configuration /// header MUST have a valid hash in order to be considered valid. uint32_t reserved_hash; } __attribute__((packed)); /// Toboot V1.0 leaves IRQs enabled, mimicking the behavior of /// AN0042. Toboot V2.0 makes this configurable by adding a /// bit to the configuration area. #define TOBOOT_CONFIG_FLAG_ENABLE_IRQ_MASK 0x01 #define TOBOOT_CONFIG_FLAG_ENABLE_IRQ_SHIFT 0 #define TOBOOT_CONFIG_FLAG_ENABLE_IRQ (1 << 0) #define TOBOOT_CONFIG_FLAG_DISABLE_IRQ (0 << 0) /// When running a normal program, you won't want Toboot to run. /// However, when developing new software it is handy to have /// Toboot run at poweron. Set this flag to enter Toboot whenever /// the system has powered on for the first time. #define TOBOOT_CONFIG_FLAG_AUTORUN_MASK 0x02 #define TOBOOT_CONFIG_FLAG_AUTORUN_SHIFT 1 #define TOBOOT_CONFIG_FLAG_AUTORUN (1 << 1) /// When we create a fake header, this flag will be set. Otherwise, /// leave the flag cleared. #define TOBOOT_CONFIG_FAKE_MASK 0x04 #define TOBOOT_CONFIG_FAKE_SHIFT 2 #define TOBOOT_CONFIG_FAKE (1 << 2) /// Various magic values describing Toboot configuration headers. #define TOBOOT_V1_MAGIC 0x70B0 #define TOBOOT_V1_MAGIC_MASK 0x0000ffff #define TOBOOT_V2_MAGIC 0x907070b2 #define TOBOOT_V2_MAGIC_MASK 0xffffffff /// This value is used to prevent manual entry into Toboot. #define TOBOOT_LOCKOUT_MAGIC 0x18349420 /// The seed value for the hash of Toboot's configuration header #define TOBOOT_HASH_SEED 0x037a5cf1 /// This is the runtime part that lives at the start of RAM. /// Running programs can use this to force entry into Toboot /// during the next reboot. struct toboot_runtime { /// Set this to 0x74624346 and reboot to enter bootloader, /// even if LOCKOUT is enabled. uint32_t magic; /// Set this to 0 when your program starts. uint8_t boot_count; /// The bootloader should set this to 0x23 for Tomu. uint8_t board_model; /// Unused. uint16_t reserved; }; /// Set runtime.magic to this value and reboot to force /// entry into Toboot. #define TOBOOT_FORCE_ENTRY_MAGIC 0x74624346 /// Use this macro to define a Toboot V2 configuration. If unspecified, /// your program will default to a legacy configuration, and will not have /// access to features such as autoboot. #define TOBOOT_CONFIGURATION(cfg) \ __attribute__ ((used, section(".vectors"))) \ const struct toboot_configuration __toboot_configuration = { \ .magic = TOBOOT_V2_MAGIC, \ .reserved_gen = 0, \ .start = 16, \ .config = cfg, \ .lock_entry = 0, \ .erase_mask_lo = 0, \ .erase_mask_hi = 0, \ .reserved_hash = 0, \ } #endif /* TOBOOT_API_H_ */ ================================================ FILE: src/u2f-apdu.c ================================================ /* * u2f-apdu.c - U2F apdu commands * * Copyright (C) 2017-2019 Sergei Glushchenko * Author: Sergei Glushchenko * * This file is a part of U2F firmware for STM32 * * 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 . * * As additional permission under GNU GPL version 3 section 7, you may * distribute non-source form of the Program without the copy of the * GNU GPL normally required by section 4, provided you inform the * recipients of GNU GPL by a written offer. * */ #include #include #include "sha256.h" #include "ecc.h" #include "hmac.h" #include "random.h" #include "board.h" #include "sys.h" #include "pbt.h" #define CLA(apdu) ((apdu)[0]) #define INS(apdu) ((apdu)[1]) #define P1(apdu) ((apdu)[2]) #define P2(apdu) ((apdu)[3]) #define LC(apdu) (((apdu)[4] << 16) | ((apdu)[5] << 8) | (apdu)[6]) #define DATA(apdu) ((apdu) + 7) // General constants #define HASH_BLOCK_SIZE 64 #define HASH_RES_SIZE 32 #define U2F_EC_KEY_SIZE 32 // EC key size in bytes #define U2F_EC_POINT_SIZE ((U2F_EC_KEY_SIZE * 2) + 1) // Size of EC point #define U2F_NONCE_SIZE 32 // size of nonce #define U2F_KH_SIZE (HASH_RES_SIZE + U2F_NONCE_SIZE) // size of key handle #define U2F_PRIV_K_SIZE 32 // size of private key #define U2F_PUB_K_SIZE 64 // size of public key #define U2F_MAX_EC_SIG_SIZE 72 // Max size of DER coded EC signature #define U2F_CTR_SIZE 4 // Size of counter field #define U2F_APPID_SIZE 32 // Size of application id #define U2F_CHAL_SIZE 32 // Size of challenge #define ENC_SIZE(x) ((x + 7) & 0xfff8) // EC (uncompressed) point #define U2F_POINT_UNCOMPRESSED 0x04 // Uncompressed point format typedef struct { uint8_t pointFormat; // Point type uint8_t x[U2F_EC_KEY_SIZE]; // X-value uint8_t y[U2F_EC_KEY_SIZE]; // Y-value } U2F_EC_POINT; // U2F native commands #define U2F_REGISTER 0x01 // Registration command #define U2F_AUTHENTICATE 0x02 // Authenticate/sign command #define U2F_VERSION 0x03 // Read version string command #define U2F_VENDOR_FIRST 0x40 // First vendor defined command #define U2F_VENDOR_LAST 0xbf // Last vendor defined command #define U2F_ATTESTATION_CERT 0x40 // Set attestation certificate and key // U2F_REGISTER command defines #define U2F_REGISTER_ID 0x05 // Version 2 registration identifier #define U2F_REGISTER_HASH_ID 0x00 // Version 2 hash identintifier typedef struct { uint8_t chal[U2F_CHAL_SIZE]; // Challenge uint8_t appId[U2F_APPID_SIZE]; // Application id } __attribute__ ((packed)) U2F_REGISTER_REQ; #define ATTESTATION_DER_MAX_LEN 512 typedef struct { uint8_t registerId; // Registration identifier (U2F_REGISTER_ID_V2) U2F_EC_POINT pubKey; // Generated public key uint8_t keyHandleLen; // Length of key handle uint8_t keyHandle[U2F_KH_SIZE]; // Key handle uint8_t attCert[ATTESTATION_DER_MAX_LEN]; // Attestation certificate uint8_t pad[2 + U2F_MAX_EC_SIG_SIZE]; // For SW1 and SW2 } __attribute__ ((packed)) U2F_REGISTER_RESP; // U2F_AUTHENTICATE command defines // Authentication control byte #define U2F_AUTH_ENFORCE 0x03 // Enforce user presence and sign #define U2F_AUTH_CHECK_ONLY 0x07 // Check only #define U2F_AUTH_FLAG_TUP 0x01 // Test of user presence set typedef struct { uint8_t chal[U2F_CHAL_SIZE]; // Challenge uint8_t appId[U2F_APPID_SIZE]; // Application id uint8_t keyHandleLen; // Length of key handle uint8_t keyHandle[U2F_KH_SIZE]; // Key handle } __attribute__ ((packed)) U2F_AUTHENTICATE_REQ; typedef struct { uint8_t flags; // U2F_AUTH_FLAG_ values uint8_t ctr[U2F_CTR_SIZE]; // Counter field (big-endian) uint8_t sig[U2F_MAX_EC_SIG_SIZE]; // Signature uint8_t pad[2]; // For SW1 and SW2 } __attribute__ ((packed)) U2F_AUTHENTICATE_RESP; // U2F_ATTESTATION_CERT command defines typedef struct { uint8_t key[U2F_EC_KEY_SIZE]; uint8_t der[ATTESTATION_DER_MAX_LEN]; } __attribute__ ((packed)) U2F_ATTESTATION_CERT_REQ; // Command status responses #define U2F_SW_NO_ERROR 0x9000 // SW_NO_ERROR #define U2F_SW_WRONG_DATA 0x6A80 // SW_WRONG_DATA #define U2F_SW_CONDITIONS_NOT_SATISFIED 0x6985 // SW_CONDITIONS_NOT_SATISFIED #define U2F_SW_COMMAND_NOT_ALLOWED 0x6986 // SW_COMMAND_NOT_ALLOWED #define U2F_SW_INS_NOT_SUPPORTED 0x6D00 // SW_INS_NOT_SUPPORTED #define U2F_SW_WRONG_LENGTH 0x6700 // SW_INS_WRONG_LENGTH #define U2F_SW_BAD_CLA 0x6E00 // SW_BAD_CLA /* simple RNG interface */ static int rng (uint8_t *buf, size_t size) { uint8_t rng_index = 0; int res; res = random_gen (&rng_index, buf, size); random_bytes_free (NULL); /* parameter isn't used. invokes neug_flush. */ return res; } /* device key */ struct device_key { /* ECC private key unique for each device */ uint8_t key[U2F_PRIV_K_SIZE]; /* SHA256 of private key to verify its integrity */ uint8_t key_hash[HASH_RES_SIZE]; /* reserved for future use */ uint8_t resrved[1024 - U2F_PRIV_K_SIZE - HASH_RES_SIZE]; }; struct device_key __attribute__ ((section(".device.key"))) device_key = { 0 }; uint32_t __attribute__ ((section(".auth.ctr"))) auth_ctr[256] = { 0 }; static uint32_t *ctr_addr = &(auth_ctr[0]); struct attestation_cert_header { uint32_t der_len; const uint8_t *der; const uint8_t *key; }; struct attestation_cert { struct attestation_cert_header hdr; uint8_t data[1024 - sizeof(struct attestation_cert_header)]; }; _Static_assert(sizeof(struct attestation_cert) == 1024, "Wrong struct attestation_cert size"); #include "cert/certificates.c" static void device_key_gen (void) { uint8_t key[U2F_PRIV_K_SIZE]; uint8_t key_hash[HASH_RES_SIZE]; sha256_context ctx; sha256_start (&ctx); sha256_update (&ctx, device_key.key, U2F_PRIV_K_SIZE); sha256_finish (&ctx, key_hash); if (memcmp (key_hash, device_key.key_hash, HASH_RES_SIZE) == 0) return; /* new device key needs to be generated */ rng (key, U2F_PRIV_K_SIZE); sha256_start (&ctx); sha256_update (&ctx, key, U2F_PRIV_K_SIZE); sha256_finish (&ctx, key_hash); /* write device key to flash */ flash_erase_page ((uintptr_t) &device_key); flash_write ((uintptr_t) device_key.key, key, U2F_PRIV_K_SIZE); flash_write ((uintptr_t) device_key.key_hash, key_hash, HASH_RES_SIZE); /* erase auth counter */ flash_erase_page ((uintptr_t) ctr_addr); } static void new_private_key (uint8_t *app_id, uint8_t *nonce, uint8_t *private_key) { hmac_sha256_context ctx; hmac_sha256_init (&ctx, device_key.key); hmac_sha256_update (&ctx, app_id, U2F_APPID_SIZE); hmac_sha256_update (&ctx, nonce, U2F_NONCE_SIZE); hmac_sha256_finish (&ctx, device_key.key, private_key); } static void make_key_handle (uint8_t *private_key, uint8_t *app_id, uint8_t *nonce, uint8_t *key_handle) { hmac_sha256_context ctx; hmac_sha256_init (&ctx, device_key.key); hmac_sha256_update (&ctx, private_key, U2F_PRIV_K_SIZE); hmac_sha256_update (&ctx, app_id, U2F_APPID_SIZE); hmac_sha256_finish (&ctx, device_key.key, key_handle); memcpy (key_handle + HASH_RES_SIZE, nonce, U2F_NONCE_SIZE); } static int recover_private_key (uint8_t *app_id, uint8_t *key_handle, uint8_t key_handle_len, uint8_t *private_key) { hmac_sha256_context ctx; uint8_t control_mac[HASH_RES_SIZE]; if (key_handle_len != U2F_KH_SIZE) return -1; hmac_sha256_init (&ctx, device_key.key); hmac_sha256_update (&ctx, app_id, U2F_APPID_SIZE); hmac_sha256_update (&ctx, key_handle + HASH_RES_SIZE, U2F_NONCE_SIZE); hmac_sha256_finish (&ctx, device_key.key, private_key); hmac_sha256_init (&ctx, device_key.key); hmac_sha256_update (&ctx, private_key, U2F_PRIV_K_SIZE); hmac_sha256_update (&ctx, app_id, U2F_APPID_SIZE); hmac_sha256_finish (&ctx, device_key.key, control_mac); return memcmp(control_mac, key_handle, HASH_RES_SIZE); } static uint8_t der_encode_uint (uint8_t *der, uint8_t *x, uint8_t x_len) { uint8_t len = 0; /* integer */ der[len++] = 0x02; /* reserve field for length, works only for short form */ der[len++] = 0; /* omit leading zeros */ while (x[0] == 0 && x_len > 0) { ++x; --x_len; } /* positive integer: 8th bit must be zero */ if (x[0] > 0x7f) der[len++] = 0; /* copy actual data */ memcpy (der + len, x, x_len); len += x_len; /* set length field */ der[1] = len - 2; return len; } static uint8_t der_encode_sig (uint8_t *der, uint8_t *sig) { uint8_t len; len = 0; der[len++] = 0x30; /* reserve length field */ der[len++] = 0; len += der_encode_uint (der + len, sig, 32); len += der_encode_uint (der + len, sig + 32, 32); der[1] = len - 2; return len; } static void register_req_hash (U2F_REGISTER_REQ *req, U2F_REGISTER_RESP *resp, uint8_t *hash) { sha256_context ctx; uint8_t resrved = 0; sha256_start (&ctx); sha256_update (&ctx, &resrved, 1); sha256_update (&ctx, req->appId, U2F_APPID_SIZE); sha256_update (&ctx, req->chal, U2F_CHAL_SIZE); sha256_update (&ctx, resp->keyHandle, resp->keyHandleLen); sha256_update (&ctx, (uint8_t *) &resp->pubKey, sizeof (resp->pubKey)); sha256_finish (&ctx, hash); } static int u2f_register (U2F_REGISTER_REQ *req, U2F_REGISTER_RESP *resp) { uint8_t private[U2F_PRIV_K_SIZE]; uint8_t nonce[U2F_NONCE_SIZE]; uint8_t hash[HASH_RES_SIZE]; uint8_t sig[64]; uint8_t sig_len; if (rng (nonce, U2F_NONCE_SIZE)) return -1; new_private_key (req->appId, nonce, private); make_key_handle (private, req->appId, nonce, resp->keyHandle); if (ecc_compute_public_p256r1 (private, resp->pubKey.x)) return -1; resp->registerId = U2F_REGISTER_ID; resp->pubKey.pointFormat = U2F_POINT_UNCOMPRESSED; resp->keyHandleLen = U2F_KH_SIZE; memcpy (resp->attCert, attestation_cert.hdr.der, attestation_cert.hdr.der_len); register_req_hash (req, resp, hash); if (ecdsa_sign_p256r1 (hash, sig, attestation_cert.hdr.key)) return -1; sig_len = der_encode_sig (resp->attCert + attestation_cert.hdr.der_len, sig); return 1 // Registration identifier (U2F_REGISTER_ID_V2) + sizeof (U2F_EC_POINT) // Generated public key + 1 // Length of key handle + U2F_KH_SIZE // Key handle + attestation_cert.hdr.der_len // Attestation certificate + sig_len; // Registration signature } static uint32_t u2f_read_ctr (void) { const int page_size = 1024 / sizeof (*ctr_addr); while (*ctr_addr != 0xffffffff) { if (ctr_addr - &(auth_ctr[0]) == page_size) break; ctr_addr++; } if (ctr_addr == &(auth_ctr[0])) return 0; return ctr_addr[-1]; } static void u2f_write_ctr (uint32_t val) { const int page_size = 1024 / sizeof (*ctr_addr); while (*ctr_addr != 0xffffffff) { if (ctr_addr - &(auth_ctr[0]) == page_size) { flash_erase_page ((uintptr_t) &(auth_ctr[0])); ctr_addr = &(auth_ctr[0]); break; } ctr_addr++; } flash_write ((uintptr_t) ctr_addr, (uint8_t *) &val, sizeof (val)); } static void u2f_inc_ctr (void) { uint32_t ctr; ctr = u2f_read_ctr (); ctr++; u2f_write_ctr (ctr); } static void auth_req_hash (U2F_AUTHENTICATE_REQ *req, U2F_AUTHENTICATE_RESP *resp, uint8_t *hash) { sha256_context ctx; sha256_start (&ctx); sha256_update (&ctx, req->appId, U2F_APPID_SIZE); sha256_update (&ctx, &resp->flags, 1); sha256_update (&ctx, resp->ctr, 4); sha256_update (&ctx, req->chal, U2F_CHAL_SIZE); sha256_finish (&ctx, hash); } static int u2f_authenticate (U2F_AUTHENTICATE_REQ *req, U2F_AUTHENTICATE_RESP *resp) { uint8_t private[U2F_PRIV_K_SIZE]; uint8_t hash[HASH_RES_SIZE]; uint8_t sig[64]; uint8_t sig_len; uint32_t ctr; resp->flags = U2F_AUTH_FLAG_TUP; ctr = u2f_read_ctr (); resp->ctr[0] = ctr >> 24 & 0xff; resp->ctr[1] = ctr >> 16 & 0xff; resp->ctr[2] = ctr >> 8 & 0xff; resp->ctr[3] = ctr & 0xff; auth_req_hash (req, resp, hash); if (recover_private_key (req->appId, req->keyHandle, req->keyHandleLen, private)) return -1; if (ecdsa_sign_p256r1 (hash, sig, private)) return -1; sig_len = der_encode_sig (resp->sig, sig); return 1 // U2F_AUTH_FLAG_ values + U2F_CTR_SIZE // Counter field (big-endian) + sig_len; // Signature } static int u2f_attestation_cert_initialized (void) { return attestation_cert.hdr.der_len != (uint32_t) -1; } static int u2f_attestation_cert_initialize (uint32_t len, U2F_ATTESTATION_CERT_REQ *req) { flash_erase_page ((uintptr_t) &attestation_cert); struct attestation_cert_header tmp; tmp.der_len = len - U2F_EC_KEY_SIZE; tmp.key = ((uint8_t *) &attestation_cert) + 16; tmp.der = tmp.key + U2F_EC_KEY_SIZE; flash_write ((uintptr_t) &attestation_cert, (uint8_t *) &tmp, sizeof (tmp)); /* req->key and req->der are unaligned, we'll use temporary buffer */ uint8_t buf[16]; for (uint32_t i = 0; i < U2F_EC_KEY_SIZE; i += 16) { memcpy (buf, req->key + i, 16); flash_write ((uintptr_t) tmp.key + i, buf, 16); } for (uint32_t i = 0; i < tmp.der_len; i += 16) { memcpy (buf, req->der + i, 16); flash_write ((uintptr_t) tmp.der + i, buf, 16); } return 0; } static int u2f_version (uint8_t *resp) { memcpy (resp, "U2F_V2", 6); return 6; } static void append_sw (uint8_t *msg, uint32_t *len, uint16_t sw) { msg[(*len)++] = (sw >> 8) & 0xff; msg[(*len)++] = sw & 0xff; } static void u2f_apdu_error (uint8_t *msg, uint32_t *len, uint16_t sw) { *len = 0; append_sw (msg, len, sw); } void u2f_apdu_init (void) { /* generate and store device private key on first run */ device_key_gen (); } int u2f_apdu_command_do (uint8_t *apdu, uint32_t len, uint8_t *resp, uint32_t *resp_len) { uint32_t Lc; int ret; Lc = LC (apdu); if (CLA (apdu) != 0) { u2f_apdu_error (resp, resp_len, U2F_SW_BAD_CLA); return 0; } if (Lc + 7 > len) { u2f_apdu_error (resp, resp_len, U2F_SW_WRONG_LENGTH); return 0; } switch (INS (apdu)) { case U2F_REGISTER: if (!u2f_attestation_cert_initialized ()) { u2f_apdu_error (resp, resp_len, U2F_SW_COMMAND_NOT_ALLOWED); break; } if (Lc != sizeof (U2F_REGISTER_REQ)) { u2f_apdu_error (resp, resp_len, U2F_SW_WRONG_LENGTH); break; } if (!user_presence_get ()) { u2f_apdu_error (resp, resp_len, U2F_SW_CONDITIONS_NOT_SATISFIED); return 0; } ret = u2f_register ((U2F_REGISTER_REQ *) DATA (apdu), (U2F_REGISTER_RESP *) resp); if (ret > 0) { user_presence_reset (); *resp_len = ret; append_sw (resp, resp_len, U2F_SW_NO_ERROR); } else { u2f_apdu_error (resp, resp_len, U2F_SW_WRONG_DATA); } break; case U2F_AUTHENTICATE: if (!u2f_attestation_cert_initialized ()) { u2f_apdu_error (resp, resp_len, U2F_SW_COMMAND_NOT_ALLOWED); break; } if (Lc != sizeof (U2F_AUTHENTICATE_REQ)) { u2f_apdu_error (resp, resp_len, U2F_SW_WRONG_LENGTH); break; } ret = u2f_authenticate ((U2F_AUTHENTICATE_REQ *) DATA (apdu), (U2F_AUTHENTICATE_RESP *)resp); if (ret > 0) { if (P1 (apdu) != U2F_AUTH_CHECK_ONLY) { if (!user_presence_get ()) { u2f_apdu_error (resp, resp_len, U2F_SW_CONDITIONS_NOT_SATISFIED); return 0; } u2f_inc_ctr (); user_presence_reset (); *resp_len = ret; append_sw (resp, resp_len, U2F_SW_NO_ERROR); } else u2f_apdu_error (resp, resp_len, U2F_SW_CONDITIONS_NOT_SATISFIED); } else u2f_apdu_error (resp, resp_len, U2F_SW_WRONG_DATA); break; case U2F_VERSION: if (Lc > 0) { u2f_apdu_error (resp, resp_len, U2F_SW_WRONG_LENGTH); break; } ret = u2f_version (resp); if (ret > 0) { *resp_len = ret; append_sw (resp, resp_len, U2F_SW_NO_ERROR); } break; case U2F_ATTESTATION_CERT: if (Lc <= U2F_EC_KEY_SIZE) { u2f_apdu_error (resp, resp_len, U2F_SW_WRONG_LENGTH); break; } if (u2f_attestation_cert_initialized ()) { u2f_apdu_error (resp, resp_len, U2F_SW_COMMAND_NOT_ALLOWED); break; } ret = u2f_attestation_cert_initialize ( Lc, (U2F_ATTESTATION_CERT_REQ*) DATA(apdu)); if (ret < 0) { u2f_apdu_error (resp, resp_len, U2F_SW_WRONG_DATA); break; } *resp_len = 0; append_sw (resp, resp_len, U2F_SW_NO_ERROR); break; default: u2f_apdu_error (resp, resp_len, U2F_SW_INS_NOT_SUPPORTED); } return 0; } ================================================ FILE: src/u2f-apdu.h ================================================ #ifndef __U2F_U2F_APDU_H__ #define __U2F_U2F_APDU_H__ void u2f_apdu_init (void); int u2f_apdu_command_do (uint8_t *apdu, uint32_t len, uint8_t *resp, uint32_t *resp_len); #endif ================================================ FILE: src/u2f-hid.c ================================================ /* * u2f-hid.c - U2F HID protocol * * Copyright (C) 2017-2019 Sergei Glushchenko * Author: Sergei Glushchenko * * This file is a part of U2F firmware for STM32 * * 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 . * * As additional permission under GNU GPL version 3 section 7, you may * distribute non-source form of the Program without the copy of the * GNU GPL normally required by section 4, provided you inform the * recipients of GNU GPL by a written offer. * */ #include #include #include #include "board.h" #include "sys.h" #include "usb-hid.h" #include "u2f-hid.h" #include "u2f-apdu.h" // Size of HID reports #define HID_RPT_SIZE 64 // Default size of raw HID report // Frame layout - command- and continuation frames #define CID_BROADCAST 0xffffffff // Broadcast channel id #define TYPE_MASK 0x80 // Frame type mask #define TYPE_INIT 0x80 // Initial frame identifier #define TYPE_CONT 0x00 // Continuation frame identifier typedef struct { uint32_t cid; // Channel identifier union { uint8_t type; // Frame type - b7 defines type struct { uint8_t cmd; // Command - b7 set uint8_t bcnth; // Message byte count - high part uint8_t bcntl; // Message byte count - low part uint8_t data[HID_RPT_SIZE - 7]; // Data payload } init; struct { uint8_t seq; // Sequence number - b7 cleared uint8_t data[HID_RPT_SIZE - 5]; // Data payload } cont; }; } __attribute__ ((packed)) U2FHID_FRAME; #define FRAME_TYPE(f) ((f).type & TYPE_MASK) #define FRAME_CMD(f) ((f).init.cmd & ~TYPE_MASK) #define MSG_LEN(f) ((f).init.bcnth*256 + (f).init.bcntl) #define FRAME_SEQ(f) ((f).cont.seq & ~TYPE_MASK) #define SET_MSG_LEN(f, len) { \ (f).init.bcnth = (uint8_t) ((len) >> 8); \ (f).init.bcntl = (uint8_t) (len); \ } // HID usage- and usage-page definitions #define FIDO_USAGE_PAGE 0xf1d0 // FIDO alliance HID usage page #define FIDO_USAGE_U2FHID 0x01 // U2FHID usage for top-level collection #define FIDO_USAGE_DATA_IN 0x20 // Raw IN data report #define FIDO_USAGE_DATA_OUT 0x21 // Raw OUT data report // General constants #define U2FHID_IF_VERSION 2 // Current interface implementation version #define U2FHID_TRANS_TIMEOUT 3000 // Default message timeout in ms // U2FHID native commands #define U2FHID_PING (TYPE_INIT | 0x01) // Echo data through local processor only #define U2FHID_MSG (TYPE_INIT | 0x03) // Send U2F message frame #define U2FHID_LOCK (TYPE_INIT | 0x04) // Send lock channel command #define U2FHID_INIT (TYPE_INIT | 0x06) // Channel initialization #define U2FHID_WINK (TYPE_INIT | 0x08) // Send device identification wink #define U2FHID_SYNC (TYPE_INIT | 0x3c) // Protocol resync command #define U2FHID_ERROR (TYPE_INIT | 0x3f) // Error response #define U2FHID_VENDOR_FIRST (TYPE_INIT | 0x40) // First vendor defined command #define U2FHID_VENDOR_LAST (TYPE_INIT | 0x7f) // Last vendor defined command // U2FHID_INIT command defines #define INIT_NONCE_SIZE 8 // Size of channel initialization challenge #define CAPFLAG_WINK 0x01 // Device supports WINK command #define CAPFLAG_LOCK 0x02 // Device supports LOCK command typedef struct { uint8_t nonce[INIT_NONCE_SIZE]; // Client application nonce } __attribute__ ((packed)) U2FHID_INIT_REQ; typedef struct { uint8_t nonce[INIT_NONCE_SIZE]; // Client application nonce uint32_t cid; // Channel identifier uint8_t versionInterface; // Interface version uint8_t versionMajor; // Major version number uint8_t versionMinor; // Minor version number uint8_t versionBuild; // Build version number uint8_t capFlags; // Capabilities flags } __attribute__ ((packed)) U2FHID_INIT_RESP; // U2FHID_SYNC command defines typedef struct { uint8_t nonce; // Client application nonce } __attribute__ ((packed)) U2FHID_SYNC_REQ; typedef struct { uint8_t nonce; // Client application nonce } __attribute__ ((packed)) U2FHID_SYNC_RESP; // Low-level error codes. Return as negatives. #define ERR_NONE 0x00 // No error #define ERR_INVALID_CMD 0x01 // Invalid command #define ERR_INVALID_PAR 0x02 // Invalid parameter #define ERR_INVALID_LEN 0x03 // Invalid message length #define ERR_INVALID_SEQ 0x04 // Invalid message sequencing #define ERR_MSG_TIMEOUT 0x05 // Message has timed out #define ERR_CHANNEL_BUSY 0x06 // Channel busy #define ERR_LOCK_REQUIRED 0x0a // Command requires channel lock #define ERR_INVALID_CID 0x0b // Invalid channel #define ERR_SYNC_FAIL 0x0b // SYNC command failed #define ERR_OTHER 0x7f // Other unspecified error #define PRIO_U2F_HID 4 extern uint8_t __process4_stack_base__[], __process4_stack_size__[]; #define STACK_ADDR_U2F_HID ((uint32_t)__process4_stack_base__) #define STACK_SIZE_U2F_HID ((uint32_t)__process4_stack_size__) #define MAX_MSGLEN 1024 #define MAX_APDU_CMDLEN 416 struct u2f_hid { uint32_t next_cid; uint32_t cid; U2FHID_FRAME frame; struct usb_hid *hid; uint8_t cmd; uint8_t seq; uint8_t msg[MAX_MSGLEN]; uint8_t apdu_cmd[MAX_APDU_CMDLEN]; uint16_t msg_len; uint16_t msg_pos; }; static struct u2f_hid u2f_hid; static int u2f_msg_init (struct u2f_hid *u2f, uint16_t len) { u2f->msg_len = len; u2f->msg_pos = 0; return 0; } static int u2f_msg_append (struct u2f_hid *u2f, uint8_t *buf, uint16_t len) { if (u2f->msg_pos + len >= u2f->msg_len) len = u2f->msg_len - u2f->msg_pos; memcpy (u2f->msg + u2f->msg_pos, buf, len); u2f->msg_pos += len; return u2f->msg_len - u2f->msg_pos; } static void u2f_send_error (struct u2f_hid *u2f, uint32_t cid, uint8_t error) { memset (u2f->frame.init.data, 0, sizeof (u2f->frame.init.data)); u2f->frame.cid = cid; u2f->frame.init.cmd = U2FHID_ERROR; u2f->frame.init.data[0] = error; SET_MSG_LEN (u2f->frame, 1); hid_send (u2f->hid, (uint8_t *) &u2f->frame, sizeof (u2f->frame)); } static void u2f_send_init (struct u2f_hid *u2f, uint32_t cid, uint32_t resp_cid, uint8_t *nonce) { U2FHID_INIT_RESP *resp; u2f->frame.cid = cid; u2f->frame.init.cmd = U2FHID_INIT; SET_MSG_LEN (u2f->frame, sizeof (U2FHID_INIT_RESP)); resp = (U2FHID_INIT_RESP *) &u2f->frame.init.data; memcpy (&resp->nonce, nonce, INIT_NONCE_SIZE); memset (u2f->frame.init.data + INIT_NONCE_SIZE, 0, sizeof (u2f->frame.init.data) - INIT_NONCE_SIZE); resp->cid = resp_cid; resp->versionInterface = U2FHID_IF_VERSION; resp->versionMajor = 1; resp->versionMinor = 1; resp->versionBuild = 1; resp->capFlags = 0; hid_send (u2f->hid, (uint8_t *) &u2f->frame, sizeof (u2f->frame)); } static void u2f_send_msg (struct u2f_hid *u2f, uint32_t cid, uint8_t cmd, uint8_t *msg, uint16_t len) { uint16_t remain; uint16_t frame_len; uint8_t seq; remain = len; u2f->frame.cid = cid; u2f->frame.init.cmd = cmd; SET_MSG_LEN (u2f->frame, len); frame_len = remain; if (frame_len > sizeof (u2f->frame.init.data)) frame_len = sizeof (u2f->frame.init.data); memset (u2f->frame.init.data, 0, sizeof (u2f->frame.init.data)); memcpy (u2f->frame.init.data, msg, frame_len); hid_send (u2f->hid, (uint8_t *) &u2f->frame, sizeof (u2f->frame)); remain -= frame_len; msg += frame_len; seq = 0; while (remain > 0) { u2f->frame.cont.seq = seq; frame_len = remain; if (frame_len > sizeof (u2f->frame.cont.data)) frame_len = sizeof (u2f->frame.cont.data); memset (u2f->frame.cont.data, 0, sizeof (u2f->frame.cont.data)); memcpy (u2f->frame.cont.data, msg, frame_len); hid_send (u2f->hid, (uint8_t *) &u2f->frame, sizeof (u2f->frame)); remain -= frame_len; msg += frame_len; ++seq; } } static void uf2_reset (struct u2f_hid *u2f) { u2f->cmd = 0; u2f->cid = 0; u2f->seq = 0; } extern uint8_t blink_is_on; static void * u2f_hid_main (void *arg) { struct u2f_hid *u2f = (struct u2f_hid *) arg; int remain = 0; int err; u2f_apdu_init (); while (1) { err = hid_recv (u2f->hid, (uint8_t *) &u2f->frame, sizeof(u2f->frame), 500000); if (err == -1 && u2f->cmd) { u2f_send_error (u2f, u2f->cid, ERR_MSG_TIMEOUT); uf2_reset (u2f); continue; } if (err == -1) continue; blink_is_on = 1; if (u2f->frame.cid == 0 || (u2f->frame.cid == CID_BROADCAST && u2f->frame.init.cmd != U2FHID_INIT)) { u2f_send_error (u2f, u2f->frame.cid, ERR_INVALID_CID); continue; } if (u2f->frame.init.cmd == U2FHID_INIT) { if (MSG_LEN (u2f->frame) != sizeof (U2FHID_INIT_REQ)) { u2f_send_error (u2f, u2f->frame.cid, ERR_INVALID_LEN); continue; } if (u2f->frame.cid == u2f->cid) { uf2_reset (u2f); } u2f_send_init ( u2f, u2f->frame.cid, u2f->frame.cid == CID_BROADCAST ? u2f->next_cid : u2f->frame.cid, u2f->frame.init.data); u2f->next_cid += 2; continue; } if (FRAME_TYPE (u2f->frame) == TYPE_INIT && u2f->cid != 0 && u2f->frame.cid != u2f->cid) { u2f_send_error (u2f, u2f->frame.cid, ERR_CHANNEL_BUSY); continue; } if (FRAME_TYPE (u2f->frame) == TYPE_INIT && (u2f->cid == 0 || u2f->cid == u2f->frame.cid)) { if (u2f->cmd) { u2f_send_error (u2f, u2f->frame.cid, ERR_INVALID_SEQ); uf2_reset (u2f); continue; } if (MSG_LEN (u2f->frame) > MAX_MSGLEN) { u2f_send_error (u2f, u2f->frame.cid, ERR_INVALID_LEN); uf2_reset (u2f); continue; } u2f->cid = u2f->frame.cid; u2f->cmd = u2f->frame.init.cmd; u2f_msg_init (u2f, MSG_LEN (u2f->frame)); remain = u2f_msg_append (u2f, u2f->frame.init.data, sizeof (u2f->frame.init.data)); } else if (FRAME_TYPE (u2f->frame) == TYPE_CONT && u2f->cid == u2f->frame.cid) { if (u2f->frame.cont.seq != u2f->seq++) { u2f_send_error (u2f, u2f->frame.cid, ERR_INVALID_SEQ); uf2_reset (u2f); continue; } remain = u2f_msg_append (u2f, u2f->frame.cont.data, sizeof (u2f->frame.cont.data)); } if (remain == 0 && u2f->cmd) { uint32_t resp_len; switch (u2f->cmd) { case U2FHID_PING: u2f_send_msg (u2f, u2f->cid, U2FHID_PING, u2f->msg, u2f->msg_len); break; case U2FHID_MSG: if (u2f->msg_len > MAX_APDU_CMDLEN) { u2f_send_error (u2f, u2f->frame.cid, ERR_INVALID_LEN); uf2_reset (u2f); continue; } memcpy (u2f->apdu_cmd, u2f->msg, u2f->msg_len); memset (u2f->msg, 0, MAX_MSGLEN); u2f_apdu_command_do (u2f->apdu_cmd, u2f->msg_len, u2f->msg, &resp_len); u2f_send_msg (u2f, u2f->cid, U2FHID_MSG, u2f->msg, resp_len); break; default: u2f_send_error (u2f, u2f->cid, ERR_INVALID_CMD); } uf2_reset (u2f); } } return NULL; } struct u2f_hid * u2f_hid_open (struct usb_hid *hid) { memset (&u2f_hid, 0, sizeof (struct u2f_hid)); u2f_hid.next_cid = 0xdeadbeaf + 12; u2f_hid.hid = hid; chopstx_create (PRIO_U2F_HID, STACK_ADDR_U2F_HID, STACK_SIZE_U2F_HID, u2f_hid_main, &u2f_hid); return &u2f_hid; } ================================================ FILE: src/u2f-hid.h ================================================ #ifndef __U2F_U2F_HID_H__ #define __U2F_U2F_HID_H__ struct usb_hid; struct u2f_hid; struct u2f_hid * u2f_hid_open (struct usb_hid *hid); #endif ================================================ FILE: src/u2f.c ================================================ /* * u2f.c - main * * Copyright (C) 2017 Sergei Glushchenko * Author: Sergei Glushchenko * * This file is a part of U2F firmware for STM32 * * 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 . * * As additional permission under GNU GPL version 3 section 7, you may * distribute non-source form of the Program without the copy of the * GNU GPL normally required by section 4, provided you inform the * recipients of GNU GPL by a written offer. * */ #include #include #include #include /* For set_led */ #include "board.h" #include "sys.h" #include "usb_lld.h" #include "usb-hid.h" #include "u2f-hid.h" #include "random.h" #include "adc.h" #if defined(HAVE_PUSH_BUTTON) #include "pbt.h" #elif defined(HAVE_CAPSENSE) #include "csn.h" #else #include "uvoid.h" #endif #include "platform.h" static chopstx_mutex_t mtx; static chopstx_cond_t cnd0; static chopstx_cond_t cnd1; uint8_t v; uint8_t blink_is_on; static void * pwm (void *arg) { (void)arg; chopstx_mutex_lock (&mtx); chopstx_cond_wait (&cnd0, &mtx); chopstx_mutex_unlock (&mtx); while (1) { set_led ((blink_is_on & v) || user_presence_get ()); chopstx_usec_wait (10*1000); } return NULL; } static void * blk (void *arg) { (void)arg; int nblk = 0; chopstx_mutex_lock (&mtx); chopstx_cond_wait (&cnd1, &mtx); chopstx_mutex_unlock (&mtx); while (1) { v = 0; chopstx_usec_wait (50*1000); v = 1; chopstx_usec_wait (50*1000); if (blink_is_on) nblk++; if (nblk == 3) { nblk = 0; blink_is_on = 0; } } return NULL; } #define PRIO_PWM 7 #define PRIO_BLK 7 extern uint8_t __process1_stack_base__[], __process1_stack_size__[]; extern uint8_t __process2_stack_base__[], __process2_stack_size__[]; #define STACK_ADDR_PWM ((uint32_t)__process1_stack_base__) #define STACK_SIZE_PWM ((uint32_t)__process1_stack_size__) #define STACK_ADDR_BLK ((uint32_t)__process2_stack_base__) #define STACK_SIZE_BLK ((uint32_t)__process2_stack_size__) int main (int argc, const char *argv[]) { struct usb_hid *hid; (void)argc; (void)argv; platform_init (); chopstx_mutex_init (&mtx); chopstx_cond_init (&cnd0); chopstx_cond_init (&cnd1); chopstx_create (PRIO_PWM, STACK_ADDR_PWM, STACK_SIZE_PWM, pwm, NULL); chopstx_create (PRIO_BLK, STACK_ADDR_BLK, STACK_SIZE_BLK, blk, NULL); chopstx_mutex_lock (&mtx); chopstx_cond_signal (&cnd0); chopstx_cond_signal (&cnd1); chopstx_mutex_unlock (&mtx); blink_is_on = 1; adc_init (); random_init (); #if defined(HAVE_PUSH_BUTTON) pbt_init (); #elif defined(HAVE_CAPSENSE) capsense_init (); #else uvoid_init (); #endif flash_unlock (); chopstx_usec_wait (200*1000); hid = hid_open (); u2f_hid_open (hid); while (1) { chopstx_usec_wait (500*1000); } random_fini (); return 0; } ================================================ FILE: src/usb-hid.c ================================================ /* * usb-hid.c - HID device descriptors and communication * * Copyright (C) 2017-2019 Sergei Glushchenko * Author: Sergei Glushchenko * * This file is a part of U2F firmware for STM32F103 and EFM32HG boards * * 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 . * * As additional permission under GNU GPL version 3 section 7, you may * distribute non-source form of the Program without the copy of the * GNU GPL normally required by section 4, provided you inform the * recipients of GNU GPL by a written offer. * */ #include #include #include #include #include #include "board.h" #include "sys.h" #include "usb_lld.h" #include "usb-hid.h" #define ENDP0_RXADDR (0x040) #define ENDP0_TXADDR (0x080) #define ENDP1_RXADDR (0x0c0) #define ENDP1_TXADDR (0x100) #define HID_INTERFACE 0 #define USB_HID_REQ_GET_REPORT 1 #define USB_HID_REQ_GET_IDLE 2 #define USB_HID_REQ_GET_PROTOCOL 3 #define USB_HID_REQ_SET_REPORT 9 #define USB_HID_REQ_SET_IDLE 10 #define USB_HID_REQ_SET_PROTOCOL 11 #define USB_DT_HID 0x21 #define USB_DT_REPORT 0x22 // Size of HID reports #define HID_RPT_SIZE 64 // Default size of raw HID report static chopstx_intr_t interrupt; static uint8_t hid_idle_rate; /* in 4ms */ /* HID report descriptor. */ #define HID_REPORT_DESC_SIZE (sizeof (hid_report_desc)) static const uint8_t hid_report_desc[] = { 0x06, 0xd0, 0xf1, /* USAGE_PAGE (FIDO Alliance) */ 0x09, 0x01, /* USAGE (Keyboard) */ 0xa1, 0x01, /* COLLECTION (Application) */ 0x09, 0x20, /* USAGE (Input report data) */ 0x15, 0x00, /* LOGICAL_MINIMUM (0) */ 0x26, 0xff, 0x00, /* LOGICAL_MAXIMUM (255) */ 0x75, 0x08, /* REPORT_SIZE (8) */ 0x95, 0x40, /* REPORT_COUNT (64) */ 0x81, 0x02, /* INPUT (Data,Var,Abs); Modifier byte */ 0x09, 0x21, /* USAGE (Output report data) */ 0x15, 0x00, /* LOGICAL_MINIMUM (0) */ 0x26, 0xff, 0x00, /* LOGICAL_MAXIMUM (255) */ 0x75, 0x08, /* REPORT_SIZE (8) */ 0x95, 0x40, /* REPORT_COUNT (64) */ 0x91, 0x02, /* OUTPUT (Data,Var,Abs); Modifier byte */ 0xc0 /* END_COLLECTION */ }; /* USB Device Descriptor */ static const uint8_t u2f_device_desc[18] = { 18, /* bLength */ DEVICE_DESCRIPTOR, /* bDescriptorType */ 0x10, 0x01, /* bcdUSB = 1.1 */ 0x00, /* bDeviceClass (Unknown). */ 0x00, /* bDeviceSubClass. */ 0x00, /* bDeviceProtocol. */ 0x40, /* bMaxPacketSize. */ 0xd0, 0x16, /* idVendor */ 0x90, 0x0e, /* idProduct */ 0x00, 0x01, /* bcdDevice */ 1, /* iManufacturer. */ 2, /* iProduct. */ 3, /* iSerialNumber. */ 1 /* bNumConfigurations. */ }; #define FEATURE_BUS_POWERED 0x80 /* Configuration Descriptor tree for a HID.*/ static const uint8_t u2f_config_desc[41] = { 9, CONFIG_DESCRIPTOR, /* bDescriptorType: Configuration */ /* Configuration Descriptor.*/ 41, 0x00, /* wTotalLength. */ 0x01, /* bNumInterfaces. */ 0x01, /* bConfigurationValue. */ 0, /* iConfiguration. */ FEATURE_BUS_POWERED, /* bmAttributes. */ 50, /* bMaxPower (100mA). */ /* Interface Descriptor.*/ 9, /* bLength: Interface Descriptor size */ INTERFACE_DESCRIPTOR, /* bDescriptorType: Interface */ HID_INTERFACE, /* bInterfaceNumber: Number of Interface */ 0x00, /* bAlternateSetting: Alternate setting */ 0x02, /* bNumEndpoints: Two endpoints used */ 0x03, /* bInterfaceClass: HID */ 0x00, /* bInterfaceSubClass: no boot */ 0x00, /* bInterfaceProtocol: 0=none */ 0x04, /* iInterface */ /* HID Descriptor.*/ 9, /* bLength: HID Descriptor size */ 0x21, /* bDescriptorType: HID */ 0x10, 0x01, /* bcdHID: HID Class Spec release number */ 0x00, /* bCountryCode: Hardware target country */ 0x01, /* bNumDescriptors: Number of HID class descriptors to follow */ 0x22, /* bDescriptorType */ HID_REPORT_DESC_SIZE, 0, /* wItemLength: Total length of Report descriptor */ /*Endpoint IN1 Descriptor*/ 7, /* bLength: Endpoint Descriptor size */ ENDPOINT_DESCRIPTOR, /* bDescriptorType: Endpoint */ 0x81, /* bEndpointAddress: (IN1) */ 0x03, /* bmAttributes: Interrupt */ 0x40, 0x00, /* wMaxPacketSize: 64 */ 0x05, /* bInterval (5ms) */ /*Endpoint OUT1 Descriptor*/ 7, /* bLength: Endpoint Descriptor size */ ENDPOINT_DESCRIPTOR, /* bDescriptorType: Endpoint */ 0x01, /* bEndpointAddress: (OUT1) */ 0x03, /* bmAttributes: Interrupt */ 0x40, 0x00, /* wMaxPacketSize: 64 */ 0x05, /* bInterval (5ms) */ }; /* * U.S. English language identifier. */ static const uint8_t usb_string0[4] = { 4, /* bLength */ STRING_DESCRIPTOR, 0x09, 0x04 /* LangID = 0x0409: US-English */ }; static const uint8_t usb_string1[] = { 7*2+2, /* bLength */ STRING_DESCRIPTOR, /* bDescriptorType */ /* Manufacturer: "unknown" */ 'u', 0, 'n', 0, 'k', 0, 'n', 0, 'o', 0, 'w', 0, 'n', 0, }; static const uint8_t usb_string2[] = { 17*2+2, /* bLength */ STRING_DESCRIPTOR, /* bDescriptorType */ #if defined(MCU_EFM32HG) /* Product name: "U2F-token (EFM32)" */ 'U', 0, '2', 0, 'F', 0, '-', 0, 't', 0, 'o', 0, 'k', 0, 'e', 0, 'n', 0, ' ', 0, '(', 0, 'E', 0, 'F', 0, 'M', 0, '3', 0, '2', 0, #else /* Product name: "U2F-token (STM32)" */ 'U', 0, '2', 0, 'F', 0, '-', 0, 't', 0, 'o', 0, 'k', 0, 'e', 0, 'n', 0, ' ', 0, '(', 0, 'S', 0, 'T', 0, 'M', 0, '3', 0, '2', 0, #endif ')', 0, }; /* * Serial Number string. */ static const uint8_t usb_string3[28] = { 28, /* bLength */ STRING_DESCRIPTOR, /* bDescriptorType */ '1', 0, '.', 0, '0', 0, '0', 0, /* Version number */ }; #define NUM_INTERFACES 1 static void usb_device_reset (struct usb_dev *dev) { usb_lld_reset (dev, FEATURE_BUS_POWERED); /* Initialize Endpoint 0 */ #if defined(MCU_EFM32HG) usb_lld_setup_endp (dev, ENDP0, EP_CONTROL, 1, 1, HID_RPT_SIZE); #else usb_lld_setup_endpoint (ENDP0, EP_CONTROL, 0, ENDP0_RXADDR, ENDP0_TXADDR, HID_RPT_SIZE); #endif } static void usb_ctrl_write_finish (struct usb_dev *dev) { struct device_req *arg = &dev->dev_req; if (arg->index == HID_INTERFACE && arg->request == USB_HID_REQ_SET_REPORT) { return; } /* * The transaction was already finished. So, it is no use to call * usb_lld_ctrl_error when the condition does not match. */ } static int usb_setup (struct usb_dev *dev) { struct device_req *arg = &dev->dev_req; if (arg->index == HID_INTERFACE) { switch (arg->request) { case USB_HID_REQ_GET_IDLE: return usb_lld_ctrl_send (dev, &hid_idle_rate, 1); case USB_HID_REQ_SET_IDLE: hid_idle_rate = arg->value >> 8; return usb_lld_ctrl_ack (dev); case USB_HID_REQ_GET_REPORT: /* Reports should go via interrupt endpoint */ return -1; case USB_HID_REQ_SET_REPORT: /* Reports should go via interrupt endpoint */ return -1; case USB_HID_REQ_GET_PROTOCOL: case USB_HID_REQ_SET_PROTOCOL: /* This driver doesn't support boot protocol. */ return -1; default: return -1; } } return -1; } static int usb_get_descriptor (struct usb_dev *dev) { struct device_req *arg = &dev->dev_req; uint8_t rcp = arg->type & RECIPIENT; uint8_t desc_type = (arg->value >> 8); uint8_t desc_index = (arg->value & 0xff); if (rcp == INTERFACE_RECIPIENT) { if (arg->index == HID_INTERFACE) { if (desc_type == USB_DT_HID) return usb_lld_ctrl_send (dev, u2f_config_desc + 9 + 9, 9); else if (desc_type == USB_DT_REPORT) return usb_lld_ctrl_send (dev, hid_report_desc, HID_REPORT_DESC_SIZE); } } else if (rcp == DEVICE_RECIPIENT) { if (desc_type == DEVICE_DESCRIPTOR) return usb_lld_ctrl_send (dev, u2f_device_desc, sizeof (u2f_device_desc)); else if (desc_type == CONFIG_DESCRIPTOR) return usb_lld_ctrl_send (dev, u2f_config_desc, sizeof (u2f_config_desc)); else if (desc_type == STRING_DESCRIPTOR) { const uint8_t *str; int size; switch (desc_index) { case 0: str = usb_string0; size = sizeof (usb_string0); break; case 1: str = usb_string1; size = sizeof (usb_string1); break; case 2: str = usb_string2; size = sizeof (usb_string2); break; case 3: str = usb_string3; size = sizeof (usb_string3); break; default: return -1; } return usb_lld_ctrl_send (dev, str, size); } } return -1; } static void hid_setup_endpoints_for_interface (struct usb_dev *dev, uint16_t interface, int stop) { #if !defined(MCU_EFM32HG) (void) dev; #endif if (interface == HID_INTERFACE) { if (!stop) #if defined(MCU_EFM32HG) usb_lld_setup_endp (dev, ENDP1, EP_INTERRUPT, 1, 1, HID_RPT_SIZE); #else usb_lld_setup_endpoint (ENDP1, EP_INTERRUPT, 0, ENDP1_RXADDR, ENDP1_TXADDR, HID_RPT_SIZE); #endif else { usb_lld_stall_tx (ENDP1); usb_lld_stall_rx (ENDP1); } } } static int usb_set_configuration (struct usb_dev *dev) { int i; uint8_t current_conf; current_conf = usb_lld_current_configuration (dev); if (current_conf == 0) { if (dev->dev_req.value != 1) return -1; usb_lld_set_configuration (dev, 1); for (i = 0; i < NUM_INTERFACES; i++) hid_setup_endpoints_for_interface (dev, i, 0); } else if (current_conf != dev->dev_req.value) { if (dev->dev_req.value != 0) return -1; usb_lld_set_configuration (dev, 0); for (i = 0; i < NUM_INTERFACES; i++) hid_setup_endpoints_for_interface (dev, i, 1); } usb_lld_ctrl_ack (dev); return 0; } static int usb_set_interface (struct usb_dev *dev) { uint16_t interface = dev->dev_req.index; uint16_t alt = dev->dev_req.value; if (interface >= NUM_INTERFACES) return -1; if (alt != 0) return -1; else { hid_setup_endpoints_for_interface (dev, interface, 0); usb_lld_ctrl_ack (dev); return 0; } } static int usb_get_interface (struct usb_dev *dev) { const uint8_t zero = 0; uint16_t interface = dev->dev_req.index; if (interface >= NUM_INTERFACES) return -1; /* We don't have alternate interface, so, always return 0. */ return usb_lld_ctrl_send (dev, &zero, 1); } static int usb_get_status_interface (struct usb_dev *dev) { const uint16_t status_info = 0; uint16_t interface = dev->dev_req.index; if (interface >= NUM_INTERFACES) return -1; return usb_lld_ctrl_send (dev, &status_info, 2); } struct usb_hid { #if defined(MCU_EFM32HG) uint8_t tx_buf[HID_RPT_SIZE] __attribute__((aligned(4))); #else uint8_t *tx_buf; #endif uint8_t rx_buf[HID_RPT_SIZE] __attribute__((aligned(4))); uint16_t tx_len; uint16_t rx_len; struct eventflag cmd_ev; struct eventflag usb_ev; struct eventflag fbk_ev; }; /* cmd events */ #define EV_TX_NEED 1 /* usb events */ #define EV_RX_DATA_READY 1 /* fbk events */ #define EV_TX_FINISHED 1 /* * Rx ready callback */ static void ep1_out_received (struct usb_hid *hid, uint16_t len) { if (len <= HID_RPT_SIZE) #if defined(MCU_EFM32HG) hid->rx_len = len; #else { usb_lld_rxcpy (hid->rx_buf, 1 /*ep_num*/, 0 /*offset*/, len); hid->rx_len = len; } #endif eventflag_signal (&hid->usb_ev, EV_RX_DATA_READY); } /* * Transmit some data */ static void ep1_transmit (struct usb_hid *hid) { #if defined(MCU_EFM32HG) usb_lld_tx_enable_buf (ENDP1, hid->tx_buf, hid->tx_len); #else usb_lld_txcpy (hid->tx_buf, 1/*ep_num*/, 0 /*offset*/, hid->tx_len); usb_lld_tx_enable (1/*ep_num*/, hid->tx_len); #endif } static void usb_rx_ready (struct usb_hid *hid, uint8_t ep_num, uint16_t len) { if (ep_num == ENDP1) ep1_out_received (hid, len); } static void usb_tx_done (struct usb_hid *hid, uint8_t ep_num, uint16_t len) { (void)hid; (void)ep_num; (void)len; if (ep_num == ENDP1) { eventflag_signal (&hid->fbk_ev, EV_TX_FINISHED); } } static void usb_tx (struct usb_hid *hid, uint8_t ep_num) { if (ep_num == ENDP1) ep1_transmit (hid); } #if defined(MCU_EFM32HG) #define INTR_REQ_USB 19 #else #define INTR_REQ_USB 20 #endif #define PRIO_HID 8 extern uint8_t __process3_stack_base__[], __process3_stack_size__[]; #define STACK_ADDR_HID ((uint32_t)__process3_stack_base__) #define STACK_SIZE_HID ((uint32_t)__process3_stack_size__) static void poll_tx_intr (uint32_t *timeout, struct eventflag *ev, chopstx_intr_t *intr) { chopstx_poll_cond_t poll_desc; struct chx_poll_head *pd_array[2] = { (struct chx_poll_head *)intr, (struct chx_poll_head *)&poll_desc }; eventflag_prepare_poll (ev, &poll_desc); chopstx_poll (timeout, 2, pd_array); } static struct usb_dev dev __attribute__((aligned(4))); static void * hid_main (void *arg) { uint32_t timeout; int e; struct usb_hid *usb_hid = (struct usb_hid *) arg; memset (usb_hid, 0, sizeof (struct usb_hid)); eventflag_init (&usb_hid->cmd_ev); eventflag_init (&usb_hid->usb_ev); eventflag_init (&usb_hid->fbk_ev); chopstx_claim_irq (&interrupt, INTR_REQ_USB); usb_lld_init (&dev, FEATURE_BUS_POWERED); while (1) { eventmask_t m; timeout = 1950 * 1000; poll_tx_intr (&timeout, &usb_hid->cmd_ev, &interrupt); if (interrupt.ready) { uint8_t ep_num; /* * When interrupt is detected, call usb_lld_event_handler. * The event may be one of following: * (1) Transfer to endpoint (bulk or interrupt) * In this case EP_NUM is encoded in the variable E. * (2) "NONE" event: some trasfer was done, but all was * done by lower layer, no other work is needed in * upper layer. * (3) Device events: Reset or Suspend * (4) Device requests to the endpoint zero. * */ e = usb_lld_event_handler (&dev); ep_num = USB_EVENT_ENDP (e); if (ep_num != 0) { if (USB_EVENT_TXRX (e)) usb_tx_done (usb_hid, ep_num, USB_EVENT_LEN (e)); else usb_rx_ready (usb_hid, ep_num, USB_EVENT_LEN (e)); } else switch (USB_EVENT_ID (e)) { case USB_EVENT_DEVICE_RESET: usb_device_reset (&dev); continue; case USB_EVENT_DEVICE_ADDRESSED: /* The addres is assigned to the device. We don't * need to do anything for this actually, but in this * application, we maintain the USB status of the * device. Usually, just "continue" as EVENT_OK is * OK. */ continue; case USB_EVENT_GET_DESCRIPTOR: if (usb_get_descriptor (&dev) < 0) usb_lld_ctrl_error (&dev); continue; case USB_EVENT_SET_CONFIGURATION: if (usb_set_configuration (&dev) < 0) usb_lld_ctrl_error (&dev); continue; case USB_EVENT_SET_INTERFACE: if (usb_set_interface (&dev) < 0) usb_lld_ctrl_error (&dev); continue; case USB_EVENT_CTRL_REQUEST: /* Device specific device request. */ if (usb_setup (&dev) < 0) usb_lld_ctrl_error (&dev); continue; case USB_EVENT_GET_STATUS_INTERFACE: if (usb_get_status_interface (&dev) < 0) usb_lld_ctrl_error (&dev); continue; case USB_EVENT_GET_INTERFACE: if (usb_get_interface (&dev) < 0) usb_lld_ctrl_error (&dev); continue; case USB_EVENT_SET_FEATURE_DEVICE: case USB_EVENT_SET_FEATURE_ENDPOINT: case USB_EVENT_CLEAR_FEATURE_DEVICE: case USB_EVENT_CLEAR_FEATURE_ENDPOINT: usb_lld_ctrl_ack (&dev); continue; case USB_EVENT_CTRL_WRITE_FINISH: /* Control WRITE transfer finished. */ usb_ctrl_write_finish (&dev); continue; case USB_EVENT_OK: case USB_EVENT_DEVICE_SUSPEND: default: continue; } } m = eventflag_get (&usb_hid->cmd_ev); if (m == EV_TX_NEED) { usb_tx (usb_hid, ENDP1); } } return NULL; } static struct usb_hid usb_hid __attribute__((aligned(4))); struct usb_hid * hid_open (void) { chopstx_create (PRIO_HID, STACK_ADDR_HID, STACK_SIZE_HID, hid_main, &usb_hid); return &usb_hid; } int hid_send (struct usb_hid *usb_hid, uint8_t *buf, uint16_t len) { eventmask_t m; if (len > HID_RPT_SIZE) return -1; usb_hid->tx_len = len; #if defined(MCU_EFM32HG) memcpy (usb_hid->tx_buf, buf, len); #else usb_hid->tx_buf = buf; #endif eventflag_signal (&usb_hid->cmd_ev, EV_TX_NEED); do { m = eventflag_wait (&usb_hid->fbk_ev); } while (m != EV_TX_FINISHED); return len; } int hid_recv (struct usb_hid *usb_hid, uint8_t *buf, uint16_t len, uint32_t timeout) { eventmask_t m; #if defined(MCU_EFM32HG) usb_lld_rx_enable_buf (ENDP1, &usb_hid->rx_buf, HID_RPT_SIZE); #else usb_lld_rx_enable (ENDP1); #endif do { m = eventflag_wait_timeout (&usb_hid->usb_ev, timeout); } while (m != EV_RX_DATA_READY && m != 0); if (m == 0) return -1; if (usb_hid->rx_len <= len) { memcpy (buf, usb_hid->rx_buf, usb_hid->rx_len); return usb_hid->rx_len; } return -1; } ================================================ FILE: src/usb-hid.h ================================================ #ifndef __U2F_USB_HID_H__ #define __U2F_USB_HID_H__ struct usb_hid; struct usb_hid * hid_open (void); int hid_send (struct usb_hid *usb_hid, uint8_t *buf, uint16_t len); int hid_recv (struct usb_hid *usb_hid, uint8_t *buf, uint16_t len, uint32_t timeout); #endif ================================================ FILE: src/uvoid.c ================================================ /* * uvoid.c - void user presence indicator * * Copyright (C) 2017 Sergei Glushchenko * Author: Sergei Glushchenko * * This file is a part of U2F firmware for STM32 * * 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 . * * As additional permission under GNU GPL version 3 section 7, you may * distribute non-source form of the Program without the copy of the * GNU GPL normally required by section 4, provided you inform the * recipients of GNU GPL by a written offer. * */ #include #include #include #include #define PRIO_UVOID 2 extern uint8_t __process6_stack_base__[], __process6_stack_size__[]; #define STACK_ADDR_UVOID ((uint32_t)__process6_stack_base__) #define STACK_SIZE_UVOID ((uint32_t)__process6_stack_size__) static int touch = 1; static void * uvoid (void *arg) { (void)arg; int i; for (i = 0; i < 100; i++) chopstx_usec_wait (100*1000); touch = 0; while (1) chopstx_usec_wait (100*1000); return NULL; } int user_presence_get (void) { return touch; } void user_presence_reset (void) { touch = 0; } void uvoid_init (void) { chopstx_create (PRIO_UVOID, STACK_ADDR_UVOID, STACK_SIZE_UVOID, uvoid, NULL); } ================================================ FILE: src/uvoid.h ================================================ #ifndef __U2F_UVOID_H__ #define __U2F_UVOID_H__ int user_presence_get (void); void user_presence_reset (void); void uvoid_init (void); #endif