diff --git a/storage/.gitignore b/storage/.gitignore new file mode 100644 index 000000000..6142305dc --- /dev/null +++ b/storage/.gitignore @@ -0,0 +1,2 @@ +*.o +*.d diff --git a/storage/COPYING b/storage/COPYING new file mode 100644 index 000000000..f288702d2 --- /dev/null +++ b/storage/COPYING @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/storage/README.md b/storage/README.md new file mode 100644 index 000000000..f44352a28 --- /dev/null +++ b/storage/README.md @@ -0,0 +1,291 @@ +# Trezor Storage + +This repository contains the implementation of Trezor's internal storage, which is common for both trezor-mcu (Trezor One) and trezor-core (Trezor T). This README also contains a detailed description of the cryptographic design. + +All tests are located in the [trezor-storage-test](https://github.com/trezor/trezor-storage-test) repository, which also includes a Python implementation to run tests against this C production version and the Python one. + +## Summary + +The PIN is no longer stored in the flash storage. A new entry is added to the flash storage consisting of a 256-bit encrypted data encryption key (EDEK) followed by a 128-bit encrypted storage authentication key (ESAK) and a 64-bit PIN verification code (PVC). The PIN is used to decrypt the EDEK and ESAK and the PVC is be used to verify that the correct PIN was used. The resulting data encryption key (DEK) is then used to encrypt/decrypt protected entries in the flash storage. We use Chacha20Poly1305 as defined in [RFC 7539](https://tools.ietf.org/html/rfc7539) to encrypt the EDEK and the protected entries. The storage authentication key (SAK) is used to authenticate the list of (APP, KEY) values for all protected entries that have been set in the storage. This prevents an attacker from erasing or adding entries to the storage. + +## Storage format + +Entries fall into three categories: + +| Category | Condition | Read | Write | +|-----------|-----------------|--------------------|--------------------| +| Private | APP = 0 | Never | Never | +| Protected | 1 ≤ APP ≤ 127 | Only when unlocked | Only when unlocked | +| Public | 128 ≤ APP ≤ 255 | Always | Only when unlocked | + +The format of public entries has remained unchanged, that is: + +| Data | KEY | APP | LEN | DATA | +|----------------|-----|-----|-----|------| +| Length (bytes) | 1 | 1 | 2 | LEN | + +Private values are used to store storage-specific information and cannot be directly accessed through the storage interface. Protected entries have the following new format: + +| Data | KEY | APP | LEN | IV | TAG | ENCRDATA | +|----------------|-----|-----|-----|----|-----|----------| +| Length (bytes) | 1 | 1 | 2 | 12 | 16 | LEN - 28 | + +The LEN value thus indicates the total length of IV, TAG and ENCRDATA. + +The random salt (32 bits), EDEK (256 bits), ESAK (128 bits) and PVC (64 bits) is stored in a single entry under APP=0, KEY=2: + +| Data | KEY | APP | LEN | SALT | EDEK | ESAK | PVC | +|----------------|-----|-----|-------|------|------|------|-----| +| Length (bytes) | 1 | 1 | 2 | 4 | 32 | 16 | 8 | +| Value | 02 | 00 | 3C 00 | | | | | + +The storage authentication tag (128 bits) is stored in a single entry under APP=0, KEY=5: + +| Data | KEY | APP | LEN | TAG | +|----------------|-----|-----|-------|-----| +| Length (bytes) | 1 | 1 | 2 | 16 | +| Value | 05 | 00 | 20 00 | | + +Furthermore, if any entry is overwritten, the old entry is erased, i.e., overwritten with 0. We are also using APP=0, KEY=0 as marker that the entry is erased (this was formerly used for the PIN entry, which is not needed anymore). + +## PIN verification and decryption of protected entries in flash storage + +1. From the flash storage read the entry containing the random salt, EDEK and PVC. + +2. Gather constant data from various system resources such as the ProcessorID (aka Unique device ID) and any hardware serial numbers that are available. The concatenation of this data with the random salt will be referred to as *salt*. +3. Prompt the user to enter the PIN. Prefix the entered PIN with a "1" digit in base 10 and convert the integer to 4 bytes in little endian byte order. Then compute: + + `PBKDF2(PRF = HMAC-SHA256, Password = pin, Salt = salt, iterations = 10000, dkLen = 352 bits)` + + The first 256 bits of the output will be used as the key encryption key (KEK) and the remaining 96 bits will be used as the key encryption initialization vector (KEIV). + + *Note: Since two blocks of output need to be produced in PBKDF2 the total number of iterations is 20000.* + +4. Compute: + + `(dek, tag) = ChaCha20Poly1305Decrypt(kek, keiv, edek)` + +5. Compare the PVC read from the flash storage with the first 64 bits of the computed tag value. If there is a mismatch, then fail. Otherwise store the DEK in a global variable. + +6. When a protected entry needs to be decrypted, load the IV, ENCRDATA and TAG of the entry and compute: + + `(data, tag) = ChaCha20Poly1305Decrypt(dek, iv, (key || app), encrdata)` + + where the APP and KEY of the entry is used as two bytes of associated data. Compare the TAG read from the flash storage with the computed tag value. If there is a mismatch, then fail. + +![summary](docs/key-derivation.svg) + +## Initializing the EDEK + +1. When the storage is initialized, generate the 32 bit random salt and 256 bit DEK using a cryptographically secure random number generator. + +2. Set a boolean value in the storage denoting that the PIN has not been set. Use an empty PIN to derive the KEK and KEIV as described above. + +3. Encrypt the DEK using the derived KEK and KEIV: + + `(edek, tag) = ChaCha20Poly1305Encrypt(kek, keiv, dek)` + +4. Store the random salt, EDEK value and the first 64 bits of the tag as the PVC. + +## Setting a new PIN + +1. If the PIN has already been set, then prompt the user to enter the old PIN value, check the PVC and compute the DEK as described above in steps 1-4. + +2. Generate a new 32 bit random salt and prompt the user to enter the new PIN value. Use these values to derive the new KEK and KEIV as described above. + +3. Encrypt the DEK using the new KEK and KEIV: + + `(edek, tag) = ChaCha20Poly1305Encrypt(kek, keiv, dek)` + +4. Store the new EDEK value and the first 64 bits of the tag as the new PVC. This operation should be atomic, i.e. either both values should be stored or neither. Overwrite the old values of the EDEK and PVC with zeros. + +## Encryption of protected entries in flash storage + +Whenever the value of an entry needs to be updated, a fresh IV is generated using a cryptographically secure random number generator and the data is encrypted as `(encrdata, tag) = ChaCha20Poly1305Encrypt(dek, iv, (key || app), data)`. + +## Storage authentication + +The storage authentication key (SAK) will be used to generate a storage authentication tag (SAT) for the list of all (APP, KEY) values of protected entries (1 ≤ APP ≤ 127) that have been set in the storage. The SAT will be checked during every get operation. When a new protected entry is added to the storage or when a protected entry is deleted from the storage, the value of the SAT will be updated. The value of the SAT is defined as the first 16 bytes of + +`HMAC-SHA-256(SAK, ⨁i HMAC-SHA-256(SAK, KEY_i || APP_i))` + +where `⨁` denotes the n-ary bitwise XOR operation and KEY_i || APP_i is a two-byte encoding of the value of the *i*-th (APP, KEY) such that 1 ≤ APP ≤ 127. + +## Design rationale + +- The purpose of the PBKDF2 function is to thwart brute-force attacks in case the attacker is able to circumvent the PIN entry counter mechanism but does not have full access to the contents of the flash storage of the device, e.g. fault injection attacks. For an attacker that would be able to read the flash storage and obtain the salt, the PBKDF2 with 20000 iterations and a 4- to 9-digit PIN would not pose an obstacle. + +- The reason why we use a separate data encryption key rather than using the output of PBKDF2 directly to encrypt the sensitive entries is so that when the user decides to change their PIN, only the EDEK needs to be reencrypted, but the remaining entries do not need to be updated. + +- We se ChaCha20 for encryption, because as a stream cipher it has no padding overhead and its implementation is readily available in trezor-crypto. A possible alternative to using ChaCha20Poly1305 for DEK encryption is to use AES-CTR with HMAC in an encrypt-then-MAC scheme. A possible alternative to using ChaCha20 for encryption of other data entries is to use AES-XTS (XEX-based tweaked-codebook mode with ciphertext stealing), which was designed specifically for disk-encryption. The APP || KEY value would be used as the tweak. + - Advantages of AES-XTS: + - Does not require an initialization vector. + - Ensures better diffusion than a stream cipher, which eliminates the above concerns about malleability and fault injection attacks. + - Disadvantages of AES-XTS: + - Not implemented in trezor-crypto. + - Requires two keys of length at least 128 bits. + +- A 32-bit PVC would be sufficient to verify the PIN value, since there would be less than a 1 in 4 chance that there exists a false PIN, which has the same PVC as the correct PIN. Nevertheless, we decided to go with a 64-bit PVC to achieve a larger security margin. The chance that there exists a false PIN, which has the same PVC as the correct PIN, then drops below 1 in 10^10. The existence of a false PIN does not appear to pose a security weakness, since the false PIN cannot be used to decrypt the protected entries. + +- Instead of using separate IVs for each entry we considered using a single IV for the entire sector. Upon sector compaction a new IV would have to be generated and the encrypted data would have to be reencrypted under the new IV. A possible issue with this approach is that compaction cannot happen without the DEK, i.e. generally data could not be written to the flash storage without knowing the PIN. This property might not always be desirable. + +## New measures for PIN entry counter protection + +The former implementation of the PIN entry counter was vulnerable to fault injection attacks. + +Under the former implementation the PIN counter storage entry consisted of 32 words initialized to 0xFFFFFFFF. The first non-zero word in this area was the current PIN failure counter. Before verifying the PIN the lowest bit with value 1 was set to 0, i.e. a value of FFFFFFFC indicated two PIN entries. Upon successful PIN entry, the word was set to 0x00000000, indicating that the next word was the PIN failure counter. Allegedly, by manipulating the voltage on the USB input an attacker could convince the device to read the PIN entry counter as 0xFFFFFFFF even if some of the bits had been set to 0. + +### Design goals + +- Make it easy to decrement the counter by changing a 1 bit to 0. +- Make it hard to reset the counter by a fault injection, i.e. counter values should not have an overly simple binary representation like 0xFFFFFFFF. +- If possible, use two or more different methods of checking the counter value so that an attacker has to mount different fault injection attacks to succeed. +- Optimize the format for successful PIN entry. +- Minimize the number of branching operations. Avoid loops, instead utilize bitwise and arithmetic operations when processing the PIN counter data. + +### Proposal summary + +Under the former implementation, for every unsuccessful PIN entry we discarded one bit from the counter, while for every successful PIN entry we discard an entire word. In the new implementation we optimize the counter operations for successful PIN entry. + +The basic idea is that there are two binary logs stored in the flash storage, e.g.: + +``` +...0001111111111111... pin_success_log +...0000001111111111... pin_entry_log +``` + +Before every PIN verification the highest 1-bit in the pin_entry_log is set to 0. If the verification succeeds, then the corresponding bit in the pin_success_log is also set to 0. The example above shows the status of the logs when the last three PIN entries were not successful. + +In actual fact the logs are not written to the flash storage exactly as shown above, but they are stored in a form that should protect them against fault injection attacks. Only half of the stored bits carry information, the other half acts as "guard bits". So a stored value `...001110...` could look like `...0g0gg1g11g0g...`, where g denotes a guard bit. The positions and the values of the guard bits are determined by a guard key. The guard_key is a randomly generated uint32 value stored as an entry in the flash memory in cleartext. The assumption behind this is that an attacker attempting to reset or decrement the PIN counter by a fault injection is not able to read the flash storage. However, the value of guard_key also needs to be protected against fault injection, so the set of valid guard_key values should be limited by some condition which is easy to verify, such as guard_key mod M == C, where M and C a suitably chosen constants. The constants should be chosen so that the binary representation of any valid guard_key value has Hamming weight between 8 and 24. These conditions are discussed below. + +### Storage format + +The PIN log has APP = 0 and KEY = 1. The DATA part of the entry consists of 33 words (132 bytes, assuming 32-bit words): + +- guard_key (1 word) +- pin_success_log (16 words) +- pin_entry_log (16 words) + +Each log is stored in big-endian word order. The byte order of each word is platform dependent. + +### Guard key validation + +The guard_key is said to be valid if the following three conditions hold true: + +1. Each byte of the binary representation of the guard_key has a balanced number of zeros and ones at the positions corresponding to the guard values (that is those bits in the mask 0xAAAAAAAA). +2. The guard_key binary representation does not contain a run of 5 (or more) zeros or ones. +3. The guard_key integer representation is congruent to 15 modulo 6311. + +Key validity can be checked with this function: + +```c +int key_validity(uint32_t guard_key) +{ + uint32_t count = (guard_key & 0x22222222) + ((guard_key >> 2) & 0x22222222); + count = count + (count >> 4); + + uint32_t zero_runs = ~guard_key; + zero_runs = zero_runs & (zero_runs >> 2); + zero_runs = zero_runs & (zero_runs >> 1); + zero_runs = zero_runs & (zero_runs >> 1); + uint32_t one_runs = guard_key; + one_runs = one_runs & (one_runs >> 2); + one_runs = one_runs & (one_runs >> 1); + one_runs = one_runs & (one_runs >> 1); + + return ((count & 0x0e0e0e0e) == 0x04040404) & (one_runs == 0) & (zero_runs == 0) & (guard_key % 6311 == 15); +} +``` + +### Key generation + +The guard_key may be generated in the following way: + +1. Generate a random integer *r* in such that 0 ≤ *r* ≤ 680552 with uniform probability. +2. Set *r* = *r* * 6311 + 15. +3. If *key_validity(r)* is not true go back to the step 1. + +Note that on average steps 1 to 3 are repeated about one hundred times. + +### Key expansion + +The guard_key is read from storage, its value is checked for validity and used to compute the guard_mask (indicating the positions of the guard bits) and guard value (indicating the values of the guard bits on their actual positions): + +```c +LOW_MASK = 0x55555555 +guard_mask = ((guard_key & LOW_MASK) << 1) | + ((~guard_key) & LOW_MASK) +guard = (((guard_key & LOW_MASK) << 1) & guard_key) | + (((~guard_key) & LOW_MASK) & (guard_key >> 1)) +``` + +**Explanation**: + +The guard_key contains two pieces of information. The position of the guard bits but also their corresponding values. The bitwise format of the guard_key is `vpvpvp...vp`. The bits labelled `p` indicate the position of each guard bit and the bits labelled `v` indicate its value. + +The guard_mask is derived from the guard_key and has the form `xyxyxy...xy` where x+y = 1 (in other words, there is exactly one 1 bit in each pair xy). First, we set the `x` bits: + +`(guard_key & LOW_MASK) << 1` + +and the `y` bits to its corresponding complement: + +`(~guard_key) & LOW_MASK` + +That ensures that only one 1 bit is present in each pair `xy`. The guard value is equal to the bits labelled `v` in the guard_key but only at the positions indicated by the guard_mask. The guard value is therefore equal to: + +``` + -------- x bits mask --------- & -- guard_key -- +guard = (((guard_key & LOW_MASK) << 1) & guard_key) | + ----- y bits mask ---- & - guard_key shifted to v bits + (((~guard_key) & LOW_MASK) & (guard_key >> 1)) +``` + +### Log initialization + +Each log is stored as 16 consecutive words each initialized to: + +`guard | ~guard_mask` + +### Removing and adding guard bits + +After reading a word from the flash storage we verify the format by checking the condition: + +`(word & guard_mask) == guard` + +and then remove the guard bits as follows: + +``` +word = word & ~guard_mask +word = ((word >> 1) | word ) & LOW_MASK +word = word | (word << 1) +``` + +This operation replaces each guard bit with the value of its neighbouring bit, e.g. `…0g0gg1g11g0g…` is converted to `…000011111100…` Thus each non-guard bit is duplicated. + +The guard bits can be added back as follows: + +`word = (word & ~guard_mask) | guard` + +### Determining the number of PIN failures + +Remove the guard bits from the words of the pin_entry_log using the operations described above and verify that the result has form 0\*1\* by checking the condition: + +`word & (word + 1) == 0` + +Then verify that the pin_entry_log and pin_success_log are in sync by checking the condition: + +`pin_entry_log & pin_success_log == pin_entry_log` + +Finally, determine the current number of PIN failures by counting the number of set bits in the evaluation of the following expression: + +`pin_success_log xor pin_entry_log` + +Note that the number of set bits in a word can be counted using bitwise and arithmetic operations. For a 32-bit word the following can be used: + +```c +count = word - ((word >> 1) & 0x55555555) +count = (count & 0x33333333) + ((count >> 2) & 0x33333333) +count = (count + (count >> 4)) & 0x0F0F0F0F +count = count + (count >> 8) +count = (count + (count >> 16)) & 0x3F +``` diff --git a/storage/docs/key-derivation.odg b/storage/docs/key-derivation.odg new file mode 100644 index 000000000..44d684d45 Binary files /dev/null and b/storage/docs/key-derivation.odg differ diff --git a/storage/docs/key-derivation.svg b/storage/docs/key-derivation.svg new file mode 100644 index 000000000..1408faf65 --- /dev/null +++ b/storage/docs/key-derivation.svg @@ -0,0 +1,411 @@ + +image/svg+xmlSALT +PVC +EDEK +32b +256b +64b +PBKDF2 +PIN ++ hardware salt +KEIV +KEK +256b +96b +ChaCha20Poly1305 +iv +cipher +text +PVC’ +SAK +128b +64b +first 64b of MAC +plain text +Flash +key +ESAK +128b +DEK +256b + \ No newline at end of file diff --git a/storage/norcow.c b/storage/norcow.c new file mode 100644 index 000000000..3ef5d6f9c --- /dev/null +++ b/storage/norcow.c @@ -0,0 +1,562 @@ +/* + * This file is part of the TREZOR project, https://trezor.io/ + * + * Copyright (c) SatoshiLabs + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include + +#include "norcow.h" +#include "flash.h" +#include "common.h" + +// NRC2 = 4e524332 +#define NORCOW_MAGIC ((uint32_t)0x3243524e) +// NRCW = 4e524357 +#define NORCOW_MAGIC_V0 ((uint32_t)0x5743524e) + +#define NORCOW_WORD_SIZE (sizeof(uint32_t)) +#define NORCOW_PREFIX_LEN NORCOW_WORD_SIZE +#define NORCOW_MAGIC_LEN NORCOW_WORD_SIZE +#define NORCOW_VERSION_LEN NORCOW_WORD_SIZE + +// The key value which is used to indicate that the entry is not set. +#define NORCOW_KEY_FREE (0xFFFF) + +// The key value which is used to indicate that the entry has been deleted. +#define NORCOW_KEY_DELETED (0x0000) + +// The offset from the beginning of the sector where stored items start. +#define NORCOW_STORAGE_START (NORCOW_HEADER_LEN + NORCOW_MAGIC_LEN + NORCOW_VERSION_LEN) + +// Map from sector index to sector number. +static const uint8_t norcow_sectors[NORCOW_SECTOR_COUNT] = NORCOW_SECTORS; + +// The index of the active reading sector and writing sector. These should be equal except when storage version upgrade or compaction is in progress. +static uint8_t norcow_active_sector = 0; +static uint8_t norcow_write_sector = 0; + +// The norcow version of the reading sector. +static uint32_t norcow_active_version = 0; + +// The offset of the first free item in the writing sector. +static uint32_t norcow_free_offset = 0; + +/* + * Returns pointer to sector, starting with offset + * Fails when there is not enough space for data of given size + */ +static const void *norcow_ptr(uint8_t sector, uint32_t offset, uint32_t size) +{ + ensure(sectrue * (sector <= NORCOW_SECTOR_COUNT), "invalid sector"); + return flash_get_address(norcow_sectors[sector], offset, size); +} + +/* + * Writes data to given sector, starting from offset + */ +static secbool norcow_write(uint8_t sector, uint32_t offset, uint32_t prefix, const uint8_t *data, uint16_t len) +{ + if (sector >= NORCOW_SECTOR_COUNT) { + return secfalse; + } + + if (offset + NORCOW_PREFIX_LEN + len > NORCOW_SECTOR_SIZE) { + return secfalse; + } + + ensure(flash_unlock_write(), NULL); + + // write prefix + ensure(flash_write_word(norcow_sectors[sector], offset, prefix), NULL); + offset += NORCOW_PREFIX_LEN; + + if (data != NULL) { + // write data + for (uint16_t i = 0; i < len; i++, offset++) { + ensure(flash_write_byte(norcow_sectors[sector], offset, data[i]), NULL); + } + } else { + offset += len; + } + + // pad with zeroes + for (; offset % NORCOW_WORD_SIZE; offset++) { + ensure(flash_write_byte(norcow_sectors[sector], offset, 0x00), NULL); + } + + ensure(flash_lock_write(), NULL); + return sectrue; +} + +/* + * Erases sector (and sets a magic) + */ +static void erase_sector(uint8_t sector, secbool set_magic) +{ +#if NORCOW_HEADER_LEN > 0 + // Backup the sector header. + uint32_t header_backup[NORCOW_HEADER_LEN/sizeof(uint32_t)]; + const void *sector_start = norcow_ptr(sector, 0, NORCOW_HEADER_LEN); + memcpy(header_backup, sector_start, sizeof(header_backup)); +#endif + + ensure(flash_erase(norcow_sectors[sector]), "erase failed"); + +#if NORCOW_HEADER_LEN > 0 + // Copy the sector header back. + ensure(flash_unlock_write(), NULL); + for (uint32_t i = 0; i < NORCOW_HEADER_LEN/sizeof(uint32_t); ++i) { + ensure(flash_write_word(norcow_sectors[sector], i*sizeof(uint32_t), header_backup[i]), NULL); + } + ensure(flash_lock_write(), NULL); +#endif + + if (sectrue == set_magic) { + ensure(norcow_write(sector, NORCOW_HEADER_LEN, NORCOW_MAGIC, NULL, 0), "set magic failed"); + ensure(norcow_write(sector, NORCOW_HEADER_LEN + NORCOW_MAGIC_LEN, ~NORCOW_VERSION, NULL, 0), "set version failed"); + } +} + +#define ALIGN4(X) (X) = ((X) + 3) & ~3 + +/* + * Reads one item starting from offset + */ +static secbool read_item(uint8_t sector, uint32_t offset, uint16_t *key, const void **val, uint16_t *len, uint32_t *pos) +{ + *pos = offset; + + const void *k = norcow_ptr(sector, *pos, 2); + if (k == NULL) return secfalse; + *pos += 2; + memcpy(key, k, sizeof(uint16_t)); + if (*key == NORCOW_KEY_FREE) { + return secfalse; + } + + const void *l = norcow_ptr(sector, *pos, 2); + if (l == NULL) return secfalse; + *pos += 2; + memcpy(len, l, sizeof(uint16_t)); + + *val = norcow_ptr(sector, *pos, *len); + if (*val == NULL) return secfalse; + *pos += *len; + ALIGN4(*pos); + return sectrue; +} + +/* + * Writes one item starting from offset + */ +static secbool write_item(uint8_t sector, uint32_t offset, uint16_t key, const void *val, uint16_t len, uint32_t *pos) +{ + uint32_t prefix = ((uint32_t)len << 16) | key; + *pos = offset + NORCOW_PREFIX_LEN + len; + ALIGN4(*pos); + return norcow_write(sector, offset, prefix, val, len); +} + +/* + * Finds the offset from the beginning of the sector where stored items start. + */ +static secbool find_start_offset(uint8_t sector, uint32_t *offset, uint32_t *version) +{ + const uint32_t *magic = norcow_ptr(sector, NORCOW_HEADER_LEN, NORCOW_MAGIC_LEN + NORCOW_VERSION_LEN); + if (magic == NULL) { + return secfalse; + } + + if (*magic == NORCOW_MAGIC) { + *offset = NORCOW_STORAGE_START; + *version = ~(magic[1]); + } else if (*magic == NORCOW_MAGIC_V0) { + *offset = NORCOW_HEADER_LEN + NORCOW_MAGIC_LEN; + *version = 0; + } else { + return secfalse; + } + + return sectrue; +} + +/* + * Finds item in given sector + */ +static secbool find_item(uint8_t sector, uint16_t key, const void **val, uint16_t *len) +{ + *val = NULL; + *len = 0; + + uint32_t offset; + uint32_t version; + if (sectrue != find_start_offset(sector, &offset, &version)) { + return secfalse; + } + + for (;;) { + uint16_t k, l; + const void *v; + uint32_t pos; + if (sectrue != read_item(sector, offset, &k, &v, &l, &pos)) { + break; + } + if (key == k) { + *val = v; + *len = l; + } + offset = pos; + } + return sectrue * (*val != NULL); +} + +/* + * Finds first unused offset in given sector + */ +static uint32_t find_free_offset(uint8_t sector) +{ + uint32_t offset; + uint32_t version; + if (sectrue != find_start_offset(sector, &offset, &version)) { + return secfalse; + } + + for (;;) { + uint16_t key, len; + const void *val; + uint32_t pos; + if (sectrue != read_item(sector, offset, &key, &val, &len, &pos)) { + break; + } + offset = pos; + } + return offset; +} + +/* + * Compacts active sector and sets new active sector + */ +static void compact(void) +{ + uint32_t offsetr; + uint32_t version; + if (sectrue != find_start_offset(norcow_active_sector, &offsetr, &version)) { + return; + } + + norcow_write_sector = (norcow_active_sector + 1) % NORCOW_SECTOR_COUNT; + erase_sector(norcow_write_sector, sectrue); + uint32_t offsetw = NORCOW_STORAGE_START; + + for (;;) { + // read item + uint16_t k, l; + const void *v; + uint32_t posr; + secbool r = read_item(norcow_active_sector, offsetr, &k, &v, &l, &posr); + if (sectrue != r) { + break; + } + offsetr = posr; + + // skip deleted items + if (k == NORCOW_KEY_DELETED) { + continue; + } + + // copy the item + uint32_t posw; + ensure(write_item(norcow_write_sector, offsetw, k, v, l, &posw), "compaction write failed"); + offsetw = posw; + } + + erase_sector(norcow_active_sector, secfalse); + norcow_active_sector = norcow_write_sector; + norcow_active_version = NORCOW_VERSION; + norcow_free_offset = find_free_offset(norcow_write_sector); +} + +/* + * Initializes storage + */ +void norcow_init(uint32_t *norcow_version) +{ + flash_init(); + secbool found = secfalse; + *norcow_version = 0; + // detect active sector - starts with magic and has highest version + for (uint8_t i = 0; i < NORCOW_SECTOR_COUNT; i++) { + uint32_t offset; + if (sectrue == find_start_offset(i, &offset, &norcow_active_version) && norcow_active_version >= *norcow_version) { + found = sectrue; + norcow_active_sector = i; + *norcow_version = norcow_active_version; + } + } + + // If no active sectors found or version downgrade, then erase. + if (sectrue != found || *norcow_version > NORCOW_VERSION) { + norcow_wipe(); + *norcow_version = NORCOW_VERSION; + } else if (*norcow_version < NORCOW_VERSION) { + // Prepare write sector for storage upgrade. + norcow_write_sector = (norcow_active_sector + 1) % NORCOW_SECTOR_COUNT; + erase_sector(norcow_write_sector, sectrue); + norcow_free_offset = find_free_offset(norcow_write_sector); + } else { + norcow_write_sector = norcow_active_sector; + norcow_free_offset = find_free_offset(norcow_write_sector); + } +} + +/* + * Wipe the storage + */ +void norcow_wipe(void) +{ + erase_sector(0, sectrue); + for (uint8_t i = 1; i < NORCOW_SECTOR_COUNT; i++) { + erase_sector(i, secfalse); + } + norcow_active_sector = 0; + norcow_active_version = NORCOW_VERSION; + norcow_write_sector = 0; + norcow_free_offset = NORCOW_STORAGE_START; +} + +/* + * Looks for the given key, returns status of the operation + */ +secbool norcow_get(uint16_t key, const void **val, uint16_t *len) +{ + return find_item(norcow_active_sector, key, val, len); +} + +/* + * Reads the next entry in the storage starting at offset. Returns secfalse if there is none. + */ +secbool norcow_get_next(uint32_t *offset, uint16_t *key, const void **val, uint16_t *len) +{ + if (*offset == 0) { + uint32_t version; + if (sectrue != find_start_offset(norcow_active_sector, offset, &version)) { + return secfalse; + } + } + + for (;;) { + uint32_t pos = 0; + secbool ret = read_item(norcow_active_sector, *offset, key, val, len, &pos); + if (sectrue != ret) { + break; + } + *offset = pos; + + // Skip deleted items. + if (*key == NORCOW_KEY_DELETED) { + continue; + } + + if (norcow_active_version == 0) { + // Check whether the item is the latest instance. + uint32_t offsetr = *offset; + for (;;) { + uint16_t k; + uint16_t l; + const void *v; + ret = read_item(norcow_active_sector, offsetr, &k, &v, &l, &offsetr); + if (sectrue != ret) { + // There is no newer instance of the item. + return sectrue; + } + if (*key == k) { + // There exists a newer instance of the item. + break; + } + } + } else { + return sectrue; + } + } + return secfalse; +} + +/* + * Sets the given key, returns status of the operation. If NULL is passed + * as val, then norcow_set allocates a new key of size len. The value should + * then be written using norcow_update_bytes(). + */ +secbool norcow_set(uint16_t key, const void *val, uint16_t len) +{ + secbool found; + return norcow_set_ex(key, val, len, &found); +} + +secbool norcow_set_ex(uint16_t key, const void *val, uint16_t len, secbool *found) +{ + // Key 0xffff is used as a marker to indicate that the entry is not set. + if (key == NORCOW_KEY_FREE) { + return secfalse; + } + + const uint8_t sector_num = norcow_sectors[norcow_write_sector]; + secbool ret = secfalse; + const void *ptr = NULL; + uint16_t len_old = 0; + *found = find_item(norcow_write_sector, key, &ptr, &len_old); + + // Try to update the entry if it already exists. + uint32_t offset = 0; + if (sectrue == *found) { + offset = (const uint8_t*) ptr - (const uint8_t *)norcow_ptr(norcow_write_sector, 0, NORCOW_SECTOR_SIZE); + if (val != NULL && len_old == len) { + ret = sectrue; + ensure(flash_unlock_write(), NULL); + for (uint16_t i = 0; i < len; i++) { + if (sectrue != flash_write_byte(sector_num, offset + i, ((const uint8_t*)val)[i])) { + ret = secfalse; + break; + } + } + ensure(flash_lock_write(), NULL); + } + } + + // If the update was not possible then write the entry as a new item. + if (secfalse == ret) { + // Delete the old item. + if (sectrue == *found) { + ensure(flash_unlock_write(), NULL); + + // Update the prefix to indicate that the old item has been deleted. + uint32_t prefix = (uint32_t)len_old << 16; + ensure(flash_write_word(sector_num, offset - NORCOW_PREFIX_LEN, prefix), NULL); + + // Delete the old item data. + uint32_t end = offset + len_old; + while (offset < end) { + ensure(flash_write_word(sector_num, offset, 0x00000000), NULL); + offset += NORCOW_WORD_SIZE; + } + + ensure(flash_lock_write(), NULL); + } + // Check whether there is enough free space and compact if full. + if (norcow_free_offset + NORCOW_PREFIX_LEN + len > NORCOW_SECTOR_SIZE) { + compact(); + } + // Write new item. + uint32_t pos; + ret = write_item(norcow_write_sector, norcow_free_offset, key, val, len, &pos); + if (sectrue == ret) { + norcow_free_offset = pos; + } + } + return ret; +} + +/* + * Deletes the given key, returns status of the operation. + */ +secbool norcow_delete(uint16_t key) +{ + // Key 0xffff is used as a marker to indicate that the entry is not set. + if (key == NORCOW_KEY_FREE) { + return secfalse; + } + + const uint8_t sector_num = norcow_sectors[norcow_write_sector]; + const void *ptr = NULL; + uint16_t len = 0; + if (sectrue != find_item(norcow_write_sector, key, &ptr, &len)) { + return secfalse; + } + + uint32_t offset = (const uint8_t*) ptr - (const uint8_t *)norcow_ptr(norcow_write_sector, 0, NORCOW_SECTOR_SIZE); + + ensure(flash_unlock_write(), NULL); + + // Update the prefix to indicate that the item has been deleted. + uint32_t prefix = (uint32_t)len << 16; + ensure(flash_write_word(sector_num, offset - NORCOW_PREFIX_LEN, prefix), NULL); + + // Delete the item data. + uint32_t end = offset + len; + while (offset < end) { + ensure(flash_write_word(sector_num, offset, 0x00000000), NULL); + offset += NORCOW_WORD_SIZE; + } + + ensure(flash_lock_write(), NULL); + + return sectrue; +} + +/* + * Update a word in flash at the given pointer. The pointer must point + * into the NORCOW area. + */ +secbool norcow_update_word(uint16_t key, uint16_t offset, uint32_t value) +{ + const void *ptr; + uint16_t len; + if (sectrue != find_item(norcow_write_sector, key, &ptr, &len)) { + return secfalse; + } + if ((offset & 3) != 0 || offset >= len) { + return secfalse; + } + uint32_t sector_offset = (const uint8_t*) ptr - (const uint8_t *)norcow_ptr(norcow_write_sector, 0, NORCOW_SECTOR_SIZE) + offset; + ensure(flash_unlock_write(), NULL); + ensure(flash_write_word(norcow_sectors[norcow_write_sector], sector_offset, value), NULL); + ensure(flash_lock_write(), NULL); + return sectrue; +} + +/* + * Update the value of the given key starting at the given offset. + */ +secbool norcow_update_bytes(const uint16_t key, const uint16_t offset, const uint8_t *data, const uint16_t len) +{ + const void *ptr; + uint16_t allocated_len; + if (sectrue != find_item(norcow_write_sector, key, &ptr, &allocated_len)) { + return secfalse; + } + if (offset + len > allocated_len) { + return secfalse; + } + uint32_t sector_offset = (const uint8_t*) ptr - (const uint8_t *)norcow_ptr(norcow_write_sector, 0, NORCOW_SECTOR_SIZE) + offset; + uint8_t sector = norcow_sectors[norcow_write_sector]; + ensure(flash_unlock_write(), NULL); + for (uint16_t i = 0; i < len; i++, sector_offset++) { + ensure(flash_write_byte(sector, sector_offset, data[i]), NULL); + } + ensure(flash_lock_write(), NULL); + return sectrue; +} + +/* + * Complete storage version upgrade + */ +secbool norcow_upgrade_finish(void) +{ + erase_sector(norcow_active_sector, secfalse); + norcow_active_sector = norcow_write_sector; + norcow_active_version = NORCOW_VERSION; + return sectrue; +} diff --git a/storage/norcow.h b/storage/norcow.h new file mode 100644 index 000000000..953f6f1d0 --- /dev/null +++ b/storage/norcow.h @@ -0,0 +1,82 @@ +/* + * This file is part of the TREZOR project, https://trezor.io/ + * + * Copyright (c) SatoshiLabs + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef __NORCOW_H__ +#define __NORCOW_H__ + +#include +#include "secbool.h" + +/* + * Storage parameters + */ + +#include "norcow_config.h" + +/* + * Initialize storage + */ +void norcow_init(uint32_t *norcow_version); + +/* + * Wipe the storage + */ +void norcow_wipe(void); + +/* + * Looks for the given key, returns status of the operation + */ +secbool norcow_get(uint16_t key, const void **val, uint16_t *len); + +/* + * Reads the next entry in the storage starting at offset. Returns secfalse if there is none. + */ +secbool norcow_get_next(uint32_t *offset, uint16_t *key, const void **val, uint16_t *len); + +/* + * Sets the given key, returns status of the operation. If NULL is passed + * as val, then norcow_set allocates a new key of size len. The value should + * then be written using norcow_update_bytes(). + */ +secbool norcow_set(uint16_t key, const void *val, uint16_t len); +secbool norcow_set_ex(uint16_t key, const void *val, uint16_t len, secbool *found); + +/* + * Deletes the given key, returns status of the operation. + */ +secbool norcow_delete(uint16_t key); + +/* + * Update a word in flash in the given key at the given offset. + * Note that you can only change bits from 1 to 0. + */ +secbool norcow_update_word(uint16_t key, uint16_t offset, uint32_t value); + +/* + * Update the value of the given key starting at the given offset. + * Note that you can only change bits from 1 to 0. + */ +secbool norcow_update_bytes(const uint16_t key, const uint16_t offset, const uint8_t *data, const uint16_t len); + +/* + * Complete storage version upgrade + */ +secbool norcow_upgrade_finish(void); + +#endif diff --git a/storage/storage.c b/storage/storage.c new file mode 100644 index 000000000..655e85c31 --- /dev/null +++ b/storage/storage.c @@ -0,0 +1,1286 @@ +/* + * This file is part of the TREZOR project, https://trezor.io/ + * + * Copyright (c) SatoshiLabs + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#include + +#include "common.h" +#include "norcow.h" +#include "storage.h" +#include "pbkdf2.h" +#include "sha2.h" +#include "hmac.h" +#include "rand.h" +#include "memzero.h" +#include "chacha20poly1305/rfc7539.h" + +#define LOW_MASK 0x55555555 + +// The APP namespace which is reserved for storage related values. +#define APP_STORAGE 0x00 + +// Norcow storage key of the PIN entry log and PIN success log. +#define PIN_LOGS_KEY ((APP_STORAGE << 8) | 0x01) + +// Norcow storage key of the combined salt, EDEK, ESAK and PIN verification code entry. +#define EDEK_PVC_KEY ((APP_STORAGE << 8) | 0x02) + +// Norcow storage key of the PIN set flag. +#define PIN_NOT_SET_KEY ((APP_STORAGE << 8) | 0x03) + +// Norcow storage key of the storage version. +#define VERSION_KEY ((APP_STORAGE << 8) | 0x04) + +// Norcow storage key of the storage authentication tag. +#define STORAGE_TAG_KEY ((APP_STORAGE << 8) | 0x05) + +// The PIN value corresponding to an empty PIN. +#define PIN_EMPTY 1 + +// Maximum number of failed unlock attempts. +// NOTE: The PIN counter logic relies on this constant being less than or equal to 16. +#define PIN_MAX_TRIES 16 + +// The total number of iterations to use in PBKDF2. +#define PIN_ITER_COUNT 20000 + +// The number of seconds required to derive the KEK and KEIV. +#define DERIVE_SECS 1 + +// If the top bit of APP is set, then the value is not encrypted. +#define FLAG_PUBLIC 0x80 + +// If the top two bits of APP are set, then the value is not encrypted and it +// can be written even when the storage is locked. +#define FLAGS_WRITE 0xC0 + +// The length of the guard key in words. +#define GUARD_KEY_WORDS 1 + +// The length of the PIN entry log or the PIN success log in words. +#define PIN_LOG_WORDS 16 + +// The length of a word in bytes. +#define WORD_SIZE (sizeof(uint32_t)) + +// The length of the hashed hardware salt in bytes. +#define HARDWARE_SALT_SIZE SHA256_DIGEST_LENGTH + +// The length of the random salt in bytes. +#define RANDOM_SALT_SIZE 4 + +// The length of the data encryption key in bytes. +#define DEK_SIZE 32 + +// The length of the storage authentication key in bytes. +#define SAK_SIZE 16 + +// The combined length of the data encryption key and the storage authentication key in bytes. +#define KEYS_SIZE (DEK_SIZE + SAK_SIZE) + +// The length of the PIN verification code in bytes. +#define PVC_SIZE 8 + +// The length of the storage authentication tag in bytes. +#define STORAGE_TAG_SIZE 16 + +// The length of the Poly1305 authentication tag in bytes. +#define POLY1305_TAG_SIZE 16 + +// The length of the ChaCha20 IV (aka nonce) in bytes as per RFC 7539. +#define CHACHA20_IV_SIZE 12 + +// The length of the ChaCha20 block in bytes. +#define CHACHA20_BLOCK_SIZE 64 + +// The length of the counter tail in words. +#define COUNTER_TAIL_WORDS 2 + +// Values used in the guard key integrity check. +#define GUARD_KEY_MODULUS 6311 +#define GUARD_KEY_REMAINDER 15 + +const char* const VERIFYING_PIN_MSG = "Verifying PIN"; +const char* const PROCESSING_MSG = "Processing"; +const char* const STARTING_MSG = "Starting up"; + +static secbool initialized = secfalse; +static secbool unlocked = secfalse; +static PIN_UI_WAIT_CALLBACK ui_callback = NULL; +static uint32_t ui_total = 0; +static uint32_t ui_rem = 0; +static const char *ui_message = NULL; +static uint8_t cached_keys[KEYS_SIZE] = {0}; +static uint8_t *const cached_dek = cached_keys; +static uint8_t *const cached_sak = cached_keys + DEK_SIZE; +static uint8_t authentication_sum[SHA256_DIGEST_LENGTH] = {0}; +static uint8_t hardware_salt[HARDWARE_SALT_SIZE] = {0}; +static uint32_t norcow_active_version = 0; +static const uint8_t TRUE_BYTE = 0x01; +static const uint8_t FALSE_BYTE = 0x00; + +static void __handle_fault(const char *msg, const char *file, int line, const char *func); +#define handle_fault(msg) (__handle_fault(msg, __FILE__, __LINE__, __func__)) + +static secbool storage_upgrade(void); +static secbool storage_set_encrypted(const uint16_t key, const void *val, const uint16_t len); +static secbool storage_get_encrypted(const uint16_t key, void *val_dest, const uint16_t max_len, uint16_t *len); + +static secbool secequal(const void* ptr1, const void* ptr2, size_t n) { + const uint8_t* p1 = ptr1; + const uint8_t* p2 = ptr2; + uint8_t diff = 0; + size_t i; + for (i = 0; i < n; ++i) { + diff |= *p1 ^ *p2; + ++p1; + ++p2; + } + + // Check loop completion in case of a fault injection attack. + if (i != n) { + handle_fault("loop completion check"); + } + + return diff ? secfalse : sectrue; +} + +static secbool secequal32(const uint32_t* ptr1, const uint32_t* ptr2, size_t n) { + uint32_t diff = 0; + size_t i; + for (i = 0; i < n; ++i) { + uint32_t mask = random32(); + diff |= (*ptr1 + mask - *ptr2) ^ mask; + ++ptr1; + ++ptr2; + } + + // Check loop completion in case of a fault injection attack. + if (i != n) { + handle_fault("loop completion check"); + } + + return diff ? secfalse : sectrue; +} + +static secbool is_protected(uint16_t key) { + const uint8_t app = key >> 8; + return ((app & FLAG_PUBLIC) == 0 && app != APP_STORAGE) ? sectrue : secfalse; +} + +/* + * Initialize the storage authentication tag for freshly wiped storage. + */ +static secbool auth_init(void) { + uint8_t tag[SHA256_DIGEST_LENGTH]; + memzero(authentication_sum, sizeof(authentication_sum)); + hmac_sha256(cached_sak, SAK_SIZE, authentication_sum, sizeof(authentication_sum), tag); + return norcow_set(STORAGE_TAG_KEY, tag, STORAGE_TAG_SIZE); +} + +/* + * Update the storage authentication tag with the given key. + */ +static secbool auth_update(uint16_t key) { + if (sectrue != is_protected(key)) { + return sectrue; + } + + uint8_t tag[SHA256_DIGEST_LENGTH]; + hmac_sha256(cached_sak, SAK_SIZE, (uint8_t*)&key, sizeof(key), tag); + for (uint32_t i = 0; i < SHA256_DIGEST_LENGTH; i++) { + authentication_sum[i] ^= tag[i]; + } + hmac_sha256(cached_sak, SAK_SIZE, authentication_sum, sizeof(authentication_sum), tag); + return norcow_set(STORAGE_TAG_KEY, tag, STORAGE_TAG_SIZE); +} + +/* + * A secure version of norcow_set(), which updates the storage authentication tag. + */ +static secbool auth_set(uint16_t key, const void *val, uint16_t len) { + secbool found; + secbool ret = norcow_set_ex(key, val, len, &found); + if (sectrue == ret && secfalse == found) { + ret = auth_update(key); + if (sectrue != ret) { + norcow_delete(key); + } + } + return ret; +} + +/* + * A secure version of norcow_get(), which checks the storage authentication tag. + */ +static secbool auth_get(uint16_t key, const void **val, uint16_t *len) +{ + *val = NULL; + *len = 0; + uint32_t sum[SHA256_DIGEST_LENGTH/sizeof(uint32_t)] = {0}; + + // Prepare inner and outer digest. + uint32_t odig[SHA256_DIGEST_LENGTH / sizeof(uint32_t)]; + uint32_t idig[SHA256_DIGEST_LENGTH / sizeof(uint32_t)]; + hmac_sha256_prepare(cached_sak, SAK_SIZE, odig, idig); + + // Prepare SHA-256 message padding. + uint32_t g[SHA256_BLOCK_LENGTH / sizeof(uint32_t)] = {0}; + uint32_t h[SHA256_BLOCK_LENGTH / sizeof(uint32_t)] = {0}; + g[15] = (SHA256_BLOCK_LENGTH + 2) * 8; + h[15] = (SHA256_BLOCK_LENGTH + SHA256_DIGEST_LENGTH) * 8; + h[8] = 0x80000000; + + uint32_t offset = 0; + uint16_t k = 0; + uint16_t l = 0; + uint16_t tag_len = 0; + uint16_t entry_count = 0; // Mitigation against fault injection. + uint16_t other_count = 0; // Mitigation against fault injection. + const void *v = NULL; + const void *tag_val = NULL; + while (sectrue == norcow_get_next(&offset, &k, &v, &l)) { + ++entry_count; + if (k == key) { + *val = v; + *len = l; + } else { + ++other_count; + } + if (sectrue != is_protected(k)) { + if (k == STORAGE_TAG_KEY) { + tag_val = v; + tag_len = l; + } + continue; + } + g[0] = (((uint32_t)k & 0xff) << 24) | (((uint32_t)k & 0xff00) << 8) | 0x8000; // Add SHA message padding. + sha256_Transform(idig, g, h); + sha256_Transform(odig, h, h); + for (uint32_t i = 0; i < SHA256_DIGEST_LENGTH/sizeof(uint32_t); i++) { + sum[i] ^= h[i]; + } + } + memcpy(h, sum, sizeof(sum)); + + sha256_Transform(idig, h, h); + sha256_Transform(odig, h, h); + + memzero(odig, sizeof(odig)); + memzero(idig, sizeof(idig)); + + // Cache the authentication sum. + for (size_t i = 0; i < SHA256_DIGEST_LENGTH/sizeof(uint32_t); i++) { +#if BYTE_ORDER == LITTLE_ENDIAN + REVERSE32(sum[i], ((uint32_t*)authentication_sum)[i]); +#else + ((uint32_t*)authentication_sum)[i] = sum[i]; +#endif + } + + // Check loop completion in case of a fault injection attack. + if (secfalse != norcow_get_next(&offset, &k, &v, &l)) { + handle_fault("loop completion check"); + } + + // Check storage authentication tag. +#if BYTE_ORDER == LITTLE_ENDIAN + for (size_t i = 0; i < SHA256_DIGEST_LENGTH/sizeof(uint32_t); i++) { + REVERSE32(h[i], h[i]); + } +#endif + if (tag_val == NULL || tag_len != STORAGE_TAG_SIZE || sectrue != secequal(h, tag_val, STORAGE_TAG_SIZE)) { + handle_fault("storage tag check"); + } + + if (*val == NULL) { + // Check for fault injection. + if (other_count != entry_count) { + handle_fault("sanity check"); + } + return secfalse; + } + return sectrue; +} + +/* + * Generates a delay of random length. Use this to protect sensitive code against fault injection. + */ +static void wait_random(void) +{ +#ifndef TREZOR_STORAGE_TEST + int wait = random32() & 0xff; + volatile int i = 0; + volatile int j = wait; + while (i < wait) { + if (i + j != wait) { + handle_fault("sanity check"); + } + ++i; + --j; + } + + // Double-check loop completion. + if (i != wait) { + handle_fault("loop completion check"); + } +#endif +} + +static void derive_kek(uint32_t pin, const uint8_t *random_salt, uint8_t kek[SHA256_DIGEST_LENGTH], uint8_t keiv[SHA256_DIGEST_LENGTH]) +{ +#if BYTE_ORDER == BIG_ENDIAN + REVERSE32(pin, pin); +#endif + + uint8_t salt[HARDWARE_SALT_SIZE + RANDOM_SALT_SIZE]; + memcpy(salt, hardware_salt, HARDWARE_SALT_SIZE); + memcpy(salt + HARDWARE_SALT_SIZE, random_salt, RANDOM_SALT_SIZE); + + uint32_t progress = (ui_total - ui_rem) * 1000 / ui_total; + if (ui_callback && ui_message) { + ui_callback(ui_rem, progress, ui_message); + } + + PBKDF2_HMAC_SHA256_CTX ctx; + pbkdf2_hmac_sha256_Init(&ctx, (const uint8_t*) &pin, sizeof(pin), salt, sizeof(salt), 1); + for (int i = 1; i <= 5; i++) { + pbkdf2_hmac_sha256_Update(&ctx, PIN_ITER_COUNT / 10); + if (ui_callback && ui_message) { + progress = ((ui_total - ui_rem) * 1000 + i * DERIVE_SECS * 100) / ui_total; + ui_callback(ui_rem - i * DERIVE_SECS / 10, progress, ui_message); + } + } + pbkdf2_hmac_sha256_Final(&ctx, kek); + + pbkdf2_hmac_sha256_Init(&ctx, (const uint8_t*) &pin, sizeof(pin), salt, sizeof(salt), 2); + for (int i = 6; i <= 10; i++) { + pbkdf2_hmac_sha256_Update(&ctx, PIN_ITER_COUNT / 10); + if (ui_callback && ui_message) { + progress = ((ui_total - ui_rem) * 1000 + i * DERIVE_SECS * 100) / ui_total; + ui_callback(ui_rem - i * DERIVE_SECS / 10, progress, ui_message); + } + } + pbkdf2_hmac_sha256_Final(&ctx, keiv); + + ui_rem -= DERIVE_SECS; + memzero(&ctx, sizeof(PBKDF2_HMAC_SHA256_CTX)); + memzero(&pin, sizeof(pin)); + memzero(&salt, sizeof(salt)); +} + +static secbool set_pin(uint32_t pin) +{ + uint8_t buffer[RANDOM_SALT_SIZE + KEYS_SIZE + POLY1305_TAG_SIZE]; + uint8_t *salt = buffer; + uint8_t *ekeys = buffer + RANDOM_SALT_SIZE; + uint8_t *pvc = buffer + RANDOM_SALT_SIZE + KEYS_SIZE; + + uint8_t kek[SHA256_DIGEST_LENGTH]; + uint8_t keiv[SHA256_DIGEST_LENGTH]; + chacha20poly1305_ctx ctx; + random_buffer(salt, RANDOM_SALT_SIZE); + derive_kek(pin, salt, kek, keiv); + rfc7539_init(&ctx, kek, keiv); + memzero(kek, sizeof(kek)); + memzero(keiv, sizeof(keiv)); + chacha20poly1305_encrypt(&ctx, cached_keys, ekeys, KEYS_SIZE); + rfc7539_finish(&ctx, 0, KEYS_SIZE, pvc); + memzero(&ctx, sizeof(ctx)); + secbool ret = norcow_set(EDEK_PVC_KEY, buffer, RANDOM_SALT_SIZE + KEYS_SIZE + PVC_SIZE); + memzero(buffer, sizeof(buffer)); + + if (ret == sectrue) + { + if (pin == PIN_EMPTY) { + ret = norcow_set(PIN_NOT_SET_KEY, &TRUE_BYTE, sizeof(TRUE_BYTE)); + } else { + ret = norcow_set(PIN_NOT_SET_KEY, &FALSE_BYTE, sizeof(FALSE_BYTE)); + } + } + + memzero(&pin, sizeof(pin)); + return ret; +} + +static secbool check_guard_key(const uint32_t guard_key) +{ + if (guard_key % GUARD_KEY_MODULUS != GUARD_KEY_REMAINDER) { + return secfalse; + } + + // Check that each byte of (guard_key & 0xAAAAAAAA) has exactly two bits set. + uint32_t count = (guard_key & 0x22222222) + ((guard_key >> 2) & 0x22222222); + count = count + (count >> 4); + if ((count & 0x0e0e0e0e) != 0x04040404) { + return secfalse; + } + + // Check that the guard_key does not contain a run of 5 (or more) zeros or ones. + uint32_t zero_runs = ~guard_key; + zero_runs = zero_runs & (zero_runs >> 2); + zero_runs = zero_runs & (zero_runs >> 1); + zero_runs = zero_runs & (zero_runs >> 1); + + uint32_t one_runs = guard_key; + one_runs = one_runs & (one_runs >> 2); + one_runs = one_runs & (one_runs >> 1); + one_runs = one_runs & (one_runs >> 1); + + if ((one_runs != 0) || (zero_runs != 0)) { + return secfalse; + } + + return sectrue; +} + +static uint32_t generate_guard_key(void) +{ + uint32_t guard_key = 0; + do { + guard_key = random_uniform((UINT32_MAX/GUARD_KEY_MODULUS) + 1) * GUARD_KEY_MODULUS + GUARD_KEY_REMAINDER; + } while (sectrue != check_guard_key(guard_key)); + return guard_key; +} + +static secbool expand_guard_key(const uint32_t guard_key, uint32_t *guard_mask, uint32_t *guard) +{ + if (sectrue != check_guard_key(guard_key)) { + handle_fault("guard key check"); + return secfalse; + } + *guard_mask = ((guard_key & LOW_MASK) << 1) | ((~guard_key) & LOW_MASK); + *guard = (((guard_key & LOW_MASK) << 1) & guard_key) | (((~guard_key) & LOW_MASK) & (guard_key >> 1)); + return sectrue; +} + +static secbool pin_logs_init(uint32_t fails) +{ + if (fails >= PIN_MAX_TRIES) { + return secfalse; + } + + // The format of the PIN_LOGS_KEY entry is: + // guard_key (1 word), pin_success_log (PIN_LOG_WORDS), pin_entry_log (PIN_LOG_WORDS) + uint32_t logs[GUARD_KEY_WORDS + 2*PIN_LOG_WORDS]; + + logs[0] = generate_guard_key(); + + uint32_t guard_mask; + uint32_t guard; + wait_random(); + if (sectrue != expand_guard_key(logs[0], &guard_mask, &guard)) { + return secfalse; + } + + uint32_t unused = guard | ~guard_mask; + for (size_t i = 0; i < 2*PIN_LOG_WORDS; ++i) { + logs[GUARD_KEY_WORDS + i] = unused; + } + + // Set the first word of the PIN entry log to indicate the requested number of fails. + logs[GUARD_KEY_WORDS + PIN_LOG_WORDS] = ((((uint32_t)0xFFFFFFFF) >> (2*fails)) & ~guard_mask) | guard; + + return norcow_set(PIN_LOGS_KEY, logs, sizeof(logs)); +} + +/* + * Initializes the values of VERSION_KEY, EDEK_PVC_KEY, PIN_NOT_SET_KEY and PIN_LOGS_KEY using an empty PIN. + * This function should be called to initialize freshly wiped storage. + */ +static void init_wiped_storage(void) +{ + if (sectrue != initialized) { + // We cannot initialize the storage contents if the hardware_salt is not set. + return; + } + random_buffer(cached_keys, sizeof(cached_keys)); + uint32_t version = NORCOW_VERSION; + ensure(auth_init(), "set_storage_auth_tag failed"); + ensure(storage_set_encrypted(VERSION_KEY, &version, sizeof(version)), "set_storage_version failed"); + ensure(pin_logs_init(0), "init_pin_logs failed"); + ui_total = DERIVE_SECS; + ui_rem = ui_total; + ui_message = PROCESSING_MSG; + ensure(set_pin(PIN_EMPTY), "init_pin failed"); + if (unlocked != sectrue) { + memzero(cached_keys, sizeof(cached_keys)); + } +} + +void storage_init(PIN_UI_WAIT_CALLBACK callback, const uint8_t *salt, const uint16_t salt_len) +{ + initialized = secfalse; + unlocked = secfalse; + norcow_init(&norcow_active_version); + initialized = sectrue; + ui_callback = callback; + + sha256_Raw(salt, salt_len, hardware_salt); + + if (norcow_active_version < NORCOW_VERSION) { + if (sectrue != storage_upgrade()) { + storage_wipe(); + ensure(secfalse, "storage_upgrade failed"); + } + } + + // If there is no EDEK, then generate a random DEK and SAK and store them. + const void *val; + uint16_t len; + if (secfalse == norcow_get(EDEK_PVC_KEY, &val, &len)) { + init_wiped_storage(); + } + memzero(cached_keys, sizeof(cached_keys)); +} + +static secbool pin_fails_reset(void) +{ + const void *logs = NULL; + uint16_t len = 0; + + if (sectrue != norcow_get(PIN_LOGS_KEY, &logs, &len) || len != WORD_SIZE*(GUARD_KEY_WORDS + 2*PIN_LOG_WORDS)) { + return secfalse; + } + + uint32_t guard_mask; + uint32_t guard; + wait_random(); + if (sectrue != expand_guard_key(*(const uint32_t*)logs, &guard_mask, &guard)) { + return secfalse; + } + + uint32_t unused = guard | ~guard_mask; + const uint32_t *success_log = ((const uint32_t*)logs) + GUARD_KEY_WORDS; + const uint32_t *entry_log = success_log + PIN_LOG_WORDS; + for (size_t i = 0; i < PIN_LOG_WORDS; ++i) { + if (entry_log[i] == unused) { + return sectrue; + } + if (success_log[i] != guard) { + if (sectrue != norcow_update_word(PIN_LOGS_KEY, sizeof(uint32_t)*(i + GUARD_KEY_WORDS), entry_log[i])) { + return secfalse; + } + } + } + return pin_logs_init(0); +} + +secbool storage_pin_fails_increase(void) +{ + if (sectrue != initialized) { + return secfalse; + } + + const void *logs = NULL; + uint16_t len = 0; + + wait_random(); + if (sectrue != norcow_get(PIN_LOGS_KEY, &logs, &len) || len != WORD_SIZE*(GUARD_KEY_WORDS + 2*PIN_LOG_WORDS)) { + handle_fault("no PIN logs"); + return secfalse; + } + + uint32_t guard_mask; + uint32_t guard; + wait_random(); + if (sectrue != expand_guard_key(*(const uint32_t*)logs, &guard_mask, &guard)) { + handle_fault("guard key expansion"); + return secfalse; + } + + const uint32_t *entry_log = ((const uint32_t*)logs) + GUARD_KEY_WORDS + PIN_LOG_WORDS; + for (size_t i = 0; i < PIN_LOG_WORDS; ++i) { + wait_random(); + if ((entry_log[i] & guard_mask) != guard) { + handle_fault("guard bits check"); + return secfalse; + } + if (entry_log[i] != guard) { + wait_random(); + uint32_t word = entry_log[i] & ~guard_mask; + word = ((word >> 1) | word) & LOW_MASK; + word = (word >> 2) | (word >> 1); + + wait_random(); + if (sectrue != norcow_update_word(PIN_LOGS_KEY, sizeof(uint32_t)*(i + GUARD_KEY_WORDS + PIN_LOG_WORDS), (word & ~guard_mask) | guard)) { + handle_fault("PIN logs update"); + return secfalse; + } + return sectrue; + } + + } + handle_fault("PIN log exhausted"); + return secfalse; +} + +static uint32_t hamming_weight(uint32_t value) +{ + value = value - ((value >> 1) & 0x55555555); + value = (value & 0x33333333) + ((value >> 2) & 0x33333333); + value = (value + (value >> 4)) & 0x0F0F0F0F; + value = value + (value >> 8); + value = value + (value >> 16); + return value & 0x3F; +} + +static secbool pin_get_fails(uint32_t *ctr) +{ + *ctr = PIN_MAX_TRIES; + + const void *logs = NULL; + uint16_t len = 0; + wait_random(); + if (sectrue != norcow_get(PIN_LOGS_KEY, &logs, &len) || len != WORD_SIZE*(GUARD_KEY_WORDS + 2*PIN_LOG_WORDS)) { + handle_fault("no PIN logs"); + return secfalse; + } + + uint32_t guard_mask; + uint32_t guard; + wait_random(); + if (sectrue != expand_guard_key(*(const uint32_t*)logs, &guard_mask, &guard)) { + handle_fault("guard key expansion"); + return secfalse; + } + const uint32_t unused = guard | ~guard_mask; + + const uint32_t *success_log = ((const uint32_t*)logs) + GUARD_KEY_WORDS; + const uint32_t *entry_log = success_log + PIN_LOG_WORDS; + volatile int current = -1; + volatile size_t i; + for (i = 0; i < PIN_LOG_WORDS; ++i) { + if ((entry_log[i] & guard_mask) != guard || (success_log[i] & guard_mask) != guard || (entry_log[i] & success_log[i]) != entry_log[i]) { + handle_fault("PIN logs format check"); + return secfalse; + } + + if (current == -1) { + if (entry_log[i] != guard) { + current = i; + } + } else { + if (entry_log[i] != unused) { + handle_fault("PIN entry log format check"); + return secfalse; + } + } + } + + if (current < 0 || current >= PIN_LOG_WORDS || i != PIN_LOG_WORDS) { + handle_fault("PIN log exhausted"); + return secfalse; + } + + // Strip the guard bits from the current entry word and duplicate each data bit. + wait_random(); + uint32_t word = entry_log[current] & ~guard_mask; + word = ((word >> 1) | word ) & LOW_MASK; + word = word | (word << 1); + // Verify that the entry word has form 0*1*. + if ((word & (word + 1)) != 0) { + handle_fault("PIN entry log format check"); + return secfalse; + } + + if (current == 0) { + ++current; + } + + // Count the number of set bits in the two current words of the success log. + wait_random(); + *ctr = hamming_weight(success_log[current-1] ^ entry_log[current-1]) + hamming_weight(success_log[current] ^ entry_log[current]); + return sectrue; +} + +secbool storage_is_unlocked(void) +{ + if (sectrue != initialized) { + return secfalse; + } + + return unlocked; +} + +void storage_lock(void) +{ + unlocked = secfalse; + memzero(cached_keys, sizeof(cached_keys)); + memzero(authentication_sum, sizeof(authentication_sum)); +} + +static secbool decrypt_dek(const uint8_t *kek, const uint8_t *keiv) +{ + const void *buffer = NULL; + uint16_t len = 0; + if (sectrue != initialized || sectrue != norcow_get(EDEK_PVC_KEY, &buffer, &len) || len != RANDOM_SALT_SIZE + KEYS_SIZE + PVC_SIZE) { + handle_fault("no EDEK"); + return secfalse; + } + + const uint8_t *ekeys = (const uint8_t*) buffer + RANDOM_SALT_SIZE; + const uint32_t *pvc = (const uint32_t*) buffer + (RANDOM_SALT_SIZE + KEYS_SIZE)/sizeof(uint32_t); + _Static_assert(((RANDOM_SALT_SIZE + KEYS_SIZE) & 3) == 0, "PVC unaligned"); + _Static_assert((PVC_SIZE & 3) == 0, "PVC size unaligned"); + + uint8_t keys[KEYS_SIZE]; + uint8_t tag[POLY1305_TAG_SIZE] __attribute__((aligned(sizeof(uint32_t)))); + chacha20poly1305_ctx ctx; + + // Decrypt the data encryption key and the storage authentication key and check the PIN verification code. + rfc7539_init(&ctx, kek, keiv); + chacha20poly1305_decrypt(&ctx, ekeys, keys, KEYS_SIZE); + rfc7539_finish(&ctx, 0, KEYS_SIZE, tag); + memzero(&ctx, sizeof(ctx)); + wait_random(); + if (secequal32((const uint32_t*) tag, pvc, PVC_SIZE/sizeof(uint32_t)) != sectrue) { + memzero(keys, sizeof(keys)); + memzero(tag, sizeof(tag)); + return secfalse; + } + memcpy(cached_keys, keys, sizeof(keys)); + memzero(keys, sizeof(keys)); + memzero(tag, sizeof(tag)); + + // Check that the authenticated version number matches the norcow version. + // NOTE: storage_get_encrypted() calls auth_get(), which initializes the authentication_sum. + uint32_t version; + if (sectrue != storage_get_encrypted(VERSION_KEY, &version, sizeof(version), &len) || len != sizeof(version) || version != norcow_active_version) { + handle_fault("storage version check"); + return secfalse; + } + + return sectrue; +} + +static secbool unlock(uint32_t pin) +{ + if (sectrue != initialized) { + return secfalse; + } + + // Get the pin failure counter + uint32_t ctr; + if (sectrue != pin_get_fails(&ctr)) { + memzero(&pin, sizeof(pin)); + return secfalse; + } + + // Wipe storage if too many failures + wait_random(); + if (ctr >= PIN_MAX_TRIES) { + storage_wipe(); + error_shutdown("Too many wrong PIN", "attempts. Storage has", "been wiped.", NULL); + return secfalse; + } + + // Sleep for 2^ctr - 1 seconds before checking the PIN. + uint32_t wait = (1 << ctr) - 1; + ui_total += wait; + uint32_t progress = 0; + for (ui_rem = ui_total; ui_rem > ui_total - wait; ui_rem--) { + for (int i = 0; i < 10; i++) { + if (ui_callback && ui_message) { + if (ui_total > 1000000) { // precise enough + progress = (ui_total - ui_rem) / (ui_total / 1000); + } else { + progress = ((ui_total - ui_rem) * 10 + i) * 100 / ui_total; + } + if (sectrue == ui_callback(ui_rem, progress, ui_message)) { + return secfalse; + } + } + hal_delay(100); + } + } + + // Read the random salt from EDEK_PVC_KEY and use it to derive the KEK and KEIV from the PIN. + const void *salt = NULL; + uint16_t len = 0; + if (sectrue != initialized || sectrue != norcow_get(EDEK_PVC_KEY, &salt, &len) || len != RANDOM_SALT_SIZE + KEYS_SIZE + PVC_SIZE) { + memzero(&pin, sizeof(pin)); + handle_fault("no EDEK"); + return secfalse; + } + uint8_t kek[SHA256_DIGEST_LENGTH]; + uint8_t keiv[SHA256_DIGEST_LENGTH]; + derive_kek(pin, (const uint8_t*) salt, kek, keiv); + memzero(&pin, sizeof(pin)); + + // First, we increase PIN fail counter in storage, even before checking the + // PIN. If the PIN is correct, we reset the counter afterwards. If not, we + // check if this is the last allowed attempt. + if (sectrue != storage_pin_fails_increase()) { + return secfalse; + } + + // Check that the PIN fail counter was incremented. + uint32_t ctr_ck; + if (sectrue != pin_get_fails(&ctr_ck) || ctr + 1 != ctr_ck) { + handle_fault("PIN counter increment"); + return secfalse; + } + + // Check that the PIN was correct. + if (sectrue != decrypt_dek(kek, keiv)) { + // Wipe storage if too many failures + wait_random(); + if (ctr + 1 >= PIN_MAX_TRIES) { + storage_wipe(); + error_shutdown("Too many wrong PIN", "attempts. Storage has", "been wiped.", NULL); + } + return secfalse; + } + memzero(kek, sizeof(kek)); + memzero(keiv, sizeof(keiv)); + + unlocked = sectrue; + + // Finally set the counter to 0 to indicate success. + return pin_fails_reset(); +} + +secbool storage_unlock(uint32_t pin) +{ + ui_total = DERIVE_SECS; + ui_rem = ui_total; + if (pin == PIN_EMPTY) { + if (ui_message == NULL) { + ui_message = STARTING_MSG; + } else { + ui_message = PROCESSING_MSG; + } + } else { + ui_message = VERIFYING_PIN_MSG; + } + return unlock(pin); +} + +/* + * Finds the encrypted data stored under key and writes its length to len. + * If val_dest is not NULL and max_len >= len, then the data is decrypted + * to val_dest using cached_dek as the decryption key. + */ +static secbool storage_get_encrypted(const uint16_t key, void *val_dest, const uint16_t max_len, uint16_t *len) +{ + const void *val_stored = NULL; + + if (sectrue != auth_get(key, &val_stored, len)) { + return secfalse; + } + + if (*len < CHACHA20_IV_SIZE + POLY1305_TAG_SIZE) { + handle_fault("ciphertext length check"); + return secfalse; + } + *len -= CHACHA20_IV_SIZE + POLY1305_TAG_SIZE; + + if (val_dest == NULL) { + return sectrue; + } + + if (*len > max_len) { + return secfalse; + } + + const uint8_t *iv = (const uint8_t*) val_stored; + const uint8_t *tag_stored = (const uint8_t*) val_stored + CHACHA20_IV_SIZE; + const uint8_t *ciphertext = (const uint8_t*) val_stored + CHACHA20_IV_SIZE + POLY1305_TAG_SIZE; + uint8_t tag_computed[POLY1305_TAG_SIZE]; + chacha20poly1305_ctx ctx; + rfc7539_init(&ctx, cached_dek, iv); + rfc7539_auth(&ctx, (const uint8_t*)&key, sizeof(key)); + chacha20poly1305_decrypt(&ctx, ciphertext, (uint8_t*) val_dest, *len); + rfc7539_finish(&ctx, sizeof(key), *len, tag_computed); + memzero(&ctx, sizeof(ctx)); + + // Verify authentication tag. + if (secequal(tag_computed, tag_stored, POLY1305_TAG_SIZE) != sectrue) { + memzero(val_dest, max_len); + memzero(tag_computed, sizeof(tag_computed)); + handle_fault("authentication tag check"); + return secfalse; + } + + memzero(tag_computed, sizeof(tag_computed)); + return sectrue; +} + +/* + * Finds the data stored under key and writes its length to len. If val_dest is + * not NULL and max_len >= len, then the data is copied to val_dest. + */ +secbool storage_get(const uint16_t key, void *val_dest, const uint16_t max_len, uint16_t *len) +{ + const uint8_t app = key >> 8; + // APP == 0 is reserved for PIN related values + if (sectrue != initialized || app == APP_STORAGE) { + return secfalse; + } + + // If the top bit of APP is set, then the value is not encrypted and can be read from a locked device. + secbool ret = secfalse; + if ((app & FLAG_PUBLIC) != 0) { + const void *val_stored = NULL; + if (sectrue != norcow_get(key, &val_stored, len)) { + return secfalse; + } + if (val_dest == NULL) { + return sectrue; + } + if (*len > max_len) { + return secfalse; + } + memcpy(val_dest, val_stored, *len); + ret = sectrue; + } else { + if (sectrue != unlocked) { + return secfalse; + } + ret = storage_get_encrypted(key, val_dest, max_len, len); + } + + return ret; +} + +/* + * Encrypts the data at val using cached_dek as the encryption key and stores the ciphertext under key. + */ +static secbool storage_set_encrypted(const uint16_t key, const void *val, const uint16_t len) +{ + if (len > UINT16_MAX - CHACHA20_IV_SIZE - POLY1305_TAG_SIZE) { + return secfalse; + } + + // Preallocate space on the flash storage. + if (sectrue != auth_set(key, NULL, CHACHA20_IV_SIZE + POLY1305_TAG_SIZE + len)) { + return secfalse; + } + + // Write the IV to the flash. + uint8_t buffer[CHACHA20_BLOCK_SIZE]; + random_buffer(buffer, CHACHA20_IV_SIZE); + uint16_t offset = 0; + if (sectrue != norcow_update_bytes(key, offset, buffer, CHACHA20_IV_SIZE)) { + return secfalse; + } + offset += CHACHA20_IV_SIZE + POLY1305_TAG_SIZE; + + // Encrypt all blocks except for the last one. + chacha20poly1305_ctx ctx; + rfc7539_init(&ctx, cached_dek, buffer); + rfc7539_auth(&ctx, (const uint8_t*)&key, sizeof(key)); + size_t i; + for (i = 0; i + CHACHA20_BLOCK_SIZE < len; i += CHACHA20_BLOCK_SIZE, offset += CHACHA20_BLOCK_SIZE) { + chacha20poly1305_encrypt(&ctx, ((const uint8_t*) val) + i, buffer, CHACHA20_BLOCK_SIZE); + if (sectrue != norcow_update_bytes(key, offset, buffer, CHACHA20_BLOCK_SIZE)) { + memzero(&ctx, sizeof(ctx)); + memzero(buffer, sizeof(buffer)); + return secfalse; + } + } + + // Encrypt final block and compute message authentication tag. + chacha20poly1305_encrypt(&ctx, ((const uint8_t*) val) + i, buffer, len - i); + secbool ret = norcow_update_bytes(key, offset, buffer, len - i); + if (sectrue == ret) { + rfc7539_finish(&ctx, sizeof(key), len, buffer); + ret = norcow_update_bytes(key, CHACHA20_IV_SIZE, buffer, POLY1305_TAG_SIZE); + } + memzero(&ctx, sizeof(ctx)); + memzero(buffer, sizeof(buffer)); + return ret; +} + +secbool storage_set(const uint16_t key, const void *val, const uint16_t len) +{ + const uint8_t app = key >> 8; + + // APP == 0 is reserved for PIN related values + if (sectrue != initialized || app == APP_STORAGE) { + return secfalse; + } + + if (sectrue != unlocked && (app & FLAGS_WRITE) != FLAGS_WRITE) { + return secfalse; + } + + secbool ret = secfalse; + if ((app & FLAG_PUBLIC) != 0) { + ret = norcow_set(key, val, len); + } else { + ret = storage_set_encrypted(key, val, len); + } + return ret; +} + +secbool storage_delete(const uint16_t key) +{ + const uint8_t app = key >> 8; + + // APP == 0 is reserved for storage related values + if (sectrue != initialized || app == APP_STORAGE) { + return secfalse; + } + + if (sectrue != unlocked && (app & FLAGS_WRITE) != FLAGS_WRITE) { + return secfalse; + } + + secbool ret = norcow_delete(key); + if (sectrue == ret) { + ret = auth_update(key); + } + return ret; +} + +secbool storage_set_counter(const uint16_t key, const uint32_t count) +{ + const uint8_t app = key >> 8; + if ((app & FLAG_PUBLIC) == 0) { + return secfalse; + } + + // The count is stored as a 32-bit integer followed by a tail of "1" bits, + // which is used as a tally. + uint32_t value[1 + COUNTER_TAIL_WORDS]; + memset(value, 0xff, sizeof(value)); + value[0] = count; + return storage_set(key, value, sizeof(value)); +} + +secbool storage_next_counter(const uint16_t key, uint32_t *count) +{ + const uint8_t app = key >> 8; + // APP == 0 is reserved for PIN related values + if (sectrue != initialized || app == APP_STORAGE || (app & FLAG_PUBLIC) == 0) { + return secfalse; + } + + if (sectrue != unlocked && (app & FLAGS_WRITE) != FLAGS_WRITE) { + return secfalse; + } + + uint16_t len = 0; + const uint32_t *val_stored = NULL; + if (sectrue != norcow_get(key, (const void**)&val_stored, &len)) { + *count = 0; + return storage_set_counter(key, 0); + } + + if (len < sizeof(uint32_t) || len % sizeof(uint32_t) != 0) { + return secfalse; + } + uint16_t len_words = len / sizeof(uint32_t); + + uint16_t i = 1; + while (i < len_words && val_stored[i] == 0) { + ++i; + } + + *count = val_stored[0] + 1 + 32 * (i - 1); + + if (i < len_words) { + *count += hamming_weight(~val_stored[i]); + return norcow_update_word(key, sizeof(uint32_t) * i, val_stored[i] >> 1); + } else { + return storage_set_counter(key, *count); + } +} + +secbool storage_has_pin(void) +{ + if (sectrue != initialized) { + return secfalse; + } + + const void *val = NULL; + uint16_t len; + if (sectrue != norcow_get(PIN_NOT_SET_KEY, &val, &len) || (len > 0 && *(uint8_t*)val != FALSE_BYTE)) { + return secfalse; + } + return sectrue; +} + +uint32_t storage_get_pin_rem(void) +{ + if (sectrue != initialized) { + return 0; + } + + uint32_t ctr = 0; + if (sectrue != pin_get_fails(&ctr)) { + return 0; + } + return PIN_MAX_TRIES - ctr; +} + +secbool storage_change_pin(uint32_t oldpin, uint32_t newpin) +{ + if (sectrue != initialized) { + return secfalse; + } + + ui_total = 2 * DERIVE_SECS; + ui_rem = ui_total; + ui_message = (oldpin != PIN_EMPTY && newpin == PIN_EMPTY) ? VERIFYING_PIN_MSG : PROCESSING_MSG; + + if (sectrue != unlock(oldpin)) { + return secfalse; + } + secbool ret = set_pin(newpin); + memzero(&oldpin, sizeof(oldpin)); + memzero(&newpin, sizeof(newpin)); + return ret; +} + +void storage_wipe(void) +{ + norcow_wipe(); + norcow_active_version = NORCOW_VERSION; + memzero(authentication_sum, sizeof(authentication_sum)); + memzero(cached_keys, sizeof(cached_keys)); + init_wiped_storage(); +} + +static void __handle_fault(const char *msg, const char *file, int line, const char *func) +{ + static secbool in_progress = secfalse; + + // If fault handling is already in progress, then we are probably facing a fault injection attack, so wipe. + if (secfalse != in_progress) { + storage_wipe(); + __fatal_error("Fault detected", msg, file, line, func); + } + + // We use the PIN fail counter as a fault counter. Increment the counter, check that it was incremented and halt. + in_progress = sectrue; + uint32_t ctr; + if (sectrue != pin_get_fails(&ctr)) { + storage_wipe(); + __fatal_error("Fault detected", msg, file, line, func); + } + + if (sectrue != storage_pin_fails_increase()) { + storage_wipe(); + __fatal_error("Fault detected", msg, file, line, func); + } + + uint32_t ctr_new; + if (sectrue != pin_get_fails(&ctr_new) || ctr + 1 != ctr_new) { + storage_wipe(); + } + __fatal_error("Fault detected", msg, file, line, func); +} + +/* + * Reads the PIN fail counter in version 0 format. Returns the current number of failed PIN entries. + */ +static secbool v0_pin_get_fails(uint32_t *ctr) +{ + const uint16_t V0_PIN_FAIL_KEY = 0x0001; + // The PIN_FAIL_KEY points to an area of words, initialized to + // 0xffffffff (meaning no PIN failures). The first non-zero word + // in this area is the current PIN failure counter. If PIN_FAIL_KEY + // has no configuration or is empty, the PIN failure counter is 0. + // We rely on the fact that flash allows to clear bits and we clear one + // bit to indicate PIN failure. On success, the word is set to 0, + // indicating that the next word is the PIN failure counter. + + // Find the current pin failure counter + const void *val = NULL; + uint16_t len = 0; + if (secfalse != norcow_get(V0_PIN_FAIL_KEY, &val, &len)) { + for (unsigned int i = 0; i < len / sizeof(uint32_t); i++) { + uint32_t word = ((const uint32_t*)val)[i]; + if (word != 0) { + *ctr = hamming_weight(~word); + return sectrue; + } + } + } + + // No PIN failures + *ctr = 0; + return sectrue; +} + +static secbool storage_upgrade(void) +{ + const uint16_t V0_PIN_KEY = 0x0000; + const uint16_t V0_PIN_FAIL_KEY = 0x0001; + uint16_t key = 0; + uint16_t len = 0; + const void *val = NULL; + + if (norcow_active_version == 0) { + random_buffer(cached_keys, sizeof(cached_keys)); + + // Initialize the storage authentication tag. + auth_init(); + + // Set the new storage version number. + uint32_t version = NORCOW_VERSION; + if (sectrue != storage_set_encrypted(VERSION_KEY, &version, sizeof(version))) { + return secfalse; + } + + // Set EDEK_PVC_KEY and PIN_NOT_SET_KEY. + ui_total = DERIVE_SECS; + ui_rem = ui_total; + ui_message = PROCESSING_MSG; + if (sectrue == norcow_get(V0_PIN_KEY, &val, &len)) { + set_pin(*(const uint32_t*)val); + } else { + set_pin(PIN_EMPTY); + } + + // Convert PIN failure counter. + uint32_t fails = 0; + v0_pin_get_fails(&fails); + pin_logs_init(fails); + + // Copy the remaining entries (encrypting the protected ones). + uint32_t offset = 0; + while (sectrue == norcow_get_next(&offset, &key, &val, &len)) { + if (key == V0_PIN_KEY || key == V0_PIN_FAIL_KEY) { + continue; + } + + secbool ret; + if (((key >> 8) & FLAG_PUBLIC) != 0) { + ret = norcow_set(key, val, len); + } else { + ret = storage_set_encrypted(key, val, len); + } + + if (sectrue != ret) { + return secfalse; + } + } + + unlocked = secfalse; + memzero(cached_keys, sizeof(cached_keys)); + } else { + return secfalse; + } + + norcow_active_version = NORCOW_VERSION; + return norcow_upgrade_finish(); +} diff --git a/storage/storage.h b/storage/storage.h new file mode 100644 index 000000000..e3a163247 --- /dev/null +++ b/storage/storage.h @@ -0,0 +1,44 @@ +/* + * This file is part of the TREZOR project, https://trezor.io/ + * + * Copyright (c) SatoshiLabs + * + * This program is free software: you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation, either version 3 of the License, or + * (at your option) any later version. + * + * This program is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this program. If not, see . + */ + +#ifndef __STORAGE_H__ +#define __STORAGE_H__ + +#include +#include +#include "secbool.h" + +typedef secbool (*PIN_UI_WAIT_CALLBACK)(uint32_t wait, uint32_t progress, const char* message); + +void storage_init(PIN_UI_WAIT_CALLBACK callback, const uint8_t *salt, const uint16_t salt_len); +void storage_wipe(void); +secbool storage_is_unlocked(void); +void storage_lock(void); +secbool storage_unlock(const uint32_t pin); +secbool storage_has_pin(void); +secbool storage_pin_fails_increase(void); +uint32_t storage_get_pin_rem(void); +secbool storage_change_pin(const uint32_t oldpin, const uint32_t newpin); +secbool storage_get(const uint16_t key, void *val, const uint16_t max_len, uint16_t *len); +secbool storage_set(const uint16_t key, const void *val, uint16_t len); +secbool storage_delete(const uint16_t key); +secbool storage_set_counter(const uint16_t key, const uint32_t count); +secbool storage_next_counter(const uint16_t key, uint32_t *count); + +#endif