[
  {
    "path": ".github/workflows/c-cpp.yml",
    "content": "name: C/C++ CI\n\non:\n  push:\n    branches: [ \"master\" ]\n  pull_request:\n    branches: [ \"master\" ]\n\njobs:\n  build:\n\n    runs-on: ubuntu-latest\n\n    steps:\n    - uses: actions/checkout@v3\n      with:\n        submodules: recursive\n    - name: instal deps\n      run: |\n        pip install -r requirements.txt --user\n        sudo apt-get update\n        sudo apt-get -yy install python-pip openssl gcc-arm-none-eabi binutils-arm-none-eabi\n    - name: make\n      run: |\n        set -e\n        mkdir artifacts\n        cd src\n        for ENFORCE_DEBUG_LOCK in 1 0 ; do\n          for CUSTOM_ATTESTATION_CERT in 1 0 ; do\n            for TARGET in TOMU MAPLE_MINI BLUE_PILL BLACK_PILL ST_DONGLE ST_DONGLE_NO_PUSH ; do\n              make TARGET=${TARGET} CUSTOM_ATTESTATION_CERT=${CUSTOM_ATTESTATION_CERT} ENFORCE_DEBUG_LOCK=${ENFORCE_DEBUG_LOCK} -j4\n              if [ \"${CUSTOM_ATTESTATION_CERT}\" = 0 ] && [ \"${ENFORCE_DEBUG_LOCK}\" = 1 ] ; then\n                cp build/u2f.bin ../artifacts/u2f-${TARGET}.bin\n              fi\n              openssl ecparam -name prime256v1 -genkey -noout -outform der -out key.der\n              ./inject_key.py --key key.der --ctr 1001\n              make clean distclean certclean\n            done\n          done\n        done\n        cd ..\n"
  },
  {
    "path": ".gitignore",
    "content": "*/build\n*/.dep\ndoc/chopstx.info\n.vs/\n"
  },
  {
    "path": ".gitmodules",
    "content": "[submodule \"chopstx\"]\n\tpath = chopstx\n\turl = https://github.com/gl-sergei/chopstx.git\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: c\nsudo: required\ndist: trusty\n\naddons:\n  apt:\n    packages:\n      - python-pip\n      - openssl\n\ninstall:\n  - pip install -r requirements.txt --user\n  - sudo apt-add-repository -y ppa:team-gcc-arm-embedded/ppa\n  - sudo apt-get update\n  - sudo apt-get install -yy gcc-arm-embedded\n\nscript:\n  - |\n    set -e\n    mkdir artefacts\n    cd src\n    for ENFORCE_DEBUG_LOCK in 1 0 ; do\n      for CUSTOM_ATTESTATION_CERT in 1 0 ; do\n        for TARGET in TOMU MAPLE_MINI BLUE_PILL BLACK_PILL ST_DONGLE ST_DONGLE_NO_PUSH ; do\n          make TARGET=${TARGET} CUSTOM_ATTESTATION_CERT=${CUSTOM_ATTESTATION_CERT} ENFORCE_DEBUG_LOCK=${ENFORCE_DEBUG_LOCK} -j4\n          if [ \"${CUSTOM_ATTESTATION_CERT}\" = 0 ] && [ \"${ENFORCE_DEBUG_LOCK}\" = 1 ] ; then\n            cp build/u2f.bin ../artefacts/u2f-${TARGET}.bin\n          fi\n          openssl ecparam -name prime256v1 -genkey -noout -outform der -out key.der\n          ./inject_key.py --key key.der --ctr 1001\n          make clean distclean certclean\n        done\n      done\n    done\n    cd ..\n\ndeploy:\n  provider: releases\n  api_key:\n    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=\n  file_glob: true\n  file: artefacts/*\n  skip_cleanup: true\n  draft: true\n  on:\n    repo: gl-sergei/u2f-token\n    tags: true\n"
  },
  {
    "path": "COPYING",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU General Public License is a free, copyleft license for\nsoftware and other kinds of works.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nthe GNU General Public License is intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Use with the GNU Affero General Public License.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU Affero General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License\n    along with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU GPL, see\n<http://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<http://www.gnu.org/philosophy/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.md",
    "content": "![GitHub Workflow Status (with event)](https://img.shields.io/github/actions/workflow/status/gl-sergei/u2f-token/.github%2Fworkflows%2Fc-cpp.yml)\n![GitHub all releases](https://img.shields.io/github/downloads/gl-sergei/u2f-token/total)\n[![Latest Release](https://img.shields.io/github/release/gl-sergei/u2f-token.svg)](https://github.com/gl-sergei/u2f-token/releases/latest)\n[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)\n\n\n\n# U2F-TOKEN firmware for STM32F103 and EFM32HG boards\n\nTurns your cheap STM32F103 or EFM32HG board into U2F token.\n\n## Supported boards\n\nU2F-TOKEN is known to work on:\n\n- [Tomu board](https://tomu.im/) (EFM32HG) is an excellent device to use for U2F\n  as it can sit entirely inside of your USB port (and it is opensource)\n- Blue pill (STM32F103) as well as Black pill\n- Countless ST32F103 based Chinese St-Link V2 clones can be turned into U2F\n  devices with U2F-TOKEN\n- Variety of Maple Mini clones which can be found on Aliexpress\n\n## Udev rules\n\nOn Linux you need to add the following rules to be able to use your device as\nnon root user. Create the file `/etc/udev/rules.d/10-u2f-token.rules` (as root)\nand paste in the following lines:\n\n``` text\nACTION==\"add|change\", KERNEL==\"hidraw*\", SUBSYSTEM==\"hidraw\", ATTRS{idVendor}==\"16d0\", ATTRS{idProduct}==\"0e90\", TAG+=\"uaccess\"\nACTION==\"add|change\", SUBSYSTEM==\"usb\", ATTRS{idVendor}==\"16d0\", ATTRS{idProduct}==\"0e90\", TAG+=\"uaccess\"\n```\n\n### Using webauthn from snap packages\n\nSnap has additional security measures so that you will need to add a tag to the hidraw rule\nfor each snap app that you want to have access to the token.\n\nFor Chromium and Firefox (snap since ubuntu 21.10) this then reads:\n``` text\nACTION==\"add|change\", KERNEL==\"hidraw*\", SUBSYSTEM==\"hidraw\", ATTRS{idVendor}==\"16d0\", ATTRS{idProduct}==\"0e90\", TAG+=\"uaccess\", TAG+=\"snap_firefox_firefox\", TAG+=\"snap_chromium_chromedriver\"\n```\n\n## Installing using prebuilt release binaries\n\n### Requirements\nPython 3.6 or later and pip are needed. You will also need the `hidapi` library:\n\n* To install on OS X run `brew install hidapi`\n* To install on Ubuntu run `sudo apt install libhidapi-hidraw0 python3-hid`\n* To install on Archlinux, run `pacman -Sy hidapi`\n\nIf you are on Linux, you will also need to install the aforementioned Udev\nrules.\n\n### Flash binary\n\nDownload the binary suitable for your board at [releases page][releases].\n\n[releases]: https://github.com/gl-sergei/u2f-token/releases\n\nBinaries for Tomu are built with bootloader support, use the following command\nto flash the firmware:\n\n``` sh\ndfu-util -d 1209:70b1 -D u2f-TOMU.bin\n```\n\nBinaries for STM32 boards are built without bootloader support, you need to\nflash the firmware using SWD or JTAG interface. Example using OpenOCD and\nSTLINK-V2:\n\n``` sh\nopenocd -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'\n```\n\n(replace BLUE_PILL with appropriate board name)\n\n### Initialize device\n\nAfter flashing device with binary it requires to be initialized.\nRelease binaries come with readout protection enabled and without attestation certificate provisioned.\nTo initialize the device, clone this repository and run\n(Python 3.6+ and the hidapi library are required):\n\n``` sh\npip3 install -r requirements.txt --user\ncd src/cert\npython3 certtool init\n```\n\nYou will see something similar to:\n\n``` text\nTrying to initialize device HIDDevice:\n    USB_16d0_0e90_14100000 | 16d0:e90 | unknown | U2F-token (STM32) | 1.00\n    release_number: 256\n    usage_page: 61904\n    usage: 1\n    interface_number: -1\nSuccess\n```\n\nThe above command will upload pre-generated `attestaion.der` from this\nrepository to the device. If for whatever reason you want to use your own\ncertificate, tweak and run `./gen.sh` to generate it.\n\nTest your key with latest Chrome or Firefox browser using [this page][yubico-test].\n\n[yubico-test]: https://demo.yubico.com/webauthn-technical/\n\n## Building and flashing\n\n### Requirements\n\n#### Build tools\n\nInstall and setup Command Line tools for Xcode on macOS.\n\nInstall build-essentials package on Debian/Ubuntu:\n\n``` sh\nsudo apt install build-essential\n```\n\n#### GNU Toolchain for ARM Embedded Processors\n\nInstalling on macOS with homebrew:\n\n``` sh\nbrew tap osx-cross/arm\nbrew install arm-gcc-bin\n```\n\nInstalling on Debian/Ubuntu:\n\n``` sh\nsudo apt-add-repository ppa:team-gcc-arm-embedded/ppa\nsudo apt update\nsudo apt install gcc-arm-embedded\n```\nFor Kali Linux:\n``` sh\napt install gcc-arm-none-eabi\n```\n\n\n#### OpenSSL\n\nMacOS comes with openssl/libressl installed out of the box.\n\nInstalling on Debian/Ubuntu:\n\n``` sh\nsudo apt install openssl\n```\n\n#### asn1crypto\n\nThere is a tiny python script used to convert certificates generated by OpenSSL\nfrom DER format into C-array. It depends on asn1crypto package.\n\nTo install with pip:\n\n``` sh\npip install --user --upgrade asn1crypto\n```\n\n#### OpenOCD\n\nInstalling on macOS with homebrew:\n\n``` sh\nbrew install open-ocd\n```\n\nInstalling on Debian/Ubuntu:\n\n``` sh\nsudo apt install openocd\n```\n\n\n### Building\n\n``` sh\ngit clone https://github.com/gl-sergei/u2f-token.git\ncd u2f-token\ngit submodule update --init\ncd src\n```\n\n``` sh\nmake TARGET=<target>\n```\n\nwill produce firmware file `build/u2f.bin`.\n\nSupported targets are:\n\n- [TOMU](http://tomu.im/)\n- [MAPLE_MINI](https://wiki.stm32duino.com/index.php?title=Maple_Mini) \n- [BLUE_PILL](https://wiki.stm32duino.com/index.php?title=Blue_Pill)\n- [BLACK_PILL](https://wiki.stm32duino.com/index.php?title=Black_Pill)\n- [ST_DONGLE](https://wiki.stm32duino.com/index.php?title=ST-LINK_clone)\n- [ST_DONGLE_NO_PUSH](https://wiki.stm32duino.com/index.php?title=ST-LINK_clone)\n\nUse BLUE_PILL or BLACK_PILL for generic STM32F103 board without push button.\n\nIf build was unsuccessful for whatever reason and you want to start from scratch\nyou may want to run\n\n``` sh\nmake clean\n```\n\nto remove all object files, or\n\n``` sh\nmake certclean\n```\n\nto remove generated certificates, or\n\n``` sh\nmake distclean\n```\n\nto remove `board.h` symlink, or even all of the above.\n\n\n### Readout protection\n\nMake sure to enable readout protection if you are going to use your device as\n2FA for your accounts. Build firmware with `ENFORCE_DEBUG_LOCK=1`:\n\n``` sh\nmake clean\nmake TARGET=<target> ENFORCE_DEBUG_LOCK=1\n```\n\n### Injecting private key\n\nFirmware generates EC private key on its first boot and erases it when it\nenters the bootloader. You may want to backup your private key and make it\nsurvive firmware upgrade. To achieve this, generate the key on your host machine\nand inject it into the firmware binary.\n\nGenerate your private key:\n\n``` sh\nopenssl ecparam -name prime256v1 -genkey -noout -outform der -out key.der\n```\n\nYou may want to encrypt your `key.der` and back it up.\n\nCheck device's authentication counter if you are going to perform the firmware\nupgrade. You can see it in Yubikey demo site output. For the new device, you can\nskip `ctr` parameter all together or set it to 1. Let's say the current counter\nvalue is 1000.\n\nUse this command to patch firmware binary:\n\n``` sh\n./inject_key.py --key key.der --ctr 1001\n```\n\n### Flashing\n\n#### To STMF103 board using ST-LINK/V2 and OpenOCD\n\nStart OpenOCD:\n\n``` sh\nopenocd -f interface/stlink-v2.cfg -f target/stm32f1x.cfg\n```\n\nOn other terminal run:\n\n``` sh\ntelnet localhost 4444\n> reset halt\n> stm32f1x unlock 0\n> reset halt\n> program build/u2f.elf verify reset\n> shutdown\n```\n\n#### To EFM32HG (Tomu) board using DFU\n\nProviding you have Toboot installed:\n\n``` sh\ndfu-util -v -d 1209:70b1 -D build/u2f.bin\n```\n\nAfter flashing device you still need to initialize device as described in [Initialize device](#initialize-device)\n\n## Security considerations\n\n\n### Random number generator (RNG)\n\nU2F-TOKEN is using [Neug][neug] to generate high quality random numbers. The\nsource of entropy is built-in Analog to Digital Converter (both STM32F103 and\nEFM32HG have ones). 32-bit ADC output is passed through CRC32 35 times to get\n1120 bit input for SHA256-based whitening element.\n\n[neug]: https://www.gniibe.org/memo/development/gnuk/rng/neug.html \"Neug\"\n\nI ran [this suite][rngtest] on 1.7M of raw RNG output from Tomu board.\n\n```text\nSUMMARY\n-------\nmonobit_test                             0.119269669219     PASS\nfrequency_within_block_test              0.11518538339      PASS\nruns_test                                0.0626194973829    PASS\nlongest_run_ones_in_a_block_test         0.585067135452     PASS\nbinary_matrix_rank_test                  0.862015222632     PASS\ndft_test                                 0.965404804209     PASS\nnon_overlapping_template_matching_test   1.00000631693      PASS\noverlapping_template_matching_test       0.35076924588      PASS\nmaurers_universal_test                   0.999954925686     PASS\nlinear_complexity_test                   0.906328320146     PASS\nserial_test                              0.159775233458     PASS\napproximate_entropy_test                 0.15960828003      PASS\ncumulative_sums_test                     0.0774471722878    PASS\nrandom_excursion_test                    0.251774950817     PASS\nrandom_excursion_variant_test            0.0871834280054    PASS\n```\n\n[rngtest]: https://github.com/dj-on-github/sp800_22_tests \"SP800-22 Rev 1a PRNG test suite\"\n\n\n### Device Key\n\nDevice key is a private key for ECDSA p256r1. Any 256 bits are valid key. It is\ngenerated using RNG on first run and stored in device's flash memory. It should\nnot leave the device. You must protect your device's flash from readout to\nprotect device key (see below).\n\n\n### Key handles\n\nU2F protocol specifies two actions - register and authenticate.\n\nRegister takes appID and challenge from the caller and returns key handle,\npublic key corresponding to that key handle and attestation certificate. No one\nusually verify the validity of attestation certificate.\n\nAuthenticate takes the key handle, appID and another challenge, then it signs\nboth with the private key corresponding to the key handle. Caller then able to\ncheck if signature has been made by the same device using a public key from\nregister step. Device in turn has to make sure to refuse signing requests for\nunknown key handles and don't mess private keys corresponding to different key\nhandles.\n\nIf embedded devices would have unlimited storage, the best would be to store all\npairs of key handle and private key on the device. But it is not the case, so\nthe private key actually computed based on key handle and device key.\n\nHere is how it is done by U2F-TOKEN firmware:\n\n\n#### Register request (`app_id` is given):\n\n1. Generate random `nonce` (32 bytes)\n2. Compute `HMAC_SHA265(app_id + nonce)` using device key. Result becomes a\n   private key (32 bytes)\n3. Compute `HMAC_SHA256(private_k + app_id) + nonce`. Result becomes a key\n   handle (64 bytes)\n4. Compute public key for the private key (it's a nice feature of ECC that\n   public key can be easily computed for given private key, but it is not that\n   easy to do vice versa) and hand it out to the caller along with the key\n   handle\n\n\n#### Authenticate request (`app_id` and key handle are given):\n\n1. Extract `nonce` (last 32 bytes of key handle)\n2. Compute `HMAC_SHA256(app_id + nonce)` using device key. This is a private key\n3. Compute `HMAC_SHA256(private_k)` and compare it to the first 32 bytes of key\n   handle, they should match. If they don't, return key not found error.\n\n\nKey handle should look random for casual observer and it does. I ran the same\nsuite on 200K of key handle data generated on Tomu board:\n\n``` text\nSUMMARY\n-------\nmonobit_test                             0.228183190471     PASS\nfrequency_within_block_test              0.226128174333     PASS\nruns_test                                0.0567490131255    PASS\nlongest_run_ones_in_a_block_test         0.748631279961     PASS\nbinary_matrix_rank_test                  0.612219673314     PASS\ndft_test                                 0.553339041027     PASS\nnon_overlapping_template_matching_test   1.00000008312      PASS\noverlapping_template_matching_test       0.932591232105     PASS\nmaurers_universal_test                   0.999315334632     PASS\nlinear_complexity_test                   0.335268833847     PASS\nserial_test                              0.201711285468     PASS\napproximate_entropy_test                 0.20129897411      PASS\ncumulative_sums_test                     0.11790756896      PASS\nrandom_excursion_test                    0.199118786038     PASS\nrandom_excursion_variant_test            0.157445636324     PASS\n```\n\n\n### Tamper resistance\n\nSTM32F103 and EFM32HG devices are not tamper resistant. Highly skilled hacker\nwith the right equipment will be able to read the contents of device's flash and\nget the device key. Then he will be able to clone your device and use it as\nsecond factor to log into your account providing that he knows your passwords as\nwell.\n\nHowever, they are resistant enough for daily use as *second factor*\nauthentication device, because:\n\n1. Firmware does not allow to read flash contents by USB, neither does it disclose\n   device key\n2. Both STM32F103 and EFM32HG have \"flash readout protection\" feature. Once\n   enabled, this feature protecting flash from being read via debug interface.\n   See [this post][p1] for EFM32, and [this question][q1] for STM32F103. See also\n   `efm32 debuglock` and `stm32f1x lock` commands in [OpenOCD manual][openocd-flash].\n\n[p1]: http://community.silabs.com/t5/32-bit-MCU/Read-Write-Protection-of-Flash-and-SRAM/td-p/106405 \"readout protection\"\n[q1]: https://stackoverflow.com/q/32509747 \"readout protection\"\n[openocd-flash]: http://openocd.org/doc/html/Flash-Commands.html \"readout protection\"\n\n## License\n\nChopstx is a threading library for Cortex-M0 and Cortex-M3 processors written by\nNiibe Yutaka.\n\nECC is taken from Gnuk project by Niibe Yutaka.\n\nSome constants and memory layout structures were taken from EFM32 platform\nlibraries by Silicon Laboratories.\n\nCopyright &copy; 2017 Sergei Glushchenko\n\nThis program is free software: you can redistribute it and/or modify it\nunder the terms of the GNU General Public License as published by\nthe Free Software Foundation, either version 3 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful, but\nWITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\nGeneral Public License for more details.\n\nYou should have received a copy of the GNU General Public License\nalong with this program.  If not, see <http://www.gnu.org/licenses/>.\n\nAs additional permission under GNU GPL version 3 section 7, you may\ndistribute non-source form of the Program without the copy of the\nGNU GPL normally required by section 4, provided you inform the\nrecipients of GNU GPL by a written offer.\n"
  },
  {
    "path": "requirements.txt",
    "content": "asn1crypto\neasyhid\npyu2f\n"
  },
  {
    "path": "src/.gitignore",
    "content": "cert/opnssl.cnf\ncert/certificates.c\nboard.h\n"
  },
  {
    "path": "src/Makefile",
    "content": "# U2F firmware\n\nPROJECT = u2f\n\nCHOPSTX = ../chopstx\n\nifeq ($(TARGET),)\n\tTARGET=MAPLE_MINI\nendif\n\nifeq ($(TARGET),MAPLE_MINI)\n\tMCU      = cortex-m3\n\tCHIP     = stm32f103\n\tDRIVERS  = pbt.c\n\tDEFS     = -DUSE_SYS3 -DFREE_STANDING -DHAVE_PUSH_BUTTON -DTARGET_MAPLE_MINI\n\tLDSCRIPT = stm32f103.ld\n\tBOARD    = $(CHOPSTX)/board/board-maple-mini.h\nelse ifeq ($(TARGET),ST_DONGLE)\n\tMCU      = cortex-m3\n\tCHIP     = stm32f103\n\tDRIVERS  = pbt.c\n\tDEFS     = -DUSE_SYS3 -DFREE_STANDING -DTARGET_ST_DONGLE -DHAVE_PUSH_BUTTON\n\tLDSCRIPT = stm32f103.ld\n\tBOARD    = $(CHOPSTX)/board/board-st-dongle.h\nelse ifeq ($(TARGET),U2F_DONGLE)\n\tMCU      = cortex-m3\n\tCHIP     = stm32f103\n\tDRIVERS  = pbt.c\n\tDEFS     = -DUSE_SYS3 -DFREE_STANDING -DTARGET_U2F_DONGLE -DHAVE_PUSH_BUTTON\n\tLDSCRIPT = stm32f103.ld\n\tBOARD    = $(CHOPSTX)/board/board-u2f-dongle.h\nelse ifeq ($(TARGET),ST_DONGLE_NO_PUSH)\n\tMCU      = cortex-m3\n\tCHIP     = stm32f103\n\tDRIVERS  = uvoid.c\n\tDEFS     = -DUSE_SYS3 -DFREE_STANDING -DTARGET_ST_DONGLE\n\tLDSCRIPT = stm32f103.ld\n\tBOARD    = $(CHOPSTX)/board/board-st-dongle.h\nelse ifeq ($(TARGET),BLUE_PILL)\n\tMCU      = cortex-m3\n\tCHIP     = stm32f103\n\tDRIVERS  = uvoid.c\n\tDEFS     = -DUSE_SYS3 -DFREE_STANDING -DBLUE_PILL\n\tLDSCRIPT = stm32f103.ld\n\tBOARD    = $(CHOPSTX)/board/board-blue-pill.h\nelse ifeq ($(TARGET),BLACK_PILL)\n\tMCU      = cortex-m3\n\tCHIP     = stm32f103\n\tDRIVERS  = uvoid.c\n\tDEFS     = -DUSE_SYS3 -DFREE_STANDING -DBLACK_PILL\n\tLDSCRIPT = stm32f103.ld\n\tBOARD    = $(CHOPSTX)/board/board-black-pill.h\nelse ifeq ($(TARGET),TOMU)\n\tMCU      = cortex-m0plus\n\tCHIP     = efm32hg\n\tDRIVERS  = csn.c\n\tDEFS     = -DMAKE_ENTRY_PUBLIC -DUSE_SYS3 -DFREE_STANDING -DMHZ=21 \\\n\t           -DHAVE_CAPSENSE -DTARGET_TOMU\n\tLDSCRIPT = efm32hg.ld\n\tBOARD    = $(CHOPSTX)/board/board-tomu.h\nendif\n\nifeq ($(ENFORCE_DEBUG_LOCK),1)\nDEFS += -DENFORCE_DEBUG_LOCK\nendif\n\nifeq ($(CUSTOM_ATTESTATION_CERT),1)\n\tGENCERT_CMD = cd cert && ./gen.sh && ( python dump-der.py > certificates.c || ( rm certificates.c && exit 1 ) )  && cd ..\nelse\n\tGENCERT_CMD = cp empty-attestation-cert.c cert/certificates.c\nendif\n\nCSRC = u2f.c usb-hid.c dbug.c u2f-hid.c u2f-apdu.c \\\n\tsha256.c neug.c random.c ec_p256r1.c bn.c jpc_p256r1.c \\\n\tcall-ec_p256r1.c modp256r1.c mod.c hmac.c platform.c $(DRIVERS)\n\nUSE_SYS = yes\nUSE_USB = yes\nUSE_ADC = yes\nUSE_EVENTFLAG = yes\n\n###################################\nCROSS = arm-none-eabi-\nCC   = $(CROSS)gcc\nLD   = $(CROSS)gcc\nOBJCOPY   = $(CROSS)objcopy\n\nCWARN = -Wall -Wextra -Wstrict-prototypes\nOPT   = -O3 -Os -g\nLIBS  =\n\n####################\ninclude $(CHOPSTX)/rules.mk\n\nboard.h:\n\tln -s $(BOARD) board.h\n\ncert/certificates.c:\n\t$(GENCERT_CMD)\n\nsys.c: board.h\nu2f.c: board.h\n\nu2f-apdu.c: cert/certificates.c\n\ndistclean: clean\n\trm -f board.h\n\ncertclean:\n\trm -f cert/certificates.c\n\trm -f cert/opnssl.cnf\n\trm -f cert/*.der\n\trm -f cert/*.pem\n\trm -f cert/*.csr\n"
  },
  {
    "path": "src/affine.h",
    "content": "/**\n * @brief\tAffine coordinates\n */\ntypedef struct\n{\n  bn256 x[1];\n  bn256 y[1];\n} ac;\n"
  },
  {
    "path": "src/bn-thumb1.h",
    "content": "/*\n * bn256_mul for ARM processours without umull instruction (Cortex-M0+)\n *\n * Some parts are generated and/or copied from TomsFastMath (public domain).\n * MULADD is adopted from \"Shades of Elliptic Curve Cryptography on Embedded\n * Processors\" by Erich Wenger, Thomas Unterluggauer and Mario Werner\n *\n * Some numbers:\n *\n *   this implementation takes 1.3120s to register / 0.6837s to authenticate\n *   uECC implementation takes 1.2960s to register / 0.6758s to authenticate\n * pure C implementation takes 1.6560s to register / 0.8558s to authenticate\n */\n\n#define COMBA_START\n\n#define COMBA_CLEAR \\\n   c0 = c1 = c2 = 0;\n\n#define COMBA_FORWARD \\\n   do { c0 = c1; c1 = c2; c2 = 0; } while (0);\n\n#define COMBA_STORE(x) \\\n   x = c0;\n\n#define COMBA_STORE2(x) \\\n   x = c1;\n\n#define COMBA_FINI\n\n#define MULADD(i, j)                                       \\\nasm (                                                      \\\n   \"ldr r1, %[_i]         \\n\\t\"                            \\\n   \"ldr r2, %[_j]         \\n\\t\"                            \\\n   \"uxth r6, r1           \\n\\t\"                            \\\n   \"uxth r7, r2           \\n\\t\"                            \\\n   \"lsr r1, r1, #16       \\n\\t\"                            \\\n   \"lsr r2, r2, #16       \\n\\t\"                            \\\n                                                           \\\n   \"mov r0, r6            \\n\\t\"                            \\\n   \"mul r0, r0, r7        \\n\\t\"                            \\\n   \"mul r6, r6, r2        \\n\\t\"                            \\\n   \"mul r2, r2, r1        \\n\\t\"                            \\\n   \"mul r1, r1, r7        \\n\\t\"                            \\\n                                                           \\\n   \"mov r7, #0            \\n\\t\"                            \\\n   \"add %0, %0, r0        \\n\\t\"                            \\\n   \"adc %1, %1, r2        \\n\\t\"                            \\\n   \"adc %2, %2, r7        \\n\\t\"                            \\\n                                                           \\\n   \"lsl r0, r6, #16       \\n\\t\"                            \\\n   \"lsr r2, r6, #16       \\n\\t\"                            \\\n   \"add %0, %0, r0        \\n\\t\"                            \\\n   \"adc %1, %1, r2        \\n\\t\"                            \\\n   \"adc %2, %2, r7        \\n\\t\"                            \\\n                                                           \\\n   \"lsl r0, r1, #16       \\n\\t\"                            \\\n   \"lsr r2, r1, #16       \\n\\t\"                            \\\n   \"add %0, %0, r0        \\n\\t\"                            \\\n   \"adc %1, %1, r2        \\n\\t\"                            \\\n   \"adc %2, %2, r7        \\n\\t\"                            \\\n                                                           \\\n   :\"=l\"(c0), \"=l\"(c1), \"=l\"(c2)                           \\\n   : \"0\"(c0), \"1\"(c1), \"2\"(c2), [_i] \"m\" (i), [_j] \"m\" (j) \\\n   : \"r0\", \"r1\", \"r2\", \"r6\", \"r7\", \"cc\");\n\nstatic inline void\nbn256_mul_thumb1 (bn512 *X, const bn256 *A, const bn256 *B)\n{\n   uint32_t c0, c1, c2, at[16];\n\n   memcpy(at, A->word, 8 * sizeof(uint32_t));\n   memcpy(at+8, B->word, 8 * sizeof(uint32_t));\n   COMBA_START;\n\n   COMBA_CLEAR;\n   /* 0 */\n   MULADD(at[0], at[8]);\n   COMBA_STORE(X->word[0]);\n   /* 1 */\n   COMBA_FORWARD;\n   MULADD(at[0], at[9]);    MULADD(at[1], at[8]);\n   COMBA_STORE(X->word[1]);\n   /* 2 */\n   COMBA_FORWARD;\n   MULADD(at[0], at[10]);    MULADD(at[1], at[9]);    MULADD(at[2], at[8]);\n   COMBA_STORE(X->word[2]);\n   /* 3 */\n   COMBA_FORWARD;\n   MULADD(at[0], at[11]);    MULADD(at[1], at[10]);    MULADD(at[2], at[9]);    MULADD(at[3], at[8]);\n   COMBA_STORE(X->word[3]);\n   /* 4 */\n   COMBA_FORWARD;\n   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]);\n   COMBA_STORE(X->word[4]);\n   /* 5 */\n   COMBA_FORWARD;\n   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]);\n   COMBA_STORE(X->word[5]);\n   /* 6 */\n   COMBA_FORWARD;\n   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]);\n   COMBA_STORE(X->word[6]);\n   /* 7 */\n   COMBA_FORWARD;\n   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]);\n   COMBA_STORE(X->word[7]);\n   /* 8 */\n   COMBA_FORWARD;\n   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]);\n   COMBA_STORE(X->word[8]);\n   /* 9 */\n   COMBA_FORWARD;\n   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]);\n   COMBA_STORE(X->word[9]);\n   /* 10 */\n   COMBA_FORWARD;\n   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]);\n   COMBA_STORE(X->word[10]);\n   /* 11 */\n   COMBA_FORWARD;\n   MULADD(at[4], at[15]);    MULADD(at[5], at[14]);    MULADD(at[6], at[13]);    MULADD(at[7], at[12]);\n   COMBA_STORE(X->word[11]);\n   /* 12 */\n   COMBA_FORWARD;\n   MULADD(at[5], at[15]);    MULADD(at[6], at[14]);    MULADD(at[7], at[13]);\n   COMBA_STORE(X->word[12]);\n   /* 13 */\n   COMBA_FORWARD;\n   MULADD(at[6], at[15]);    MULADD(at[7], at[14]);\n   COMBA_STORE(X->word[13]);\n   /* 14 */\n   COMBA_FORWARD;\n   MULADD(at[7], at[15]);\n   COMBA_STORE(X->word[14]);\n   COMBA_STORE2(X->word[15]);\n   COMBA_FINI;\n}\n"
  },
  {
    "path": "src/bn.c",
    "content": "/*\n * bn.c -- 256-bit (and 512-bit) bignum calculation\n *\n * Copyright (C) 2011, 2013, 2014 Free Software Initiative of Japan\n * Author: NIIBE Yutaka <gniibe@fsij.org>\n *\n * This file is a part of Gnuk, a GnuPG USB Token implementation.\n *\n * Gnuk is free software: you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Gnuk is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public\n * License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include <stdint.h>\n#include <string.h>\n#ifndef BN256_NO_RANDOM\n#include \"random.h\"\n#endif\n#include \"bn.h\"\n\nuint32_t\nbn256_add (bn256 *X, const bn256 *A, const bn256 *B)\n{\n  int i;\n  uint32_t v;\n  uint32_t carry = 0;\n  uint32_t *px;\n  const uint32_t *pa, *pb;\n\n  px = X->word;\n  pa = A->word;\n  pb = B->word;\n\n  for (i = 0; i < BN256_WORDS; i++)\n    {\n      v = *pb;\n      *px = *pa + carry;\n      carry = (*px < carry);\n      *px += v;\n      carry += (*px < v);\n      px++;\n      pa++;\n      pb++;\n    }\n\n  return carry;\n}\n\nuint32_t\nbn256_sub (bn256 *X, const bn256 *A, const bn256 *B)\n{\n  int i;\n  uint32_t v;\n  uint32_t borrow = 0;\n  uint32_t *px;\n  const uint32_t *pa, *pb;\n\n  px = X->word;\n  pa = A->word;\n  pb = B->word;\n\n  for (i = 0; i < BN256_WORDS; i++)\n    {\n      uint32_t borrow0 = (*pa < borrow);\n\n      v = *pb;\n      *px = *pa - borrow;\n      borrow = (*px < v) + borrow0;\n      *px -= v;\n      px++;\n      pa++;\n      pb++;\n    }\n\n  return borrow;\n}\n\nuint32_t\nbn256_add_uint (bn256 *X, const bn256 *A, uint32_t w)\n{\n  int i;\n  uint32_t carry = w;\n  uint32_t *px;\n  const uint32_t *pa;\n\n  px = X->word;\n  pa = A->word;\n\n  for (i = 0; i < BN256_WORDS; i++)\n    {\n      *px = *pa + carry;\n      carry = (*px < carry);\n      px++;\n      pa++;\n    }\n\n  return carry;\n}\n\nuint32_t\nbn256_sub_uint (bn256 *X, const bn256 *A, uint32_t w)\n{\n  int i;\n  uint32_t borrow = w;\n  uint32_t *px;\n  const uint32_t *pa;\n\n  px = X->word;\n  pa = A->word;\n\n  for (i = 0; i < BN256_WORDS; i++)\n    {\n      uint32_t borrow0 = (*pa < borrow);\n\n      *px = *pa - borrow;\n      borrow = borrow0;\n      px++;\n      pa++;\n    }\n\n  return borrow;\n}\n\n#ifndef BN256_C_IMPLEMENTATION\n#define ASM_IMPLEMENTATION 1\n#endif\n\n#if defined(ASM_IMPLEMENTATION) && !defined(__thumb2__) && defined(__thumb__)\n#include \"bn-thumb1.h\"\n#endif\n\nvoid\nbn256_mul (bn512 *X, const bn256 *A, const bn256 *B)\n{\n#if defined(ASM_IMPLEMENTATION) && defined(__thumb2__)\n#include \"muladd_256.h\"\n  const uint32_t *s;\n  uint32_t *d;\n  uint32_t w;\n  uint32_t c;\n\n  memset (X->word, 0, sizeof (uint32_t)*BN256_WORDS*2);\n\n  s = A->word;  d = &X->word[0];  w = B->word[0];  MULADD_256 (s, d, w, c);\n  s = A->word;  d = &X->word[1];  w = B->word[1];  MULADD_256 (s, d, w, c);\n  s = A->word;  d = &X->word[2];  w = B->word[2];  MULADD_256 (s, d, w, c);\n  s = A->word;  d = &X->word[3];  w = B->word[3];  MULADD_256 (s, d, w, c);\n  s = A->word;  d = &X->word[4];  w = B->word[4];  MULADD_256 (s, d, w, c);\n  s = A->word;  d = &X->word[5];  w = B->word[5];  MULADD_256 (s, d, w, c);\n  s = A->word;  d = &X->word[6];  w = B->word[6];  MULADD_256 (s, d, w, c);\n  s = A->word;  d = &X->word[7];  w = B->word[7];  MULADD_256 (s, d, w, c);\n#elif defined(ASM_IMPLEMENTATION) && defined(__thumb__)\n  bn256_mul_thumb1 (X, A, B);\n#else\n  int i, j, k;\n  int i_beg, i_end;\n  uint32_t r0, r1, r2;\n\n  r0 = r1 = r2 = 0;\n  for (k = 0; k <= (BN256_WORDS - 1)*2; k++)\n    {\n      if (k < BN256_WORDS)\n\t{\n\t  i_beg = 0;\n\t  i_end = k;\n\t}\n      else\n\t{\n\t  i_beg = k - BN256_WORDS + 1;\n\t  i_end = BN256_WORDS - 1;\n\t}\n\n      for (i = i_beg; i <= i_end; i++)\n\t{\n\t  uint64_t uv;\n\t  uint32_t u, v;\n\t  uint32_t carry;\n\n\t  j = k - i;\n\n\t  uv = ((uint64_t )A->word[i])*((uint64_t )B->word[j]);\n\t  v = uv;\n\t  u = (uv >> 32);\n\t  r0 += v;\n\t  carry = (r0 < v);\n\t  r1 += carry;\n\t  carry = (r1 < carry);\n\t  r1 += u;\n\t  carry += (r1 < u);\n\t  r2 += carry;\n\t}\n\n      X->word[k] = r0;\n      r0 = r1;\n      r1 = r2;\n      r2 = 0;\n    }\n\n  X->word[k] = r0;\n#endif\n}\n\nvoid\nbn256_sqr (bn512 *X, const bn256 *A)\n{\n#if defined(ASM_IMPLEMENTATION) && defined(__thumb2__)\n  int i;\n\n  memset (X->word, 0, sizeof (bn512));\n  for (i = 0; i < BN256_WORDS; i++)\n    {\n      uint32_t *wij = &X->word[i*2];\n      const uint32_t *xj = &A->word[i];\n      uint32_t x_i = *xj++;\n      uint32_t c;\n\n      asm (/* (C,R4,R5) := w_i_i + x_i*x_i; w_i_i := R5; */\n           \"mov    %[c], #0\\n\\t\"\n           \"ldr    r5, [%[wij]]\\n\\t\"          /* R5 := w_i_i; */\n           \"mov    r4, %[c]\\n\\t\"\n           \"umlal  r5, r4, %[x_i], %[x_i]\\n\\t\"\n           \"str    r5, [%[wij]], #4\\n\\t\"\n           \"cmp    %[xj], %[x_max1]\\n\\t\"\n           \"bhi    0f\\n\\t\"\n           \"mov    r9, %[c]\\n\\t\"  /* R9 := 0, the constant ZERO from here.  */\n           \"beq    1f\\n\"\n   \"2:\\n\\t\"\n           \"ldmia  %[xj]!, { r7, r8 }\\n\\t\"\n           \"ldmia  %[wij], { r5, r6 }\\n\\t\"\n           /* (C,R4,R5) := (C,R4) + w_i_j + 2*x_i*x_j; */\n           \"umull  r7, r12, %[x_i], r7\\n\\t\"\n           \"adds   r5, r5, r4\\n\\t\"\n           \"adc    r4, %[c], r9\\n\\t\"\n           \"adds   r5, r5, r7\\n\\t\"\n           \"adcs   r4, r4, r12\\n\\t\"\n           \"adc    %[c], r9, r9\\n\\t\"\n           \"adds   r5, r5, r7\\n\\t\"\n           \"adcs   r4, r4, r12\\n\\t\"\n           \"adc    %[c], %[c], r9\\n\\t\"\n           /* (C,R4,R6) := (C,R4) + w_i_j + 2*x_i*x_j; */\n           \"adds   r6, r6, r4\\n\\t\"\n           \"adc    r4, %[c], r9\\n\\t\"\n           \"umull  r7, r12, %[x_i], r8\\n\\t\"\n           \"adds   r6, r6, r7\\n\\t\"\n           \"adcs   r4, r4, r12\\n\\t\"\n           \"adc    %[c], r9, r9\\n\\t\"\n           \"adds   r6, r6, r7\\n\\t\"\n           \"adcs   r4, r4, r12\\n\\t\"\n           \"adc    %[c], %[c], r9\\n\\t\"\n           /**/\n           \"stmia  %[wij]!, { r5, r6 }\\n\\t\"\n           \"cmp    %[xj], %[x_max1]\\n\\t\"\n           \"bcc    2b\\n\\t\"\n           \"bne    0f\\n\"\n   \"1:\\n\\t\"\n           /* (C,R4,R5) := (C,R4) + w_i_j + 2*x_i*x_j; */\n           \"ldr    r5, [%[wij]]\\n\\t\"\n           \"ldr    r6, [%[xj]], #4\\n\\t\"\n           \"adds   r5, r5, r4\\n\\t\"\n           \"adc    r4, %[c], r9\\n\\t\"\n           \"umull  r7, r12, %[x_i], r6\\n\\t\"\n           \"adds   r5, r5, r7\\n\\t\"\n           \"adcs   r4, r4, r12\\n\\t\"\n           \"adc    %[c], r9, r9\\n\\t\"\n           \"adds   r5, r5, r7\\n\\t\"\n           \"adcs   r4, r4, r12\\n\\t\"\n           \"adc    %[c], %[c], r9\\n\\t\"\n           \"str    r5, [%[wij]], #4\\n\"\n   \"0:\\n\\t\"\n           \"ldr    r5, [%[wij]]\\n\\t\"\n           \"adds   r4, r4, r5\\n\\t\"\n           \"adc    %[c], %[c], #0\\n\\t\"\n           \"str    r4, [%[wij]], #4\"\n           : [c] \"=&r\" (c), [wij] \"=r\" (wij), [xj] \"=r\" (xj)\n           : [x_i] \"r\" (x_i), [x_max1] \"r\" (&A->word[BN256_WORDS-1]),\n             \"[wij]\" (wij), \"[xj]\" (xj)\n           : \"r4\", \"r5\", \"r6\", \"r7\", \"r8\", \"r9\", \"r12\", \"memory\", \"cc\");\n\n      if (i < BN256_WORDS - 1)\n\t*wij = c;\n    }\n#elif defined(ASM_IMPLEMENTATION) && defined(__thumb__)\n  bn256_mul_thumb1 (X, A, A);\n#else\n  int i, j, k;\n  int i_beg, i_end;\n  uint32_t r0, r1, r2;\n\n  r0 = r1 = r2 = 0;\n  for (k = 0; k <= (BN256_WORDS - 1)*2; k++)\n    {\n      if (k < BN256_WORDS)\n\t{\n\t  i_beg = 0;\n\t  i_end = k/2;\n\t}\n      else\n\t{\n\t  i_beg = k - BN256_WORDS + 1;\n\t  i_end = k/2;\n\t}\n\n      for (i = i_beg; i <= i_end; i++)\n\t{\n\t  uint64_t uv;\n\t  uint32_t u, v;\n\t  uint32_t carry;\n\n\t  j = k - i;\n\n\t  uv = ((uint64_t )A->word[i])*((uint64_t )A->word[j]);\n\t  if (i < j)\n\t    {\n\t      r2 += ((uv >> 63) != 0);\n\t      uv <<= 1;\n\t    }\n\t  v = uv;\n\t  u = (uv >> 32);\n\t  r0 += v;\n\t  carry = (r0 < v);\n\t  r1 += carry;\n\t  carry = (r1 < carry);\n\t  r1 += u;\n\t  carry += (r1 < u);\n\t  r2 += carry;\n\t}\n\n      X->word[k] = r0;\n      r0 = r1;\n      r1 = r2;\n      r2 = 0;\n    }\n\n  X->word[k] = r0;\n#endif\n}\n\nuint32_t\nbn256_shift (bn256 *X, const bn256 *A, int shift)\n{\n  int i;\n  uint32_t carry = 0, next_carry;\n\n  if (shift > 0)\n    {\n      for (i = 0; i < BN256_WORDS; i++)\n\t{\n\t  next_carry = A->word[i] >> (32 - shift);\n\t  X->word[i] = (A->word[i] << shift) | carry;\n\t  carry = next_carry;\n\t}\n    }\n  else\n    {\n      shift = -shift;\n\n      for (i = BN256_WORDS - 1; i >= 0; i--)\n\t{\n\t  next_carry = A->word[i] & ((1 << shift) - 1);\n\t  X->word[i] = (A->word[i] >> shift) | (carry << (32 - shift));\n\t  carry = next_carry;\n\t}\n    }\n\n  return carry;\n}\n\nint\nbn256_is_zero (const bn256 *X)\n{\n  int i;\n  int r = 1;\n\n  for (i = 0; i < BN256_WORDS; i++)\n    r &=  (X->word[i] == 0);\n\n  return r;\n}\n\nint\nbn256_is_even (const bn256 *X)\n{\n  return !(X->word[0] & 1);\n}\n\nint\nbn256_is_ge (const bn256 *A, const bn256 *B)\n{\n  uint32_t borrow;\n  bn256 tmp[1];\n\n  borrow = bn256_sub (tmp, A, B);\n  return borrow == 0;\n}\n\n\nint\nbn256_cmp (const bn256 *A, const bn256 *B)\n{\n  uint32_t borrow;\n  int is_zero;\n  bn256 tmp[1];\n\n  borrow = bn256_sub (tmp, A, B);\n  is_zero = bn256_is_zero (tmp);\n  return is_zero ? 0 : (borrow ? -1 : 1);\n}\n\n\n#ifndef BN256_NO_RANDOM\nvoid\nbn256_random (bn256 *X)\n{\n  const uint8_t *rand = random_bytes_get ();\n\n  X->word[7] = ((uint32_t *)rand)[7];\n  X->word[6] = ((uint32_t *)rand)[6];\n  X->word[5] = ((uint32_t *)rand)[5];\n  X->word[4] = ((uint32_t *)rand)[4];\n  X->word[3] = ((uint32_t *)rand)[3];\n  X->word[2] = ((uint32_t *)rand)[2];\n  X->word[1] = ((uint32_t *)rand)[1];\n  X->word[0] = ((uint32_t *)rand)[0];\n\n  random_bytes_free (rand);\n}\n#endif\n"
  },
  {
    "path": "src/bn.h",
    "content": "#define BN256_WORDS 8\ntypedef struct bn256 {\n  uint32_t word[ BN256_WORDS ]; /* Little endian */\n} bn256;\n\n#define BN512_WORDS 16\ntypedef struct bn512 {\n  uint32_t word[ BN512_WORDS ]; /* Little endian */\n} bn512;\n\nuint32_t bn256_add (bn256 *X, const bn256 *A, const bn256 *B);\nuint32_t bn256_sub (bn256 *X, const bn256 *A, const bn256 *B);\nuint32_t bn256_add_uint (bn256 *X, const bn256 *A, uint32_t w);\nuint32_t bn256_sub_uint (bn256 *X, const bn256 *A, uint32_t w);\n\nvoid bn256_mul (bn512 *X, const bn256 *A, const bn256 *B);\nvoid bn256_sqr (bn512 *X, const bn256 *A);\nuint32_t bn256_shift (bn256 *X, const bn256 *A, int shift);\nint bn256_is_zero (const bn256 *X);\nint bn256_is_even (const bn256 *X);\nint bn256_is_ge (const bn256 *A, const bn256 *B);\nint bn256_cmp (const bn256 *A, const bn256 *B);\nvoid bn256_random (bn256 *X);\n"
  },
  {
    "path": "src/call-ec.c",
    "content": "/*\n * call-ec.c - interface between Gnuk and Elliptic curve over GF(prime)\n *\n * Copyright (C) 2013, 2014 Free Software Initiative of Japan\n * Author: NIIBE Yutaka <gniibe@fsij.org>\n *\n * This file is a part of Gnuk, a GnuPG USB Token implementation.\n *\n * Gnuk is free software: you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Gnuk is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public\n * License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"field-group-select.h\"\n\n/* We are little-endian in the computation, but the protocol is big-endian.  */\n\n#define ECDSA_BYTE_SIZE 32\n#define ECDH_BYTE_SIZE 32\n\nint\nFUNC(ecdsa_sign) (const uint8_t *hash, uint8_t *output,\n\t\t  const uint8_t *key_data)\n{\n  int i;\n  bn256 r[1], s[1], z[1], d[1];\n  uint8_t *p;\n\n  p = (uint8_t *)d;\n  for (i = 0; i < ECDSA_BYTE_SIZE; i++)\n    p[ECDSA_BYTE_SIZE - i - 1] = key_data[i];\n\n  p = (uint8_t *)z;\n  for (i = 0; i < ECDSA_BYTE_SIZE; i++)\n    p[ECDSA_BYTE_SIZE - i - 1] = hash[i];\n\n  FUNC(ecdsa) (r, s, z, d);\n  p = (uint8_t *)r;\n  for (i = 0; i < ECDSA_BYTE_SIZE; i++)\n    *output++ = p[ECDSA_BYTE_SIZE - i - 1];\n  p = (uint8_t *)s;\n  for (i = 0; i < ECDSA_BYTE_SIZE; i++)\n    *output++ = p[ECDSA_BYTE_SIZE - i - 1];\n  return 0;\n}\n\nint\nFUNC(ecc_compute_public) (const uint8_t *key_data, uint8_t *p0)\n{\n  uint8_t *p, *p1;\n  ac q[1];\n  bn256 k[1];\n  int i;\n\n  p = (uint8_t *)k;\n  for (i = 0; i < ECDSA_BYTE_SIZE; i++)\n    p[ECDSA_BYTE_SIZE - i - 1] = key_data[i];\n  if (FUNC(compute_kG) (q, k) < 0)\n    return 1;\n\n  p = p0;\n  p1 = (uint8_t *)q->x;\n  for (i = 0; i < ECDSA_BYTE_SIZE; i++)\n    *p++ = p1[ECDSA_BYTE_SIZE - i - 1];\n  p1 = (uint8_t *)q->y;\n  for (i = 0; i < ECDSA_BYTE_SIZE; i++)\n    *p++ = p1[ECDSA_BYTE_SIZE - i - 1];\n\n  return 0;\n}\n\nint\nFUNC(ecdh_decrypt) (const uint8_t *input, uint8_t *output,\n\t\t    const uint8_t *key_data)\n{\n  bn256 k[1];\n  ac X[1], P[1];\n  int i;\n  uint8_t *p0;\n  const uint8_t *p1;\n  int r;\n\n  p0 = (uint8_t *)k;\n  for (i = 0; i < ECDH_BYTE_SIZE; i++)\n    p0[ECDH_BYTE_SIZE - i - 1] = key_data[i];\n\n  p1 = input+1;\t\t\t/* skip '04' */\n  p0 = (uint8_t *)P->x;\n  for (i = 0; i < ECDH_BYTE_SIZE; i++)\n    p0[ECDH_BYTE_SIZE - i - 1] = *p1++;\n  p0 = (uint8_t *)P->y;\n  for (i = 0; i < ECDH_BYTE_SIZE; i++)\n    p0[ECDH_BYTE_SIZE - i - 1] = *p1++;\n\n  r = FUNC(compute_kP) (X, k, P);\n  if (r == 0)\n    {\n      p0 = output;\n      p1 = (const uint8_t *)X->x;\n      *p0++ = 4;\n      for (i = 0; i < ECDH_BYTE_SIZE; i++)\n\t*p0++ = p1[ECDH_BYTE_SIZE - i - 1];\n      p1 = (const uint8_t *)X->y;\n      for (i = 0; i < ECDH_BYTE_SIZE; i++)\n\t*p0++ = p1[ECDH_BYTE_SIZE - i - 1];\n    }\n\n  return r;\n}\n\n\n/**\n * @brief Check if a secret d0 is valid or not\n *\n * @param D0\tscalar D0: secret\n * @param D1\tscalar D1: secret candidate N-D0\n *\n * Return 0 on error.\n * Return -1 when D1 should be used as the secret\n * Return 1 when D0 should be used as the secret\n */\nint\nFUNC(ecc_check_secret) (const uint8_t *d0, uint8_t *d1)\n{\n  return FUNC(check_secret) ((const bn256 *)d0, (bn256 *)d1);\n}\n"
  },
  {
    "path": "src/call-ec_p256r1.c",
    "content": "/*\n * call-ec_p256r1.c - interface between Gnuk and Elliptic curve over\n *                    GF(p256r1)\n *\n * Copyright (C) 2014 Free Software Initiative of Japan\n * Author: NIIBE Yutaka <gniibe@fsij.org>\n *\n * This file is a part of Gnuk, a GnuPG USB Token implementation.\n *\n * Gnuk is free software: you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Gnuk is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public\n * License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"bn.h\"\n#include \"affine.h\"\n#include \"jpc-ac_p256r1.h\"\n#include \"ec_p256r1.h\"\n\n#define FIELD p256r1\n\n#include \"call-ec.c\"\n"
  },
  {
    "path": "src/cert/attestation.pem",
    "content": "-----BEGIN CERTIFICATE-----\nMIIBTzCB9qADAgECAgkAk23OEsqXqkowCgYIKoZIzj0EAwIwITELMAkGA1UEBhMC\nVVMxEjAQBgNVBAMMCVUyRiBUb2tlbjAeFw0xOTAzMTAxMjA2NTZaFw0yOTAzMDcx\nMjA2NTZaMCExCzAJBgNVBAYTAlVTMRIwEAYDVQQDDAlVMkYgVG9rZW4wWTATBgcq\nhkjOPQIBBggqhkjOPQMBBwNCAAQmAqzENDN9eViFl5uuJBsQWKROfrFtAN7c/wSf\nzwAYrQqMlqwSKPdTBq3+dcbVfETTwjBdZR/lIdAvfqHHJI//oxcwFTATBgsrBgEE\nAYLlHAIBAQQEAwIFIDAKBggqhkjOPQQDAgNIADBFAiB0IvcCgmbDTSYuHN4oDbc2\n0pww4UyBYOeju3hkQO6+PQIhAJFLv29sWYypzdI4WyPdOpiSUWkH3Jni08FkAdJL\nZZkT\n-----END CERTIFICATE-----\n"
  },
  {
    "path": "src/cert/attestation_key.pem",
    "content": "-----BEGIN EC PARAMETERS-----\nBggqhkjOPQMBBw==\n-----END EC PARAMETERS-----\n-----BEGIN EC PRIVATE KEY-----\nMHcCAQEEIAV6k2UmLr8tw/+bt8m+7mWdhatCToLIm/dChWIXfeswoAoGCCqGSM49\nAwEHoUQDQgAEJgKsxDQzfXlYhZebriQbEFikTn6xbQDe3P8En88AGK0KjJasEij3\nUwat/nXG1XxE08IwXWUf5SHQL36hxySP/w==\n-----END EC PRIVATE KEY-----\n"
  },
  {
    "path": "src/cert/certtool",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# certtool - Initialize U2F-token with attestation certificate\n#\n# Copyright (C) 2019 Sergei Glushchenko\n# Author: Sergei Glushchenko <gl.sergei@gmail.com>\n#\n# This file is a part of U2F firmware for STM32 and EFM32HG\n#\n# This program is free software: you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n#\n# As additional permission under GNU GPL version 3 section 7, you may\n# distribute non-source form of the Program without the copy of the\n# GNU GPL normally required by section 4, provided you inform the\n# recipients of GNU GPL by a written offer.\n\nimport easyhid\nimport struct\nimport secrets\nimport argparse\n\nfrom asn1crypto.keys import ECPrivateKey\n\nFIDO_USAGE_PAGE = 0xF1D0\nU2F_USAGE = 1\nHID_RPT_SIZE = 64\n\nCMD_INIT = 0x06\nCMD_MSG = 0x03\nCMD_ERROR = 0x3f\n\nVID = 0x16d0\nPID = 0x0e90\n\nBROADCAST_CID = 0xffffffff\n\ndef sendCommand(dev, channel, cmd, data):\n    msg = struct.pack('>IBH', channel, cmd | 0x80, len(data))\n    msg += data[:HID_RPT_SIZE - 7]\n    data = data[HID_RPT_SIZE - 7:]\n    dev.write(msg)\n    seq = 0\n    while data:\n        msg = struct.pack('>IB', channel, seq)\n        msg += data[:HID_RPT_SIZE - 5]\n        data = data[HID_RPT_SIZE - 5:]\n        dev.write(msg)\n        seq += 1\n\ndef recvResponse(dev, channel):\n    data = dev.read()\n    ret_channel, cmd, len = struct.unpack(\">IBH\", data[:7])\n    if ret_channel != channel:\n        raise Exception(\"Wrong channel\")\n    if cmd == CMD_ERROR | 0x80:\n        raise Exception(\"HID Error: {:d}\".format(data[6]))\n    return data[7:7+len]\n\ndef init(dev):\n    dev.open()\n    nonce = secrets.token_bytes(8)\n    sendCommand(dev, BROADCAST_CID, CMD_INIT, nonce)\n    data = recvResponse(dev, BROADCAST_CID)\n    if data[:8] != nonce:\n        raise Exception(\"Invalid nonce\")\n    channel, = struct.unpack(\">I\", data[8:8+4])\n    return channel\n\ndef put_cert(dev, cert, key):\n    channel = init(dev)\n    cla, ins, p1, p2 = 0, 0x40, 0, 0\n    Lc = len(cert) + len(key)\n    data = struct.pack('>BBBBBH', cla, ins, p1, p2, 0, Lc)\n    data += key + cert\n    sendCommand(dev, channel, CMD_MSG, data)\n    data = recvResponse(dev, channel)\n    if data != b'\\x90\\x00':\n        raise Exception(\"APDU Error: \" + data.hex())\n\ndef load_key(pk_der):\n    pk = ECPrivateKey.load(pk_der)\n    pk_hex = format(pk['private_key'].native, '064x')\n    return bytes.fromhex(pk_hex)\n\ndef command_list(args):\n    e = easyhid.Enumeration()\n    devices = [ dev for dev in e.find() if dev.vendor_id == VID and dev.product_id == PID ]\n\n    for dev in devices:\n        print(dev.description())\n\ndef command_init(args):\n    e = easyhid.Enumeration()\n    devices = [ dev for dev in e.find() if dev.vendor_id == VID and dev.product_id == PID ]\n\n    if len(devices) < 1:\n        raise Exception(\"No U2F devices found\")\n\n    with open(args.certificate, \"rb\") as f:\n        cert = f.read()\n\n    with open(args.key, \"rb\") as f:\n        key = load_key(f.read())\n\n    for dev in devices:\n        print(\"Trying to initialize device {}\".format(dev.description()))\n        try:\n            put_cert(dev, cert, key)\n            print('Success')\n        except Exception as e:\n            print(e)\n\ndef main():\n    parser = argparse.ArgumentParser(\n        description=\"Initialize U2F-token with attestation certificate\")\n    subparsers = parser.add_subparsers(help='available commands')\n    parser_list = subparsers.add_parser('list', help='list U2F devices')\n    parser_list.set_defaults(func=command_list)\n    parser_init = subparsers.add_parser('init', help='init U2F devices')\n    parser_init.add_argument(\"--certificate\", default=\"attestation.der\",\n                             help=\"attestation certificate in DER format\")\n    parser_init.add_argument(\"--key\", default=\"attestation_key.der\",\n                             help=\"attestation certificate key in DER format\")\n    parser_init.set_defaults(func=command_init)\n    args = parser.parse_args()\n\n    args.func(args)\n\nif __name__ == \"__main__\":\n    main()\n"
  },
  {
    "path": "src/cert/csr.csr",
    "content": "-----BEGIN CERTIFICATE REQUEST-----\nMIHbMIGDAgEAMCExCzAJBgNVBAYTAlVTMRIwEAYDVQQDDAlVMkYgVG9rZW4wWTAT\nBgcqhkjOPQIBBggqhkjOPQMBBwNCAAQmAqzENDN9eViFl5uuJBsQWKROfrFtAN7c\n/wSfzwAYrQqMlqwSKPdTBq3+dcbVfETTwjBdZR/lIdAvfqHHJI//oAAwCgYIKoZI\nzj0EAwIDRwAwRAIgdTIhqIC351IBcpkXhZxoCa2CcFgE/YSXUJIu5Z0VU8ECIAT4\nC85tQCenIO6q9dDb6lXrnAaT0xEf+sb5rkxJKjoO\n-----END CERTIFICATE REQUEST-----\n"
  },
  {
    "path": "src/cert/dump-der.py",
    "content": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# dump-der.py - convert DER encoded certificate and EC key into C header\n#\n# Copyright (C) 2017-2019 Sergei Glushchenko\n# Author: Sergei Glushchenko <gl.sergei@gmail.com>\n#\n# This file is a part of U2F firmware for STM32 and EFM32HG\n#\n# This program is free software: you can redistribute it and/or modify it\n# under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful, but\n# WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n# General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program.  If not, see <http://www.gnu.org/licenses/>.\n#\n# As additional permission under GNU GPL version 3 section 7, you may\n# distribute non-source form of the Program without the copy of the\n# GNU GPL normally required by section 4, provided you inform the\n# recipients of GNU GPL by a written offer.\n\nfrom __future__ import print_function\nfrom asn1crypto.keys import ECPrivateKey\n\nattestation_cert_def = '''\nstruct attestation_cert  __attribute__ ((section(\".attestation.cert\"))) attestation_cert = {{\n  .hdr = {{\n    .der_len = ATTESTATION_DER_LEN,\n    .der = attestation_cert.data,\n    .key = attestation_cert.data + ATTESTATION_DER_LEN,\n  }},\n  .data = {{{}}}\n}};'''\n\ndef pk_to_hex_bytes(name, pk_der):\n    # parse der format\n    pk = ECPrivateKey.load(pk_der)\n\n    # extract private key\n    pk_native = pk['private_key'].native\n\n    # translate to hex string\n    pk_hex = format(pk_native, '064x')\n\n    # split by pairs of characters\n    hex_bytes = [\"0x\" + pk_hex[i:i + 2] for i in range(0, len(pk_hex), 2)]\n\n    return hex_bytes\n\ndef cert_to_hex_bytes(name, der):\n    if hasattr(der, 'hex'):\n        hex_str = der.hex()\n    else:\n        hex_str = der.encode('hex')\n    hex_bytes = [\"0x\" + hex_str[i:i + 2] for i in range(0, len(hex_str), 2)]\n\n    return hex_bytes\n\nwith open(\"attestation.der\", \"rb\") as f:\n    cert_bytes = cert_to_hex_bytes(\"attestation_der\", f.read())\nwith open(\"attestation_key.der\", \"rb\") as f:\n    key_bytes = pk_to_hex_bytes(\"attestation_key\", f.read())\n\nprint(\"#define ATTESTATION_DER_LEN {}\".format(len(cert_bytes)))\nprint(attestation_cert_def.format(\", \".join(cert_bytes + key_bytes + ['0x0'] * (1024 - 12 - len(cert_bytes) - len(key_bytes)))))\n\n"
  },
  {
    "path": "src/cert/gen.sh",
    "content": "#!/usr/bin/env bash\n\nset -e\n\ncat > opnssl.cnf <<EOF\n\n[req]\nx509_extensions = usr_cert\n\n[usr_cert]\n1.3.6.1.4.1.45724.2.1.1=ASN1:FORMAT:BITLIST,BITSTRING:2\n\nEOF\n\n# generate key and self-signed certificate\nopenssl ecparam -genkey -name prime256v1 -out attestation_key.pem\nopenssl req -new -sha256 -key attestation_key.pem -out csr.csr -subj \"/C=US/CN=U2F Token\"\nopenssl req -config opnssl.cnf -x509 -sha256 -days 3650 -key attestation_key.pem -in csr.csr -out attestation.pem\n\n# convert to der\nopenssl x509 -outform der -in attestation.pem -out attestation.der\nopenssl ec -in attestation_key.pem -outform der -out attestation_key.der\n"
  },
  {
    "path": "src/csn.c",
    "content": "/*\n * csn.c - capsense driver and user presence indicator\n *\n * Copyright (C) 2017 Sergei Glushchenko\n * Author: Sergei Glushchenko <gl.sergei@gmail.com>\n *\n * This file is a part of U2F firmware for EFM32\n *\n * This program is free software: you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n * As additional permission under GNU GPL version 3 section 7, you may\n * distribute non-source form of the Program without the copy of the\n * GNU GPL normally required by section 4, provided you inform the\n * recipients of GNU GPL by a written offer.\n *\n */\n\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n#include <chopstx.h>\n\n#include \"board.h\"\n#include \"sys.h\"\n\n#include <mcu/efm32hg.h>\n\n#define MASKED_WRITE(reg, mask, val) { (reg) = (((reg) & ~(mask)) | (val)); }\n\n#define INTR_REQ_TIMER0 2\n#define INTR_REQ_TIMER1 7\n#define PRIO_CSN 8\n\nextern uint8_t __process6_stack_base__[], __process6_stack_size__[];\n\n#define STACK_ADDR_CSN ((uint32_t)__process6_stack_base__)\n#define STACK_SIZE_CSN ((uint32_t)__process6_stack_size__)\n\nstatic uint32_t present = 0;\nstatic uint32_t count_max[2] = {0, 0};\n\nstatic chopstx_intr_t timer1_intr;\n\nstatic void\nmeasure_start (int ch)\n{\n  /* select channel */\n  MASKED_WRITE(ACMP0->INPUTSEL, 0x07, ch);\n\n  /* reset and start timers */\n  TIMER0->CNT = 0;\n  TIMER1->CNT = 0;\n  TIMER0->CMD = (1 << 0);  /* start */\n  TIMER1->CMD = (1 << 0);  /* start */\n}\n\nstatic uint32_t\nmeasure_stop (void)\n{\n  TIMER0->CMD = (1 << 1);  /* stop */\n  TIMER1->CMD = (1 << 1);  /* stop */\n\n  TIMER1->IFC = 1; /* clear interrupt flag */\n\n  return TIMER0->CNT;\n}\n\nstatic void *\ncsn (void *arg)\n{\n  int ch = 0;\n  int since_last_touch = 0;\n\n  (void)arg;\n\n  chopstx_claim_irq (&timer1_intr, INTR_REQ_TIMER1);\n\n  measure_start (ch);\n\n  while (1)\n    {\n      uint32_t touch = 0;\n\n      struct chx_poll_head *pd_array[1] = {\n        (struct chx_poll_head *)&timer1_intr\n      };\n\n      chopstx_poll (NULL, 1, pd_array);\n\n      if (timer1_intr.ready)\n        {\n          uint32_t count;\n          uint32_t threshold;\n\n          count = measure_stop ();\n\n          threshold = count_max[ch] - count_max[ch] / 2;\n          if (count > 0 && count < threshold)\n            touch |= 1 << ch;\n          else\n            touch &= ~(1 << ch);\n\n          if (count > threshold)\n            count_max[ch] = (count_max[ch] + count) / 2;\n\n          if (present > 0)\n            --present;\n\n          if (touch)\n            {\n              if (since_last_touch > 10)\n                {\n                  if (present > 0)\n                    present = 0;   /* clear user presence */\n                  else\n                    present = 500; /* set user presence for 10 seconds */\n                }\n              since_last_touch = 0;\n            }\n          else\n            ++since_last_touch;\n\n          if (since_last_touch > 1000)\n            since_last_touch = 1000;\n\n          ch ^= 1;\n\n          measure_start (ch);\n        }\n    }\n\n  return NULL;\n}\n\nint\nuser_presence_get (void)\n{\n  return (present > 0);\n}\n\nvoid\nuser_presence_reset (void)\n{\n  present = 0;\n}\n\nvoid\ncapsense_init (void)\n{\n  CMU->HFPERCLKEN0 |= CMU_HFPERCLKEN0_ACMP0\n                      | CMU_HFPERCLKEN0_TIMER0 | CMU_HFPERCLKEN0_PRS\n                      | CMU_HFPERCLKEN0_TIMER1;\n\n  /* Set control register. No need to set interrupt modes */\n  ACMP0->CTRL = (0x0 << 31)    /* FULLBIAS */\n                | (0x0 << 30)  /* HALFBIAS */\n                | (0x7 << 24)  /* BIASPROG */\n                | (0x7 <<  8)  /* WARMTIME */\n                | (0x5 <<  4); /* HYSTSEL */\n\n  /* Select capacative sensing mode by selecting a resistor and enabling it */\n  ACMP0->INPUTSEL= (0x03 << 28)   /* CSRESSEL */\n                   | (0x01 << 24) /* CSRESEN */\n                   | (0x00 << 16) /* LPREF */\n                   | (0x3d <<  8) /* VDDLEVEL */\n                   | (0x0B <<  4);/* NEGSEL = CAPSENSE */\n\n  /* Enable ACMP if requested. */\n  MASKED_WRITE(ACMP0->CTRL, 0x1, 1);\n\n  MASKED_WRITE(ACMP0->INPUTSEL, 0x07, 0);\n\n  while (!(ACMP0->STATUS & 0x1 /* ACMPACT */)) {};\n\n  /* Initialize TIMER0 - Prescaler 2^10, clock source CC1, top value 0xFFFF */\n  TIMER0->CTRL = (0xA << 24)               /* PRESC = DIV1024 */\n                 | (1 << 16);              /* CLKSEL = CC1 */\n  TIMER0->TOP  = 0xFFFF;\n\n  /*Set up TIMER0 CC1 to trigger on PRS ch 0 */\n  TIMER0->CC[1].CTRL = (1 << 0)            /* MODE = INPUTCAPTURE */\n                       | (0 << 16)         /* PRSSEL = PRSCH0 */\n                       | (1 << 20)         /* INSEL = PRS */\n                       | (2 << 26)         /* ICEVCTRL = RISING */\n                       | (2 << 24);        /* ICEDGE = BOTH */\n\n  /* Set up PRS ch 0 to trigger on ACMP0 output */\n  PRS->CH[0].CTRL = (1 << 24)              /* EDSEL = POSEDGE */\n                    | (2 << 16)            /* SOURCESEL = ACMP0 */\n                    | (0 << 0);            /* SIGSEL = ACMP0OUT */\n\n  /* Initialize TIMER1 - Prescaler 2^10, top value 40 * MHZ,\n  interrupt on overflow */\n  TIMER1->CTRL = (0xa << 24);  /* PRESC_DIV1024 */\n  TIMER1->TOP  = 40 * MHZ;\n  TIMER1->IEN  = (1 << 0);     /* IEN_OF */\n  TIMER1->CNT  = 0;\n\n  chopstx_create (PRIO_CSN, STACK_ADDR_CSN, STACK_SIZE_CSN, csn, NULL);\n}\n"
  },
  {
    "path": "src/csn.h",
    "content": "#ifndef __U2F_CSN_H__\n\n#define __U2F_CSN_H__\n\nint\nuser_presence_get (void);\n\nvoid\nuser_presence_reset (void);\n\nvoid\ncapsense_init (void);\n\n#endif\n"
  },
  {
    "path": "src/dbug.c",
    "content": "/*\n * dbug.c - debugging routines\n *\n * Copyright (C) 2017 Sergei Glushchenko\n * Author: Sergei Glushchenko <gl.sergei@gmail.com>\n *\n * This file is a part of U2F firmware for STM32\n *\n * This program is free software: you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n * As additional permission under GNU GPL version 3 section 7, you may\n * distribute non-source form of the Program without the copy of the\n * GNU GPL normally required by section 4, provided you inform the\n * recipients of GNU GPL by a written offer.\n *\n */\n\n#include <stdint.h>\n#include <string.h>\n\n/* some debugging routines */\nvoid\ndbg_send_command (int command, void *message)\n{\n  asm (\"mov r0, %[cmd];\"\n       \"mov r1, %[msg];\"\n       \"bkpt #0xAB\"\n       :\n       : [cmd] \"r\" (command), [msg] \"r\" (message)\n       : \"r0\", \"r1\", \"memory\");\n}\n\nvoid\ndbg_print(const char *text)\n{\n  uint32_t msg[3];\n\n  msg[0] = 2 /*stderr*/;\n  msg[1] = (uint32_t) text;\n  msg[2] = strlen(text);\n\n  dbg_send_command (0x05, msg);\n}\n"
  },
  {
    "path": "src/dbug.h",
    "content": "#ifndef __U2F_DBUG_H__\n\n#define __U2F_DBUG_H__\n\nvoid\ndbg_send_command (int command, void *message);\n\nvoid\ndbg_print(const char *text);\n\n#endif\n"
  },
  {
    "path": "src/ec_p256r1.c",
    "content": "/*                                                    -*- coding: utf-8 -*-\n * ec_p256r1.c - Elliptic curve over GF(p256r1)\n *\n * Copyright (C) 2014 Free Software Initiative of Japan\n * Author: NIIBE Yutaka <gniibe@fsij.org>\n *\n * This file is a part of Gnuk, a GnuPG USB Token implementation.\n *\n * Gnuk is free software: you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Gnuk is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public\n * License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include <stdint.h>\n#include <string.h>\n#include \"bn.h\"\n#include \"modp256r1.h\"\n#include \"affine.h\"\n#include \"jpc-ac_p256r1.h\"\n#include \"mod.h\"\n#include \"ec_p256r1.h\"\n\n#define FIELD p256r1\n#define COEFFICIENT_A_IS_MINUS_3 1\n\n/*\n * a = -3 mod p256r1\n */\nstatic const bn256 coefficient_a[1] = {\n  {{  0xfffffffc, 0xffffffff, 0xffffffff, 0x00000000,\n      0x00000000, 0x00000000, 0x00000001, 0xffffffff }}\n};\n\nstatic const bn256 coefficient_b[1] = {\n  {{ 0x27d2604b, 0x3bce3c3e, 0xcc53b0f6, 0x651d06b0,\n     0x769886bc, 0xb3ebbd55, 0xaa3a93e7, 0x5ac635d8 }}\n};\n\n\nstatic const ac precomputed_KG[15] = {\n  {\n    {{{ 0xd898c296, 0xf4a13945, 0x2deb33a0, 0x77037d81,\n\t0x63a440f2, 0xf8bce6e5, 0xe12c4247, 0x6b17d1f2 }}},\n    {{{ 0x37bf51f5, 0xcbb64068, 0x6b315ece, 0x2bce3357,\n\t0x7c0f9e16, 0x8ee7eb4a, 0xfe1a7f9b, 0x4fe342e2 }}}\n  }, {\n    {{{ 0x8e14db63, 0x90e75cb4, 0xad651f7e, 0x29493baa,\n\t0x326e25de, 0x8492592e, 0x2811aaa5, 0x0fa822bc }}},\n    {{{ 0x5f462ee7, 0xe4112454, 0x50fe82f5, 0x34b1a650,\n\t0xb3df188b, 0x6f4ad4bc, 0xf5dba80d, 0xbff44ae8 }}}\n  }, {\n    {{{ 0x097992af, 0x93391ce2, 0x0d35f1fa, 0xe96c98fd,\n\t0x95e02789, 0xb257c0de, 0x89d6726f, 0x300a4bbc }}},\n    {{{ 0xc08127a0, 0xaa54a291, 0xa9d806a5, 0x5bb1eead,\n\t0xff1e3c6f, 0x7f1ddb25, 0xd09b4644, 0x72aac7e0 }}}\n  }, {\n    {{{ 0xd789bd85, 0x57c84fc9, 0xc297eac3, 0xfc35ff7d,\n\t0x88c6766e, 0xfb982fd5, 0xeedb5e67, 0x447d739b }}},\n    {{{ 0x72e25b32, 0x0c7e33c9, 0xa7fae500, 0x3d349b95,\n\t0x3a4aaff7, 0xe12e9d95, 0x834131ee, 0x2d4825ab }}}\n  }, {\n    {{{ 0x2a1d367f, 0x13949c93, 0x1a0a11b7, 0xef7fbd2b,\n\t0xb91dfc60, 0xddc6068b, 0x8a9c72ff, 0xef951932 }}},\n    {{{ 0x7376d8a8, 0x196035a7, 0x95ca1740, 0x23183b08,\n\t0x022c219c, 0xc1ee9807, 0x7dbb2c9b, 0x611e9fc3 }}}\n  }, {\n    {{{ 0x0b57f4bc, 0xcae2b192, 0xc6c9bc36, 0x2936df5e,\n\t0xe11238bf, 0x7dea6482, 0x7b51f5d8, 0x55066379 }}},\n    {{{ 0x348a964c, 0x44ffe216, 0xdbdefbe1, 0x9fb3d576,\n\t0x8d9d50e5, 0x0afa4001, 0x8aecb851, 0x15716484 }}}\n  }, {\n    {{{ 0xfc5cde01, 0xe48ecaff, 0x0d715f26, 0x7ccd84e7,\n\t0xf43e4391, 0xa2e8f483, 0xb21141ea, 0xeb5d7745 }}},\n    {{{ 0x731a3479, 0xcac917e2, 0x2844b645, 0x85f22cfe,\n\t0x58006cee, 0x0990e6a1, 0xdbecc17b, 0xeafd72eb }}}\n  }, {\n    {{{ 0x313728be, 0x6cf20ffb, 0xa3c6b94a, 0x96439591,\n\t0x44315fc5, 0x2736ff83, 0xa7849276, 0xa6d39677 }}},\n    {{{ 0xc357f5f4, 0xf2bab833, 0x2284059b, 0x824a920c,\n\t0x2d27ecdf, 0x66b8babd, 0x9b0b8816, 0x674f8474 }}}\n  }, {\n    {{{ 0x677c8a3e, 0x2df48c04, 0x0203a56b, 0x74e02f08,\n\t0xb8c7fedb, 0x31855f7d, 0x72c9ddad, 0x4e769e76 }}},\n    {{{ 0xb824bbb0, 0xa4c36165, 0x3b9122a5, 0xfb9ae16f,\n\t0x06947281, 0x1ec00572, 0xde830663, 0x42b99082 }}}\n  }, {\n    {{{ 0xdda868b9, 0x6ef95150, 0x9c0ce131, 0xd1f89e79,\n\t0x08a1c478, 0x7fdc1ca0, 0x1c6ce04d, 0x78878ef6 }}},\n    {{{ 0x1fe0d976, 0x9c62b912, 0xbde08d4f, 0x6ace570e,\n\t0x12309def, 0xde53142c, 0x7b72c321, 0xb6cb3f5d }}}\n  }, {\n    {{{ 0xc31a3573, 0x7f991ed2, 0xd54fb496, 0x5b82dd5b,\n\t0x812ffcae, 0x595c5220, 0x716b1287, 0x0c88bc4d }}},\n    {{{ 0x5f48aca8, 0x3a57bf63, 0xdf2564f3, 0x7c8181f4,\n\t0x9c04e6aa, 0x18d1b5b3, 0xf3901dc6, 0xdd5ddea3 }}}\n  }, {\n    {{{ 0x3e72ad0c, 0xe96a79fb, 0x42ba792f, 0x43a0a28c,\n\t0x083e49f3, 0xefe0a423, 0x6b317466, 0x68f344af }}},\n    {{{ 0x3fb24d4a, 0xcdfe17db, 0x71f5c626, 0x668bfc22,\n\t0x24d67ff3, 0x604ed93c, 0xf8540a20, 0x31b9c405 }}}\n  }, {\n    {{{ 0xa2582e7f, 0xd36b4789, 0x4ec39c28, 0xd1a1014,\n\t0xedbad7a0, 0x663c62c3, 0x6f461db9, 0x4052bf4b }}},\n    {{{ 0x188d25eb, 0x235a27c3, 0x99bfcc5b, 0xe724f339,\n\t0x71d70cc8, 0x862be6bd, 0x90b0fc61, 0xfecf4d51 }}}\n  }, {\n    {{{ 0xa1d4cfac, 0x74346c10, 0x8526a7a4, 0xafdf5cc0,\n\t0xf62bff7a, 0x123202a8, 0xc802e41a, 0x1eddbae2 }}},\n    {{{ 0xd603f844, 0x8fa0af2d, 0x4c701917, 0x36e06b7e,\n\t0x73db33a0, 0x0c45f452, 0x560ebcfc, 0x43104d86 }}}\n  }, {\n    {{{ 0x0d1d78e5, 0x9615b511, 0x25c4744b, 0x66b0de32,\n\t0x6aaf363a, 0x0a4a46fb, 0x84f7a21c, 0xb48e26b4 }}},\n    {{{ 0x21a01b2d, 0x06ebb0f6, 0x8b7b0f98, 0xc004e404,\n\t0xfed6f668, 0x64131bcd, 0x4d4d3dab, 0xfac01540 }}}\n  }\n};\n\nstatic const ac precomputed_2E_KG[15] = {\n  {\n    {{{ 0x185a5943, 0x3a5a9e22, 0x5c65dfb6, 0x1ab91936,\n\t0x262c71da, 0x21656b32, 0xaf22af89, 0x7fe36b40 }}},\n    {{{ 0x699ca101, 0xd50d152c, 0x7b8af212, 0x74b3d586,\n\t0x07dca6f1, 0x9f09f404, 0x25b63624, 0xe697d458 }}}\n  }, {\n    {{{ 0x7512218e, 0xa84aa939, 0x74ca0141, 0xe9a521b0,\n\t0x18a2e902, 0x57880b3a, 0x12a677a6, 0x4a5b5066 }}},\n    {{{ 0x4c4f3840, 0x0beada7a, 0x19e26d9d, 0x626db154,\n\t0xe1627d40, 0xc42604fb, 0xeac089f1, 0xeb13461c }}}\n  }, {\n    {{{ 0x27a43281, 0xf9faed09, 0x4103ecbc, 0x5e52c414,\n\t0xa815c857, 0xc342967a, 0x1c6a220a, 0x0781b829 }}},\n    {{{ 0xeac55f80, 0x5a8343ce, 0xe54a05e3, 0x88f80eee,\n\t0x12916434, 0x97b2a14f, 0xf0151593, 0x690cde8d }}}\n  }, {\n    {{{ 0xf7f82f2a, 0xaee9c75d, 0x4afdf43a, 0x9e4c3587,\n\t0x37371326, 0xf5622df4, 0x6ec73617, 0x8a535f56 }}},\n    {{{ 0x223094b7, 0xc5f9a0ac, 0x4c8c7669, 0xcde53386,\n\t0x085a92bf, 0x37e02819, 0x68b08bd7, 0x0455c084 }}}\n  }, {\n    {{{ 0x9477b5d9, 0x0c0a6e2c, 0x876dc444, 0xf9a4bf62,\n\t0xb6cdc279, 0x5050a949, 0xb77f8276, 0x06bada7a }}},\n    {{{ 0xea48dac9, 0xc8b4aed1, 0x7ea1070f, 0xdebd8a4b,\n\t0x1366eb70, 0x427d4910, 0x0e6cb18a, 0x5b476dfd }}}\n  }, {\n    {{{ 0x278c340a, 0x7c5c3e44, 0x12d66f3b, 0x4d546068,\n\t0xae23c5d8, 0x29a751b1, 0x8a2ec908, 0x3e29864e }}},\n    {{{ 0x26dbb850, 0x142d2a66, 0x765bd780, 0xad1744c4,\n\t0xe322d1ed, 0x1f150e68, 0x3dc31e7e, 0x239b90ea }}}\n  }, {\n    {{{ 0x7a53322a, 0x78c41652, 0x09776f8e, 0x305dde67,\n\t0xf8862ed4, 0xdbcab759, 0x49f72ff7, 0x820f4dd9 }}},\n    {{{ 0x2b5debd4, 0x6cc544a6, 0x7b4e8cc4, 0x75be5d93,\n\t0x215c14d3, 0x1b481b1b, 0x783a05ec, 0x140406ec }}}\n  }, {\n    {{{ 0xe895df07, 0x6a703f10, 0x01876bd8, 0xfd75f3fa,\n\t0x0ce08ffe, 0xeb5b06e7, 0x2783dfee, 0x68f6b854 }}},\n    {{{ 0x78712655, 0x90c76f8a, 0xf310bf7f, 0xcf5293d2,\n\t0xfda45028, 0xfbc8044d, 0x92e40ce6, 0xcbe1feba }}}\n  }, {\n    {{{ 0x4396e4c1, 0xe998ceea, 0x6acea274, 0xfc82ef0b,\n\t0x2250e927, 0x230f729f, 0x2f420109, 0xd0b2f94d }}},\n    {{{ 0xb38d4966, 0x4305addd, 0x624c3b45, 0x10b838f8,\n\t0x58954e7a, 0x7db26366, 0x8b0719e5, 0x97145982 }}}\n  }, {\n    {{{ 0x23369fc9, 0x4bd6b726, 0x53d0b876, 0x57f2929e,\n\t0xf2340687, 0xc2d5cba4, 0x4a866aba, 0x96161000 }}},\n    {{{ 0x2e407a5e, 0x49997bcd, 0x92ddcb24, 0x69ab197d,\n\t0x8fe5131c, 0x2cf1f243, 0xcee75e44, 0x7acb9fad }}}\n  }, {\n    {{{ 0x23d2d4c0, 0x254e8394, 0x7aea685b, 0xf57f0c91,\n\t0x6f75aaea, 0xa60d880f, 0xa333bf5b, 0x24eb9acc }}},\n    {{{ 0x1cda5dea, 0xe3de4ccb, 0xc51a6b4f, 0xfeef9341,\n\t0x8bac4c4d, 0x743125f8, 0xacd079cc, 0x69f891c5 }}}\n  }, {\n    {{{ 0x702476b5, 0xeee44b35, 0xe45c2258, 0x7ed031a0,\n\t0xbd6f8514, 0xb422d1e7, 0x5972a107, 0xe51f547c }}},\n    {{{ 0xc9cf343d, 0xa25bcd6f, 0x097c184e, 0x8ca922ee,\n\t0xa9fe9a06, 0xa62f98b3, 0x25bb1387, 0x1c309a2b }}}\n  }, {\n    {{{ 0x1967c459, 0x9295dbeb, 0x3472c98e, 0xb0014883,\n\t0x08011828, 0xc5049777, 0xa2c4e503, 0x20b87b8a }}},\n    {{{ 0xe057c277, 0x3063175d, 0x8fe582dd, 0x1bd53933,\n\t0x5f69a044, 0x0d11adef, 0x919776be, 0xf5c6fa49 }}}\n  }, {\n    {{{ 0x0fd59e11, 0x8c944e76, 0x102fad5f, 0x3876cba1,\n\t0xd83faa56, 0xa454c3fa, 0x332010b9, 0x1ed7d1b9 }}},\n    {{{ 0x0024b889, 0xa1011a27, 0xac0cd344, 0x05e4d0dc,\n\t0xeb6a2a24, 0x52b520f0, 0x3217257a, 0x3a2b03f0 }}}\n  }, {\n    {{{ 0xdf1d043d, 0xf20fc2af, 0xb58d5a62, 0xf330240d,\n\t0xa0058c3b, 0xfc7d229c, 0xc78dd9f6, 0x15fee545 }}},\n    {{{ 0x5bc98cda, 0x501e8288, 0xd046ac04, 0x41ef80e5,\n\t0x461210fb, 0x557d9f49, 0xb8753f81, 0x4ab5b6b2 }}}\n  }\n};\n\n/*\n * N: order of G\n */\nstatic const bn256 N[1] = {\n  {{ 0xfc632551, 0xf3b9cac2, 0xa7179e84, 0xbce6faad,\n     0xffffffff, 0xffffffff, 0x00000000, 0xffffffff }}\n};\n\n/*\n * MU = 2^512 / N\n * MU = ( (1 << 256) | MU_lower )\n */\nstatic const bn256 MU_lower[1] = {\n  {{ 0xeedf9bfe, 0x012ffd85, 0xdf1a6c21, 0x43190552,\n     0xffffffff, 0xfffffffe, 0xffffffff, 0x00000000 }}\n};\n\n\n#include \"ecc.c\"\n"
  },
  {
    "path": "src/ec_p256r1.h",
    "content": "int compute_kP_p256r1 (ac *X, const bn256 *K, const ac *P);\nint compute_kG_p256r1 (ac *X, const bn256 *K);\nvoid ecdsa_p256r1 (bn256 *r, bn256 *s, const bn256 *z, const bn256 *d);\nint check_secret_p256r1 (const bn256 *q, bn256 *d1);\n"
  },
  {
    "path": "src/ecc.c",
    "content": "/*                                                    -*- coding: utf-8 -*-\n * ecc.c - Elliptic curve over GF(prime)\n *\n * Copyright (C) 2011, 2013, 2014, 2015\n *               Free Software Initiative of Japan\n * Author: NIIBE Yutaka <gniibe@fsij.org>\n *\n * This file is a part of Gnuk, a GnuPG USB Token implementation.\n *\n * Gnuk is free software: you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Gnuk is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public\n * License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n/*\n * References:\n *\n * [1] Suite B Implementer's Guide to FIPS 186-3 (ECDSA), February 3, 2010.\n *\n * [2] Michael Brown, Darrel Hankerson, Julio López, and Alfred Menezes,\n *     Software Implementation of the NIST Elliptic Curves Over Prime Fields,\n *     Proceedings of the 2001 Conference on Topics in Cryptology: The\n *     Cryptographer's Track at RSA\n *     Pages 250-265, Springer-Verlag London, UK, 2001\n *     ISBN:3-540-41898-9\n *\n * [3] Mustapha Hedabou, Pierre Pinel, Lucien Bénéteau,\n *     A comb method to render ECC resistant against Side Channel Attacks,\n *     2004\n */\n\n#include \"field-group-select.h\"\n\n/*\n * Coefficients\n */\n/*\n * static const bn256 *coefficient_a;\n * static const bn256 *coefficient_b;\n */\n/*\n * N: order of G\n */\n/*\n * static const bn256 N[1];\n */\n/*\n * MU = 2^512 / N\n * MU = ( (1 << 256) | MU_lower )\n */\n/*\n * static const bn256 MU_lower[1];\n */\n\n/*\n * w = 4\n * m = 256\n * d = 64\n * e = 32\n */\n\n/*\n * static const ac precomputed_KG[15];\n * static const ac precomputed_2E_KG[15];\n */\n\n#if TEST\n/*\n * Generator of Elliptic curve over GF(p256)\n */\nconst ac *G = &precomputed_KG[0];\n#endif\n\n\nstatic int\nget_vk (const bn256 *K, int i)\n{\n  uint32_t w0, w1, w2, w3;\n\n  if (i < 32)\n    {\n      w3 = K->word[6]; w2 = K->word[4]; w1 = K->word[2]; w0 = K->word[0];\n    }\n  else\n    {\n      w3 = K->word[7]; w2 = K->word[5]; w1 = K->word[3]; w0 = K->word[1];\n      i -= 32;\n    }\n\n  w3 >>= i;  w2 >>= i;  w1 >>= i;  w0 >>= i;\n  return ((w3 & 1) << 3) | ((w2 & 1) << 2) | ((w1 & 1) << 1) | (w0 & 1);\n}\n\n\n/**\n * @brief\tX  = k * G\n *\n * @param K\tscalar k\n *\n * Return -1 on error.\n * Return 0 on success.\n */\nint\nFUNC(compute_kG) (ac *X, const bn256 *K)\n{\n  uint8_t index[64]; /* Lower 4-bit for index absolute value, msb is\n\t\t\tfor sign (encoded as: 0 means 1, 1 means -1).  */\n  bn256 K_dash[1];\n  jpc Q[1], tmp[1], *dst;\n  int i;\n  int vk;\n  uint32_t k_is_even = bn256_is_even (K);\n\n  bn256_sub_uint (K_dash, K, k_is_even);\n  /* It keeps the condition: 1 <= K' <= N - 2, and K' is odd.  */\n\n  /* Fill index.  */\n  vk = get_vk (K_dash, 0);\n  for (i = 1; i < 64; i++)\n    {\n      int vk_next, is_zero;\n\n      vk_next = get_vk (K_dash, i);\n      is_zero = (vk_next == 0);\n      index[i-1] = (vk - 1) | (is_zero << 7);\n      vk = (is_zero ? vk : vk_next);\n    }\n  index[63] = vk - 1;\n\n  memset (Q->z, 0, sizeof (bn256)); /* infinity */\n  for (i = 31; i >= 0; i--)\n    {\n      FUNC(jpc_double) (Q, Q);\n      FUNC(jpc_add_ac_signed) (Q, Q, &precomputed_2E_KG[index[i+32]&0x0f],\n\t\t\t       index[i+32] >> 7);\n      FUNC(jpc_add_ac_signed) (Q, Q, &precomputed_KG[index[i]&0x0f],\n\t\t\t       index[i] >> 7);\n    }\n\n  dst = k_is_even ? Q : tmp;\n  FUNC(jpc_add_ac) (dst, Q, &precomputed_KG[0]);\n\n  return FUNC(jpc_to_ac) (X, Q);\n}\n\n\n\n/**\n * check if P is on the curve.\n *\n * Return -1 on error.\n * Return 0 on success.\n */\nstatic int\npoint_is_on_the_curve (const ac *P)\n{\n  bn256 s[1], t[1];\n\n  /* Elliptic curve: y^2 = x^3 + a*x + b */\n  MFNC(sqr) (s, P->x);\n  MFNC(mul) (s, s, P->x);\n\n#ifndef COEFFICIENT_A_IS_ZERO\n  MFNC(mul) (t, coefficient_a, P->x);\n  MFNC(add) (s, s, t);\n#endif\n  MFNC(add) (s, s, coefficient_b);\n\n  MFNC(sqr) (t, P->y);\n  if (bn256_cmp (s, t) == 0)\n    return 0;\n  else\n    return -1;\n}\n\n\nstatic int\nget_vk_kP (const bn256 *K, int i)\n{\n  uint32_t w;\n  uint8_t blk = i/32;\n  uint8_t pos = i%32;\n  uint8_t col = 3*(pos % 11) + (pos >= 11) + (pos >= 22);\n  uint8_t word_index = (blk * 3) + (pos / 11);\n\n  w = ((K->word[word_index] >> col) & 7);\n  if (word_index < 7 && (pos == 10 || pos == 21))\n    {\n      uint8_t mask;\n      uint8_t shift;\n\n      word_index++;\n      if (pos == 10)\n\t{\n\t  shift = 2;\n\t  mask = 4;\n\t}\n      else\n\t{\n\t  shift = 1;\n\t  mask = 6;\n\t}\n\n      w |= ((K->word[word_index] << shift) & mask);\n    }\n\n  return w;\n}\n\n/**\n * @brief\tX  = k * P\n *\n * @param K\tscalar k\n * @param P\tP in affine coordiate\n *\n * Return -1 on error.\n * Return 0 on success.\n *\n * For the curve (cofactor is 1 and n is prime), possible error cases are:\n *\n *     P is not on the curve.\n *     P = G, k = n\n *     Something wrong in the code.\n *\n * Mathmatically, k=1 and P=O is another possible case, but O cannot be\n * represented by affine coordinate.\n */\nint\nFUNC(compute_kP) (ac *X, const bn256 *K, const ac *P)\n{\n  uint8_t index[86]; /* Lower 2-bit for index absolute value, msb is\n\t\t\tfor sign (encoded as: 0 means 1, 1 means -1).  */\n  bn256 K_dash[1];\n  uint32_t k_is_even = bn256_is_even (K);\n  jpc Q[1], tmp[1], *dst;\n  int i;\n  int vk;\n  ac P3[1], P5[1], P7[1];\n  const ac *p_Pi[4];\n\n  if (point_is_on_the_curve (P) < 0)\n    return -1;\n\n  if (bn256_sub (K_dash, K, N) == 0)\t/* >= N, it's too big.  */\n    return -1;\n\n  bn256_sub_uint (K_dash, K, k_is_even);\n  /* It keeps the condition: 1 <= K' <= N - 2, and K' is odd.  */\n\n  p_Pi[0] = P;\n  p_Pi[1] = P3;\n  p_Pi[2] = P5;\n  p_Pi[3] = P7;\n\n  {\n    jpc Q1[1];\n\n    memcpy (Q->x, P->x, sizeof (bn256));\n    memcpy (Q->y, P->y, sizeof (bn256));\n    memset (Q->z, 0, sizeof (bn256));\n    Q->z->word[0] = 1;\n\n    FUNC(jpc_double) (Q, Q);\n    FUNC(jpc_add_ac) (Q1, Q, P);\n    if (FUNC(jpc_to_ac) (P3, Q1) < 0) /* Never occurs, except coding errors.  */\n      return -1;\n    FUNC(jpc_double) (Q, Q);\n    FUNC(jpc_add_ac) (Q1, Q, P);\n    if (FUNC(jpc_to_ac) (P5, Q1) < 0) /* Never occurs, except coding errors.  */\n      return -1;\n\n    memcpy (Q->x, P3->x, sizeof (bn256));\n    memcpy (Q->y, P3->y, sizeof (bn256));\n    memset (Q->z, 0, sizeof (bn256));\n    Q->z->word[0] = 1;\n    FUNC(jpc_double) (Q, Q);\n    FUNC(jpc_add_ac) (Q1, Q, P);\n    if (FUNC(jpc_to_ac) (P7, Q1) < 0) /* Never occurs, except coding errors.  */\n      return -1;\n  }\n\n  /* Fill index.  */\n  vk = get_vk_kP (K_dash, 0);\n  for (i = 1; i < 86; i++)\n    {\n      int vk_next, is_even;\n\n      vk_next = get_vk_kP (K_dash, i);\n      is_even = ((vk_next & 1) == 0);\n      index[i-1] = (is_even << 7) | ((is_even?7-vk:vk-1) >> 1);\n      vk = vk_next + is_even;\n    }\n  index[85] = ((vk - 1) >> 1);\n\n  memset (Q->z, 0, sizeof (bn256)); /* infinity */\n  for (i = 85; i >= 0; i--)\n    {\n      FUNC(jpc_double) (Q, Q);\n      FUNC(jpc_double) (Q, Q);\n      FUNC(jpc_double) (Q, Q);\n      FUNC(jpc_add_ac_signed) (Q, Q, p_Pi[index[i]&0x03], index[i] >> 7);\n    }\n\n  dst = k_is_even ? Q : tmp;\n  FUNC(jpc_add_ac) (dst, Q, P);\n\n  return FUNC(jpc_to_ac) (X, Q);\n}\n\n\n/**\n * @brief Compute signature (r,s) of hash string z with secret key d\n */\nvoid\nFUNC(ecdsa) (bn256 *r, bn256 *s, const bn256 *z, const bn256 *d)\n{\n  bn256 k[1];\n  ac KG[1];\n  bn512 tmp[1];\n  bn256 k_inv[1];\n  uint32_t carry;\n#define borrow carry\n#define tmp_k k_inv\n\n  do\n    {\n      do\n\t{\n\t  bn256_random (k);\n\t  if (bn256_add_uint (k, k, 1))\n\t    continue;\n\t  if (bn256_sub (tmp_k, k, N) == 0)\t/* >= N, it's too big.  */\n\t    continue;\n\t  /* 1 <= k <= N - 1 */\n\t  FUNC(compute_kG) (KG, k);\n\t  borrow = bn256_sub (r, KG->x, N);\n\t  if (borrow)\n\t    memcpy (r, KG->x, sizeof (bn256));\n\t  else\n\t    memcpy (KG->x, r, sizeof (bn256));\n\t}\n      while (bn256_is_zero (r));\n\n      mod_inv (k_inv, k, N);\n      bn256_mul (tmp, r, d);\n      mod_reduce (s, tmp, N, MU_lower);\n      carry = bn256_add (s, s, z);\n      if (carry)\n\tbn256_sub (s, s, N);\n      else\n\tbn256_sub ((bn256 *)tmp, s, N);\n      bn256_mul (tmp, s, k_inv);\n      mod_reduce (s, tmp, N, MU_lower);\n    }\n  while (bn256_is_zero (s));\n\n#undef tmp_k\n#undef borrow\n}\n\n\n/**\n * @brief Check if a secret d0 is valid or not\n *\n * @param D0\tscalar D0: secret\n * @param D1\tscalar D1: secret candidate N-D0\n *\n * Return 0 on error.\n * Return -1 when D1 should be used as the secret\n * Return 1 when D0 should be used as the secret\n */\nint\nFUNC(check_secret) (const bn256 *d0, bn256 *d1)\n{\n  ac Q0[1], Q1[1];\n\n  if (bn256_is_zero (d0) || bn256_sub (d1, N, d0) != 0)\n    /* == 0 or >= N, it's not valid.  */\n    return 0;\n\n  FUNC(compute_kG) (Q0, d0);\n  FUNC(compute_kG) (Q1, d1);\n\n  /*\n   * Jivsov compliant key check\n   */\n  return bn256_cmp (Q1[0].y, Q0[0].y);\n}\n"
  },
  {
    "path": "src/ecc.h",
    "content": "\nint ecdsa_sign_p256r1 (const uint8_t *hash, uint8_t *output,\n           const uint8_t *key_data);\nuint8_t *ecc_compute_public_p256r1 (const uint8_t *key_data, uint8_t *public);\nint ecc_check_secret_p256r1 (const uint8_t *d0, uint8_t *d1);\nint ecdh_decrypt_p256r1 (const uint8_t *input, uint8_t *output,\n       const uint8_t *key_data);\n"
  },
  {
    "path": "src/efm32hg.ld",
    "content": "/*\n * EFM32HG memory setup.\n */\n__main_stack_size__      = 0x0200; /* Idle+Exception handlers */\n__process0_stack_size__  = 0x0200; /* Main program            */\n__process1_stack_size__  = 0x0100; /* pwd                     */\n__process2_stack_size__  = 0x0100; /* blk                     */\n__process3_stack_size__  = 0x0200; /* usb-hid                 */\n__process4_stack_size__  = 0x0800; /* u2f-hid                 */\n__process5_stack_size__  = 0x0200; /* rng                     */\n__process6_stack_size__  = 0x0100; /* pbt / csn               */\n\nMEMORY\n{\n    flash  : org = 0x00004000, len = 46k\n    ram : org = 0x20000000, len = 8k\n    flash1 : org = 0x00004000+0xb400, len = 3k\n}\n\n__ram_start__           = ORIGIN(ram);\n__ram_size__            = 8k;\n__ram_end__             = __ram_start__ + __ram_size__;\n\nSECTIONS\n{\n    . = 0;\n\n    _text = .;\n\n    .text : ALIGN(16) SUBALIGN(8)\n    {\n    . = ALIGN(16);\n        KEEP(*(.first_page.first_words))\n    . = ORIGIN(flash) + 0x90;\n        KEEP(*(.toboot.config))\n        KEEP(*(.sys.vectors))\n        *(.text.startup.*)\n    build/sys-*.o(.text)\n    build/sys-*.o(.text.*)\n    build/sys-*.o(.rodata)\n    build/sys-*.o(.rodata.*)\n    /*\n     * Because of alignment requirement\n     * of startup.vectors, align to 256.\n     */\n    . = ALIGN(256);\n        KEEP(*(.startup.vectors))\n    . = ALIGN(16);\n        *(.text)\n        *(.text.*)\n        *(.rodata)\n        *(.rodata.*)\n        *(.glue_7t)\n        *(.glue_7)\n        *(.gcc*)\n    . = ALIGN(8);\n    } > flash\n\n    /DISCARD/ :\n    {\n        *(.bss.startup.0)\n    }\n\n    .ARM.extab : {*(.ARM.extab* .gnu.linkonce.armextab.*)} > flash\n\n    .ARM.exidx : {\n        PROVIDE(__exidx_start = .);\n        *(.ARM.exidx* .gnu.linkonce.armexidx.*)\n        PROVIDE(__exidx_end = .);\n     } > flash\n\n    .eh_frame_hdr : {*(.eh_frame_hdr)} > flash\n\n    .eh_frame : ONLY_IF_RO {*(.eh_frame)} > flash\n\n    .textalign : ONLY_IF_RO { . = ALIGN(8); } > flash\n\n    _etext = .;\n    _textdata = _etext;\n\n    .process_stack :\n    {\n        . = ALIGN(8);\n\n        __process6_stack_base__ = .;\n        . += __process6_stack_size__;\n        . = ALIGN(8);\n        __process6_stack_end__ = .;\n\n        __process5_stack_base__ = .;\n        . += __process5_stack_size__;\n        . = ALIGN(8);\n        __process5_stack_end__ = .;\n\n        __process4_stack_base__ = .;\n        . += __process4_stack_size__;\n        . = ALIGN(8);\n        __process4_stack_end__ = .;\n\n        __process3_stack_base__ = .;\n        . += __process3_stack_size__;\n        . = ALIGN(8);\n        __process3_stack_end__ = .;\n\n        __process2_stack_base__ = .;\n        . += __process2_stack_size__;\n        . = ALIGN(8);\n        __process2_stack_end__ = .;\n\n        __process1_stack_base__ = .;\n        . += __process1_stack_size__;\n        . = ALIGN(8);\n        __process1_stack_end__ = .;\n\n        __process0_stack_base__ = .;\n        . += __process0_stack_size__;\n        . = ALIGN(8);\n        __process0_stack_end__ = .;\n    } > ram\n\n    .main_stack :\n    {\n        . = ALIGN(8);\n        __main_stack_base__ = .;\n        . += __main_stack_size__;\n        . = ALIGN(8);\n        __main_stack_end__ = .;\n    } > ram\n\n    .data :\n    {\n        . = ALIGN(4);\n        PROVIDE(_data = .);\n        *(.data)\n        . = ALIGN(4);\n        *(.data.*)\n        . = ALIGN(4);\n        *(.ramtext)\n        . = ALIGN(4);\n        PROVIDE(_edata = .);\n    } > ram AT > flash\n\n    .bss :\n    {\n        . = ALIGN(4);\n        PROVIDE(_bss_start = .);\n        *(.bss)\n        . = ALIGN(4);\n        *(.bss.*)\n        . = ALIGN(4);\n        *(COMMON)\n        . = ALIGN(512);\n    __usb_bdt__ = .;\n        . += 512;\n        PROVIDE(_bss_end = .);\n    } > ram\n\n    .flash_storage :\n    {\n        . = ALIGN (1024);\n        _attestation_cert_base = .;\n        *(.attestation.cert);\n        . = ALIGN (1024);\n        _device_key_base = .;\n        *(.device.key);\n        . = ALIGN (1024);\n        _auth_ctr_base = .;\n        *(.auth.ctr);\n        . = ALIGN (1024);\n    } > flash1\n\n    PROVIDE(end = .);\n    _end            = .;\n}\n\n__heap_base__   = _end;\n__heap_end__    = __ram_end__;\n"
  },
  {
    "path": "src/empty-attestation-cert.c",
    "content": "struct attestation_cert  __attribute__ ((section(\".attestation.cert\")))\nattestation_cert = {\n  .hdr = {\n    .der_len = (uint32_t) -1,\n    .der = NULL,\n    .key = NULL\n  }\n};\n"
  },
  {
    "path": "src/field-group-select.h",
    "content": "#define CONCAT0(a,b) a##b\n#define CONCAT1(a,b) CONCAT0(a,b)\n#define CONCAT2(a,b,c) CONCAT1(a,b##c)\n#define CONCAT3(a,b,c) CONCAT2(a,b,c)\n\n#define FUNC(func) CONCAT1(func##_,FIELD)\n#define MFNC(func) CONCAT3(mod,FIELD,_##func)\n"
  },
  {
    "path": "src/gdb.commands",
    "content": "file build/u2f.elf\ntarget remote localhost:3333\nmonitor arm semihosting enable\nmonitor reset halt\nload build/u2f.elf\n\n"
  },
  {
    "path": "src/hmac.c",
    "content": "/*\n * hmac.c - HMAC\n *\n * Copyright (C) 2017 Sergei Glushchenko\n * Author: Sergei Glushchenko <gl.sergei@gmail.com>\n *\n * This file is a part of U2F firmware for STM32\n *\n * This program is free software: you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n * As additional permission under GNU GPL version 3 section 7, you may\n * distribute non-source form of the Program without the copy of the\n * GNU GPL normally required by section 4, provided you inform the\n * recipients of GNU GPL by a written offer.\n *\n */\n#include <stdint.h>\n\n#include \"sha256.h\"\n#include \"hmac.h\"\n\nstatic void\n_hmac_sha256_init (const hmac_context *ctx)\n{\n  hmac_sha256_context *context = (hmac_sha256_context *)ctx;\n  sha256_start(&context->sha_ctx);\n}\n\nstatic void\n_hmac_sha256_update (const hmac_context *ctx, const uint8_t *message,\n                    unsigned message_size)\n{\n  hmac_sha256_context *context = (hmac_sha256_context *)ctx;\n  sha256_update(&context->sha_ctx, message, message_size);\n}\n\nstatic void\n_hmac_sha256_finish (const hmac_context *ctx, uint8_t *hash_result)\n{\n  hmac_sha256_context *context = (hmac_sha256_context *)ctx;\n  sha256_finish(&context->sha_ctx, hash_result);\n}\n\n/* Compute an HMAC using K as a key (as in RFC 6979). Note that K is always\n   the same size as the hash result size. */\nstatic void\nhmac_init(const hmac_context *ctx, const uint8_t *K)\n{\n  uint8_t *pad = ctx->tmp + 2 * ctx->result_size;\n  unsigned i;\n  for (i = 0; i < ctx->result_size; ++i)\n    pad[i] = K[i] ^ 0x36;\n  for (; i < ctx->block_size; ++i)\n    pad[i] = 0x36;\n\n  ctx->init_hash (ctx);\n  ctx->update_hash (ctx, pad, ctx->block_size);\n}\n\nstatic void\nhmac_update(const hmac_context *ctx,\n            const uint8_t *message,\n            unsigned message_size)\n{\n  ctx->update_hash (ctx, message, message_size);\n}\n\nstatic void\nhmac_finish(const hmac_context *ctx,\n            const uint8_t *K,\n            uint8_t *result)\n{\n  uint8_t *pad = ctx->tmp + 2 * ctx->result_size;\n  unsigned i;\n  for (i = 0; i < ctx->result_size; ++i)\n    pad[i] = K[i] ^ 0x5c;\n  for (; i < ctx->block_size; ++i)\n    pad[i] = 0x5c;\n\n  ctx->finish_hash (ctx, result);\n\n  ctx->init_hash (ctx);\n  ctx->update_hash (ctx, pad, ctx->block_size);\n  ctx->update_hash (ctx, result, ctx->result_size);\n  ctx->finish_hash (ctx, result);\n}\n\nvoid\nhmac_sha256_init (hmac_sha256_context *ctx, const uint8_t *K)\n{\n  ctx->hmac_ctx.init_hash = _hmac_sha256_init;\n  ctx->hmac_ctx.update_hash = _hmac_sha256_update;\n  ctx->hmac_ctx.finish_hash = _hmac_sha256_finish;\n  ctx->hmac_ctx.block_size = 64;\n  ctx->hmac_ctx.result_size = 32;\n  ctx->hmac_ctx.tmp = ctx->tmp;\n  hmac_init (&ctx->hmac_ctx, K);\n}\n\nvoid\nhmac_sha256_update (const hmac_sha256_context *ctx, const uint8_t *message,\n                    unsigned message_size)\n{\n  hmac_update (&ctx->hmac_ctx, message, message_size);\n}\n\nvoid\nhmac_sha256_finish (const hmac_sha256_context *ctx, const uint8_t *K,\n                    uint8_t *hash_result)\n{\n  hmac_finish (&ctx->hmac_ctx, K, hash_result);\n}\n"
  },
  {
    "path": "src/hmac.h",
    "content": "\ntypedef struct hmac_context {\n  void (*init_hash)(const struct hmac_context *context);\n  void (*update_hash)(const struct hmac_context *context,\n                      const uint8_t *message,\n                      unsigned message_size);\n  void (*finish_hash)(const struct hmac_context *context, uint8_t *hash_result);\n  unsigned block_size; /* Hash function block size in bytes, eg 64 for SHA-256. */\n  unsigned result_size; /* Hash function result size in bytes, eg 32 for SHA-256. */\n  uint8_t *tmp; /* Must point to a buffer of at least (2 * result_size + block_size) bytes. */\n} hmac_context;\n\n\ntypedef struct hmac_sha256_context {\n  hmac_context hmac_ctx;\n  sha256_context sha_ctx;\n  uint8_t tmp[32 * 2 + 64];\n} hmac_sha256_context;\n\nvoid\nhmac_sha256_init (hmac_sha256_context *ctx, const uint8_t *K);\n\nvoid\nhmac_sha256_update (const hmac_sha256_context *ctx, const uint8_t *message,\n                    unsigned message_size);\n\nvoid\nhmac_sha256_finish (const hmac_sha256_context *ctx, const uint8_t *K,\n                    uint8_t *hash_result);\n"
  },
  {
    "path": "src/inject_key.py",
    "content": "#!/usr/bin/env python\n\n#\n# Use this script to inject your own private key and authentication counter\n# into U2F binary. Might be useful if you want keys to survive firmware updates.\n#\n# Example:\n#\n# Generate EC private key with openssl:\n# > openssl ecparam -name prime256v1 -genkey -noout -outform der > key.der\n#\n# Inject generated key into u2f.bin and set auth counter to 100:\n# > python3 inject_key.py --key key.der --ctr 100\n#\n\nfrom __future__ import print_function\nfrom asn1crypto.keys import ECPrivateKey\nimport hashlib\nimport argparse\nimport sys\nimport struct\nimport os\nimport tempfile\nimport subprocess\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--elf\", default=\"build/u2f.elf\",\n                    help=\".elf file to inject keys into\")\nparser.add_argument(\"--key\", help=\"EC private key in DER format\")\nparser.add_argument(\"--ctr\", default=1, type=int, help=\"value of auth counter\")\nargs = parser.parse_args()\n\n# load and parse private key\nif args.key:\n    with open(args.key, \"rb\") as f:\n        der = f.read()\nelse:\n    stdin = sys.stdin.buffer if hasattr(sys.stdin, \"buffer\") else sys.stdin\n    der = stdin.read()\nkey = ECPrivateKey.load(der)\n\n# convert key into raw bytes and calculate it's sha256\nkey_bytes = bytearray.fromhex(format(key[\"private_key\"].native, '064x'))\nkey_hash = hashlib.sha256(key_bytes).digest()\n\n# fill authentication counter\nctr_bytes = struct.pack(\"<I\", args.ctr) * 256\n\n# pad key and append ctr to produce 2k output blob\nblob = (key_bytes + key_hash).ljust(1024, b\"\\x00\") + ctr_bytes\n\nassert len(blob) == 2048\nfname, fext = os.path.splitext(args.elf)\nassert fext == \".elf\"\n\nwith tempfile.NamedTemporaryFile(mode='w+b', buffering=0, delete=True) as f:\n    # dump contents of .flash_storage section\n    ret = subprocess.call([\"arm-none-eabi-objcopy\", \"--dump-section\",\n                           \".flash_storage=\" + f.name, args.elf])\n    if ret != 0:\n        raise Exception(\"Failed to dump flash storage section of .elf file!\")\n    # patch contents of .flash_storage section with desired key and counter\n    f.seek(-0x800, 2)\n    f.write(blob)\n    f.flush()\n    ret = subprocess.call([\"arm-none-eabi-objcopy\", \"--update-section\",\n                           \".flash_storage=\" + f.name, args.elf])\n    if ret != 0:\n        raise Exception(\"Failed to patch .elf file!\")\n    # generate binary for bootloader\n    ret = subprocess.call([\"arm-none-eabi-objcopy\", \"-O\", \"binary\",\n                           args.elf, fname + \".bin\"])\n    if ret != 0:\n        raise Exception(\"Failed to create .bin file!\")\n"
  },
  {
    "path": "src/inject_key_bin.py",
    "content": "#!/usr/bin/env python\n\n#\n# Use this script to inject your own private key and authentication counter\n# into U2F binary. Might be useful if you want keys to survive firmware updates.\n#\n# Example:\n#\n# Generate EC private key with openssl:\n# > openssl ecparam -name prime256v1 -genkey -noout -outform der > key.der\n#\n# Inject generated key into u2f.bin and set auth counter to 100:\n# > python3 inject_key_bin.py --key key.der --ctr 100 --bin build/u2f.bin\n#\n# key will not be modified if --key parameter is not present\n# counter will not be modified if --ctr parameter is not present\n\nfrom __future__ import print_function\nfrom asn1crypto.keys import ECPrivateKey\nimport hashlib\nimport argparse\nimport sys\nimport struct\nimport os\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--bin\", default=\"build/u2f.bin\",\n                    help='.bin file to inject keys into. Or \"stdin\"')\nparser.add_argument(\"--key\", help=\"EC private key in DER format\")\nparser.add_argument(\"--ctr\", default=0, type=lambda x: int(x,0), help=\"Value of auth counter\")\nparser.add_argument(\"--offset\", default=0, type=lambda x: int(x,0), help=\"Offset within file to patch\")\nargs = parser.parse_args()\n\nfname, fext = os.path.splitext(args.bin)\nassert fext == \".bin\"\n\nfsize = os.path.getsize(args.bin)\n\nprint(\"Target binary file %s, size 0x%X\" % (args.bin, fsize))\n\nif args.offset:\n    offset = args.offset\nelse:\n    offset = fsize - 0x800\n\n# load and parse private key\nif not args.key:\n    print(\"Key not modified\")\nelse:\n    key_offset = offset\n    print(\"Injecting key from %s at 0x%0X\" % (args.key, key_offset))\n    if args.key == \"stdin\":\n        stdin = sys.stdin.buffer if hasattr(sys.stdin, \"buffer\") else sys.stdin\n        der = stdin.read()\n    else:\n        with open(args.key, \"rb\") as f:\n            der = f.read()\n    key = ECPrivateKey.load(der)\n\n    # convert key into raw bytes and calculate it's sha256\n    key_bytes = bytearray.fromhex(format(key[\"private_key\"].native, '064x'))\n    key_hash = hashlib.sha256(key_bytes).digest()\n    # pad key to 1KiB\n    key_blob = (key_bytes + key_hash).ljust(1024, b\"\\x00\")\n    assert len(key_blob) == 1024\n\n    with open(args.bin, 'r+b') as f:\n        f.seek(key_offset)\n        f.write(key_blob)\n\nif not args.ctr:\n    print(\"Counter not modified\")\nelse:\n    ctr_offset = offset + 0x400\n    print(\"Injecting counter %d at 0x%0X\" % (args.ctr, ctr_offset))\n    # fill authentication counter\n    ctr_blob = struct.pack(\"<I\", args.ctr) * 256\n\n    with open(args.bin, 'r+b') as f:\n        f.seek(ctr_offset)\n        f.write(ctr_blob)\n"
  },
  {
    "path": "src/jpc-ac_p256r1.h",
    "content": "/**\n * @brief\tJacobian projective coordinates\n */\ntypedef struct\n{\n  bn256 x[1];\n  bn256 y[1];\n  bn256 z[1];\n} jpc;\n\nvoid jpc_double_p256r1 (jpc *X, const jpc *A);\nvoid jpc_add_ac_p256r1 (jpc *X, const jpc *A, const ac *B);\nvoid jpc_add_ac_signed_p256r1 (jpc *X, const jpc *A, const ac *B, int minus);\nint jpc_to_ac_p256r1 (ac *X, const jpc *A);\n"
  },
  {
    "path": "src/jpc.c",
    "content": "/*\n * jpc.c -- arithmetic on Jacobian projective coordinates.\n *\n * Copyright (C) 2011, 2013 Free Software Initiative of Japan\n * Author: NIIBE Yutaka <gniibe@fsij.org>\n *\n * This file is a part of Gnuk, a GnuPG USB Token implementation.\n *\n * Gnuk is free software: you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Gnuk is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public\n * License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include \"field-group-select.h\"\n\n/**\n * @brief\tX = 2 * A\n *\n * @param X\tDestination JPC\n * @param A\tJPC\n */\nvoid\nFUNC(jpc_double) (jpc *X, const jpc *A)\n{\n  bn256 a[1], b[1], c[1], tmp0[1];\n  bn256 *d;\n\n  if (bn256_is_zero (A->z))\t\t/* A is infinite */\n    return;\n\n  d = X->x;\n  MFNC(sqr) (a, A->y);\n  memcpy (b, a, sizeof (bn256));\n  MFNC(mul) (a, a, A->x);\n  MFNC(shift) (a, a, 2);\n\n  MFNC(sqr) (b, b);\n  MFNC(shift) (b, b, 3);\n\n#if defined(COEFFICIENT_A_IS_MINUS_3)\n  MFNC(sqr) (tmp0, A->z);\n  MFNC(sub) (c, A->x, tmp0);\n  MFNC(add) (tmp0, tmp0, A->x);\n  MFNC(mul) (tmp0, tmp0, c);\n  MFNC(shift) (c, tmp0, 1);\n  MFNC(add) (c, c, tmp0);\n#elif defined (COEFFICIENT_A_IS_ZERO)\n  MFNC(sqr) (tmp0, A->x);\n  MFNC(shift) (c, tmp0, 1);\n  MFNC(add) (c, c, tmp0);\n#else\n#error \"not supported.\"\n#endif\n\n  MFNC(sqr) (d, c);\n  MFNC(shift) (tmp0, a, 1);\n  MFNC(sub) (d, d, tmp0);\n\n  MFNC(mul) (X->z, A->y, A->z);\n  MFNC(shift) (X->z, X->z, 1);\n\n  MFNC(sub) (tmp0, a, d);\n  MFNC(mul) (tmp0, c, tmp0);\n  MFNC(sub) (X->y, tmp0, b);\n}\n\n/**\n * @brief\tX = A + B\n *\n * @param X\tDestination JPC\n * @param A\tJPC\n * @param B\tAC\n * @param MINUS if 1 subtraction, addition otherwise.\n */\nvoid\nFUNC(jpc_add_ac_signed) (jpc *X, const jpc *A, const ac *B, int minus)\n{\n  bn256 a[1], b[1], c[1], d[1], tmp[1];\n#define minus_B_y c\n#define c_sqr a\n#define c_cube b\n#define x1_c_sqr c\n#define x1_c_sqr_2 c\n#define c_cube_plus_x1_c_sqr_2 c\n#define x1_c_sqr_copy a\n#define y3_tmp c\n#define y1_c_cube a\n\n  if (bn256_is_zero (A->z))\t\t/* A is infinite */\n    {\n      memcpy (X->x, B->x, sizeof (bn256));\n      if (minus)\n\t{\n\t  memcpy (tmp, B->y, sizeof (bn256));\n\t  bn256_sub (X->y, CONST_P256, B->y);\n\t}\n      else\n\t{\n\t  memcpy (X->y, B->y, sizeof (bn256));\n\t  bn256_sub (tmp, CONST_P256, B->y);\n\t}\n      memset (X->z, 0, sizeof (bn256));\n      X->z->word[0] = 1;\n      return;\n    }\n\n  MFNC(sqr) (a, A->z);\n  memcpy (b, a, sizeof (bn256));\n  MFNC(mul) (a, a, B->x);\n\n  MFNC(mul) (b, b, A->z);\n  if (minus)\n    {\n      bn256_sub (minus_B_y, CONST_P256, B->y);\n      MFNC(mul) (b, b, minus_B_y);\n    }\n  else\n    {\n      bn256_sub (tmp, CONST_P256, B->y);\n      MFNC(mul) (b, b, B->y);\n    }\n\n  if (bn256_cmp (A->x, a) == 0 && bn256_cmp (A->y, b) == 0)\n    {\n      FUNC(jpc_double) (X, A);\n      return;\n    }\n\n  MFNC(sub) (c, a, A->x);\n  MFNC(sub) (d, b, A->y);\n\n  MFNC(mul) (X->z, A->z, c);\n\n  MFNC(sqr) (c_sqr, c);\n  MFNC(mul) (c_cube, c_sqr, c);\n\n  MFNC(mul) (x1_c_sqr, A->x, c_sqr);\n\n  MFNC(sqr) (X->x, d);\n  memcpy (x1_c_sqr_copy, x1_c_sqr, sizeof (bn256));\n  MFNC(shift) (x1_c_sqr_2, x1_c_sqr, 1);\n  MFNC(add) (c_cube_plus_x1_c_sqr_2, x1_c_sqr_2, c_cube);\n  MFNC(sub) (X->x, X->x, c_cube_plus_x1_c_sqr_2);\n\n  MFNC(sub) (y3_tmp, x1_c_sqr_copy, X->x);\n  MFNC(mul) (y3_tmp, y3_tmp, d);\n  MFNC(mul) (y1_c_cube, A->y, c_cube);\n  MFNC(sub) (X->y, y3_tmp, y1_c_cube);\n}\n\n/**\n * @brief\tX = A + B\n *\n * @param X\tDestination JPC\n * @param A\tJPC\n * @param B\tAC\n */\nvoid\nFUNC(jpc_add_ac) (jpc *X, const jpc *A, const ac *B)\n{\n  FUNC(jpc_add_ac_signed) (X, A, B, 0);\n}\n\n/**\n * @brief\tX = convert A\n *\n * @param X\tDestination AC\n * @param A\tJPC\n *\n * Return -1 on error (infinite).\n * Return 0 on success.\n */\nint\nFUNC(jpc_to_ac) (ac *X, const jpc *A)\n{\n  bn256 z_inv[1], z_inv_sqr[1];\n\n  if (bn256_is_zero (A->z))\n    return -1;\n\n  mod_inv (z_inv, A->z, CONST_P256);\n\n  MFNC(sqr) (z_inv_sqr, z_inv);\n  MFNC(mul) (z_inv, z_inv, z_inv_sqr);\n\n  MFNC(mul) (X->x, A->x, z_inv_sqr);\n  MFNC(mul) (X->y, A->y, z_inv);\n  return 0;\n}\n"
  },
  {
    "path": "src/jpc_p256r1.c",
    "content": "/*\n * jpc_p256r1.c -- arithmetic on Jacobian projective coordinates for p256r1.\n *\n * Copyright (C) 2014 Free Software Initiative of Japan\n * Author: NIIBE Yutaka <gniibe@fsij.org>\n *\n * This file is a part of Gnuk, a GnuPG USB Token implementation.\n *\n * Gnuk is free software: you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Gnuk is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public\n * License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include <stdint.h>\n#include <string.h>\n#include \"bn.h\"\n#include \"mod.h\"\n#include \"modp256r1.h\"\n#include \"affine.h\"\n#include \"jpc-ac_p256r1.h\"\n\n#define FIELD p256r1\n#define CONST_P256 P256R1\n#define COEFFICIENT_A_IS_MINUS_3 1\n\n#include \"jpc.c\"\n"
  },
  {
    "path": "src/mod.c",
    "content": "/*\n * mod.c -- modulo arithmetic\n *\n * Copyright (C) 2011, 2014 Free Software Initiative of Japan\n * Author: NIIBE Yutaka <gniibe@fsij.org>\n *\n * This file is a part of Gnuk, a GnuPG USB Token implementation.\n *\n * Gnuk is free software: you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Gnuk is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public\n * License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include <stdint.h>\n#include <string.h>\n#include \"bn.h\"\n\n/**\n * @brief X = A mod B (using MU=(1<<(256)+MU_lower)) (Barret reduction)\n *\n */\nvoid\nmod_reduce (bn256 *X, const bn512 *A, const bn256 *B, const bn256 *MU_lower)\n{\n  bn256 q[1];\n  bn512 q_big[1], tmp[1];\n  uint32_t carry;\n#define borrow carry\n  uint32_t borrow_next;\n\n  memset (q, 0, sizeof (bn256));\n  q->word[0] = A->word[15];\n  bn256_mul (tmp, q, MU_lower);\n  tmp->word[8] += A->word[15];\n  carry = (tmp->word[8] < A->word[15]);\n  tmp->word[9] += carry;\n\n  q->word[7] = A->word[14];\n  q->word[6] = A->word[13];\n  q->word[5] = A->word[12];\n  q->word[4] = A->word[11];\n  q->word[3] = A->word[10];\n  q->word[2] = A->word[9];\n  q->word[1] = A->word[8];\n  q->word[0] = A->word[7];\n  bn256_mul (q_big, q, MU_lower);\n  bn256_add ((bn256 *)&q_big->word[8], (bn256 *)&q_big->word[8], q);\n\n  q->word[0] = q_big->word[9] + tmp->word[1];\n  carry = (q->word[0] < tmp->word[1]);\n\n  q->word[1] = q_big->word[10] + carry;\n  carry = (q->word[1] < carry);\n  q->word[1] += tmp->word[2];\n  carry += (q->word[1] < tmp->word[2]);\n\n  q->word[2] = q_big->word[11] + carry;\n  carry = (q->word[2] < carry);\n  q->word[2] += tmp->word[3];\n  carry += (q->word[2] < tmp->word[3]);\n\n  q->word[3] = q_big->word[12] + carry;\n  carry = (q->word[3] < carry);\n  q->word[3] += tmp->word[4];\n  carry += (q->word[3] < tmp->word[4]);\n\n  q->word[4] = q_big->word[13] + carry;\n  carry = (q->word[4] < carry);\n  q->word[4] += tmp->word[5];\n  carry += (q->word[4] < tmp->word[5]);\n\n  q->word[5] = q_big->word[14] + carry;\n  carry = (q->word[5] < carry);\n  q->word[5] += tmp->word[6];\n  carry += (q->word[5] < tmp->word[6]);\n\n  q->word[6] = q_big->word[15] + carry;\n  carry = (q->word[6] < carry);\n  q->word[6] += tmp->word[7];\n  carry += (q->word[6] < tmp->word[7]);\n\n  q->word[7] = carry;\n  q->word[7] += tmp->word[8];\n  carry = (q->word[7] < tmp->word[8]);\n\n  memset (q_big, 0, sizeof (bn512));\n  q_big->word[8] = A->word[8];\n  q_big->word[7] = A->word[7];\n  q_big->word[6] = A->word[6];\n  q_big->word[5] = A->word[5];\n  q_big->word[4] = A->word[4];\n  q_big->word[3] = A->word[3];\n  q_big->word[2] = A->word[2];\n  q_big->word[1] = A->word[1];\n  q_big->word[0] = A->word[0];\n\n  bn256_mul (tmp, q, B);\n  tmp->word[8] += carry * B->word[0];\n  tmp->word[15] = tmp->word[14] = tmp->word[13] = tmp->word[12]\n    = tmp->word[11] = tmp->word[10] = tmp->word[9] = 0;\n\n  borrow = bn256_sub (X, (bn256 *)&q_big->word[0], (bn256 *)&tmp->word[0]);\n  borrow_next = (q_big->word[8] < borrow);\n  q_big->word[8] -= borrow;\n  borrow_next += (q_big->word[8] < tmp->word[8]);\n  q_big->word[8] -= tmp->word[8];\n\n  carry = q_big->word[8];\n  if (carry)\n    carry -= bn256_sub (X, X, B);\n  else\n    bn256_sub (q, X, B);\n\n  if (carry)\n    carry -= bn256_sub (X, X, B);\n  else\n    bn256_sub (q, X, B);\n\n  borrow = bn256_sub (q, X, B);\n  if (borrow)\n    memcpy (q, X, sizeof (bn256));\n  else\n    memcpy (X, q, sizeof (bn256));\n#undef borrow\n}\n\n/*\n * Reference:\n * Donald E. Knuth, The Art of Computer Programming, Vol. 2:\n * Seminumerical Algorithms, 3rd ed. Reading, MA: Addison-Wesley, 1998\n *\n * Max loop: X=0x8000...0000 and N=0xffff...ffff\n */\n#define MAX_GCD_STEPS_BN256 (3*256-2)\n\n/**\n * @brief C = X^(-1) mod N\n *\n * Assume X and N are co-prime (or N is prime).\n * NOTE: If X==0, it return 0.\n *\n */\nvoid\nmod_inv (bn256 *C, const bn256 *X, const bn256 *N)\n{\n  bn256 u[1], v[1], tmp[1];\n  bn256 A[1] = { { { 1, 0, 0, 0, 0, 0, 0, 0 } } };\n  uint32_t carry;\n#define borrow carry\n  int n = MAX_GCD_STEPS_BN256;\n\n  memset (C, 0, sizeof (bn256));\n  memcpy (u, X, sizeof (bn256));\n  memcpy (v, N, sizeof (bn256));\n\n  while (n--)\n    {\n      int c = (bn256_is_even (u) << 1) + bn256_is_even (v);\n\n      switch (c)\n\t{\n\tcase 3:\n\t  bn256_shift (u, u, -1);\n\t  if (bn256_is_even (A))\n\t    {\n\t      bn256_add (tmp, A, N);\n\t      carry = 0;\n\t    }\n\t  else\n\t    carry = bn256_add (A, A, N);\n\n\t  bn256_shift (A, A, -1);\n\t  A->word[7] |= carry * 0x80000000;\n\n\t  bn256_shift (v, v, -1);\n\t  if (bn256_is_even (C))\n\t    {\n\t      bn256_add (tmp, C, N);\n\t      carry = 0;\n\t    }\n\t  else\n\t    carry = bn256_add (C, C, N);\n\n\t  bn256_shift (C, C, -1);\n\t  C->word[7] |= carry * 0x80000000;\n\n\t  if (bn256_is_ge (tmp, tmp))\n\t    {\n\t      bn256_sub (tmp, tmp, tmp);\n\t      borrow = bn256_sub (tmp, tmp, tmp);\n\t      if (borrow)\n\t\tbn256_add (tmp, tmp, tmp);\n\t      else\n\t\tbn256_add (tmp, A, N);\n\t    }\n\t  else\n\t    {\n\t      bn256_sub (tmp, tmp, tmp);\n\t      borrow = bn256_sub (tmp, tmp, tmp);\n\t      if (borrow)\n\t\tbn256_add (tmp, tmp, tmp);\n\t      else\n\t\tbn256_add (tmp, tmp, N);\n\t    }\n\t  break;\n\n\tcase 1:\n\t  bn256_shift (tmp, tmp, -1);\n\t  if (bn256_is_even (tmp))\n\t    {\n\t      bn256_add (tmp, tmp, N);\n\t      carry = 0;\n\t    }\n\t  else\n\t    carry = bn256_add (tmp, tmp, N);\n\n\t  bn256_shift (tmp, tmp, -1);\n\t  tmp->word[7] |= carry * 0x80000000;\n\n\t  bn256_shift (v, v, -1);\n\t  if (bn256_is_even (C))\n\t    {\n\t      bn256_add (tmp, C, N);\n\t      carry = 0;\n\t    }\n\t  else\n\t    carry = bn256_add (C, C, N);\n\n\t  bn256_shift (C, C, -1);\n\t  C->word[7] |= carry * 0x80000000;\n\n\t  if (bn256_is_ge (tmp, tmp))\n\t    {\n\t      bn256_sub (tmp, tmp, tmp);\n\t      borrow = bn256_sub (tmp, tmp, tmp);\n\t      if (borrow)\n\t\tbn256_add (tmp, tmp, tmp);\n\t      else\n\t\tbn256_add (tmp, A, N);\n\t    }\n\t  else\n\t    {\n\t      bn256_sub (tmp, tmp, tmp);\n\t      borrow = bn256_sub (tmp, tmp, tmp);\n\t      if (borrow)\n\t\tbn256_add (tmp, tmp, tmp);\n\t      else\n\t\tbn256_add (tmp, tmp, N);\n\t    }\n\t  break;\n\n\tcase 2:\n\t  bn256_shift (u, u, -1);\n\t  if (bn256_is_even (A))\n\t    {\n\t      bn256_add (tmp, A, N);\n\t      carry = 0;\n\t    }\n\t  else\n\t    carry = bn256_add (A, A, N);\n\n\t  bn256_shift (A, A, -1);\n\t  A->word[7] |= carry * 0x80000000;\n\n\t  bn256_shift (tmp, tmp, -1);\n\t  if (bn256_is_even (tmp))\n\t    {\n\t      bn256_add (tmp, tmp, N);\n\t      carry = 0;\n\t    }\n\t  else\n\t    carry = bn256_add (tmp, tmp, N);\n\n\t  bn256_shift (tmp, tmp, -1);\n\t  tmp->word[7] |= carry * 0x80000000;\n\n\t  if (bn256_is_ge (tmp, tmp))\n\t    {\n\t      bn256_sub (tmp, tmp, tmp);\n\t      borrow = bn256_sub (tmp, tmp, tmp);\n\t      if (borrow)\n\t\tbn256_add (tmp, tmp, tmp);\n\t      else\n\t\tbn256_add (tmp, A, N);\n\t    }\n\t  else\n\t    {\n\t      bn256_sub (tmp, tmp, tmp);\n\t      borrow = bn256_sub (tmp, tmp, tmp);\n\t      if (borrow)\n\t\tbn256_add (tmp, tmp, tmp);\n\t      else\n\t\tbn256_add (tmp, tmp, N);\n\t    }\n\t  break;\n\n\tcase 0:\n\t  bn256_shift (tmp, tmp, -1);\n\t  if (bn256_is_even (tmp))\n\t    {\n\t      bn256_add (tmp, tmp, N);\n\t      carry = 0;\n\t    }\n\t  else\n\t    carry = bn256_add (tmp, tmp, N);\n\n\t  bn256_shift (tmp, tmp, -1);\n\t  tmp->word[7] |= carry * 0x80000000;\n\n\t  bn256_shift (tmp, tmp, -1);\n\t  if (bn256_is_even (tmp))\n\t    {\n\t      bn256_add (tmp, tmp, N);\n\t      carry = 0;\n\t    }\n\t  else\n\t    carry = bn256_add (tmp, tmp, N);\n\n\t  bn256_shift (tmp, tmp, -1);\n\t  tmp->word[7] |= carry * 0x80000000;\n\n\t  if (bn256_is_ge (u, v))\n\t    {\n\t      bn256_sub (u, u, v);\n\t      borrow = bn256_sub (A, A, C);\n\t      if (borrow)\n\t\tbn256_add (A, A, N);\n\t      else\n\t\tbn256_add (tmp, A, N);\n\t    }\n\t  else\n\t    {\n\t      bn256_sub (v, v, u);\n\t      borrow = bn256_sub (C, C, A);\n\t      if (borrow)\n\t\tbn256_add (C, C, N);\n\t      else\n\t\tbn256_add (tmp, C, N);\n\t    }\n\t  break;\n\t}\n    }\n#undef borrow\n}\n"
  },
  {
    "path": "src/mod.h",
    "content": "void mod_reduce (bn256 *X, const bn512 *A, const bn256 *B,\n\t\t const bn256 *MU_lower);\nvoid mod_inv (bn256 *X, const bn256 *A, const bn256 *N);\n"
  },
  {
    "path": "src/modp256r1.c",
    "content": "/*\n * modp256r1.c -- modulo arithmetic for p256r1\n *\n * Copyright (C) 2011, 2013, 2014, 2016\n *               Free Software Initiative of Japan\n * Author: NIIBE Yutaka <gniibe@fsij.org>\n *\n * This file is a part of Gnuk, a GnuPG USB Token implementation.\n *\n * Gnuk is free software: you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Gnuk is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public\n * License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n/*\n * p256 =  2^256 - 2^224 + 2^192 + 2^96 - 1\n */\n#include <stdint.h>\n#include <string.h>\n\n#include \"bn.h\"\n#include \"modp256r1.h\"\n\n/*\n256      224      192      160      128       96       64       32        0\n2^256\n  1 00000000 00000000 00000000 00000000 00000000 00000000 00000000 00000000\n2^256 - 2^224\n  0 ffffffff 00000000 00000000 00000000 00000000 00000000 00000000 00000000\n2^256 - 2^224 + 2^192\n  0 ffffffff 00000001 00000000 00000000 00000000 00000000 00000000 00000000\n2^256 - 2^224 + 2^192 + 2^96\n  0 ffffffff 00000001 00000000 00000000 00000001 00000000 00000000 00000000\n2^256 - 2^224 + 2^192 + 2^96 - 1\n  0 ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff\n*/\nconst bn256 p256r1 = { {0xffffffff, 0xffffffff, 0xffffffff, 0x00000000,\n\t\t\t0x00000000, 0x00000000, 0x00000001, 0xffffffff} };\n\n/*\n * Implementation Note.\n *\n * It's always modulo p256r1.\n *\n * Once, I tried redundant representation which caused wrong\n * calculation.  Implementation could be correct with redundant\n * representation, but it found that it's more expensive.\n *\n */\n\n/**\n * @brief  X = (A + B) mod p256r1\n */\nvoid\nmodp256r1_add (bn256 *X, const bn256 *A, const bn256 *B)\n{\n  uint32_t cond;\n  bn256 tmp[1];\n\n  cond = (bn256_add (X, A, B) == 0);\n  cond &= bn256_sub (tmp, X, P256R1);\n  if (cond)\n    /* No-carry AND borrow */\n    memcpy (tmp, tmp, sizeof (bn256));\n  else\n    memcpy (X, tmp, sizeof (bn256));\n}\n\n/**\n * @brief  X = (A - B) mod p256r1\n */\nvoid\nmodp256r1_sub (bn256 *X, const bn256 *A, const bn256 *B)\n{\n  uint32_t borrow;\n  bn256 tmp[1];\n\n  borrow = bn256_sub (X, A, B);\n  bn256_add (tmp, X, P256R1);\n  if (borrow)\n    memcpy (X, tmp, sizeof (bn256));\n  else\n    memcpy (tmp, tmp, sizeof (bn256));\n}\n\n/**\n * @brief  X = A mod p256r1\n */\nvoid\nmodp256r1_reduce (bn256 *X, const bn512 *A)\n{\n  bn256 tmp[1], tmp0[1];\n  uint32_t borrow;\n\n#define S1 X\n#define S2 tmp\n#define S3 tmp\n#define S4 tmp\n#define S5 tmp\n#define S6 tmp\n#define S7 tmp\n#define S8 tmp\n#define S9 tmp\n\n  S1->word[7] = A->word[7];\n  S1->word[6] = A->word[6];\n  S1->word[5] = A->word[5];\n  S1->word[4] = A->word[4];\n  S1->word[3] = A->word[3];\n  S1->word[2] = A->word[2];\n  S1->word[1] = A->word[1];\n  S1->word[0] = A->word[0];\n  borrow = bn256_sub (tmp0, S1, P256R1);\n  if (borrow)\n    memcpy (tmp0, tmp0, sizeof (bn256));\n  else\n    memcpy (S1, tmp0, sizeof (bn256));\n  /* X = S1 */\n\n  S2->word[7] = A->word[15];\n  S2->word[6] = A->word[14];\n  S2->word[5] = A->word[13];\n  S2->word[4] = A->word[12];\n  S2->word[3] = A->word[11];\n  S2->word[2] = S2->word[1] = S2->word[0] = 0;\n  /* X += 2 * S2 */\n  modp256r1_add (X, X, S2);\n  modp256r1_add (X, X, S2);\n\n  S3->word[7] = 0;\n  S3->word[6] = A->word[15];\n  S3->word[5] = A->word[14];\n  S3->word[4] = A->word[13];\n  S3->word[3] = A->word[12];\n  S3->word[2] = S3->word[1] = S3->word[0] = 0;\n  /* X += 2 * S3 */\n  modp256r1_add (X, X, S3);\n  modp256r1_add (X, X, S3);\n\n  S4->word[7] = A->word[15];\n  S4->word[6] = A->word[14];\n  S4->word[5] = S4->word[4] = S4->word[3] = 0;\n  S4->word[2] = A->word[10];\n  S4->word[1] = A->word[9];\n  S4->word[0] = A->word[8];\n  /* X += S4 */\n  modp256r1_add (X, X, S4);\n\n  S5->word[7] = A->word[8];\n  S5->word[6] = A->word[13];\n  S5->word[5] = A->word[15];\n  S5->word[4] = A->word[14];\n  S5->word[3] = A->word[13];\n  S5->word[2] = A->word[11];\n  S5->word[1] = A->word[10];\n  S5->word[0] = A->word[9];\n  borrow = bn256_sub (tmp0, S5, P256R1);\n  if (borrow)\n    memcpy (tmp0, tmp0, sizeof (bn256));\n  else\n    memcpy (S5, tmp0, sizeof (bn256));\n  /* X += S5 */\n  modp256r1_add (X, X, S5);\n\n  S6->word[7] = A->word[10];\n  S6->word[6] = A->word[8];\n  S6->word[5] = S6->word[4] = S6->word[3] = 0;\n  S6->word[2] = A->word[13];\n  S6->word[1] = A->word[12];\n  S6->word[0] = A->word[11];\n  borrow = bn256_sub (tmp0, S6, P256R1);\n  if (borrow)\n    memcpy (tmp0, tmp0, sizeof (bn256));\n  else\n    memcpy (S6, tmp0, sizeof (bn256));\n  /* X -= S6 */\n  modp256r1_sub (X, X, S6);\n\n  S7->word[7] = A->word[11];\n  S7->word[6] = A->word[9];\n  S7->word[5] = S7->word[4] = 0;\n  S7->word[3] = A->word[15];\n  S7->word[2] = A->word[14];\n  S7->word[1] = A->word[13];\n  S7->word[0] = A->word[12];\n  borrow = bn256_sub (tmp0, S7, P256R1);\n  if (borrow)\n    memcpy (tmp0, tmp0, sizeof (bn256));\n  else\n    memcpy (S7, tmp0, sizeof (bn256));\n  /* X -= S7 */\n  modp256r1_sub (X, X, S7);\n\n  S8->word[7] = A->word[12];\n  S8->word[6] = 0;\n  S8->word[5] = A->word[10];\n  S8->word[4] = A->word[9];\n  S8->word[3] = A->word[8];\n  S8->word[2] = A->word[15];\n  S8->word[1] = A->word[14];\n  S8->word[0] = A->word[13];\n  /* X -= S8 */\n  modp256r1_sub (X, X, S8);\n\n  S9->word[7] = A->word[13];\n  S9->word[6] = 0;\n  S9->word[5] = A->word[11];\n  S9->word[4] = A->word[10];\n  S9->word[3] = A->word[9];\n  S9->word[2] = 0;\n  S9->word[1] = A->word[15];\n  S9->word[0] = A->word[14];\n  /* X -= S9 */\n  modp256r1_sub (X, X, S9);\n\n  borrow = bn256_sub (tmp, X, P256R1);\n  if (borrow)\n    memcpy (tmp, X, sizeof (bn256));\n  else\n    memcpy (X, tmp, sizeof (bn256));\n\n#undef S1\n#undef S2\n#undef S3\n#undef S4\n#undef S5\n#undef S6\n#undef S7\n#undef S8\n#undef S9\n}\n\n/**\n * @brief  X = (A * B) mod p256r1\n */\nvoid\nmodp256r1_mul (bn256 *X, const bn256 *A, const bn256 *B)\n{\n  bn512 AB[1];\n\n  bn256_mul (AB, A, B);\n  modp256r1_reduce (X, AB);\n}\n\n/**\n * @brief  X = A * A mod p256r1\n */\nvoid\nmodp256r1_sqr (bn256 *X, const bn256 *A)\n{\n  bn512 AA[1];\n\n  bn256_sqr (AA, A);\n  modp256r1_reduce (X, AA);\n}\n\n\n/**\n * @brief  X = (A << shift) mod p256r1\n * @note   shift < 32\n */\nvoid\nmodp256r1_shift (bn256 *X, const bn256 *A, int shift)\n{\n  uint32_t carry;\n#define borrow carry\n  bn256 tmp[1];\n\n  carry = bn256_shift (X, A, shift);\n  if (shift < 0)\n    return;\n\n  memset (tmp, 0, sizeof (bn256));\n  tmp->word[7] = carry;\n  tmp->word[0] = carry;\n  modp256r1_add (X, X, tmp);\n\n  tmp->word[7] = 0;\n  tmp->word[0] = 0;\n  tmp->word[6] = carry;\n  tmp->word[3] = carry;\n  modp256r1_sub (X, X, tmp);\n\n  borrow = bn256_sub (tmp, X, P256R1);\n  if (borrow)\n    memcpy (tmp, X, sizeof (bn256));\n  else\n    memcpy (X, tmp, sizeof (bn256));\n#undef borrow\n}\n"
  },
  {
    "path": "src/modp256r1.h",
    "content": "extern const bn256 p256r1;\n#define P256R1 (&p256r1)\n\nvoid modp256r1_add (bn256 *X, const bn256 *A, const bn256 *B);\nvoid modp256r1_sub (bn256 *X, const bn256 *A, const bn256 *B);\nvoid modp256r1_reduce (bn256 *X, const bn512 *A);\nvoid modp256r1_mul (bn256 *X, const bn256 *A, const bn256 *B);\nvoid modp256r1_sqr (bn256 *X, const bn256 *A);\nvoid modp256r1_shift (bn256 *X, const bn256 *A, int shift);\n"
  },
  {
    "path": "src/muladd_256.h",
    "content": "#define MULADD_256_ASM(s_,d_,w_,c_)                      \\\n asm ( \"ldmia  %[s]!, { r8, r9, r10 } \\n\\t\"              \\\n       \"ldmia  %[d], { r5, r6, r7 }   \\n\\t\"              \\\n       \"umull  r4, r8, %[w], r8       \\n\\t\"              \\\n       \"adds   r5, r5, r4             \\n\\t\"              \\\n       \"adcs   r6, r6, r8             \\n\\t\"              \\\n       \"umull  r4, r8, %[w], r9       \\n\\t\"              \\\n       \"adc    %[c], r8, #0           \\n\\t\"              \\\n       \"adds   r6, r6, r4             \\n\\t\"              \\\n       \"adcs   r7, r7, %[c]           \\n\\t\"              \\\n       \"umull  r4, r8, %[w], r10      \\n\\t\"              \\\n       \"adc    %[c], r8, #0           \\n\\t\"              \\\n       \"adds   r7, r7, r4             \\n\\t\"              \\\n       \"stmia  %[d]!, { r5, r6, r7 }  \\n\\t\"              \\\n       \"ldmia  %[s]!, { r8, r9, r10 } \\n\\t\"              \\\n       \"ldmia  %[d], { r5, r6, r7 }   \\n\\t\"              \\\n       \"adcs   r5, r5, %[c]           \\n\\t\"              \\\n       \"umull  r4, r8, %[w], r8       \\n\\t\"              \\\n       \"adc    %[c], r8, #0           \\n\\t\"              \\\n       \"adds   r5, r5, r4             \\n\\t\"              \\\n       \"adcs   r6, r6, %[c]           \\n\\t\"              \\\n       \"umull  r4, r8, %[w], r9       \\n\\t\"              \\\n       \"adc    %[c], r8, #0           \\n\\t\"              \\\n       \"adds   r6, r6, r4             \\n\\t\"              \\\n       \"adcs   r7, r7, %[c]           \\n\\t\"              \\\n       \"umull  r4, r8, %[w], r10      \\n\\t\"              \\\n       \"adc    %[c], r8, #0           \\n\\t\"              \\\n       \"adds   r7, r7, r4             \\n\\t\"              \\\n       \"stmia  %[d]!, { r5, r6, r7 }  \\n\\t\"              \\\n       \"ldmia  %[s]!, { r8, r9 }      \\n\\t\"              \\\n       \"ldmia  %[d], { r5, r6 }       \\n\\t\"              \\\n       \"adcs   r5, r5, %[c]           \\n\\t\"              \\\n       \"umull  r4, r8, %[w], r8       \\n\\t\"              \\\n       \"adc    %[c], r8, #0           \\n\\t\"              \\\n       \"adds   r5, r5, r4             \\n\\t\"              \\\n       \"adcs   r6, r6, %[c]           \\n\\t\"              \\\n       \"umull  r4, r8, %[w], r9       \\n\\t\"              \\\n       \"adc    %[c], r8, #0           \\n\\t\"              \\\n       \"adds   r6, r6, r4             \\n\\t\"              \\\n       \"adc    %[c], %[c], #0         \\n\\t\"              \\\n       \"stmia  %[d]!, { r5, r6 }\"                        \\\n       : [s] \"=&r\" (s_), [d] \"=&r\" (d_), [c] \"=&r\" (c_)  \\\n       : \"[s]\" (s_), \"[d]\" (d_), [w] \"r\" (w_)            \\\n       : \"r4\", \"r5\", \"r6\", \"r7\", \"r8\", \"r9\", \"r10\",      \\\n         \"memory\", \"cc\" )\n\n#define MULADD_256(s__,d__,w__,c__) do { \\\n  MULADD_256_ASM(s__,d__,w__,c__);\t \\\n  *d__ = c__;                            \\\n} while (0)\n"
  },
  {
    "path": "src/neug.c",
    "content": "/*\n * neug.c - true random number generation\n *\n * Copyright (C) 2011, 2012, 2013, 2016, 2017\n *               Free Software Initiative of Japan\n * Author: NIIBE Yutaka <gniibe@fsij.org>\n *\n * This file is a part of NeuG, a True Random Number Generator\n * implementation based on quantization error of ADC (for STM32F103).\n *\n * NeuG is free software: you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * NeuG is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public\n * License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include <stdint.h>\n#include <string.h>\n#include <chopstx.h>\n\n#include \"board.h\"\n#include \"sys.h\"\n#include \"neug.h\"\n#if !defined (GNU_LINUX_EMULATION) && !defined(MCU_EFM32HG)\n#include \"mcu/stm32f103.h\"\n#endif\n#include \"adc.h\"\n#include \"sha256.h\"\n\n#if defined (GNU_LINUX_EMULATION) || defined(MCU_EFM32HG)\nstatic const uint32_t crc32_rv_table[256] = {\n  0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9, 0x130476dc, 0x17c56b6b,\n  0x1a864db2, 0x1e475005, 0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61,\n  0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd, 0x4c11db70, 0x48d0c6c7,\n  0x4593e01e, 0x4152fda9, 0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75,\n  0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011, 0x791d4014, 0x7ddc5da3,\n  0x709f7b7a, 0x745e66cd, 0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039,\n  0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5, 0xbe2b5b58, 0xbaea46ef,\n  0xb7a96036, 0xb3687d81, 0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d,\n  0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49, 0xc7361b4c, 0xc3f706fb,\n  0xceb42022, 0xca753d95, 0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1,\n  0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d, 0x34867077, 0x30476dc0,\n  0x3d044b19, 0x39c556ae, 0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072,\n  0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16, 0x018aeb13, 0x054bf6a4,\n  0x0808d07d, 0x0cc9cdca, 0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde,\n  0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02, 0x5e9f46bf, 0x5a5e5b08,\n  0x571d7dd1, 0x53dc6066, 0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,\n  0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e, 0xbfa1b04b, 0xbb60adfc,\n  0xb6238b25, 0xb2e29692, 0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6,\n  0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a, 0xe0b41de7, 0xe4750050,\n  0xe9362689, 0xedf73b3e, 0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2,\n  0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686, 0xd5b88683, 0xd1799b34,\n  0xdc3abded, 0xd8fba05a, 0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637,\n  0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb, 0x4f040d56, 0x4bc510e1,\n  0x46863638, 0x42472b8f, 0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53,\n  0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47, 0x36194d42, 0x32d850f5,\n  0x3f9b762c, 0x3b5a6b9b, 0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff,\n  0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623, 0xf12f560e, 0xf5ee4bb9,\n  0xf8ad6d60, 0xfc6c70d7, 0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b,\n  0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f, 0xc423cd6a, 0xc0e2d0dd,\n  0xcda1f604, 0xc960ebb3, 0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7,\n  0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b, 0x9b3660c6, 0x9ff77d71,\n  0x92b45ba8, 0x9675461f, 0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3,\n  0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640, 0x4e8ee645, 0x4a4ffbf2,\n  0x470cdd2b, 0x43cdc09c, 0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8,\n  0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24, 0x119b4be9, 0x155a565e,\n  0x18197087, 0x1cd86d30, 0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,\n  0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088, 0x2497d08d, 0x2056cd3a,\n  0x2d15ebe3, 0x29d4f654, 0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0,\n  0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c, 0xe3a1cbc1, 0xe760d676,\n  0xea23f0af, 0xeee2ed18, 0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4,\n  0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0, 0x9abc8bd5, 0x9e7d9662,\n  0x933eb0bb, 0x97ffad0c, 0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668,\n  0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4\n};\n\nstatic uint32_t crc;\n\nvoid\ncrc32_rv_reset (void)\n{\n  crc = 0xffffffff;\n}\n\nvoid\ncrc32_rv_step (uint32_t v)\n{\n  crc = crc32_rv_table[(crc ^ (v << 0))  >> 24] ^ (crc << 8);\n  crc = crc32_rv_table[(crc ^ (v << 8))  >> 24] ^ (crc << 8);\n  crc = crc32_rv_table[(crc ^ (v << 16)) >> 24] ^ (crc << 8);\n  crc = crc32_rv_table[(crc ^ (v << 24)) >> 24] ^ (crc << 8);\n}\n\nuint32_t\ncrc32_rv_get (void)\n{\n  return crc;\n}\n\nuint32_t\nrbit (uint32_t v)\n{\n  v = ((v >> 1) & 0x55555555) | ((v & 0x55555555) << 1);\n  v = ((v >> 2) & 0x33333333) | ((v & 0x33333333) << 2);\n  v = ((v >> 4) & 0x0F0F0F0F) | ((v & 0x0F0F0F0F) << 4);\n  v = ((v >> 8) & 0x00FF00FF) | ((v & 0x00FF00FF) << 8);\n  v = ( v >> 16             ) | ( v               << 16);\n  return v;\n}\n#else\nvoid\ncrc32_rv_reset (void)\n{\n  RCC->AHBENR |= RCC_AHBENR_CRCEN;\n  CRC->CR = CRC_CR_RESET;\n}\n\nvoid\ncrc32_rv_step (uint32_t v)\n{\n  CRC->DR = v;\n}\n\nuint32_t\ncrc32_rv_get (void)\n{\n  return CRC->DR;\n}\n\nuint32_t\nrbit (uint32_t v)\n{\n  uint32_t r;\n\n  asm (\"rbit\t%0, %1\" : \"=r\" (r) : \"r\" (v));\n  return r;\n}\n#endif\n\nstatic chopstx_mutex_t mode_mtx;\nstatic chopstx_cond_t  mode_cond;\n\nstatic sha256_context sha256_ctx_data;\nstatic uint32_t sha256_output[SHA256_DIGEST_SIZE/sizeof (uint32_t)];\n\n/*\n * To be a full entropy source, the requirement is to have N samples\n * for output of 256-bit, where:\n *\n *      N = (256 * 2) / <min-entropy of a sample>\n *\n * For example, N should be more than 103 for min-entropy = 5.0.\n *\n * On the other hand, in the section 6.2 \"Full Entropy Source\n * Requirements\", it says:\n *\n *     At least twice the block size of the underlying cryptographic\n *     primitive shall be provided as input to the conditioning\n *     function to produce full entropy output.\n *\n * For us, cryptographic primitive is SHA-256 and its blocksize is\n * 512-bit (64-byte), thus, N >= 128.\n *\n * We chose N=140.  Note that we have \"additional bits\" of 16-byte for\n * last block (feedback from previous output of SHA-256) to feed\n * hash_df function of SHA-256, together with sample data of 140-byte.\n *\n * N=140 corresponds to min-entropy >= 3.68.\n *\n */\n#define NUM_NOISE_INPUTS 140\n\n#define EP_ROUND_0 0 /* initial-five-byte and 3-byte, then 56-byte-input */\n#define EP_ROUND_1 1 /* 64-byte-input */\n#define EP_ROUND_2 2 /* 17-byte-input */\n#define EP_ROUND_RAW      3 /* 32-byte-input */\n#define EP_ROUND_RAW_DATA 4 /* 32-byte-input */\n\n#define EP_ROUND_0_INPUTS 56\n#define EP_ROUND_1_INPUTS 64\n#define EP_ROUND_2_INPUTS 17\n#define EP_ROUND_RAW_INPUTS 32\n#define EP_ROUND_RAW_DATA_INPUTS 32\n\nstatic uint8_t ep_round;\n\nstatic void noise_source_continuous_test (uint8_t noise);\nstatic void noise_source_continuous_test_word (uint8_t b0, uint8_t b1,\n\t\t\t\t\t       uint8_t b2, uint8_t b3);\n\n/*\n * Hash_df initial string:\n *\n *  Initial five bytes are:\n *    1,          : counter = 1\n *    0, 0, 1, 0  : no_of_bits_returned (in big endian)\n *\n *  Then, three-byte from noise source follows.\n *\n *  One-byte was used in the previous turn, and we have three bytes in\n *  CRC32.\n */\nstatic void ep_fill_initial_string (void)\n{\n  uint32_t v = crc32_rv_get ();\n  uint8_t b1, b2, b3;\n\n  b3 = v >> 24;\n  b2 = v >> 16;\n  b1 = v >> 8;\n\n  noise_source_continuous_test (b1);\n  noise_source_continuous_test (b2);\n  noise_source_continuous_test (b3);\n\n  adc_buf[0] = 0x01000001;\n  adc_buf[1] = (v & 0xffffff00);\n}\n\nstatic void ep_init (int mode)\n{\n  if (mode == NEUG_MODE_RAW)\n    {\n      ep_round = EP_ROUND_RAW;\n      adc_start_conversion (0, EP_ROUND_RAW_INPUTS);\n    }\n  else if (mode == NEUG_MODE_RAW_DATA)\n    {\n      ep_round = EP_ROUND_RAW_DATA;\n      adc_start_conversion (0, EP_ROUND_RAW_DATA_INPUTS / 4);\n    }\n  else\n    {\n      ep_round = EP_ROUND_0;\n      ep_fill_initial_string ();\n      adc_start_conversion (2, EP_ROUND_0_INPUTS);\n    }\n}\n\n\nstatic void ep_fill_wbuf_v (int i, int test, uint32_t v)\n{\n  if (test)\n    {\n      uint8_t b0, b1, b2, b3;\n\n      b3 = v >> 24;\n      b2 = v >> 16;\n      b1 = v >> 8;\n      b0 = v;\n\n      noise_source_continuous_test_word (b0, b1, b2, b3);\n    }\n\n  sha256_ctx_data.wbuf[i] = v;\n}\n\n/* Here, we assume a little endian architecture.  */\nstatic int ep_process (int mode)\n{\n  int i, n;\n  uint32_t v;\n\n  if (ep_round == EP_ROUND_0)\n    {\n      sha256_start (&sha256_ctx_data);\n      sha256_ctx_data.wbuf[0] = adc_buf[0];\n      sha256_ctx_data.wbuf[1] = adc_buf[1];\n      for (i = 0; i < EP_ROUND_0_INPUTS / 4; i++)\n\t{\n\t  crc32_rv_step (adc_buf[i*4 + 2]);\n\t  crc32_rv_step (adc_buf[i*4 + 3]);\n\t  crc32_rv_step (adc_buf[i*4 + 4]);\n\t  crc32_rv_step (adc_buf[i*4 + 5]);\n\t  v = crc32_rv_get ();\n\t  ep_fill_wbuf_v (i+2, 1, v);\n\t}\n\n      adc_start_conversion (0, EP_ROUND_1_INPUTS);\n      sha256_process (&sha256_ctx_data);\n      ep_round++;\n      return 0;\n    }\n  else if (ep_round == EP_ROUND_1)\n    {\n      for (i = 0; i < EP_ROUND_1_INPUTS / 4; i++)\n\t{\n\t  crc32_rv_step (adc_buf[i*4]);\n\t  crc32_rv_step (adc_buf[i*4 + 1]);\n\t  crc32_rv_step (adc_buf[i*4 + 2]);\n\t  crc32_rv_step (adc_buf[i*4 + 3]);\n\t  v = crc32_rv_get ();\n\t  ep_fill_wbuf_v (i, 1, v);\n\t}\n\n      adc_start_conversion (0, EP_ROUND_2_INPUTS + 3);\n      sha256_process (&sha256_ctx_data);\n      ep_round++;\n      return 0;\n    }\n  else if (ep_round == EP_ROUND_2)\n    {\n      for (i = 0; i < EP_ROUND_2_INPUTS / 4; i++)\n\t{\n\t  crc32_rv_step (adc_buf[i*4]);\n\t  crc32_rv_step (adc_buf[i*4 + 1]);\n\t  crc32_rv_step (adc_buf[i*4 + 2]);\n\t  crc32_rv_step (adc_buf[i*4 + 3]);\n\t  v = crc32_rv_get ();\n\t  ep_fill_wbuf_v (i, 1, v);\n\t}\n\n      crc32_rv_step (adc_buf[i*4]);\n      crc32_rv_step (adc_buf[i*4 + 1]);\n      crc32_rv_step (adc_buf[i*4 + 2]);\n      crc32_rv_step (adc_buf[i*4 + 3]);\n      v = crc32_rv_get () & 0xff;   /* First byte of CRC32 is used here.  */\n      noise_source_continuous_test (v);\n      sha256_ctx_data.wbuf[i] = v;\n      ep_init (NEUG_MODE_CONDITIONED); /* The rest three-byte of\n\t\t\t\t\t  CRC32 is used here.  */\n      n = SHA256_DIGEST_SIZE / 2;\n      memcpy (((uint8_t *)sha256_ctx_data.wbuf) + EP_ROUND_2_INPUTS,\n\t      sha256_output, n);\n      sha256_ctx_data.total[0] = 5 + NUM_NOISE_INPUTS + n;\n      sha256_finish (&sha256_ctx_data, (uint8_t *)sha256_output);\n      return SHA256_DIGEST_SIZE / sizeof (uint32_t);\n    }\n  else if (ep_round == EP_ROUND_RAW)\n    {\n      for (i = 0; i < EP_ROUND_RAW_INPUTS / 4; i++)\n\t{\n\t  crc32_rv_step (adc_buf[i*4]);\n\t  crc32_rv_step (adc_buf[i*4 + 1]);\n\t  crc32_rv_step (adc_buf[i*4 + 2]);\n\t  crc32_rv_step (adc_buf[i*4 + 3]);\n\t  v = crc32_rv_get ();\n\t  ep_fill_wbuf_v (i, 1, v);\n\t}\n\n      ep_init (mode);\n      return EP_ROUND_RAW_INPUTS / 4;\n    }\n  else if (ep_round == EP_ROUND_RAW_DATA)\n    {\n      for (i = 0; i < EP_ROUND_RAW_DATA_INPUTS / 4; i++)\n\t{\n\t  v = adc_buf[i];\n\t  ep_fill_wbuf_v (i, 0, v);\n\t}\n\n      ep_init (mode);\n      return EP_ROUND_RAW_DATA_INPUTS / 4;\n    }\n\n  return 0;\n}\n\n\nstatic const uint32_t *ep_output (int mode)\n{\n  if (mode)\n    return sha256_ctx_data.wbuf;\n  else\n    return sha256_output;\n}\n\f\n#define REPETITION_COUNT           1\n#define ADAPTIVE_PROPORTION_64     2\n#define ADAPTIVE_PROPORTION_4096   4\n\nuint8_t neug_err_state;\nuint16_t neug_err_cnt;\nuint16_t neug_err_cnt_rc;\nuint16_t neug_err_cnt_p64;\nuint16_t neug_err_cnt_p4k;\n\nuint16_t neug_rc_max;\nuint16_t neug_p64_max;\nuint16_t neug_p4k_max;\n\nstatic void noise_source_cnt_max_reset (void)\n{\n  neug_err_cnt = neug_err_cnt_rc = neug_err_cnt_p64 = neug_err_cnt_p4k = 0;\n  neug_rc_max = neug_p64_max = neug_p4k_max = 0;\n}\n\nstatic void noise_source_error_reset (void)\n{\n  neug_err_state = 0;\n}\n\nstatic void noise_source_error (uint32_t err)\n{\n  neug_err_state |= err;\n  neug_err_cnt++;\n\n  if ((err & REPETITION_COUNT))\n    neug_err_cnt_rc++;\n  if ((err & ADAPTIVE_PROPORTION_64))\n    neug_err_cnt_p64++;\n  if ((err & ADAPTIVE_PROPORTION_4096))\n    neug_err_cnt_p4k++;\n}\n\n/*\n * For health tests, we assume that the device noise source has\n * min-entropy >= 4.2.  Observing raw data stream (before CRC-32) has\n * more than 4.2 bit/byte entropy.  When the data stream after CRC-32\n * filter will be less than 4.2 bit/byte entropy, that must be\n * something wrong.  Note that even we observe < 4.2, we still have\n * some margin, since we use NUM_NOISE_INPUTS=140.\n *\n */\n\n/* Cuttoff = 9, when min-entropy = 4.2, W= 2^-30 */\n/* ceiling of (1+30/4.2) */\n#define REPITITION_COUNT_TEST_CUTOFF 9\n\nstatic uint8_t rct_a;\nstatic uint8_t rct_b;\n\nstatic void repetition_count_test (uint8_t sample)\n{\n  if (rct_a == sample)\n    {\n      rct_b++;\n      if (rct_b >= REPITITION_COUNT_TEST_CUTOFF)\n\tnoise_source_error (REPETITION_COUNT);\n      if (rct_b > neug_rc_max)\n\tneug_rc_max = rct_b;\n   }\n  else\n    {\n      rct_a = sample;\n      rct_b = 1;\n    }\n}\n\nstatic void repetition_count_test_word (uint8_t b0, uint8_t b1,\n\t\t\t\t\tuint8_t b2, uint8_t b3)\n{\n  if (rct_a == b0)\n    rct_b++;\n  else\n    {\n      rct_a = b0;\n      rct_b = 1;\n    }\n\n  if (rct_a == b1)\n    rct_b++;\n  else\n    {\n      rct_a = b1;\n      rct_b = 1;\n    }\n\n  if (rct_a == b2)\n    rct_b++;\n  else\n    {\n      rct_a = b2;\n      rct_b = 1;\n    }\n\n  if (rct_a == b3)\n    rct_b++;\n  else\n    {\n      rct_a = b3;\n      rct_b = 1;\n    }\n\n  if (rct_b >= REPITITION_COUNT_TEST_CUTOFF)\n    noise_source_error (REPETITION_COUNT);\n  if (rct_b > neug_rc_max)\n    neug_rc_max = rct_b;\n}\n\n/* Cuttoff = 18, when min-entropy = 4.2, W= 2^-30 */\n/* With R, qbinom(1-2^-30,64,2^-4.2) */\n#define ADAPTIVE_PROPORTION_64_TEST_CUTOFF 18\n\nstatic uint8_t ap64t_a;\nstatic uint8_t ap64t_b;\nstatic uint8_t ap64t_s;\n\nstatic void adaptive_proportion_64_test (uint8_t sample)\n{\n  if (ap64t_s++ >= 64)\n    {\n      ap64t_a = sample;\n      ap64t_s = 1;\n      ap64t_b = 0;\n    }\n  else\n    if (ap64t_a == sample)\n      {\n\tap64t_b++;\n\tif (ap64t_b > ADAPTIVE_PROPORTION_64_TEST_CUTOFF)\n\t  noise_source_error (ADAPTIVE_PROPORTION_64);\n\tif (ap64t_b > neug_p64_max)\n\t  neug_p64_max = ap64t_b;\n      }\n}\n\nstatic void adaptive_proportion_64_test_word (uint8_t b0, uint8_t b1,\n\t\t\t\t\t      uint8_t b2, uint8_t b3)\n{\n  if (ap64t_s >= 64)\n    {\n      ap64t_a = b0;\n      ap64t_s = 4;\n      ap64t_b = 0;\n    }\n  else\n    {\n      ap64t_s += 4;\n\n      if (ap64t_a == b0)\n\tap64t_b++;\n    }\n\n  if (ap64t_a == b1)\n    ap64t_b++;\n\n  if (ap64t_a == b2)\n    ap64t_b++;\n\n  if (ap64t_a == b3)\n    ap64t_b++;\n\n  if (ap64t_b > ADAPTIVE_PROPORTION_64_TEST_CUTOFF)\n    noise_source_error (ADAPTIVE_PROPORTION_64);\n  if (ap64t_b > neug_p64_max)\n    neug_p64_max = ap64t_b;\n}\n\n/* Cuttoff = 315, when min-entropy = 4.2, W= 2^-30 */\n/* With R, qbinom(1-2^-30,4096,2^-4.2) */\n#define ADAPTIVE_PROPORTION_4096_TEST_CUTOFF 315\n\nstatic uint8_t ap4096t_a;\nstatic uint16_t ap4096t_b;\nstatic uint16_t ap4096t_s;\n\nstatic void adaptive_proportion_4096_test (uint8_t sample)\n{\n  if (ap4096t_s++ >= 4096)\n    {\n      ap4096t_a = sample;\n      ap4096t_s = 1;\n      ap4096t_b = 0;\n    }\n  else\n    if (ap4096t_a == sample)\n      {\n\tap4096t_b++;\n\tif (ap4096t_b > ADAPTIVE_PROPORTION_4096_TEST_CUTOFF)\n\t  noise_source_error (ADAPTIVE_PROPORTION_4096);\n\tif (ap4096t_b > neug_p4k_max)\n\t  neug_p4k_max = ap4096t_b;\n      }\n}\n\nstatic void adaptive_proportion_4096_test_word (uint8_t b0, uint8_t b1,\n\t\t\t\t\t\tuint8_t b2, uint8_t b3)\n{\n  if (ap4096t_s >= 4096)\n    {\n      ap4096t_a = b0;\n      ap4096t_s = 4;\n      ap4096t_b = 0;\n    }\n  else\n    {\n      ap4096t_s += 4;\n\n      if (ap4096t_a == b0)\n\tap4096t_b++;\n    }\n\n  if (ap4096t_a == b1)\n    ap4096t_b++;\n\n  if (ap4096t_a == b2)\n\tap4096t_b++;\n\n  if (ap4096t_a == b3)\n    ap4096t_b++;\n\n  if (ap4096t_b > ADAPTIVE_PROPORTION_4096_TEST_CUTOFF)\n    noise_source_error (ADAPTIVE_PROPORTION_4096);\n  if (ap4096t_b > neug_p4k_max)\n    neug_p4k_max = ap4096t_b;\n}\n\n\nstatic void noise_source_continuous_test (uint8_t noise)\n{\n  repetition_count_test (noise);\n  adaptive_proportion_64_test (noise);\n  adaptive_proportion_4096_test (noise);\n}\n\nstatic void noise_source_continuous_test_word (uint8_t b0, uint8_t b1,\n\t\t\t\t\t       uint8_t b2, uint8_t b3)\n{\n  repetition_count_test_word (b0, b1, b2, b3);\n  adaptive_proportion_64_test_word (b0, b1, b2, b3);\n  adaptive_proportion_4096_test_word (b0, b1, b2, b3);\n}\n\f\n/*\n * Ring buffer, filled by generator, consumed by neug_get routine.\n */\nstruct rng_rb {\n  uint32_t *buf;\n  chopstx_mutex_t m;\n  chopstx_cond_t data_available;\n  chopstx_cond_t space_available;\n  uint8_t head, tail;\n  uint8_t size;\n  unsigned int full :1;\n  unsigned int empty :1;\n};\n\nstatic void rb_init (struct rng_rb *rb, uint32_t *p, uint8_t size)\n{\n  rb->buf = p;\n  rb->size = size;\n  chopstx_mutex_init (&rb->m);\n  chopstx_cond_init (&rb->data_available);\n  chopstx_cond_init (&rb->space_available);\n  rb->head = rb->tail = 0;\n  rb->full = 0;\n  rb->empty = 1;\n}\n\nstatic void rb_add (struct rng_rb *rb, uint32_t v)\n{\n  rb->buf[rb->tail++] = v;\n  if (rb->tail == rb->size)\n    rb->tail = 0;\n  if (rb->tail == rb->head)\n    rb->full = 1;\n  rb->empty = 0;\n}\n\nstatic uint32_t rb_del (struct rng_rb *rb)\n{\n  uint32_t v = rb->buf[rb->head++];\n\n  if (rb->head == rb->size)\n    rb->head = 0;\n  if (rb->head == rb->tail)\n    rb->empty = 1;\n  rb->full = 0;\n\n  return v;\n}\n\nuint8_t neug_mode;\nstatic int rng_should_terminate;\nstatic chopstx_t rng_thread;\n\n\n/**\n * @brief Random number generation thread.\n */\nstatic void *\nrng (void *arg)\n{\n  struct rng_rb *rb = (struct rng_rb *)arg;\n  int mode = neug_mode;\n\n  rng_should_terminate = 0;\n  chopstx_mutex_init (&mode_mtx);\n  chopstx_cond_init (&mode_cond);\n\n  /* Enable ADCs */\n  adc_start ();\n\n  ep_init (mode);\n  while (!rng_should_terminate)\n    {\n      int err;\n      int n;\n\n      err = adc_wait_completion ();\n\n      chopstx_mutex_lock (&mode_mtx);\n      if (err || mode != neug_mode)\n\t{\n\t  mode = neug_mode;\n\n\t  noise_source_cnt_max_reset ();\n\n\t  /* Discarding data available, re-initiate from the start.  */\n\t  ep_init (mode);\n\t  chopstx_cond_signal (&mode_cond);\n\t  chopstx_mutex_unlock (&mode_mtx);\n\t  continue;\n\t}\n      else\n\tchopstx_mutex_unlock (&mode_mtx);\n\n      if ((n = ep_process (mode)))\n\t{\n\t  int i;\n\t  const uint32_t *vp;\n\n\t  if (neug_err_state != 0\n\t      && (mode == NEUG_MODE_CONDITIONED || mode == NEUG_MODE_RAW))\n\t    {\n\t      /* Don't use the result and do it again.  */\n\t      noise_source_error_reset ();\n\t      continue;\n\t    }\n\n\t  vp = ep_output (mode);\n\n\t  chopstx_mutex_lock (&rb->m);\n\t  while (rb->full)\n\t    chopstx_cond_wait (&rb->space_available, &rb->m);\n\n\t  for (i = 0; i < n; i++)\n\t    {\n\t      rb_add (rb, *vp++);\n\t      if (rb->full)\n\t\tbreak;\n\t    }\n\n\t  chopstx_cond_signal (&rb->data_available);\n\t  chopstx_mutex_unlock (&rb->m);\n\t}\n    }\n\n  adc_stop ();\n\n  return NULL;\n}\n\nstatic struct rng_rb the_ring_buffer;\n\nextern uint8_t __process5_stack_base__[], __process5_stack_size__[];\n#define STACK_ADDR_RNG ((uint32_t)__process5_stack_base__)\n#define STACK_SIZE_RNG ((uint32_t)__process5_stack_size__)\n#define PRIO_RNG 2\n\n/**\n * @brief Initialize NeuG.\n */\nvoid\nneug_init (uint32_t *buf, uint8_t size)\n{\n  const uint32_t *u = (const uint32_t *)unique_device_id ();\n  struct rng_rb *rb = &the_ring_buffer;\n  int i;\n\n  crc32_rv_reset ();\n\n  /*\n   * This initialization ensures that it generates different sequence\n   * even if all physical conditions are same.\n   */\n  for (i = 0; i < 3; i++)\n    crc32_rv_step (*u++);\n\n  neug_mode = NEUG_MODE_CONDITIONED;\n  rb_init (rb, buf, size);\n\n  rng_thread = chopstx_create (PRIO_RNG, STACK_ADDR_RNG, STACK_SIZE_RNG,\n\t\t\t       rng, rb);\n}\n\n/**\n * @breif Flush random bytes.\n */\nvoid\nneug_flush (void)\n{\n  struct rng_rb *rb = &the_ring_buffer;\n\n  chopstx_mutex_lock (&rb->m);\n  while (!rb->empty)\n    (void)rb_del (rb);\n  chopstx_cond_signal (&rb->space_available);\n  chopstx_mutex_unlock (&rb->m);\n}\n\n\n/**\n * @brief  Wakes up RNG thread to generate random numbers.\n */\nvoid\nneug_kick_filling (void)\n{\n  struct rng_rb *rb = &the_ring_buffer;\n\n  chopstx_mutex_lock (&rb->m);\n  if (!rb->full)\n    chopstx_cond_signal (&rb->space_available);\n  chopstx_mutex_unlock (&rb->m);\n}\n\n/**\n * @brief  Get random word (32-bit) from NeuG.\n * @detail With NEUG_KICK_FILLING, it wakes up RNG thread.\n *         With NEUG_NO_KICK, it doesn't wake up RNG thread automatically,\n *         it is needed to call neug_kick_filling later.\n */\nuint32_t\nneug_get (int kick)\n{\n  struct rng_rb *rb = &the_ring_buffer;\n  uint32_t v;\n\n  chopstx_mutex_lock (&rb->m);\n  while (rb->empty)\n    chopstx_cond_wait (&rb->data_available, &rb->m);\n  v = rb_del (rb);\n  if (kick)\n    chopstx_cond_signal (&rb->space_available);\n  chopstx_mutex_unlock (&rb->m);\n\n  return v;\n}\n\nint\nneug_get_nonblock (uint32_t *p)\n{\n  struct rng_rb *rb = &the_ring_buffer;\n  int r = 0;\n\n  chopstx_mutex_lock (&rb->m);\n  if (rb->empty)\n    {\n      r = -1;\n      chopstx_cond_signal (&rb->space_available);\n    }\n  else\n    *p = rb_del (rb);\n  chopstx_mutex_unlock (&rb->m);\n\n  return r;\n}\n\nint neug_consume_random (void (*proc) (uint32_t, int))\n{\n  int i = 0;\n  struct rng_rb *rb = &the_ring_buffer;\n\n  chopstx_mutex_lock (&rb->m);\n  while (!rb->empty)\n    {\n      uint32_t v;\n\n      v = rb_del (rb);\n      proc (v, i);\n      i++;\n    }\n  chopstx_cond_signal (&rb->space_available);\n  chopstx_mutex_unlock (&rb->m);\n\n  return i;\n}\n\nvoid\nneug_wait_full (void)\n{\n  struct rng_rb *rb = &the_ring_buffer;\n\n  chopstx_mutex_lock (&rb->m);\n  while (!rb->full)\n    chopstx_cond_wait (&rb->data_available, &rb->m);\n  chopstx_mutex_unlock (&rb->m);\n}\n\nvoid\nneug_fini (void)\n{\n  rng_should_terminate = 1;\n  neug_get (1);\n  chopstx_join (rng_thread, NULL);\n}\n\nvoid\nneug_mode_select (uint8_t mode)\n{\n  if (neug_mode == mode)\n    return;\n\n  neug_wait_full ();\n\n  chopstx_mutex_lock (&mode_mtx);\n  neug_mode = mode;\n  neug_flush ();\n  chopstx_cond_wait (&mode_cond, &mode_mtx);\n  chopstx_mutex_unlock (&mode_mtx);\n\n  neug_wait_full ();\n  neug_flush ();\n}\n"
  },
  {
    "path": "src/neug.h",
    "content": "#define NEUG_NO_KICK      0\n#define NEUG_KICK_FILLING 1\n\n#define NEUG_PRE_LOOP 32\n\n#define NEUG_MODE_CONDITIONED 0\t/* Conditioned data.             */\n#define NEUG_MODE_RAW         1\t/* CRC-32 filtered sample data.  */\n#define NEUG_MODE_RAW_DATA    2\t/* Sample data directly.         */\n\nextern uint8_t neug_mode;\nextern uint16_t neug_err_cnt;\nextern uint16_t neug_err_cnt_rc;\nextern uint16_t neug_err_cnt_p64;\nextern uint16_t neug_err_cnt_p4k;\nextern uint16_t neug_rc_max;\nextern uint16_t neug_p64_max;\nextern uint16_t neug_p4k_max;\n\nvoid neug_init (uint32_t *buf, uint8_t size);\nuint32_t neug_get (int kick);\nint neug_get_nonblock (uint32_t *p);\nvoid neug_kick_filling (void);\nvoid neug_flush (void);\nvoid neug_wait_full (void);\nvoid neug_fini (void);\nvoid neug_mode_select (uint8_t mode);\n\nint neug_consume_random (void (*proc) (uint32_t, int));\n\nvoid crc32_rv_reset (void);\nvoid crc32_rv_step (uint32_t v);\nuint32_t crc32_rv_get (void);\nuint32_t rbit (uint32_t v);\n"
  },
  {
    "path": "src/pbt.c",
    "content": "/*\n * pbt.c - push button driver and user presence indicator\n *\n * Copyright (C) 2017 Sergei Glushchenko\n * Author: Sergei Glushchenko <gl.sergei@gmail.com>\n *\n * This file is a part of U2F firmware for STM32\n *\n * This program is free software: you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n * As additional permission under GNU GPL version 3 section 7, you may\n * distribute non-source form of the Program without the copy of the\n * GNU GPL normally required by section 4, provided you inform the\n * recipients of GNU GPL by a written offer.\n *\n */\n\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n#include <chopstx.h>\n\n#include \"board.h\"\n#include \"sys.h\"\n\n#include <mcu/stm32f103.h>\n\n#define PRIO_PBT 2\n\nextern uint8_t __process6_stack_base__[], __process6_stack_size__[];\n\n#define STACK_ADDR_PBT ((uint32_t)__process6_stack_base__)\n#define STACK_SIZE_PBT ((uint32_t)__process6_stack_size__)\n\n/* chopstx does not expose generic GPIO interface */\n\nstruct GPIO {\n  volatile uint32_t CRL;\n  volatile uint32_t CRH;\n  volatile uint32_t IDR;\n  volatile uint32_t ODR;\n  volatile uint32_t BSRR;\n  volatile uint32_t BRR;\n  volatile uint32_t LCKR;\n};\n\n#define GPIOA_BASE  (APB2PERIPH_BASE + 0x0800)\n#define GPIOA   ((struct GPIO *) GPIOA_BASE)\n#define GPIOB_BASE  (APB2PERIPH_BASE + 0x0C00)\n#define GPIOB   ((struct GPIO *) GPIOB_BASE)\n#define GPIOC_BASE  (APB2PERIPH_BASE + 0x1000)\n#define GPIOC   ((struct GPIO *) GPIOC_BASE)\n#define GPIOD_BASE  (APB2PERIPH_BASE + 0x1400)\n#define GPIOD   ((struct GPIO *) GPIOD_BASE)\n#define GPIOE_BASE  (APB2PERIPH_BASE + 0x1800)\n#define GPIOE   ((struct GPIO *) GPIOE_BASE)\n\n#if defined(TARGET_MAPLE_MINI)\n#define GPIO_PBT_RD    8\n#define GPIO_PBT_BASE  GPIOB_BASE\n#define GPIO_PBT_IS_LO 0\n#elif defined(TARGET_ST_DONGLE)\n#define GPIO_PBT_RD    5\n#define GPIO_PBT_BASE  GPIOA_BASE\n#define GPIO_PBT_IS_LO 1\n#elif defined(TARGET_U2F_DONGLE)\n#define GPIO_PBT_RD    14\n#define GPIO_PBT_BASE  GPIOC_BASE\n#define GPIO_PBT_IS_LO 1\n#endif\n\n#ifdef GPIO_PBT_BASE\nstatic struct GPIO *const GPIO_PBT = (struct GPIO *)GPIO_PBT_BASE;\n#endif\n\nstatic int touch = 0;\n\nstatic int\npbt_get (void)\n{\n  return ((GPIO_PBT->IDR >> GPIO_PBT_RD) & 1) ^ GPIO_PBT_IS_LO;\n}\n\nstatic chopstx_intr_t intr;\n\nstatic void *\npbt (void *arg)\n{\n  (void)arg;\n  uint32_t timeout;\n  uint32_t count = 0;\n  int since_last_touch = 0;\n\n  while (1)\n    {\n      timeout = 100 * 1000;  /* 0.1 sec */\n      struct chx_poll_head *pd_array[1] = {\n        (struct chx_poll_head *)&intr\n      };\n      chopstx_poll (&timeout, 1, pd_array);\n\n      if (!intr.ready && count > 0)\n        --count;\n\n      if (pbt_get ())\n        {\n          if (since_last_touch > 5)\n            {\n              touch ^= 1;\n              count = 100;       /* remember user presence for 10 seconds */\n            }\n          since_last_touch = 0;\n        }\n        else\n          ++since_last_touch;\n\n        if (since_last_touch > 1000)\n          since_last_touch = 1000;\n\n      if (count == 0)\n        touch = 0;\n    }\n\n  return NULL;\n}\n\nint\nuser_presence_get (void)\n{\n  return touch;\n}\n\nvoid\nuser_presence_reset (void)\n{\n  touch = 0;\n}\n\nvoid\npbt_init (void)\n{\n  const uint32_t line = GPIO_PBT_RD;\n\n  /* EXTIx[3:0]: EXTI x configuration (x= 8) - 0001: PB[x] pin */\n  AFIO->EXTICR[2] |= 1;\n  EXTI->IMR |= (1 << line);\n  EXTI->FTSR |= (1 << line);\n\n  chopstx_claim_irq (&intr, line);\n\n  chopstx_create (PRIO_PBT, STACK_ADDR_PBT, STACK_SIZE_PBT, pbt, NULL);\n}\n"
  },
  {
    "path": "src/pbt.h",
    "content": "#ifndef __U2F_PBT_H__\n\n#define __U2F_PBT_H__\n\nint\nuser_presence_get (void);\n\nvoid\nuser_presence_reset (void);\n\nvoid\npbt_init (void);\n\n#endif\n"
  },
  {
    "path": "src/platform.c",
    "content": "/*\n * platform.c - platform specific hacks\n *\n * Copyright (C) 2018 Sean Cross,\n *                    Sergei Glushchenko\n * Author: Sergei Glushchenko <gl.sergei@gmail.com>\n *\n * This file is a part of U2F firmware\n * Bootloader-spcific parts were copied ftom toboot.\n *\n * This program is free software: you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n * As additional permission under GNU GPL version 3 section 7, you may\n * distribute non-source form of the Program without the copy of the\n * GNU GPL normally required by section 4, provided you inform the\n * recipients of GNU GPL by a written offer.\n *\n */\n\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n#include \"board.h\"\n#include \"sys.h\"\n\n#if defined(TARGET_TOMU)\n#include \"toboot.h\"\n#include <mcu/efm32hg.h>\n\nstatic struct toboot_configuration\n__attribute__ ((used, section(\".toboot.config\")))\ntoboot_config = {\n  .align = 0,\n  .magic = TOBOOT_V2_MAGIC,\n  .reserved_gen = 0,\n  .start = 16,\n  .config = TOBOOT_CONFIG_FLAG_AUTORUN,\n  .lock_entry = 0,\n  .erase_mask_lo = 0x00000000,\n  .erase_mask_hi = 0xe0000000,\n  .reserved_hash = 0\n};\n\n#define LOCKBITS_BASE   (0x0FE04000UL) /* Lock-bits page base address */\n#define DEBUG_LOCK_WORD (LOCKBITS_BASE + (127 * 4))\n\nconst volatile uint32_t *dlw = (volatile uint32_t *) DEBUG_LOCK_WORD;\n\n#if defined(ENFORCE_DEBUG_LOCK)\n/* Debug lock EFM32HG device by clearing DEBUG LOCK WORD */\nstatic void\ndebug_lock_maybe (void)\n{\n  uint8_t zero[] = { 0x0, 0x0, 0x0, 0x0 };\n  if (*dlw != 0)\n    flash_write ((uintptr_t) dlw, zero, sizeof (zero));\n}\n#endif /* ENFORCE_DEBUG_LOCK */\n\n#else /* STM32F1x obiously */\n\n#define OPTION_BYTES_ADDR 0x1ffff800\n\n#if defined(ENFORCE_DEBUG_LOCK)\n/* Debug lock STM32F1x device */\nstatic void\ndebug_lock_maybe (void)\n{\n  uint32_t ob_val = * (uint32_t *) (OPTION_BYTES_ADDR);\n\n  if ((ob_val & 0xff) != 0xff)\n    {\n      flash_unlock ();\n      flash_protect ();\n      nvic_system_reset ();\n    }\n}\n#endif /* ENFORCE_DEBUG_LOCK */\n\n#endif /* TARGET_TOMU */\n\n/* Preform platform-specific actions */\nvoid\nplatform_init (void)\n{\n\n#if defined(ENFORCE_DEBUG_LOCK)\n  debug_lock_maybe ();\n#endif\n}\n"
  },
  {
    "path": "src/platform.h",
    "content": "#ifndef __U2F_PLATFORM_H__\n\n#define __U2F_PLATFORM_H__\n\nvoid\nplatform_init (void);\n\n#endif /* __U2F_PLATFORM_H__ */\n"
  },
  {
    "path": "src/random.c",
    "content": "/*\n * random.c -- get random bytes\n *\n * Copyright (C) 2010, 2011, 2012, 2013, 2015\n *               Free Software Initiative of Japan\n * Author: NIIBE Yutaka <gniibe@fsij.org>\n *\n * This file is a part of Gnuk, a GnuPG USB Token implementation.\n *\n * Gnuk is free software: you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * Gnuk is distributed in the hope that it will be useful, but WITHOUT\n * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY\n * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public\n * License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n */\n\n#include <stdint.h>\n#include <string.h>\n\n#include \"neug.h\"\n\n#define RANDOM_BYTES_LENGTH 32\nstatic uint32_t random_word[RANDOM_BYTES_LENGTH/sizeof (uint32_t)];\n\nvoid\nrandom_init (void)\n{\n  int i;\n\n  neug_init (random_word, RANDOM_BYTES_LENGTH/sizeof (uint32_t));\n\n  for (i = 0; i < NEUG_PRE_LOOP; i++)\n    (void)neug_get (NEUG_KICK_FILLING);\n}\n\nvoid\nrandom_fini (void)\n{\n  neug_fini ();\n}\n\n/*\n * Return pointer to random 32-byte\n */\nconst uint8_t *\nrandom_bytes_get (void)\n{\n  neug_wait_full ();\n  return (const uint8_t *)random_word;\n}\n\n/*\n * Free pointer to random 32-byte\n */\nvoid\nrandom_bytes_free (const uint8_t *p)\n{\n  (void)p;\n  memset (random_word, 0, RANDOM_BYTES_LENGTH);\n  neug_flush ();\n}\n\n/*\n * Return 4-byte salt\n */\nvoid\nrandom_get_salt (uint8_t *p)\n{\n  uint32_t rnd;\n\n  rnd = neug_get (NEUG_KICK_FILLING);\n  memcpy (p, &rnd, sizeof (uint32_t));\n  rnd = neug_get (NEUG_KICK_FILLING);\n  memcpy (p + sizeof (uint32_t), &rnd, sizeof (uint32_t));\n}\n\n\n/*\n * Random byte iterator\n */\nint\nrandom_gen (void *arg, unsigned char *out, size_t out_len)\n{\n  uint8_t *index_p = (uint8_t *)arg;\n  uint8_t index = *index_p;\n  size_t n;\n\n  while (out_len)\n    {\n      neug_wait_full ();\n\n      n = RANDOM_BYTES_LENGTH - index;\n      if (n > out_len)\n\tn = out_len;\n\n      memcpy (out, ((unsigned char *)random_word) + index, n);\n      out += n;\n      out_len -= n;\n      index += n;\n\n      if (index >= RANDOM_BYTES_LENGTH)\n\t{\n\t  index = 0;\n\t  neug_flush ();\n\t}\n    }\n\n  *index_p = index;\n\n  return 0;\n}\n"
  },
  {
    "path": "src/random.h",
    "content": "void random_init (void);\nvoid random_fini (void);\n\n/* 32-byte random bytes */\nconst uint8_t *random_bytes_get (void);\nvoid random_bytes_free (const uint8_t *p);\n\n/* 8-byte salt */\nvoid random_get_salt (uint8_t *p);\n\n/* iterator returning a byta at a time */\nint random_gen (void *arg, unsigned char *output, size_t output_len);\n"
  },
  {
    "path": "src/sha256.c",
    "content": "/*\n * sha256.c -- Compute SHA-256 hash\n *\n * Just for little endian architecture.\n *\n * Code taken from:\n *  http://gladman.plushost.co.uk/oldsite/cryptography_technology/sha/index.php\n *\n *  File names are sha2.c, sha2.h, brg_types.h, brg_endian.h\n *  in the archive sha2-07-01-07.zip.\n *\n * Code is modified in the style of PolarSSL API.\n *\n * See original copyright notice below.\n */\n/*\n ---------------------------------------------------------------------------\n Copyright (c) 2002, Dr Brian Gladman, Worcester, UK.   All rights reserved.\n\n LICENSE TERMS\n\n The free distribution and use of this software in both source and binary\n form is allowed (with or without changes) provided that:\n\n   1. distributions of this source code include the above copyright\n      notice, this list of conditions and the following disclaimer;\n\n   2. distributions in binary form include the above copyright\n      notice, this list of conditions and the following disclaimer\n      in the documentation and/or other associated materials;\n\n   3. the copyright holder's name is not used to endorse products\n      built using this software without specific written permission.\n\n ALTERNATIVELY, provided that this notice is retained in full, this product\n may be distributed under the terms of the GNU General Public License (GPL),\n in which case the provisions of the GPL apply INSTEAD OF those given above.\n\n DISCLAIMER\n\n This software is provided 'as is' with no explicit or implied warranties\n in respect of its properties, including, but not limited to, correctness\n and/or fitness for purpose.\n ---------------------------------------------------------------------------\n Issue Date: 01/08/2005\n*/\n\n#include <string.h>\n#include <stdint.h>\n#include <stdlib.h>\n#include \"sha256.h\"\n\n#define SHA256_MASK (SHA256_BLOCK_SIZE - 1)\n\nstatic void memcpy_output_bswap32 (unsigned char *dst, const uint32_t *p)\n{\n  int i;\n  uint32_t q = 0;\n\n  for (i = 0; i < 32; i++)\n    {\n      if ((i & 3) == 0)\n\tq = __builtin_bswap32 (p[i >> 2]); /* bswap32 is GCC extention */\n      dst[i] = q >> ((i & 3) * 8);\n    }\n}\n\n#define rotr32(x,n)   (((x) >> n) | ((x) << (32 - n)))\n\n#define ch(x,y,z)       ((z) ^ ((x) & ((y) ^ (z))))\n#define maj(x,y,z)      (((x) & (y)) | ((z) & ((x) ^ (y))))\n\n/* round transforms for SHA256 compression functions */\n#define vf(n,i) v[(n - i) & 7]\n\n#define hf(i) (p[i & 15] += \\\n    g_1(p[(i + 14) & 15]) + p[(i + 9) & 15] + g_0(p[(i + 1) & 15]))\n\n#define v_cycle0(i)                                 \\\n    p[i] = __builtin_bswap32 (p[i]);                \\\n    vf(7,i) += p[i] + k_0[i]                        \\\n    + s_1(vf(4,i)) + ch(vf(4,i),vf(5,i),vf(6,i));   \\\n    vf(3,i) += vf(7,i);                             \\\n    vf(7,i) += s_0(vf(0,i))+ maj(vf(0,i),vf(1,i),vf(2,i))\n\n#define v_cycle(i, j)                               \\\n    vf(7,i) += hf(i) + k_0[i+j]                     \\\n    + s_1(vf(4,i)) + ch(vf(4,i),vf(5,i),vf(6,i));   \\\n    vf(3,i) += vf(7,i);                             \\\n    vf(7,i) += s_0(vf(0,i))+ maj(vf(0,i),vf(1,i),vf(2,i))\n\n#define s_0(x)  (rotr32((x),  2) ^ rotr32((x), 13) ^ rotr32((x), 22))\n#define s_1(x)  (rotr32((x),  6) ^ rotr32((x), 11) ^ rotr32((x), 25))\n#define g_0(x)  (rotr32((x),  7) ^ rotr32((x), 18) ^ ((x) >>  3))\n#define g_1(x)  (rotr32((x), 17) ^ rotr32((x), 19) ^ ((x) >> 10))\n#define k_0     k256\n\nstatic const uint32_t k256[64] = {\n  0X428A2F98, 0X71374491, 0XB5C0FBCF, 0XE9B5DBA5,\n  0X3956C25B, 0X59F111F1, 0X923F82A4, 0XAB1C5ED5,\n  0XD807AA98, 0X12835B01, 0X243185BE, 0X550C7DC3,\n  0X72BE5D74, 0X80DEB1FE, 0X9BDC06A7, 0XC19BF174,\n  0XE49B69C1, 0XEFBE4786, 0X0FC19DC6, 0X240CA1CC,\n  0X2DE92C6F, 0X4A7484AA, 0X5CB0A9DC, 0X76F988DA,\n  0X983E5152, 0XA831C66D, 0XB00327C8, 0XBF597FC7,\n  0XC6E00BF3, 0XD5A79147, 0X06CA6351, 0X14292967,\n  0X27B70A85, 0X2E1B2138, 0X4D2C6DFC, 0X53380D13,\n  0X650A7354, 0X766A0ABB, 0X81C2C92E, 0X92722C85,\n  0XA2BFE8A1, 0XA81A664B, 0XC24B8B70, 0XC76C51A3,\n  0XD192E819, 0XD6990624, 0XF40E3585, 0X106AA070,\n  0X19A4C116, 0X1E376C08, 0X2748774C, 0X34B0BCB5,\n  0X391C0CB3, 0X4ED8AA4A, 0X5B9CCA4F, 0X682E6FF3,\n  0X748F82EE, 0X78A5636F, 0X84C87814, 0X8CC70208,\n  0X90BEFFFA, 0XA4506CEB, 0XBEF9A3F7, 0XC67178F2,\n};\n\nvoid\nsha256_process (sha256_context *ctx)\n{\n  uint32_t i;\n  uint32_t *p = ctx->wbuf;\n  uint32_t v[8];\n\n  memcpy (v, ctx->state, 8 * sizeof (uint32_t));\n\n  v_cycle0 ( 0); v_cycle0 ( 1); v_cycle0 ( 2); v_cycle0 ( 3);\n  v_cycle0 ( 4); v_cycle0 ( 5); v_cycle0 ( 6); v_cycle0 ( 7);\n  v_cycle0 ( 8); v_cycle0 ( 9); v_cycle0 (10); v_cycle0 (11);\n  v_cycle0 (12); v_cycle0 (13); v_cycle0 (14); v_cycle0 (15);\n\n  for (i = 16; i < 64; i += 16)\n    {\n      v_cycle ( 0, i); v_cycle ( 1, i); v_cycle ( 2, i); v_cycle ( 3, i);\n      v_cycle ( 4, i); v_cycle ( 5, i); v_cycle ( 6, i); v_cycle ( 7, i);\n      v_cycle ( 8, i); v_cycle ( 9, i); v_cycle (10, i); v_cycle (11, i);\n      v_cycle (12, i); v_cycle (13, i); v_cycle (14, i); v_cycle (15, i);\n    }\n\n  ctx->state[0] += v[0];\n  ctx->state[1] += v[1];\n  ctx->state[2] += v[2];\n  ctx->state[3] += v[3];\n  ctx->state[4] += v[4];\n  ctx->state[5] += v[5];\n  ctx->state[6] += v[6];\n  ctx->state[7] += v[7];\n}\n\nvoid\nsha256_update (sha256_context *ctx, const unsigned char *input,\n               unsigned int ilen)\n{\n  uint32_t left = (ctx->total[0] & SHA256_MASK);\n  uint32_t fill = SHA256_BLOCK_SIZE - left;\n\n  ctx->total[0] += ilen;\n  if (ctx->total[0] < ilen)\n    ctx->total[1]++;\n\n  while (ilen >= fill)\n    {\n      memcpy (((unsigned char*)ctx->wbuf) + left, input, fill);\n      sha256_process (ctx);\n      input += fill;\n      ilen -= fill;\n      left = 0;\n      fill = SHA256_BLOCK_SIZE;\n    }\n\n  memcpy (((unsigned char*)ctx->wbuf) + left, input, ilen);\n}\n\nvoid\nsha256_finish (sha256_context *ctx, unsigned char output[32])\n{\n  uint32_t last = (ctx->total[0] & SHA256_MASK);\n\n  ctx->wbuf[last >> 2] = __builtin_bswap32 (ctx->wbuf[last >> 2]);\n  ctx->wbuf[last >> 2] &= 0xffffff80 << (8 * (~last & 3));\n  ctx->wbuf[last >> 2] |= 0x00000080 << (8 * (~last & 3));\n  ctx->wbuf[last >> 2] = __builtin_bswap32 (ctx->wbuf[last >> 2]);\n\n  if (last > SHA256_BLOCK_SIZE - 9)\n    {\n      if (last < 60)\n        ctx->wbuf[15] = 0;\n      sha256_process (ctx);\n      last = 0;\n    }\n  else\n    last = (last >> 2) + 1;\n\n  while (last < 14)\n    ctx->wbuf[last++] = 0;\n\n  ctx->wbuf[14] = __builtin_bswap32 ((ctx->total[0] >> 29) | (ctx->total[1] << 3));\n  ctx->wbuf[15] = __builtin_bswap32 (ctx->total[0] << 3);\n  sha256_process (ctx);\n\n  memcpy_output_bswap32 (output, ctx->state);\n  memset (ctx, 0, sizeof (sha256_context));\n}\n\nstatic const uint32_t initial_state[8] =\n{\n  0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,\n  0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19\n};\n\nvoid\nsha256_start (sha256_context *ctx)\n{\n  ctx->total[0] = ctx->total[1] = 0;\n  memcpy (ctx->state, initial_state, 8 * sizeof(uint32_t));\n}\n\nvoid\nsha256 (const unsigned char *input, unsigned int ilen,\n        unsigned char output[32])\n{\n  sha256_context ctx;\n\n  sha256_start (&ctx);\n  sha256_update (&ctx, input, ilen);\n  sha256_finish (&ctx, output);\n}\n"
  },
  {
    "path": "src/sha256.h",
    "content": "#define SHA256_DIGEST_SIZE  32\n#define SHA256_BLOCK_SIZE   64\n\ntypedef struct\n{\n  uint32_t total[2];\n  uint32_t state[8];\n  uint32_t wbuf[16];\n} sha256_context;\n\nvoid sha256 (const unsigned char *input, unsigned int ilen,\n\t     unsigned char output[32]);\nvoid sha256_start (sha256_context *ctx);\nvoid sha256_finish (sha256_context *ctx, unsigned char output[32]);\nvoid sha256_update (sha256_context *ctx, const unsigned char *input,\n\t\t    unsigned int ilen);\nvoid sha256_process (sha256_context *ctx);\n"
  },
  {
    "path": "src/stm32f103.ld",
    "content": "/*\n * ST32F103 memory setup.\n */\n__main_stack_size__      = 0x0100; /* Idle+Exception handlers */\n__process0_stack_size__  = 0x0400; /* Main program            */\n__process1_stack_size__  = 0x0200; /* pwd                     */\n__process2_stack_size__  = 0x0200; /* blk                     */\n__process3_stack_size__  = 0x0200; /* usb-hid                 */\n__process4_stack_size__  = 0x1000; /* u2f-hid                 */\n__process5_stack_size__  = 0x0500; /* rng                     */\n__process6_stack_size__  = 0x0200; /* pbt                     */\n\nMEMORY\n{\n    flash0 : org = 0x08000000, len = 4k\n    flash  : org = 0x08000000+0x1000, len = 58k\n    flash1 : org = 0x08000000+0xf400, len = 3k\n    ram : org = 0x20000000, len = 20k\n}\n\n__ram_start__           = ORIGIN(ram);\n__ram_size__            = 20k;\n__ram_end__             = __ram_start__ + __ram_size__;\n\nSECTIONS\n{\n    . = 0;\n\n    .sys : ALIGN(4) SUBALIGN(4)\n    {\n\t_sys = .;\n\tKEEP(*(.vectors))\n\t. = ALIGN(16);\n\tKEEP(*(.sys.version))\n\tKEEP(*(.sys.board_id))\n\tKEEP(*(.sys.board_name))\n\tbuild/sys-*.o(.text)\n\tbuild/sys-*.o(.text.*)\n\tbuild/sys-*.o(.rodata)\n\tbuild/sys-*.o(.rodata.*)\n\t. = ALIGN(1024);\n\t*(.sys.0)\n\t*(.sys.1)\n\t*(.sys.2)\n    } > flash0\n\n    _text = .;\n\n    .startup : ALIGN(128) SUBALIGN(128)\n    {\n        KEEP(*(.startup.vectors))\n        . = ALIGN (16);\n    } > flash =0xffffffff\n\n    .text : ALIGN(16) SUBALIGN(16)\n    {\n        *(.text.startup.*)\n        *(.text)\n        *(.text.*)\n        *(.rodata)\n        *(.rodata.*)\n        *(.glue_7t)\n        *(.glue_7)\n        *(.gcc*)\n\t. = ALIGN(8);\n    } > flash\n\n    .ARM.extab : {*(.ARM.extab* .gnu.linkonce.armextab.*)} > flash\n\n    .ARM.exidx : {\n        PROVIDE(__exidx_start = .);\n        *(.ARM.exidx* .gnu.linkonce.armexidx.*)\n        PROVIDE(__exidx_end = .);\n     } > flash\n\n    .eh_frame_hdr : {*(.eh_frame_hdr)} > flash\n\n    .eh_frame : ONLY_IF_RO {*(.eh_frame)} > flash\n\n    .textalign : ONLY_IF_RO { . = ALIGN(8); } > flash\n\n    _etext = .;\n    _textdata = _etext;\n\n    .process_stack :\n    {\n        . = ALIGN(8);\n\n        __process6_stack_base__ = .;\n        . += __process6_stack_size__;\n        . = ALIGN(8);\n        __process6_stack_end__ = .;\n\n        __process5_stack_base__ = .;\n        . += __process5_stack_size__;\n        . = ALIGN(8);\n        __process5_stack_end__ = .;\n\n        __process4_stack_base__ = .;\n        . += __process4_stack_size__;\n        . = ALIGN(8);\n        __process4_stack_end__ = .;\n\n        __process3_stack_base__ = .;\n        . += __process3_stack_size__;\n        . = ALIGN(8);\n        __process3_stack_end__ = .;\n\n        __process2_stack_base__ = .;\n        . += __process2_stack_size__;\n        . = ALIGN(8);\n        __process2_stack_end__ = .;\n\n        __process1_stack_base__ = .;\n        . += __process1_stack_size__;\n        . = ALIGN(8);\n        __process1_stack_end__ = .;\n\n        __process0_stack_base__ = .;\n        . += __process0_stack_size__;\n        . = ALIGN(8);\n        __process0_stack_end__ = .;\n    } > ram\n\n    .main_stack :\n    {\n        . = ALIGN(8);\n        __main_stack_base__ = .;\n        . += __main_stack_size__;\n        . = ALIGN(8);\n        __main_stack_end__ = .;\n    } > ram\n\n    .data :\n    {\n        . = ALIGN(4);\n        PROVIDE(_data = .);\n        *(.data)\n        . = ALIGN(4);\n        *(.data.*)\n        . = ALIGN(4);\n        *(.ramtext)\n        . = ALIGN(4);\n        PROVIDE(_edata = .);\n    } > ram AT > flash\n\n    .bss :\n    {\n        . = ALIGN(4);\n        PROVIDE(_bss_start = .);\n        *(.bss)\n        . = ALIGN(4);\n        *(.bss.*)\n        . = ALIGN(4);\n        *(COMMON)\n        . = ALIGN(4);\n        PROVIDE(_bss_end = .);\n    } > ram\n\n    .flash_storage :\n    {\n        . = ALIGN (1024);\n        _attestation_cert_base = .;\n        *(.attestation.cert);\n        . = ALIGN (1024);\n        _device_key_base = .;\n        *(.device.key);\n        . = ALIGN (1024);\n        _auth_ctr_base = .;\n        *(.auth.ctr);\n        . = ALIGN (1024);\n    } > flash1\n\n    PROVIDE(end = .);\n    _end            = .;\n}\n\n__heap_base__   = _end;\n__heap_end__    = __ram_end__;\n"
  },
  {
    "path": "src/toboot.h",
    "content": "#ifndef TOBOOT_API_H_\n#define TOBOOT_API_H_\n\n#include <stdint.h>\n\n/// Store this configuration struct at offset 0x94 from the start\n/// of your binary image.\n/// You may set all RESERVED values to 0. as they will be calculated\n/// when the program is written to flash.\nstruct toboot_configuration {\n    /// Our LD script using ALIGN(8).\n    uint32_t align;\n\n    /// Set to 0x907070b2 to indicate a valid configuration header.\n    uint32_t magic;\n\n    /// Reserved value.  Used as a generational counter.  Toboot will\n    /// overwrite this value with a monotonically-increasing counter\n    /// every time a new image is burned.  This is used to determine\n    /// which image is the newest.\n    uint16_t reserved_gen;\n\n    /// The starting page for your program in 1024-byte blocks.\n    /// Toboot itself sets this to 0.  If this is nonzero, then it\n    /// must be located after the Toboot image.  Toboot is currently\n    /// under 5 kilobytes, so make sure this value is at least 6.\n    uint8_t  start;\n\n    /// Configuration bitmask.  See below for values.\n    uint8_t  config;\n\n    /// Set to 0x18349420 to prevent the user from entering Toboot manually.\n    /// Use this value with caution, as it can be used to lockout a Tomu.\n    uint32_t lock_entry;\n\n    /// A bitmask of sectors to erase when updating the program.  Each \"1\"\n    /// causes that sector to be erased, unless it's Toboot itself.  Bit values\n    /// determine flash blocks 0-31.\n    uint32_t erase_mask_lo;\n\n    /// A bitmask of sectors to erase when updating the program.  Each \"1\"\n    /// causes that sector to e erased.  Use these two values to e.g. force\n    /// private keys to be erased when updating.  Bit values determine flash\n    /// blocks 32-63.\n    uint32_t erase_mask_hi;\n\n    /// A hash of the entire header, minus this entry.  Toboot calculates\n    /// this when it programs the first block.  A Toboot configuration\n    /// header MUST have a valid hash in order to be considered valid.\n    uint32_t reserved_hash;\n} __attribute__((packed));\n\n/// Toboot V1.0 leaves IRQs enabled, mimicking the behavior of\n/// AN0042.  Toboot V2.0 makes this configurable by adding a\n/// bit to the configuration area.\n#define TOBOOT_CONFIG_FLAG_ENABLE_IRQ_MASK  0x01\n#define TOBOOT_CONFIG_FLAG_ENABLE_IRQ_SHIFT 0\n#define TOBOOT_CONFIG_FLAG_ENABLE_IRQ       (1 << 0)\n#define TOBOOT_CONFIG_FLAG_DISABLE_IRQ      (0 << 0)\n\n/// When running a normal program, you won't want Toboot to run.\n/// However, when developing new software it is handy to have\n/// Toboot run at poweron.  Set this flag to enter Toboot whenever\n/// the system has powered on for the first time.\n#define TOBOOT_CONFIG_FLAG_AUTORUN_MASK        0x02\n#define TOBOOT_CONFIG_FLAG_AUTORUN_SHIFT       1\n#define TOBOOT_CONFIG_FLAG_AUTORUN             (1 << 1)\n\n/// When we create a fake header, this flag will be set.  Otherwise,\n/// leave the flag cleared.\n#define TOBOOT_CONFIG_FAKE_MASK 0x04\n#define TOBOOT_CONFIG_FAKE_SHIFT 2\n#define TOBOOT_CONFIG_FAKE (1 << 2)\n\n/// Various magic values describing Toboot configuration headers.\n#define TOBOOT_V1_MAGIC         0x70B0\n#define TOBOOT_V1_MAGIC_MASK    0x0000ffff\n#define TOBOOT_V2_MAGIC         0x907070b2\n#define TOBOOT_V2_MAGIC_MASK    0xffffffff\n\n/// This value is used to prevent manual entry into Toboot.\n#define TOBOOT_LOCKOUT_MAGIC    0x18349420\n\n/// The seed value for the hash of Toboot's configuration header\n#define TOBOOT_HASH_SEED 0x037a5cf1\n\n/// This is the runtime part that lives at the start of RAM.\n/// Running programs can use this to force entry into Toboot\n/// during the next reboot.\nstruct toboot_runtime {\n    /// Set this to 0x74624346 and reboot to enter bootloader,\n    /// even if LOCKOUT is enabled.\n    uint32_t magic;\n\n    /// Set this to 0 when your program starts.\n    uint8_t  boot_count;\n\n    /// The bootloader should set this to 0x23 for Tomu.\n    uint8_t  board_model;\n\n    /// Unused.\n    uint16_t reserved;\n};\n\n/// Set runtime.magic to this value and reboot to force\n/// entry into Toboot.\n#define TOBOOT_FORCE_ENTRY_MAGIC    0x74624346\n\n/// Use this macro to define a Toboot V2 configuration.  If unspecified,\n/// your program will default to a legacy configuration, and will not have\n/// access to features such as autoboot.\n#define TOBOOT_CONFIGURATION(cfg)                                        \\\n    __attribute__ ((used, section(\".vectors\")))                          \\\n    const struct toboot_configuration __toboot_configuration = {         \\\n        .magic          = TOBOOT_V2_MAGIC,                               \\\n        .reserved_gen   = 0,                                             \\\n        .start          = 16,                                            \\\n        .config         = cfg,                                           \\\n        .lock_entry     = 0,                                             \\\n        .erase_mask_lo  = 0,                                             \\\n        .erase_mask_hi  = 0,                                             \\\n        .reserved_hash  = 0,                                             \\\n}\n\n#endif /* TOBOOT_API_H_ */\n"
  },
  {
    "path": "src/u2f-apdu.c",
    "content": "/*\n * u2f-apdu.c - U2F apdu commands\n *\n * Copyright (C) 2017-2019 Sergei Glushchenko\n * Author: Sergei Glushchenko <gl.sergei@gmail.com>\n *\n * This file is a part of U2F firmware for STM32\n *\n * This program is free software: you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n * As additional permission under GNU GPL version 3 section 7, you may\n * distribute non-source form of the Program without the copy of the\n * GNU GPL normally required by section 4, provided you inform the\n * recipients of GNU GPL by a written offer.\n *\n */\n\n#include <stdint.h>\n#include <string.h>\n#include \"sha256.h\"\n#include \"ecc.h\"\n#include \"hmac.h\"\n#include \"random.h\"\n#include \"board.h\"\n#include \"sys.h\"\n#include \"pbt.h\"\n\n#define CLA(apdu)  ((apdu)[0])\n#define INS(apdu)  ((apdu)[1])\n#define P1(apdu)   ((apdu)[2])\n#define P2(apdu)   ((apdu)[3])\n#define LC(apdu)   (((apdu)[4] << 16) | ((apdu)[5] << 8) | (apdu)[6])\n#define DATA(apdu) ((apdu) + 7)\n\n\n// General constants\n\n#define HASH_BLOCK_SIZE                 64\n#define HASH_RES_SIZE                   32\n\n#define U2F_EC_KEY_SIZE         32      // EC key size in bytes\n#define U2F_EC_POINT_SIZE       ((U2F_EC_KEY_SIZE * 2) + 1) // Size of EC point\n#define U2F_NONCE_SIZE          32      // size of nonce\n#define U2F_KH_SIZE             (HASH_RES_SIZE + U2F_NONCE_SIZE) // size of key handle\n#define U2F_PRIV_K_SIZE         32      // size of private key\n#define U2F_PUB_K_SIZE          64      // size of public key\n#define U2F_MAX_EC_SIG_SIZE     72      // Max size of DER coded EC signature\n#define U2F_CTR_SIZE            4       // Size of counter field\n#define U2F_APPID_SIZE          32      // Size of application id\n#define U2F_CHAL_SIZE           32      // Size of challenge\n\n#define ENC_SIZE(x)             ((x + 7) & 0xfff8)\n\n// EC (uncompressed) point\n\n#define U2F_POINT_UNCOMPRESSED  0x04    // Uncompressed point format\n\ntypedef struct {\n    uint8_t pointFormat;                // Point type\n    uint8_t x[U2F_EC_KEY_SIZE];         // X-value\n    uint8_t y[U2F_EC_KEY_SIZE];         // Y-value\n} U2F_EC_POINT;\n\n// U2F native commands\n\n#define U2F_REGISTER            0x01    // Registration command\n#define U2F_AUTHENTICATE        0x02    // Authenticate/sign command\n#define U2F_VERSION             0x03    // Read version string command\n\n#define U2F_VENDOR_FIRST        0x40    // First vendor defined command\n#define U2F_VENDOR_LAST         0xbf    // Last vendor defined command\n\n#define U2F_ATTESTATION_CERT    0x40    // Set attestation certificate and key\n\n// U2F_REGISTER command defines\n\n#define U2F_REGISTER_ID         0x05    // Version 2 registration identifier\n#define U2F_REGISTER_HASH_ID    0x00    // Version 2 hash identintifier\n\ntypedef struct {\n    uint8_t chal[U2F_CHAL_SIZE];        // Challenge\n    uint8_t appId[U2F_APPID_SIZE];      // Application id\n} __attribute__ ((packed)) U2F_REGISTER_REQ;\n\n#define ATTESTATION_DER_MAX_LEN 512\n\ntypedef struct {\n    uint8_t registerId;                       // Registration identifier (U2F_REGISTER_ID_V2)\n    U2F_EC_POINT pubKey;                      // Generated public key\n    uint8_t keyHandleLen;                     // Length of key handle\n    uint8_t keyHandle[U2F_KH_SIZE];           // Key handle\n    uint8_t attCert[ATTESTATION_DER_MAX_LEN]; // Attestation certificate\n    uint8_t pad[2 + U2F_MAX_EC_SIG_SIZE];     // For SW1 and SW2\n} __attribute__ ((packed)) U2F_REGISTER_RESP;\n\n// U2F_AUTHENTICATE command defines\n\n// Authentication control byte\n\n#define U2F_AUTH_ENFORCE        0x03    // Enforce user presence and sign\n#define U2F_AUTH_CHECK_ONLY     0x07    // Check only\n#define U2F_AUTH_FLAG_TUP       0x01    // Test of user presence set\n\ntypedef struct {\n    uint8_t chal[U2F_CHAL_SIZE];        // Challenge\n    uint8_t appId[U2F_APPID_SIZE];      // Application id\n    uint8_t keyHandleLen;               // Length of key handle\n    uint8_t keyHandle[U2F_KH_SIZE];     // Key handle\n} __attribute__ ((packed)) U2F_AUTHENTICATE_REQ;\n\ntypedef struct {\n    uint8_t flags;                      // U2F_AUTH_FLAG_ values\n    uint8_t ctr[U2F_CTR_SIZE];          // Counter field (big-endian)\n    uint8_t sig[U2F_MAX_EC_SIG_SIZE];   // Signature\n    uint8_t pad[2];                     // For SW1 and SW2\n} __attribute__ ((packed)) U2F_AUTHENTICATE_RESP;\n\n// U2F_ATTESTATION_CERT command defines\n\ntypedef struct {\n    uint8_t key[U2F_EC_KEY_SIZE];\n    uint8_t der[ATTESTATION_DER_MAX_LEN];\n} __attribute__ ((packed)) U2F_ATTESTATION_CERT_REQ;\n\n// Command status responses\n\n#define U2F_SW_NO_ERROR                 0x9000 // SW_NO_ERROR\n#define U2F_SW_WRONG_DATA               0x6A80 // SW_WRONG_DATA\n#define U2F_SW_CONDITIONS_NOT_SATISFIED 0x6985 // SW_CONDITIONS_NOT_SATISFIED\n#define U2F_SW_COMMAND_NOT_ALLOWED      0x6986 // SW_COMMAND_NOT_ALLOWED\n#define U2F_SW_INS_NOT_SUPPORTED        0x6D00 // SW_INS_NOT_SUPPORTED\n#define U2F_SW_WRONG_LENGTH             0x6700 // SW_INS_WRONG_LENGTH\n#define U2F_SW_BAD_CLA                  0x6E00 // SW_BAD_CLA\n\n/* simple RNG interface */\n\nstatic int\nrng (uint8_t *buf, size_t size)\n{\n  uint8_t rng_index = 0;\n  int res;\n\n  res = random_gen (&rng_index, buf, size);\n  random_bytes_free (NULL);   /* parameter isn't used. invokes neug_flush. */\n\n  return res;\n}\n\n/* device key */\n\nstruct device_key\n{\n  /* ECC private key unique for each device */\n  uint8_t key[U2F_PRIV_K_SIZE];\n  /* SHA256 of private key to verify its integrity */\n  uint8_t key_hash[HASH_RES_SIZE];\n  /* reserved for future use */\n  uint8_t resrved[1024 - U2F_PRIV_K_SIZE - HASH_RES_SIZE];\n};\n\nstruct device_key __attribute__ ((section(\".device.key\"))) device_key = { 0 };\n\nuint32_t __attribute__ ((section(\".auth.ctr\"))) auth_ctr[256] = { 0 };\nstatic uint32_t *ctr_addr = &(auth_ctr[0]);\n\nstruct attestation_cert_header\n{\n  uint32_t der_len;\n  const uint8_t *der;\n  const uint8_t *key;\n};\n\nstruct attestation_cert\n{\n  struct attestation_cert_header hdr;\n  uint8_t data[1024 - sizeof(struct attestation_cert_header)];\n};\n\n_Static_assert(sizeof(struct attestation_cert) == 1024, \"Wrong struct attestation_cert size\");\n\n#include \"cert/certificates.c\"\n\nstatic void\ndevice_key_gen (void)\n{\n  uint8_t key[U2F_PRIV_K_SIZE];\n  uint8_t key_hash[HASH_RES_SIZE];\n  sha256_context ctx;\n\n  sha256_start (&ctx);\n  sha256_update (&ctx, device_key.key, U2F_PRIV_K_SIZE);\n  sha256_finish (&ctx, key_hash);\n\n  if (memcmp (key_hash, device_key.key_hash, HASH_RES_SIZE) == 0)\n    return;\n\n  /* new device key needs to be generated */\n  rng (key, U2F_PRIV_K_SIZE);\n\n  sha256_start (&ctx);\n  sha256_update (&ctx, key, U2F_PRIV_K_SIZE);\n  sha256_finish (&ctx, key_hash);\n\n  /* write device key to flash */\n  flash_erase_page ((uintptr_t) &device_key);\n  flash_write ((uintptr_t) device_key.key, key, U2F_PRIV_K_SIZE);\n  flash_write ((uintptr_t) device_key.key_hash, key_hash, HASH_RES_SIZE);\n\n  /* erase auth counter */\n  flash_erase_page ((uintptr_t) ctr_addr);\n}\n\n\nstatic void\nnew_private_key (uint8_t *app_id, uint8_t *nonce, uint8_t *private_key)\n{\n  hmac_sha256_context ctx;\n\n  hmac_sha256_init (&ctx, device_key.key);\n  hmac_sha256_update (&ctx, app_id, U2F_APPID_SIZE);\n  hmac_sha256_update (&ctx, nonce, U2F_NONCE_SIZE);\n  hmac_sha256_finish (&ctx, device_key.key, private_key);\n}\n\nstatic void\nmake_key_handle (uint8_t *private_key, uint8_t *app_id,\n                 uint8_t *nonce, uint8_t *key_handle)\n{\n  hmac_sha256_context ctx;\n\n  hmac_sha256_init (&ctx, device_key.key);\n  hmac_sha256_update (&ctx, private_key, U2F_PRIV_K_SIZE);\n  hmac_sha256_update (&ctx, app_id, U2F_APPID_SIZE);\n  hmac_sha256_finish (&ctx, device_key.key, key_handle);\n\n  memcpy (key_handle + HASH_RES_SIZE, nonce, U2F_NONCE_SIZE);\n}\n\nstatic int\nrecover_private_key (uint8_t *app_id, uint8_t *key_handle,\n                     uint8_t key_handle_len, uint8_t *private_key)\n{\n  hmac_sha256_context ctx;\n  uint8_t control_mac[HASH_RES_SIZE];\n\n  if (key_handle_len != U2F_KH_SIZE)\n    return -1;\n\n  hmac_sha256_init (&ctx, device_key.key);\n  hmac_sha256_update (&ctx, app_id, U2F_APPID_SIZE);\n  hmac_sha256_update (&ctx, key_handle + HASH_RES_SIZE, U2F_NONCE_SIZE);\n  hmac_sha256_finish (&ctx, device_key.key, private_key);\n\n  hmac_sha256_init (&ctx, device_key.key);\n  hmac_sha256_update (&ctx, private_key, U2F_PRIV_K_SIZE);\n  hmac_sha256_update (&ctx, app_id, U2F_APPID_SIZE);\n  hmac_sha256_finish (&ctx, device_key.key, control_mac);\n\n  return memcmp(control_mac, key_handle, HASH_RES_SIZE);\n}\n\nstatic uint8_t\nder_encode_uint (uint8_t *der, uint8_t *x, uint8_t x_len)\n{\n  uint8_t len = 0;\n\n  /* integer */\n  der[len++] = 0x02;\n\n  /* reserve field for length, works only for short form */\n  der[len++] = 0;\n\n  /* omit leading zeros */\n  while (x[0] == 0 && x_len > 0)\n    {\n      ++x;\n      --x_len;\n    }\n\n  /* positive integer: 8th bit must be zero */\n  if (x[0] > 0x7f)\n    der[len++] = 0;\n\n  /* copy actual data */\n  memcpy (der + len, x, x_len);\n  len += x_len;\n\n  /* set length field */\n  der[1] = len - 2;\n\n  return len;\n}\n\nstatic uint8_t\nder_encode_sig (uint8_t *der, uint8_t *sig)\n{\n  uint8_t len;\n\n  len = 0;\n\n  der[len++] = 0x30;\n\n  /* reserve length field */\n  der[len++] = 0;\n\n  len += der_encode_uint (der + len, sig, 32);\n  len += der_encode_uint (der + len, sig + 32, 32);\n\n  der[1] = len - 2;\n\n  return len;\n}\n\nstatic void\nregister_req_hash (U2F_REGISTER_REQ *req, U2F_REGISTER_RESP *resp,\n                   uint8_t *hash)\n{\n  sha256_context ctx;\n  uint8_t resrved = 0;\n\n  sha256_start (&ctx);\n  sha256_update (&ctx, &resrved, 1);\n  sha256_update (&ctx, req->appId, U2F_APPID_SIZE);\n  sha256_update (&ctx, req->chal, U2F_CHAL_SIZE);\n  sha256_update (&ctx, resp->keyHandle, resp->keyHandleLen);\n  sha256_update (&ctx, (uint8_t *) &resp->pubKey, sizeof (resp->pubKey));\n  sha256_finish (&ctx, hash);\n}\n\nstatic int\nu2f_register (U2F_REGISTER_REQ *req, U2F_REGISTER_RESP *resp)\n{\n  uint8_t private[U2F_PRIV_K_SIZE];\n  uint8_t nonce[U2F_NONCE_SIZE];\n  uint8_t hash[HASH_RES_SIZE];\n  uint8_t sig[64];\n  uint8_t sig_len;\n\n  if (rng (nonce, U2F_NONCE_SIZE))\n    return -1;\n\n  new_private_key (req->appId, nonce, private);\n  make_key_handle (private, req->appId, nonce, resp->keyHandle);\n\n  if (ecc_compute_public_p256r1 (private, resp->pubKey.x))\n    return -1;\n\n  resp->registerId = U2F_REGISTER_ID;\n  resp->pubKey.pointFormat = U2F_POINT_UNCOMPRESSED;\n  resp->keyHandleLen = U2F_KH_SIZE;\n  memcpy (resp->attCert, attestation_cert.hdr.der, attestation_cert.hdr.der_len);\n\n  register_req_hash (req, resp, hash);\n\n  if (ecdsa_sign_p256r1 (hash, sig, attestation_cert.hdr.key))\n    return -1;\n\n  sig_len = der_encode_sig (resp->attCert + attestation_cert.hdr.der_len, sig);\n\n  return 1                              // Registration identifier (U2F_REGISTER_ID_V2)\n         + sizeof (U2F_EC_POINT)        // Generated public key\n         + 1                            // Length of key handle\n         + U2F_KH_SIZE                  // Key handle\n         + attestation_cert.hdr.der_len // Attestation certificate\n         + sig_len;                     // Registration signature\n}\n\nstatic uint32_t\nu2f_read_ctr (void)\n{\n  const int page_size = 1024 / sizeof (*ctr_addr);\n\n  while (*ctr_addr != 0xffffffff)\n    {\n      if (ctr_addr - &(auth_ctr[0]) == page_size)\n        break;\n      ctr_addr++;\n    }\n\n  if (ctr_addr == &(auth_ctr[0]))\n    return 0;\n\n  return ctr_addr[-1];\n}\n\nstatic void\nu2f_write_ctr (uint32_t val)\n{\n  const int page_size = 1024 / sizeof (*ctr_addr);\n\n  while (*ctr_addr != 0xffffffff)\n    {\n      if (ctr_addr - &(auth_ctr[0]) == page_size)\n        {\n          flash_erase_page ((uintptr_t) &(auth_ctr[0]));\n          ctr_addr = &(auth_ctr[0]);\n          break;\n        }\n      ctr_addr++;\n    }\n\n  flash_write ((uintptr_t) ctr_addr, (uint8_t *) &val, sizeof (val));\n}\n\nstatic void\nu2f_inc_ctr (void)\n{\n  uint32_t ctr;\n\n  ctr = u2f_read_ctr ();\n  ctr++;\n  u2f_write_ctr (ctr);\n}\n\nstatic void\nauth_req_hash (U2F_AUTHENTICATE_REQ *req, U2F_AUTHENTICATE_RESP *resp,\n               uint8_t *hash)\n{\n  sha256_context ctx;\n\n  sha256_start (&ctx);\n  sha256_update (&ctx, req->appId, U2F_APPID_SIZE);\n  sha256_update (&ctx, &resp->flags, 1);\n  sha256_update (&ctx, resp->ctr, 4);\n  sha256_update (&ctx, req->chal, U2F_CHAL_SIZE);\n  sha256_finish (&ctx, hash);\n}\n\nstatic int\nu2f_authenticate (U2F_AUTHENTICATE_REQ *req, U2F_AUTHENTICATE_RESP *resp)\n{\n  uint8_t private[U2F_PRIV_K_SIZE];\n  uint8_t hash[HASH_RES_SIZE];\n  uint8_t sig[64];\n  uint8_t sig_len;\n  uint32_t ctr;\n\n  resp->flags = U2F_AUTH_FLAG_TUP;\n\n  ctr = u2f_read_ctr ();\n\n  resp->ctr[0] = ctr >> 24 & 0xff;\n  resp->ctr[1] = ctr >> 16 & 0xff;\n  resp->ctr[2] = ctr >>  8 & 0xff;\n  resp->ctr[3] = ctr       & 0xff;\n\n  auth_req_hash (req, resp, hash);\n\n  if (recover_private_key (req->appId, req->keyHandle,\n                           req->keyHandleLen, private))\n    return -1;\n\n  if (ecdsa_sign_p256r1 (hash, sig, private))\n    return -1;\n\n  sig_len = der_encode_sig (resp->sig, sig);\n\n  return 1                        // U2F_AUTH_FLAG_ values\n         + U2F_CTR_SIZE           // Counter field (big-endian)\n         + sig_len;               // Signature\n}\n\nstatic int\nu2f_attestation_cert_initialized (void)\n{\n  return attestation_cert.hdr.der_len != (uint32_t) -1;\n}\n\nstatic int\nu2f_attestation_cert_initialize (uint32_t len, U2F_ATTESTATION_CERT_REQ *req)\n{\n  flash_erase_page ((uintptr_t) &attestation_cert);\n\n  struct attestation_cert_header tmp;\n  tmp.der_len = len - U2F_EC_KEY_SIZE;\n  tmp.key = ((uint8_t *) &attestation_cert) + 16;\n  tmp.der = tmp.key + U2F_EC_KEY_SIZE;\n  flash_write ((uintptr_t) &attestation_cert, (uint8_t *) &tmp, sizeof (tmp));\n\n  /* req->key and req->der are unaligned, we'll use temporary buffer */\n  uint8_t buf[16];\n\n  for (uint32_t i = 0; i < U2F_EC_KEY_SIZE; i += 16)\n    {\n      memcpy (buf, req->key + i, 16);\n      flash_write ((uintptr_t) tmp.key + i, buf, 16);\n    }\n\n  for (uint32_t i = 0; i < tmp.der_len; i += 16)\n    {\n      memcpy (buf, req->der + i, 16);\n      flash_write ((uintptr_t) tmp.der + i, buf, 16);\n    }\n\n  return 0;\n}\n\nstatic int\nu2f_version (uint8_t *resp)\n{\n  memcpy (resp, \"U2F_V2\", 6);\n  return 6;\n}\n\nstatic void\nappend_sw (uint8_t *msg, uint32_t *len, uint16_t sw)\n{\n  msg[(*len)++] = (sw >> 8) & 0xff;\n  msg[(*len)++] = sw & 0xff;\n}\n\nstatic void\nu2f_apdu_error (uint8_t *msg, uint32_t *len, uint16_t sw)\n{\n  *len = 0;\n  append_sw (msg, len, sw);\n}\n\nvoid\nu2f_apdu_init (void)\n{\n  /* generate and store device private key on first run */\n  device_key_gen ();\n}\n\nint\nu2f_apdu_command_do (uint8_t *apdu, uint32_t len,\n                     uint8_t *resp, uint32_t *resp_len)\n{\n  uint32_t Lc;\n  int ret;\n\n  Lc = LC (apdu);\n\n  if (CLA (apdu) != 0)\n    {\n      u2f_apdu_error (resp, resp_len, U2F_SW_BAD_CLA);\n      return 0;\n    }\n\n  if (Lc + 7 > len)\n    {\n      u2f_apdu_error (resp, resp_len, U2F_SW_WRONG_LENGTH);\n      return 0;\n    }\n\n  switch (INS (apdu))\n    {\n    case U2F_REGISTER:\n      if (!u2f_attestation_cert_initialized ())\n        {\n          u2f_apdu_error (resp, resp_len, U2F_SW_COMMAND_NOT_ALLOWED);\n          break;\n        }\n      if (Lc != sizeof (U2F_REGISTER_REQ))\n        {\n          u2f_apdu_error (resp, resp_len, U2F_SW_WRONG_LENGTH);\n          break;\n        }\n      if (!user_presence_get ())\n        {\n          u2f_apdu_error (resp, resp_len, U2F_SW_CONDITIONS_NOT_SATISFIED);\n          return 0;\n        }\n      ret = u2f_register ((U2F_REGISTER_REQ *) DATA (apdu),\n                          (U2F_REGISTER_RESP *) resp);\n      if (ret > 0)\n        {\n          user_presence_reset ();\n          *resp_len = ret;\n          append_sw (resp, resp_len, U2F_SW_NO_ERROR);\n        }\n      else\n        {\n          u2f_apdu_error (resp, resp_len, U2F_SW_WRONG_DATA);\n        }\n      break;\n    case U2F_AUTHENTICATE:\n      if (!u2f_attestation_cert_initialized ())\n        {\n          u2f_apdu_error (resp, resp_len, U2F_SW_COMMAND_NOT_ALLOWED);\n          break;\n        }\n      if (Lc != sizeof (U2F_AUTHENTICATE_REQ))\n        {\n          u2f_apdu_error (resp, resp_len, U2F_SW_WRONG_LENGTH);\n          break;\n        }\n      ret = u2f_authenticate ((U2F_AUTHENTICATE_REQ *) DATA (apdu),\n                              (U2F_AUTHENTICATE_RESP *)resp);\n      if (ret > 0)\n        {\n          if (P1 (apdu) != U2F_AUTH_CHECK_ONLY)\n            {\n            if (!user_presence_get ())\n              {\n                u2f_apdu_error (resp, resp_len,\n                                U2F_SW_CONDITIONS_NOT_SATISFIED);\n                return 0;\n              }\n              u2f_inc_ctr ();\n              user_presence_reset ();\n              *resp_len = ret;\n              append_sw (resp, resp_len, U2F_SW_NO_ERROR);\n            }\n          else\n            u2f_apdu_error (resp, resp_len, U2F_SW_CONDITIONS_NOT_SATISFIED);\n        }\n      else\n        u2f_apdu_error (resp, resp_len, U2F_SW_WRONG_DATA);\n      break;\n    case U2F_VERSION:\n      if (Lc > 0)\n        {\n          u2f_apdu_error (resp, resp_len, U2F_SW_WRONG_LENGTH);\n          break;\n        }\n      ret = u2f_version (resp);\n      if (ret > 0)\n        {\n          *resp_len = ret;\n          append_sw (resp, resp_len, U2F_SW_NO_ERROR);\n        }\n      break;\n    case U2F_ATTESTATION_CERT:\n      if (Lc <= U2F_EC_KEY_SIZE)\n        {\n          u2f_apdu_error (resp, resp_len, U2F_SW_WRONG_LENGTH);\n          break;\n        }\n      if (u2f_attestation_cert_initialized ())\n        {\n          u2f_apdu_error (resp, resp_len, U2F_SW_COMMAND_NOT_ALLOWED);\n          break;\n        }\n      ret = u2f_attestation_cert_initialize (\n              Lc, (U2F_ATTESTATION_CERT_REQ*) DATA(apdu));\n      if (ret < 0)\n        {\n          u2f_apdu_error (resp, resp_len, U2F_SW_WRONG_DATA);\n          break;\n        }\n      *resp_len = 0;\n      append_sw (resp, resp_len, U2F_SW_NO_ERROR);\n      break;\n    default:\n      u2f_apdu_error (resp, resp_len, U2F_SW_INS_NOT_SUPPORTED);\n    }\n\n  return 0;\n}\n\n"
  },
  {
    "path": "src/u2f-apdu.h",
    "content": "#ifndef __U2F_U2F_APDU_H__\n\n#define __U2F_U2F_APDU_H__\n\nvoid\nu2f_apdu_init (void);\n\nint\nu2f_apdu_command_do (uint8_t *apdu, uint32_t len,\n                     uint8_t *resp, uint32_t *resp_len);\n\n#endif\n"
  },
  {
    "path": "src/u2f-hid.c",
    "content": "/*\n * u2f-hid.c - U2F HID protocol\n *\n * Copyright (C) 2017-2019 Sergei Glushchenko\n * Author: Sergei Glushchenko <gl.sergei@gmail.com>\n *\n * This file is a part of U2F firmware for STM32\n *\n * This program is free software: you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n * As additional permission under GNU GPL version 3 section 7, you may\n * distribute non-source form of the Program without the copy of the\n * GNU GPL normally required by section 4, provided you inform the\n * recipients of GNU GPL by a written offer.\n *\n */\n\n#include <stdint.h>\n#include <string.h>\n#include <chopstx.h>\n\n#include \"board.h\"\n#include \"sys.h\"\n#include \"usb-hid.h\"\n#include \"u2f-hid.h\"\n#include \"u2f-apdu.h\"\n\n// Size of HID reports\n\n#define HID_RPT_SIZE            64      // Default size of raw HID report\n\n// Frame layout - command- and continuation frames\n\n#define CID_BROADCAST           0xffffffff // Broadcast channel id\n\n#define TYPE_MASK               0x80    // Frame type mask\n#define TYPE_INIT               0x80    // Initial frame identifier\n#define TYPE_CONT               0x00    // Continuation frame identifier\n\ntypedef struct {\n  uint32_t cid;                        // Channel identifier\n  union {\n    uint8_t type;                      // Frame type - b7 defines type\n    struct {\n      uint8_t cmd;                     // Command - b7 set\n      uint8_t bcnth;                   // Message byte count - high part\n      uint8_t bcntl;                   // Message byte count - low part\n      uint8_t data[HID_RPT_SIZE - 7];  // Data payload\n    } init;\n    struct {\n      uint8_t seq;                     // Sequence number - b7 cleared\n      uint8_t data[HID_RPT_SIZE - 5];  // Data payload\n    } cont;\n  };\n} __attribute__ ((packed)) U2FHID_FRAME;\n\n#define FRAME_TYPE(f) ((f).type & TYPE_MASK)\n#define FRAME_CMD(f)  ((f).init.cmd & ~TYPE_MASK)\n#define MSG_LEN(f)    ((f).init.bcnth*256 + (f).init.bcntl)\n#define FRAME_SEQ(f)  ((f).cont.seq & ~TYPE_MASK)\n\n#define SET_MSG_LEN(f, len) { \\\n                              (f).init.bcnth = (uint8_t) ((len) >> 8); \\\n                              (f).init.bcntl = (uint8_t) (len); \\\n                            }\n\n// HID usage- and usage-page definitions\n\n#define FIDO_USAGE_PAGE         0xf1d0  // FIDO alliance HID usage page\n#define FIDO_USAGE_U2FHID       0x01    // U2FHID usage for top-level collection\n#define FIDO_USAGE_DATA_IN      0x20    // Raw IN data report\n#define FIDO_USAGE_DATA_OUT     0x21    // Raw OUT data report\n\n// General constants\n\n#define U2FHID_IF_VERSION       2       // Current interface implementation version\n#define U2FHID_TRANS_TIMEOUT    3000    // Default message timeout in ms\n\n// U2FHID native commands\n\n#define U2FHID_PING         (TYPE_INIT | 0x01)  // Echo data through local processor only\n#define U2FHID_MSG          (TYPE_INIT | 0x03)  // Send U2F message frame\n#define U2FHID_LOCK         (TYPE_INIT | 0x04)  // Send lock channel command\n#define U2FHID_INIT         (TYPE_INIT | 0x06)  // Channel initialization\n#define U2FHID_WINK         (TYPE_INIT | 0x08)  // Send device identification wink\n#define U2FHID_SYNC         (TYPE_INIT | 0x3c)  // Protocol resync command\n#define U2FHID_ERROR        (TYPE_INIT | 0x3f)  // Error response\n\n#define U2FHID_VENDOR_FIRST (TYPE_INIT | 0x40)  // First vendor defined command\n#define U2FHID_VENDOR_LAST  (TYPE_INIT | 0x7f)  // Last vendor defined command\n\n// U2FHID_INIT command defines\n\n#define INIT_NONCE_SIZE         8       // Size of channel initialization challenge\n#define CAPFLAG_WINK            0x01    // Device supports WINK command\n#define CAPFLAG_LOCK            0x02    // Device supports LOCK command\n\ntypedef struct {\n  uint8_t nonce[INIT_NONCE_SIZE];       // Client application nonce\n} __attribute__ ((packed)) U2FHID_INIT_REQ;\n\ntypedef struct {\n  uint8_t nonce[INIT_NONCE_SIZE];       // Client application nonce\n  uint32_t cid;                         // Channel identifier\n  uint8_t versionInterface;             // Interface version\n  uint8_t versionMajor;                 // Major version number\n  uint8_t versionMinor;                 // Minor version number\n  uint8_t versionBuild;                 // Build version number\n  uint8_t capFlags;                     // Capabilities flags\n} __attribute__ ((packed)) U2FHID_INIT_RESP;\n\n// U2FHID_SYNC command defines\n\ntypedef struct {\n  uint8_t nonce;                        // Client application nonce\n} __attribute__ ((packed)) U2FHID_SYNC_REQ;\n\ntypedef struct {\n  uint8_t nonce;                        // Client application nonce\n} __attribute__ ((packed)) U2FHID_SYNC_RESP;\n\n// Low-level error codes. Return as negatives.\n\n#define ERR_NONE                0x00    // No error\n#define ERR_INVALID_CMD         0x01    // Invalid command\n#define ERR_INVALID_PAR         0x02    // Invalid parameter\n#define ERR_INVALID_LEN         0x03    // Invalid message length\n#define ERR_INVALID_SEQ         0x04    // Invalid message sequencing\n#define ERR_MSG_TIMEOUT         0x05    // Message has timed out\n#define ERR_CHANNEL_BUSY        0x06    // Channel busy\n#define ERR_LOCK_REQUIRED       0x0a    // Command requires channel lock\n#define ERR_INVALID_CID         0x0b    // Invalid channel\n#define ERR_SYNC_FAIL           0x0b    // SYNC command failed\n#define ERR_OTHER               0x7f    // Other unspecified error\n\n\n#define PRIO_U2F_HID      4\n\nextern uint8_t __process4_stack_base__[], __process4_stack_size__[];\n#define STACK_ADDR_U2F_HID ((uint32_t)__process4_stack_base__)\n#define STACK_SIZE_U2F_HID ((uint32_t)__process4_stack_size__)\n\n#define MAX_MSGLEN 1024\n#define MAX_APDU_CMDLEN 416\n\nstruct u2f_hid {\n  uint32_t next_cid;\n  uint32_t cid;\n  U2FHID_FRAME frame;\n  struct usb_hid *hid;\n  uint8_t cmd;\n  uint8_t seq;\n  uint8_t msg[MAX_MSGLEN];\n  uint8_t apdu_cmd[MAX_APDU_CMDLEN];\n  uint16_t msg_len;\n  uint16_t msg_pos;\n};\n\nstatic struct u2f_hid u2f_hid;\n\nstatic int\nu2f_msg_init (struct u2f_hid *u2f, uint16_t len)\n{\n  u2f->msg_len = len;\n  u2f->msg_pos = 0;\n\n  return 0;\n}\n\nstatic int\nu2f_msg_append (struct u2f_hid *u2f, uint8_t *buf, uint16_t len)\n{\n  if (u2f->msg_pos + len >= u2f->msg_len)\n    len = u2f->msg_len - u2f->msg_pos;\n  memcpy (u2f->msg + u2f->msg_pos, buf, len);\n  u2f->msg_pos += len;\n  return u2f->msg_len - u2f->msg_pos;\n}\n\nstatic void\nu2f_send_error (struct u2f_hid *u2f, uint32_t cid, uint8_t error)\n{\n  memset (u2f->frame.init.data, 0, sizeof (u2f->frame.init.data));\n  u2f->frame.cid = cid;\n  u2f->frame.init.cmd = U2FHID_ERROR;\n  u2f->frame.init.data[0] = error;\n  SET_MSG_LEN (u2f->frame, 1);\n  hid_send (u2f->hid, (uint8_t *) &u2f->frame, sizeof (u2f->frame));\n}\n\nstatic void\nu2f_send_init (struct u2f_hid *u2f, uint32_t cid, uint32_t resp_cid,\n               uint8_t *nonce)\n{\n  U2FHID_INIT_RESP *resp;\n\n  u2f->frame.cid = cid;\n  u2f->frame.init.cmd = U2FHID_INIT;\n  SET_MSG_LEN (u2f->frame, sizeof (U2FHID_INIT_RESP));\n\n  resp = (U2FHID_INIT_RESP *) &u2f->frame.init.data;\n  memcpy (&resp->nonce, nonce, INIT_NONCE_SIZE);\n  memset (u2f->frame.init.data + INIT_NONCE_SIZE, 0,\n          sizeof (u2f->frame.init.data) - INIT_NONCE_SIZE);\n  resp->cid = resp_cid;\n  resp->versionInterface = U2FHID_IF_VERSION;\n  resp->versionMajor = 1;\n  resp->versionMinor = 1;\n  resp->versionBuild = 1;\n  resp->capFlags = 0;\n\n  hid_send (u2f->hid, (uint8_t *) &u2f->frame, sizeof (u2f->frame));\n}\n\nstatic void\nu2f_send_msg (struct u2f_hid *u2f, uint32_t cid, uint8_t cmd, uint8_t *msg,\n              uint16_t len)\n{\n  uint16_t remain;\n  uint16_t frame_len;\n  uint8_t seq;\n\n  remain = len;\n\n  u2f->frame.cid = cid;\n  u2f->frame.init.cmd = cmd;\n  SET_MSG_LEN (u2f->frame, len);\n\n  frame_len = remain;\n\n  if (frame_len > sizeof (u2f->frame.init.data))\n    frame_len = sizeof (u2f->frame.init.data);\n\n  memset (u2f->frame.init.data, 0, sizeof (u2f->frame.init.data));\n  memcpy (u2f->frame.init.data, msg, frame_len);\n\n  hid_send (u2f->hid, (uint8_t *) &u2f->frame, sizeof (u2f->frame));\n\n  remain -= frame_len;\n  msg += frame_len;\n  seq = 0;\n\n  while (remain > 0)\n    {\n      u2f->frame.cont.seq = seq;\n\n      frame_len = remain;\n\n      if (frame_len > sizeof (u2f->frame.cont.data))\n        frame_len = sizeof (u2f->frame.cont.data);\n\n      memset (u2f->frame.cont.data, 0, sizeof (u2f->frame.cont.data));\n      memcpy (u2f->frame.cont.data, msg, frame_len);\n\n      hid_send (u2f->hid, (uint8_t *) &u2f->frame, sizeof (u2f->frame));\n\n      remain -= frame_len;\n      msg += frame_len;\n      ++seq;\n    }\n}\n\nstatic void\nuf2_reset (struct u2f_hid *u2f)\n{\n  u2f->cmd = 0;\n  u2f->cid = 0;\n  u2f->seq = 0;\n}\n\nextern uint8_t blink_is_on;\n\nstatic void *\nu2f_hid_main (void *arg)\n{\n  struct u2f_hid *u2f = (struct u2f_hid *) arg;\n  int remain = 0;\n  int err;\n\n  u2f_apdu_init ();\n\n  while (1)\n    {\n      err = hid_recv (u2f->hid, (uint8_t *) &u2f->frame,\n                      sizeof(u2f->frame), 500000);\n\n      if (err == -1 && u2f->cmd)\n        {\n          u2f_send_error (u2f, u2f->cid, ERR_MSG_TIMEOUT);\n          uf2_reset (u2f);\n          continue;\n        }\n\n      if (err == -1)\n        continue;\n\n      blink_is_on = 1;\n\n      if (u2f->frame.cid == 0 ||\n          (u2f->frame.cid == CID_BROADCAST\n           && u2f->frame.init.cmd != U2FHID_INIT))\n        {\n          u2f_send_error (u2f, u2f->frame.cid, ERR_INVALID_CID);\n          continue;\n        }\n\n      if (u2f->frame.init.cmd == U2FHID_INIT)\n        {\n          if (MSG_LEN (u2f->frame) != sizeof (U2FHID_INIT_REQ))\n            {\n              u2f_send_error (u2f, u2f->frame.cid, ERR_INVALID_LEN);\n              continue;\n            }\n\n          if (u2f->frame.cid == u2f->cid)\n            {\n              uf2_reset (u2f);\n            }\n\n          u2f_send_init (\n            u2f,\n            u2f->frame.cid,\n            u2f->frame.cid == CID_BROADCAST ?\n              u2f->next_cid : u2f->frame.cid,\n            u2f->frame.init.data);\n\n          u2f->next_cid += 2;\n\n          continue;\n        }\n\n      if (FRAME_TYPE (u2f->frame) == TYPE_INIT &&\n          u2f->cid != 0 && u2f->frame.cid != u2f->cid)\n        {\n          u2f_send_error (u2f, u2f->frame.cid, ERR_CHANNEL_BUSY);\n          continue;\n        }\n\n      if (FRAME_TYPE (u2f->frame) == TYPE_INIT &&\n          (u2f->cid == 0 || u2f->cid == u2f->frame.cid))\n        {\n          if (u2f->cmd)\n            {\n              u2f_send_error (u2f, u2f->frame.cid, ERR_INVALID_SEQ);\n              uf2_reset (u2f);\n              continue;\n            }\n\n          if (MSG_LEN (u2f->frame) > MAX_MSGLEN)\n            {\n              u2f_send_error (u2f, u2f->frame.cid, ERR_INVALID_LEN);\n              uf2_reset (u2f);\n              continue;\n            }\n\n          u2f->cid = u2f->frame.cid;\n          u2f->cmd = u2f->frame.init.cmd;\n          u2f_msg_init (u2f, MSG_LEN (u2f->frame));\n          remain = u2f_msg_append (u2f, u2f->frame.init.data,\n                                   sizeof (u2f->frame.init.data));\n        }\n      else if (FRAME_TYPE (u2f->frame) == TYPE_CONT &&\n               u2f->cid == u2f->frame.cid)\n        {\n          if (u2f->frame.cont.seq != u2f->seq++)\n            {\n              u2f_send_error (u2f, u2f->frame.cid, ERR_INVALID_SEQ);\n              uf2_reset (u2f);\n              continue;\n            }\n          remain = u2f_msg_append (u2f, u2f->frame.cont.data,\n                                   sizeof (u2f->frame.cont.data));\n        }\n\n      if (remain == 0 && u2f->cmd)\n        {\n          uint32_t resp_len;\n\n          switch (u2f->cmd)\n            {\n              case U2FHID_PING:\n                u2f_send_msg (u2f, u2f->cid, U2FHID_PING, u2f->msg,\n                              u2f->msg_len);\n                break;\n              case U2FHID_MSG:\n                if (u2f->msg_len > MAX_APDU_CMDLEN)\n                  {\n                    u2f_send_error (u2f, u2f->frame.cid, ERR_INVALID_LEN);\n                    uf2_reset (u2f);\n                    continue;\n                  }\n                memcpy (u2f->apdu_cmd, u2f->msg, u2f->msg_len);\n                memset (u2f->msg, 0, MAX_MSGLEN);\n                u2f_apdu_command_do (u2f->apdu_cmd, u2f->msg_len,\n                                     u2f->msg, &resp_len);\n                u2f_send_msg (u2f, u2f->cid, U2FHID_MSG, u2f->msg, resp_len);\n                break;\n              default:\n                u2f_send_error (u2f, u2f->cid, ERR_INVALID_CMD);\n            }\n          uf2_reset (u2f);\n        }\n    }\n\n  return NULL;\n}\n\nstruct u2f_hid *\nu2f_hid_open (struct usb_hid *hid)\n{\n  memset (&u2f_hid, 0, sizeof (struct u2f_hid));\n\n  u2f_hid.next_cid = 0xdeadbeaf + 12;\n  u2f_hid.hid = hid;\n\n  chopstx_create (PRIO_U2F_HID, STACK_ADDR_U2F_HID, STACK_SIZE_U2F_HID,\n                  u2f_hid_main, &u2f_hid);\n\n  return &u2f_hid;\n}\n"
  },
  {
    "path": "src/u2f-hid.h",
    "content": "#ifndef __U2F_U2F_HID_H__\n\n#define __U2F_U2F_HID_H__\n\nstruct usb_hid;\nstruct u2f_hid;\n\nstruct u2f_hid *\nu2f_hid_open (struct usb_hid *hid);\n\n#endif\n"
  },
  {
    "path": "src/u2f.c",
    "content": "/*\n * u2f.c - main\n *\n * Copyright (C) 2017 Sergei Glushchenko\n * Author: Sergei Glushchenko <gl.sergei@gmail.com>\n *\n * This file is a part of U2F firmware for STM32\n *\n * This program is free software: you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n * As additional permission under GNU GPL version 3 section 7, you may\n * distribute non-source form of the Program without the copy of the\n * GNU GPL normally required by section 4, provided you inform the\n * recipients of GNU GPL by a written offer.\n *\n */\n\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n#include <chopstx.h>\n\n/* For set_led */\n#include \"board.h\"\n#include \"sys.h\"\n\n#include \"usb_lld.h\"\n\n#include \"usb-hid.h\"\n#include \"u2f-hid.h\"\n#include \"random.h\"\n#include \"adc.h\"\n\n#if defined(HAVE_PUSH_BUTTON)\n#include \"pbt.h\"\n#elif defined(HAVE_CAPSENSE)\n#include \"csn.h\"\n#else\n#include \"uvoid.h\"\n#endif\n\n#include \"platform.h\"\n\nstatic chopstx_mutex_t mtx;\nstatic chopstx_cond_t cnd0;\nstatic chopstx_cond_t cnd1;\n\nuint8_t v;\nuint8_t blink_is_on;\n\nstatic void *\npwm (void *arg)\n{\n  (void)arg;\n\n  chopstx_mutex_lock (&mtx);\n  chopstx_cond_wait (&cnd0, &mtx);\n  chopstx_mutex_unlock (&mtx);\n\n  while (1)\n    {\n      set_led ((blink_is_on & v) || user_presence_get ());\n      chopstx_usec_wait (10*1000);\n    }\n\n  return NULL;\n}\n\nstatic void *\nblk (void *arg)\n{\n  (void)arg;\n\n  int nblk = 0;\n\n  chopstx_mutex_lock (&mtx);\n  chopstx_cond_wait (&cnd1, &mtx);\n  chopstx_mutex_unlock (&mtx);\n\n  while (1)\n    {\n      v = 0;\n      chopstx_usec_wait (50*1000);\n      v = 1;\n      chopstx_usec_wait (50*1000);\n      if (blink_is_on)\n        nblk++;\n      if (nblk == 3)\n        {\n          nblk = 0;\n          blink_is_on = 0;\n        }\n    }\n\n  return NULL;\n}\n\n#define PRIO_PWM 7\n#define PRIO_BLK 7\n\nextern uint8_t __process1_stack_base__[], __process1_stack_size__[];\nextern uint8_t __process2_stack_base__[], __process2_stack_size__[];\n\n#define STACK_ADDR_PWM ((uint32_t)__process1_stack_base__)\n#define STACK_SIZE_PWM ((uint32_t)__process1_stack_size__)\n\n#define STACK_ADDR_BLK ((uint32_t)__process2_stack_base__)\n#define STACK_SIZE_BLK ((uint32_t)__process2_stack_size__)\n\n\nint\nmain (int argc, const char *argv[])\n{\n  struct usb_hid *hid;\n\n  (void)argc;\n  (void)argv;\n\n  platform_init ();\n\n  chopstx_mutex_init (&mtx);\n  chopstx_cond_init (&cnd0);\n  chopstx_cond_init (&cnd1);\n\n  chopstx_create (PRIO_PWM, STACK_ADDR_PWM, STACK_SIZE_PWM, pwm, NULL);\n  chopstx_create (PRIO_BLK, STACK_ADDR_BLK, STACK_SIZE_BLK, blk, NULL);\n\n  chopstx_mutex_lock (&mtx);\n  chopstx_cond_signal (&cnd0);\n  chopstx_cond_signal (&cnd1);\n  chopstx_mutex_unlock (&mtx);\n\n  blink_is_on = 1;\n\n  adc_init ();\n\n  random_init ();\n\n#if defined(HAVE_PUSH_BUTTON)\n  pbt_init ();\n#elif defined(HAVE_CAPSENSE)\n  capsense_init ();\n#else\n  uvoid_init ();\n#endif\n\n  flash_unlock ();\n\n  chopstx_usec_wait (200*1000);\n\n  hid = hid_open ();\n  u2f_hid_open (hid);\n\n  while (1)\n    {\n      chopstx_usec_wait (500*1000);\n    }\n\n  random_fini ();\n\n  return 0;\n}\n"
  },
  {
    "path": "src/usb-hid.c",
    "content": "/*\n * usb-hid.c - HID device descriptors and communication\n *\n * Copyright (C) 2017-2019 Sergei Glushchenko\n * Author: Sergei Glushchenko <gl.sergei@gmail.com>\n *\n * This file is a part of U2F firmware for STM32F103 and EFM32HG boards\n *\n * This program is free software: you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n * As additional permission under GNU GPL version 3 section 7, you may\n * distribute non-source form of the Program without the copy of the\n * GNU GPL normally required by section 4, provided you inform the\n * recipients of GNU GPL by a written offer.\n *\n */\n\n#include <stdint.h>\n#include <stdlib.h>\n#include <chopstx.h>\n#include <eventflag.h>\n#include <string.h>\n#include \"board.h\"\n#include \"sys.h\"\n#include \"usb_lld.h\"\n\n#include \"usb-hid.h\"\n\n\n#define ENDP0_RXADDR        (0x040)\n#define ENDP0_TXADDR        (0x080)\n#define ENDP1_RXADDR        (0x0c0)\n#define ENDP1_TXADDR        (0x100)\n\n#define HID_INTERFACE 0\n\n#define USB_HID_REQ_GET_REPORT   1\n#define USB_HID_REQ_GET_IDLE     2\n#define USB_HID_REQ_GET_PROTOCOL 3\n#define USB_HID_REQ_SET_REPORT   9\n#define USB_HID_REQ_SET_IDLE     10\n#define USB_HID_REQ_SET_PROTOCOL 11\n\n#define USB_DT_HID                      0x21\n#define USB_DT_REPORT                   0x22\n\n// Size of HID reports\n\n#define HID_RPT_SIZE            64      // Default size of raw HID report\n\nstatic chopstx_intr_t interrupt;\n\nstatic uint8_t hid_idle_rate;   /* in 4ms */\n\n/* HID report descriptor.  */\n#define HID_REPORT_DESC_SIZE (sizeof (hid_report_desc))\n\nstatic const uint8_t hid_report_desc[] = {\n  0x06, 0xd0, 0xf1, /* USAGE_PAGE (FIDO Alliance) */\n  0x09, 0x01,       /* USAGE (Keyboard) */\n\n  0xa1, 0x01,       /* COLLECTION (Application) */\n\n  0x09, 0x20,       /*   USAGE (Input report data) */\n  0x15, 0x00,       /*   LOGICAL_MINIMUM (0) */\n  0x26, 0xff, 0x00, /*   LOGICAL_MAXIMUM (255) */\n  0x75, 0x08,       /*   REPORT_SIZE (8) */\n  0x95, 0x40,       /*   REPORT_COUNT (64) */\n  0x81, 0x02,       /*   INPUT (Data,Var,Abs); Modifier byte */\n\n  0x09, 0x21,       /*   USAGE (Output report data) */\n  0x15, 0x00,       /*   LOGICAL_MINIMUM (0) */\n  0x26, 0xff, 0x00, /*   LOGICAL_MAXIMUM (255) */\n  0x75, 0x08,       /*   REPORT_SIZE (8) */\n  0x95, 0x40,       /*   REPORT_COUNT (64) */\n  0x91, 0x02,       /*   OUTPUT (Data,Var,Abs); Modifier byte */\n\n  0xc0              /* END_COLLECTION */\n};\n\n/* USB Device Descriptor */\nstatic const uint8_t u2f_device_desc[18] = {\n  18,                /* bLength */\n  DEVICE_DESCRIPTOR, /* bDescriptorType */\n  0x10, 0x01,        /* bcdUSB = 1.1 */\n  0x00,              /* bDeviceClass (Unknown). */\n  0x00,              /* bDeviceSubClass. */\n  0x00,              /* bDeviceProtocol. */\n  0x40,              /* bMaxPacketSize. */\n  0xd0, 0x16,        /* idVendor */\n  0x90, 0x0e,        /* idProduct */\n  0x00, 0x01,        /* bcdDevice */\n  1,                 /* iManufacturer. */\n  2,                 /* iProduct. */\n  3,                 /* iSerialNumber. */\n  1                  /* bNumConfigurations. */\n};\n\n#define FEATURE_BUS_POWERED        0x80\n\n/* Configuration Descriptor tree for a HID.*/\nstatic const uint8_t u2f_config_desc[41] = {\n  9,\n  CONFIG_DESCRIPTOR,   /* bDescriptorType: Configuration */\n  /* Configuration Descriptor.*/\n  41, 0x00,            /* wTotalLength. */\n  0x01,                /* bNumInterfaces. */\n  0x01,                /* bConfigurationValue. */\n  0,                   /* iConfiguration. */\n  FEATURE_BUS_POWERED, /* bmAttributes. */\n  50,                  /* bMaxPower (100mA). */\n\n  /* Interface Descriptor.*/\n  9,                    /* bLength: Interface Descriptor size */\n  INTERFACE_DESCRIPTOR, /* bDescriptorType: Interface */\n  HID_INTERFACE,        /* bInterfaceNumber: Number of Interface */\n  0x00,                 /* bAlternateSetting: Alternate setting */\n  0x02,                 /* bNumEndpoints: Two endpoints used */\n  0x03,                 /* bInterfaceClass: HID */\n  0x00,                 /* bInterfaceSubClass: no boot */\n  0x00,                 /* bInterfaceProtocol: 0=none */\n  0x04,                 /* iInterface */\n\n  /* HID Descriptor.*/\n  9,                       /* bLength: HID Descriptor size */\n  0x21,                    /* bDescriptorType: HID */\n  0x10, 0x01,              /* bcdHID: HID Class Spec release number */\n  0x00,                    /* bCountryCode: Hardware target country */\n  0x01,                    /* bNumDescriptors: Number of HID class descriptors to follow */\n  0x22,                    /* bDescriptorType */\n  HID_REPORT_DESC_SIZE, 0, /* wItemLength: Total length of Report descriptor */\n\n  /*Endpoint IN1 Descriptor*/\n  7,                      /* bLength: Endpoint Descriptor size */\n  ENDPOINT_DESCRIPTOR,    /* bDescriptorType: Endpoint */\n  0x81,                   /* bEndpointAddress: (IN1) */\n  0x03,                   /* bmAttributes: Interrupt */\n  0x40, 0x00,             /* wMaxPacketSize: 64 */\n  0x05,                   /* bInterval (5ms) */\n\n  /*Endpoint OUT1 Descriptor*/\n  7,                      /* bLength: Endpoint Descriptor size */\n  ENDPOINT_DESCRIPTOR,    /* bDescriptorType: Endpoint */\n  0x01,                   /* bEndpointAddress: (OUT1) */\n  0x03,                   /* bmAttributes: Interrupt */\n  0x40, 0x00,             /* wMaxPacketSize: 64 */\n  0x05,                   /* bInterval (5ms) */\n};\n\n\n/*\n * U.S. English language identifier.\n */\nstatic const uint8_t usb_string0[4] = {\n  4,                                /* bLength */\n  STRING_DESCRIPTOR,\n  0x09, 0x04                        /* LangID = 0x0409: US-English */\n};\n\nstatic const uint8_t usb_string1[] = {\n  7*2+2,                            /* bLength */\n  STRING_DESCRIPTOR,                /* bDescriptorType */\n  /* Manufacturer: \"unknown\" */\n  'u', 0, 'n', 0, 'k', 0, 'n', 0, 'o', 0, 'w', 0, 'n', 0,\n};\n\nstatic const uint8_t usb_string2[] = {\n  17*2+2,                           /* bLength */\n  STRING_DESCRIPTOR,                /* bDescriptorType */\n#if defined(MCU_EFM32HG)\n  /* Product name: \"U2F-token (EFM32)\" */\n  'U', 0, '2', 0, 'F', 0, '-', 0, 't', 0, 'o', 0, 'k', 0, 'e', 0,\n  'n', 0, ' ', 0, '(', 0, 'E', 0, 'F', 0, 'M', 0, '3', 0, '2', 0,\n#else\n  /* Product name: \"U2F-token (STM32)\" */\n  'U', 0, '2', 0, 'F', 0, '-', 0, 't', 0, 'o', 0, 'k', 0, 'e', 0,\n  'n', 0, ' ', 0, '(', 0, 'S', 0, 'T', 0, 'M', 0, '3', 0, '2', 0,\n#endif\n  ')', 0,\n};\n\n/*\n * Serial Number string.\n */\nstatic const uint8_t usb_string3[28] = {\n  28,                               /* bLength */\n  STRING_DESCRIPTOR,                /* bDescriptorType */\n  '1', 0,  '.', 0,  '0', 0, '0', 0, /* Version number */\n};\n\n\n#define NUM_INTERFACES 1\n\n\nstatic void\nusb_device_reset (struct usb_dev *dev)\n{\n  usb_lld_reset (dev, FEATURE_BUS_POWERED);\n\n  /* Initialize Endpoint 0 */\n#if defined(MCU_EFM32HG)\n  usb_lld_setup_endp (dev, ENDP0, EP_CONTROL, 1, 1, HID_RPT_SIZE);\n#else\n  usb_lld_setup_endpoint (ENDP0, EP_CONTROL, 0,\n            ENDP0_RXADDR, ENDP0_TXADDR, HID_RPT_SIZE);\n#endif\n}\n\n\n\nstatic void\nusb_ctrl_write_finish (struct usb_dev *dev)\n{\n  struct device_req *arg = &dev->dev_req;\n\n  if (arg->index == HID_INTERFACE && arg->request == USB_HID_REQ_SET_REPORT)\n    {\n      return;\n    }\n\n  /*\n   * The transaction was already finished.  So, it is no use to call\n   * usb_lld_ctrl_error when the condition does not match.\n   */\n}\n\n\n\nstatic int\nusb_setup (struct usb_dev *dev)\n{\n  struct device_req *arg = &dev->dev_req;\n\n  if (arg->index == HID_INTERFACE)\n    {\n      switch (arg->request)\n        {\n        case USB_HID_REQ_GET_IDLE:\n          return usb_lld_ctrl_send (dev, &hid_idle_rate, 1);\n        case USB_HID_REQ_SET_IDLE:\n          hid_idle_rate = arg->value >> 8;\n          return usb_lld_ctrl_ack (dev);\n\n        case USB_HID_REQ_GET_REPORT:\n          /* Reports should go via interrupt endpoint */\n          return -1;\n\n        case USB_HID_REQ_SET_REPORT:\n          /* Reports should go via interrupt endpoint */\n          return -1;\n\n        case USB_HID_REQ_GET_PROTOCOL:\n        case USB_HID_REQ_SET_PROTOCOL:\n          /* This driver doesn't support boot protocol.  */\n          return -1;\n\n        default:\n          return -1;\n        }\n    }\n\n  return -1;\n}\n\nstatic int\nusb_get_descriptor (struct usb_dev *dev)\n{\n  struct device_req *arg = &dev->dev_req;\n  uint8_t rcp = arg->type & RECIPIENT;\n  uint8_t desc_type = (arg->value >> 8);\n  uint8_t desc_index = (arg->value & 0xff);\n\n  if (rcp == INTERFACE_RECIPIENT)\n    {\n      if (arg->index == HID_INTERFACE)\n        {\n          if (desc_type == USB_DT_HID)\n            return usb_lld_ctrl_send (dev, u2f_config_desc + 9 + 9, 9);\n          else if (desc_type == USB_DT_REPORT)\n            return usb_lld_ctrl_send (dev, hid_report_desc,\n                                      HID_REPORT_DESC_SIZE);\n        }\n    }\n  else if (rcp == DEVICE_RECIPIENT)\n    {\n      if (desc_type == DEVICE_DESCRIPTOR)\n        return usb_lld_ctrl_send (dev,\n                                  u2f_device_desc, sizeof (u2f_device_desc));\n      else if (desc_type == CONFIG_DESCRIPTOR)\n        return usb_lld_ctrl_send (dev,\n                                  u2f_config_desc, sizeof (u2f_config_desc));\n      else if (desc_type == STRING_DESCRIPTOR)\n        {\n          const uint8_t *str;\n          int size;\n\n          switch (desc_index)\n            {\n            case 0:\n              str = usb_string0;\n              size = sizeof (usb_string0);\n              break;\n            case 1:\n              str = usb_string1;\n              size = sizeof (usb_string1);\n              break;\n            case 2:\n              str = usb_string2;\n              size = sizeof (usb_string2);\n              break;\n            case 3:\n              str = usb_string3;\n              size = sizeof (usb_string3);\n              break;\n            default:\n              return -1;\n            }\n\n          return usb_lld_ctrl_send (dev, str, size);\n        }\n  }\n\n  return -1;\n}\n\nstatic void\nhid_setup_endpoints_for_interface (struct usb_dev *dev,\n                                   uint16_t interface, int stop)\n{\n#if !defined(MCU_EFM32HG)\n  (void) dev;\n#endif\n  if (interface == HID_INTERFACE)\n    {\n      if (!stop)\n#if defined(MCU_EFM32HG)\n        usb_lld_setup_endp (dev, ENDP1, EP_INTERRUPT, 1, 1, HID_RPT_SIZE);\n#else\n        usb_lld_setup_endpoint (ENDP1, EP_INTERRUPT, 0,\n                  ENDP1_RXADDR, ENDP1_TXADDR, HID_RPT_SIZE);\n#endif\n      else\n        {\n          usb_lld_stall_tx (ENDP1);\n          usb_lld_stall_rx (ENDP1);\n        }\n    }\n}\n\nstatic int\nusb_set_configuration (struct usb_dev *dev)\n{\n  int i;\n  uint8_t current_conf;\n\n  current_conf = usb_lld_current_configuration (dev);\n  if (current_conf == 0)\n    {\n      if (dev->dev_req.value != 1)\n        return -1;\n\n      usb_lld_set_configuration (dev, 1);\n      for (i = 0; i < NUM_INTERFACES; i++)\n        hid_setup_endpoints_for_interface (dev, i, 0);\n    }\n  else if (current_conf != dev->dev_req.value)\n    {\n      if (dev->dev_req.value != 0)\n        return -1;\n\n      usb_lld_set_configuration (dev, 0);\n      for (i = 0; i < NUM_INTERFACES; i++)\n        hid_setup_endpoints_for_interface (dev, i, 1);\n    }\n\n  usb_lld_ctrl_ack (dev);\n  return 0;\n}\n\n\nstatic int\nusb_set_interface (struct usb_dev *dev)\n{\n  uint16_t interface = dev->dev_req.index;\n  uint16_t alt = dev->dev_req.value;\n\n  if (interface >= NUM_INTERFACES)\n    return -1;\n\n  if (alt != 0)\n    return -1;\n  else\n    {\n      hid_setup_endpoints_for_interface (dev, interface, 0);\n      usb_lld_ctrl_ack (dev);\n      return 0;\n    }\n}\n\nstatic int\nusb_get_interface (struct usb_dev *dev)\n{\n  const uint8_t zero = 0;\n  uint16_t interface = dev->dev_req.index;\n\n  if (interface >= NUM_INTERFACES)\n    return -1;\n\n  /* We don't have alternate interface, so, always return 0.  */\n  return usb_lld_ctrl_send (dev, &zero, 1);\n}\n\nstatic int\nusb_get_status_interface (struct usb_dev *dev)\n{\n  const uint16_t status_info = 0;\n  uint16_t interface = dev->dev_req.index;\n\n  if (interface >= NUM_INTERFACES)\n    return -1;\n\n  return usb_lld_ctrl_send (dev, &status_info, 2);\n}\n\nstruct usb_hid {\n#if defined(MCU_EFM32HG)\n  uint8_t tx_buf[HID_RPT_SIZE] __attribute__((aligned(4)));\n#else\n  uint8_t *tx_buf;\n#endif\n  uint8_t rx_buf[HID_RPT_SIZE] __attribute__((aligned(4)));\n  uint16_t tx_len;\n  uint16_t rx_len;\n  struct eventflag cmd_ev;\n  struct eventflag usb_ev;\n  struct eventflag fbk_ev;\n};\n\n/* cmd events */\n#define EV_TX_NEED         1\n\n/* usb events */\n#define EV_RX_DATA_READY   1\n\n/* fbk events */\n#define EV_TX_FINISHED     1\n\n/*\n * Rx ready callback\n */\n\nstatic void\nep1_out_received (struct usb_hid *hid, uint16_t len)\n{\n  if (len <= HID_RPT_SIZE)\n#if defined(MCU_EFM32HG)\n    hid->rx_len = len;\n#else\n    {\n      usb_lld_rxcpy (hid->rx_buf, 1 /*ep_num*/, 0 /*offset*/, len);\n      hid->rx_len = len;\n    }\n#endif\n\n  eventflag_signal (&hid->usb_ev, EV_RX_DATA_READY);\n}\n\n\n/*\n * Transmit some data\n */\n\nstatic void\nep1_transmit (struct usb_hid *hid)\n{\n#if defined(MCU_EFM32HG)\n  usb_lld_tx_enable_buf (ENDP1, hid->tx_buf, hid->tx_len);\n#else\n  usb_lld_txcpy (hid->tx_buf, 1/*ep_num*/, 0 /*offset*/, hid->tx_len);\n  usb_lld_tx_enable (1/*ep_num*/, hid->tx_len);\n#endif\n}\n\nstatic void\nusb_rx_ready (struct usb_hid *hid, uint8_t ep_num, uint16_t len)\n{\n  if (ep_num == ENDP1)\n    ep1_out_received (hid, len);\n}\n\nstatic void\nusb_tx_done (struct usb_hid *hid, uint8_t ep_num, uint16_t len)\n{\n  (void)hid;\n  (void)ep_num;\n  (void)len;\n\n  if (ep_num == ENDP1)\n    {\n      eventflag_signal (&hid->fbk_ev, EV_TX_FINISHED);\n    }\n}\n\nstatic void\nusb_tx (struct usb_hid *hid, uint8_t ep_num)\n{\n  if (ep_num == ENDP1)\n    ep1_transmit (hid);\n}\n\n\n#if defined(MCU_EFM32HG)\n#define INTR_REQ_USB 19\n#else\n#define INTR_REQ_USB 20\n#endif\n#define PRIO_HID     8\n\nextern uint8_t __process3_stack_base__[], __process3_stack_size__[];\n#define STACK_ADDR_HID ((uint32_t)__process3_stack_base__)\n#define STACK_SIZE_HID ((uint32_t)__process3_stack_size__)\n\n\nstatic void\npoll_tx_intr (uint32_t *timeout, struct eventflag *ev, chopstx_intr_t *intr)\n{\n  chopstx_poll_cond_t poll_desc;\n  struct chx_poll_head *pd_array[2] = {\n    (struct chx_poll_head *)intr,\n    (struct chx_poll_head *)&poll_desc\n  };\n\n  eventflag_prepare_poll (ev, &poll_desc);\n  chopstx_poll (timeout, 2, pd_array);\n}\n\nstatic struct usb_dev dev __attribute__((aligned(4)));\n\nstatic void *\nhid_main (void *arg)\n{\n  uint32_t timeout;\n  int e;\n\n  struct usb_hid *usb_hid = (struct usb_hid *) arg;\n\n  memset (usb_hid, 0, sizeof (struct usb_hid));\n\n  eventflag_init (&usb_hid->cmd_ev);\n  eventflag_init (&usb_hid->usb_ev);\n  eventflag_init (&usb_hid->fbk_ev);\n\n  chopstx_claim_irq (&interrupt, INTR_REQ_USB);\n  usb_lld_init (&dev, FEATURE_BUS_POWERED);\n\n  while (1)\n    {\n      eventmask_t m;\n\n      timeout = 1950 * 1000;\n      poll_tx_intr (&timeout, &usb_hid->cmd_ev, &interrupt);\n\n      if (interrupt.ready)\n        {\n          uint8_t ep_num;\n          /*\n           * When interrupt is detected, call usb_lld_event_handler.\n           * The event may be one of following:\n           *    (1) Transfer to endpoint (bulk or interrupt)\n           *        In this case EP_NUM is encoded in the variable E.\n           *    (2) \"NONE\" event: some trasfer was done, but all was\n           *        done by lower layer, no other work is needed in\n           *        upper layer.\n           *    (3) Device events: Reset or Suspend\n           *    (4) Device requests to the endpoint zero.\n           *        \n           */\n          e = usb_lld_event_handler (&dev);\n          ep_num = USB_EVENT_ENDP (e);\n\n          if (ep_num != 0)\n            {\n              if (USB_EVENT_TXRX (e))\n                usb_tx_done (usb_hid, ep_num, USB_EVENT_LEN (e));\n              else\n                usb_rx_ready (usb_hid, ep_num, USB_EVENT_LEN (e));\n            }\n          else\n            switch (USB_EVENT_ID (e))\n              {\n              case USB_EVENT_DEVICE_RESET:\n                usb_device_reset (&dev);\n                continue;\n\n              case USB_EVENT_DEVICE_ADDRESSED:\n                /* The addres is assigned to the device.  We don't\n                 * need to do anything for this actually, but in this\n                 * application, we maintain the USB status of the\n                 * device.  Usually, just \"continue\" as EVENT_OK is\n                 * OK.\n                 */\n                continue;\n\n              case USB_EVENT_GET_DESCRIPTOR:\n                if (usb_get_descriptor (&dev) < 0)\n                  usb_lld_ctrl_error (&dev);\n                continue;\n\n              case USB_EVENT_SET_CONFIGURATION:\n                if (usb_set_configuration (&dev) < 0)\n                  usb_lld_ctrl_error (&dev);\n                continue;\n\n              case USB_EVENT_SET_INTERFACE:\n                if (usb_set_interface (&dev) < 0)\n                  usb_lld_ctrl_error (&dev);\n                continue;\n\n              case USB_EVENT_CTRL_REQUEST:\n                /* Device specific device request.  */\n                if (usb_setup (&dev) < 0)\n                  usb_lld_ctrl_error (&dev);\n                continue;\n\n              case USB_EVENT_GET_STATUS_INTERFACE:\n                if (usb_get_status_interface (&dev) < 0)\n                  usb_lld_ctrl_error (&dev);\n                continue;\n\n              case USB_EVENT_GET_INTERFACE:\n                if (usb_get_interface (&dev) < 0)\n                  usb_lld_ctrl_error (&dev);\n                continue;\n\n              case USB_EVENT_SET_FEATURE_DEVICE:\n              case USB_EVENT_SET_FEATURE_ENDPOINT:\n              case USB_EVENT_CLEAR_FEATURE_DEVICE:\n              case USB_EVENT_CLEAR_FEATURE_ENDPOINT:\n                usb_lld_ctrl_ack (&dev);\n                continue;\n\n              case USB_EVENT_CTRL_WRITE_FINISH:\n                /* Control WRITE transfer finished.  */\n                usb_ctrl_write_finish (&dev);\n                continue;\n\n              case USB_EVENT_OK:\n              case USB_EVENT_DEVICE_SUSPEND:\n              default:\n                continue;\n              }\n        }\n\n      m = eventflag_get (&usb_hid->cmd_ev);\n\n      if (m == EV_TX_NEED)\n        {\n          usb_tx (usb_hid, ENDP1);\n        }\n\n    }\n\n  return NULL;\n}\n\nstatic struct usb_hid usb_hid __attribute__((aligned(4)));\n\nstruct usb_hid *\nhid_open (void)\n{\n  chopstx_create (PRIO_HID, STACK_ADDR_HID, STACK_SIZE_HID, hid_main, &usb_hid);\n  return &usb_hid;\n}\n\nint\nhid_send (struct usb_hid *usb_hid, uint8_t *buf, uint16_t len)\n{\n  eventmask_t m;\n\n  if (len > HID_RPT_SIZE)\n    return -1;\n\n  usb_hid->tx_len = len;\n#if defined(MCU_EFM32HG)\n  memcpy (usb_hid->tx_buf, buf, len);\n#else\n  usb_hid->tx_buf = buf;\n#endif\n  eventflag_signal (&usb_hid->cmd_ev, EV_TX_NEED);\n\n  do\n    {\n      m = eventflag_wait (&usb_hid->fbk_ev);\n    }\n  while (m != EV_TX_FINISHED);\n\n  return len;\n}\n\nint\nhid_recv (struct usb_hid *usb_hid, uint8_t *buf, uint16_t len, uint32_t timeout)\n{\n  eventmask_t m;\n\n#if defined(MCU_EFM32HG)\n  usb_lld_rx_enable_buf (ENDP1, &usb_hid->rx_buf, HID_RPT_SIZE);\n#else\n  usb_lld_rx_enable (ENDP1);\n#endif\n\n  do\n    {\n      m = eventflag_wait_timeout (&usb_hid->usb_ev, timeout);\n    }\n  while (m != EV_RX_DATA_READY && m != 0);\n\n  if (m == 0)\n    return -1;\n\n  if (usb_hid->rx_len <= len)\n    {\n      memcpy (buf, usb_hid->rx_buf, usb_hid->rx_len);\n      return usb_hid->rx_len;\n    }\n\n  return -1;\n}\n"
  },
  {
    "path": "src/usb-hid.h",
    "content": "#ifndef __U2F_USB_HID_H__\n\n#define __U2F_USB_HID_H__\n\nstruct usb_hid;\n\nstruct usb_hid *\nhid_open (void);\n\nint\nhid_send (struct usb_hid *usb_hid, uint8_t *buf, uint16_t len);\n\nint\nhid_recv (struct usb_hid *usb_hid, uint8_t *buf, uint16_t len, uint32_t timeout);\n\n#endif\n"
  },
  {
    "path": "src/uvoid.c",
    "content": "/*\n * uvoid.c - void user presence indicator\n *\n * Copyright (C) 2017 Sergei Glushchenko\n * Author: Sergei Glushchenko <gl.sergei@gmail.com>\n *\n * This file is a part of U2F firmware for STM32\n *\n * This program is free software: you can redistribute it and/or modify it\n * under the terms of the GNU General Public License as published by\n * the Free Software Foundation, either version 3 of the License, or\n * (at your option) any later version.\n *\n * This program is distributed in the hope that it will be useful, but\n * WITHOUT ANY WARRANTY; without even the implied warranty of\n * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU\n * General Public License for more details.\n *\n * You should have received a copy of the GNU General Public License\n * along with this program.  If not, see <http://www.gnu.org/licenses/>.\n *\n * As additional permission under GNU GPL version 3 section 7, you may\n * distribute non-source form of the Program without the copy of the\n * GNU GPL normally required by section 4, provided you inform the\n * recipients of GNU GPL by a written offer.\n *\n */\n\n#include <stdint.h>\n#include <stdlib.h>\n#include <string.h>\n#include <chopstx.h>\n\n#define PRIO_UVOID 2\n\nextern uint8_t __process6_stack_base__[], __process6_stack_size__[];\n\n#define STACK_ADDR_UVOID ((uint32_t)__process6_stack_base__)\n#define STACK_SIZE_UVOID ((uint32_t)__process6_stack_size__)\n\nstatic int touch = 1;\n\nstatic void *\nuvoid (void *arg)\n{\n  (void)arg;\n\n  int i;\n\n  for (i = 0; i < 100; i++)\n    chopstx_usec_wait (100*1000);\n\n  touch = 0;\n\n  while (1)\n    chopstx_usec_wait (100*1000);\n\n  return NULL;\n}\n\nint\nuser_presence_get (void)\n{\n  return touch;\n}\n\nvoid\nuser_presence_reset (void)\n{\n  touch = 0;\n}\n\nvoid\nuvoid_init (void)\n{\n  chopstx_create (PRIO_UVOID, STACK_ADDR_UVOID, STACK_SIZE_UVOID, uvoid, NULL);\n}\n"
  },
  {
    "path": "src/uvoid.h",
    "content": "#ifndef __U2F_UVOID_H__\n\n#define __U2F_UVOID_H__\n\nint\nuser_presence_get (void);\n\nvoid\nuser_presence_reset (void);\n\nvoid\nuvoid_init (void);\n\n#endif\n"
  }
]