1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2024-11-22 07:28:10 +00:00

MONOREPO MERGE trezor-storage

This commit is contained in:
matejcik 2019-04-15 19:15:05 +02:00
commit 71f2c0ef25
9 changed files with 3352 additions and 0 deletions

2
storage/.gitignore vendored Normal file
View File

@ -0,0 +1,2 @@
*.o
*.d

674
storage/COPYING Normal file
View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<https://www.gnu.org/licenses/>.
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
<https://www.gnu.org/licenses/why-not-lgpl.html>.

291
storage/README.md Normal file
View File

@ -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
```

Binary file not shown.

View File

@ -0,0 +1,411 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 888 456"
height="456"
width="888"
xml:space="preserve"
id="svg2"
version="1.1"><metadata
id="metadata8"><rdf:RDF><cc:Work
rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs
id="defs6"><clipPath
id="clipPath18"
clipPathUnits="userSpaceOnUse"><path
id="path16"
d="M 0,0 H 792 V 612 H 0 Z" /></clipPath><clipPath
id="clipPath22"
clipPathUnits="userSpaceOnUse"><path
style="clip-rule:evenodd"
id="path20"
d="M 0,0.028 H 791.971 V 611.999 H 0 Z" /></clipPath></defs><g
transform="matrix(1.3333333,0,0,-1.3333333,0,456)"
id="g10"><g
transform="translate(-62,-234)"
id="g12"><g
id="g14" /><g
id="g316"><g
id="g314"
clip-path="url(#clipPath18)"><g
id="g312"><g
id="g310"
clip-path="url(#clipPath22)"><path
id="path24"
style="fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke:none"
d="M 0,612 H 791.972 V 0.028 L 0,0.028 Z" /><path
id="path26"
style="fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke:none"
d="m 409.011,513.836 h -23.102 v 21.458 h 46.204 v -21.458 z" /><g
id="g30"><path
id="path28"
style="fill:none;stroke:#000000;stroke-width:0.75;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1"
d="m 409.011,513.836 h -23.102 v 21.458 h 46.204 v -21.458 z" /></g><g
id="g36"><text
id="text34"
style="font-variant:normal;font-weight:normal;font-size:13.01099968px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,393.307,519.987)"><tspan
id="tspan32"
y="0"
x="0 8.6913481 17.30463 23.510878">SALT</tspan></text>
</g><path
id="path38"
style="fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke:none"
d="m 652.28,513.836 h -29.083 v 21.458 h 58.167 v -21.458 z" /><g
id="g42"><path
id="path40"
style="fill:none;stroke:#000000;stroke-width:0.75;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1"
d="m 652.28,513.836 h -29.083 v 21.458 h 58.167 v -21.458 z" /></g><g
id="g48"><text
id="text46"
style="font-variant:normal;font-weight:normal;font-size:13.01099968px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,639.014,519.987)"><tspan
id="tspan44"
y="0"
x="0 8.6132822 17.226564">PVC</tspan></text>
</g><path
id="path50"
style="fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke:none"
d="m 486.397,513.836 h -54.595 v 21.458 h 109.162 v -21.458 z" /><g
id="g54"><path
id="path52"
style="fill:none;stroke:#000000;stroke-width:0.75;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1"
d="m 486.397,513.836 h -54.595 v 21.458 h 109.162 v -21.458 z" /></g><g
id="g60"><text
id="text58"
style="font-variant:normal;font-weight:normal;font-size:13.01099968px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,468.709,519.987)"><tspan
id="tspan56"
y="0"
x="0 8.6913481 17.994213 26.68556">EDEK</tspan></text>
</g><g
id="g66"><text
id="text64"
style="font-variant:normal;font-weight:normal;font-size:10.00599957px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,404.504,537.506)"><tspan
id="tspan62"
y="0"
x="0 5.5933542 11.096654">32b</tspan></text>
</g><g
id="g72"><text
id="text70"
style="font-variant:normal;font-weight:normal;font-size:10.00599957px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,475.398,537.392)"><tspan
id="tspan68"
y="0"
x="0 5.5933542 11.096654 16.599955">256b</tspan></text>
</g><g
id="g78"><text
id="text76"
style="font-variant:normal;font-weight:normal;font-size:10.00599957px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,643.209,537.392)"><tspan
id="tspan74"
y="0"
x="0 5.5033002 11.0066">64b</tspan></text>
</g><path
id="path80"
style="fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke:none"
d="m 191.197,410.627 h -57.6 v 35.546 h 115.2 v -35.546 z" /><g
id="g84"><path
id="path82"
style="fill:none;stroke:#729fcf;stroke-width:0.75;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1"
d="m 191.197,410.627 h -57.6 v 35.546 h 115.2 v -35.546 z" /></g><g
id="g90"><text
id="text88"
style="font-variant:normal;font-weight:normal;font-size:14.99499989px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,162.113,423.213)"><tspan
id="tspan86"
y="0"
x="0 9.9866695 19.883369 29.870041 40.666439 49.768406">PBKDF2</tspan></text>
</g><path
id="path92"
style="fill:none;stroke:#000000;stroke-width:0.1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1"
d="m 97.2,427.323 h 23.811" /><path
id="path94"
style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:none"
d="m 133.2,427.323 -12.756,4.252 v -8.504 z" /><g
id="g100"><text
id="text98"
style="font-variant:normal;font-weight:normal;font-size:14.99499989px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#ce181e;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,66.813,421.597)"><tspan
id="tspan96"
y="0"
x="0 9.8966999 14.080305">PIN</tspan></text>
</g><path
id="path102"
style="fill:none;stroke:#000000;stroke-width:0.1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1"
d="M 409.011,513.808 V 479.991 H 191.197 v -25.682" /><path
id="path104"
style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:none"
d="m 191.197,446.173 2.834,8.504 h -5.669 z" /><g
id="g110"><text
id="text108"
style="font-variant:normal;font-weight:normal;font-size:10.99800014px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,275.613,482.995)"><tspan
id="tspan106"
y="0"
x="0 6.4888201 9.6782398 15.78213 21.886021 25.570351 31.67424 39.570805 45.762676 49.447006 55.5509 58.641335 64.140335 70.332207 72.630791">+ hardware salt</tspan></text>
</g><path
id="path112"
style="fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke:none"
d="M 447.165,417.458 H 410.57 v 21.459 h 73.162 v -21.459 z" /><g
id="g116"><path
id="path114"
style="fill:none;stroke:#000000;stroke-width:0.75;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1"
d="M 447.165,417.458 H 410.57 v 21.459 h 73.162 v -21.459 z" /></g><g
id="g122"><text
id="text120"
style="font-variant:normal;font-weight:normal;font-size:13.01099968px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,432.397,423.694)"><tspan
id="tspan118"
y="0"
x="0 8.6132822 17.30463 20.908676">KEIV</tspan></text>
</g><path
id="path124"
style="fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke:none"
d="m 356.003,417.458 h -54.595 v 21.459 H 410.57 v -21.459 z" /><g
id="g128"><path
id="path126"
style="fill:none;stroke:#000000;stroke-width:0.75;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1"
d="m 356.003,417.458 h -54.595 v 21.459 H 410.57 v -21.459 z" /></g><g
id="g134"><text
id="text132"
style="font-variant:normal;font-weight:normal;font-size:13.01099968px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,342.992,423.694)"><tspan
id="tspan130"
y="0"
x="0 8.6913481 17.30463">KEK</tspan></text>
</g><g
id="g140"><text
id="text138"
style="font-variant:normal;font-weight:normal;font-size:10.00599957px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,345.005,441.099)"><tspan
id="tspan136"
y="0"
x="0 5.5933542 11.096654 16.599955">256b</tspan></text>
</g><g
id="g146"><text
id="text144"
style="font-variant:normal;font-weight:normal;font-size:10.00599957px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,439.087,440.986)"><tspan
id="tspan142"
y="0"
x="0 5.5033002 11.0066">96b</tspan></text>
</g><path
id="path148"
style="fill:none;stroke:#000000;stroke-width:0.1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1"
d="m 248.4,428.4 h 41.811" /><path
id="path150"
style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:none"
d="m 302.4,428.4 -12.756,4.252 v -8.504 z" /><path
id="path152"
style="fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke:none"
d="m 621.609,342.595 h -91.19 v 35.547 h 182.353 v -35.547 z" /><g
id="g156"><path
id="path154"
style="fill:none;stroke:#729fcf;stroke-width:0.75;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1"
d="m 621.609,342.595 h -91.19 v 35.547 h 182.353 v -35.547 z" /></g><g
id="g162"><text
id="text160"
style="font-variant:normal;font-weight:normal;font-size:14.99499989px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,554.202,355.209)"><tspan
id="tspan158"
y="0"
x="0 10.7964 19.178604 27.56081 38.357208 46.739414 55.12162 63.503826 71.886032 81.78273 90.164932 93.553802 101.14127 109.43351 117.92068 126.30289">ChaCha20Poly1305</tspan></text>
</g><path
id="path164"
style="fill:none;stroke:#000000;stroke-width:0.1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1"
d="M 356.003,417.43 V 354.954 H 522.369" /><path
id="path166"
style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:none"
d="M 530.504,354.954 522,357.789 v -5.669 z" /><path
id="path168"
style="fill:none;stroke:#000000;stroke-width:0.1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1"
d="m 447.165,417.43 v -51.137 h 75.204" /><path
id="path170"
style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:none"
d="M 530.504,366.293 522,369.128 v -5.67 z" /><path
id="path172"
style="fill:none;stroke:#000000;stroke-width:0.1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1"
d="M 486.397,513.808 V 464.4 h 135.212 v -78.123" /><path
id="path174"
style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:none"
d="m 621.609,378.142 2.835,8.504 h -5.669 z" /><g
id="g180"><text
id="text178"
style="font-variant:normal;font-weight:normal;font-size:10.00599957px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,506.211,368.986)"><tspan
id="tspan176"
y="0"
x="0 2.1012599">iv</tspan></text>
</g><g
id="g186"><text
id="text184"
style="font-variant:normal;font-weight:normal;font-size:10.00599957px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,588.189,394.809)"><tspan
id="tspan182"
y="0"
x="0 5.0930538 7.194314 12.697614 18.200914 23.794268">cipher</tspan></text>
</g><g
id="g192"><text
id="text190"
style="font-variant:normal;font-weight:normal;font-size:10.00599957px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,593.688,383.613)"><tspan
id="tspan188"
y="0"
x="0 2.7916739 8.2949743 13.388028">text</tspan></text>
</g><path
id="path194"
style="fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke:none"
d="m 675.978,250.186 h -27.326 v 21.458 h 54.624 v -21.458 z" /><g
id="g198"><path
id="path196"
style="fill:none;stroke:#000000;stroke-width:0.75;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1"
d="m 675.978,250.186 h -27.326 v 21.458 h 54.624 v -21.458 z" /></g><g
id="g204"><text
id="text202"
style="font-variant:normal;font-weight:normal;font-size:13.01099968px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,661.209,256.394)"><tspan
id="tspan200"
y="0"
x="0 8.6913481 17.30463 26.698572">PVC</tspan></text>
</g><path
id="path206"
style="fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke:none"
d="m 606.926,250.186 h -41.754 v 21.458 h 83.48 v -21.458 z" /><g
id="g210"><path
id="path208"
style="fill:none;stroke:#000000;stroke-width:0.75;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1"
d="m 606.926,250.186 h -41.754 v 21.458 h 83.48 v -21.458 z" /></g><g
id="g216"><text
id="text214"
style="font-variant:normal;font-weight:normal;font-size:13.01099968px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,594,256.394)"><tspan
id="tspan212"
y="0"
x="0 8.6132822 17.30463">SAK</tspan></text>
</g><g
id="g222"><text
id="text220"
style="font-variant:normal;font-weight:normal;font-size:10.00599957px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,597.288,239.811)"><tspan
id="tspan218"
y="0"
x="0 5.5033002 11.0066 16.509899">128b</tspan></text>
</g><g
id="g228"><text
id="text226"
style="font-variant:normal;font-weight:normal;font-size:10.00599957px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,668.608,239.698)"><tspan
id="tspan224"
y="0"
x="0 5.5933542 11.096654">64b</tspan></text>
</g><path
id="path230"
style="fill:none;stroke:#000000;stroke-width:0.1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1"
d="M 621.609,342.595 V 307.106 H 511.88 v -27.355" /><path
id="path232"
style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:none"
d="m 511.88,271.616 2.835,8.504 h -5.669 z" /><path
id="path234"
style="fill:none;stroke:#000000;stroke-width:0.1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1"
d="m 621.609,342.595 v -35.489 h 54.369 v -27.355" /><path
id="path236"
style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:none"
d="m 675.978,271.616 2.835,8.504 h -5.67 z" /><g
id="g242"><text
id="text240"
style="font-variant:normal;font-weight:normal;font-size:10.00599957px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,628.299,309.402)"><tspan
id="tspan238"
y="0"
x="0 2.7016201 4.9029398 8.2049198 13.297974 15.999594 18.791267 24.294567 29.797869 35.39122 38.092842 43.686195 46.387817 49.179489 57.48447 64.088432">first 64b of MAC</tspan></text>
</g><g
id="g248"><text
id="text246"
style="font-variant:normal;font-weight:normal;font-size:10.00599957px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,574.413,309.288)"><tspan
id="tspan244"
y="0"
x="0 5.5933542 7.6946139 13.287968 15.389228 20.892529 23.684202 26.385822 31.979176 36.982178">plain text</tspan></text>
</g><g
id="g252"><path
id="path250"
style="fill:none;stroke:#808080;stroke-width:0.75;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1"
d="M 541.417,490.904 H 360 v 79.2 h 362.835 v -79.2 z" /></g><g
id="g258"><text
id="text256"
style="font-variant:normal;font-weight:normal;font-size:13.01099968px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#808080;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,687.997,558.198)"><tspan
id="tspan254"
y="0"
x="0 7.9106879 10.79913 18.007223 24.512724">Flash</tspan></text>
</g><g
id="g264"><text
id="text262"
style="font-variant:normal;font-weight:normal;font-size:10.00599957px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,501.109,342.51)"><tspan
id="tspan260"
y="0"
x="0 5.0029998 10.596354">key</tspan></text>
</g><path
id="path266"
style="fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke:none"
d="m 581.471,513.808 h -41.754 v 21.458 h 83.508 v -21.458 z" /><g
id="g270"><path
id="path268"
style="fill:none;stroke:#000000;stroke-width:0.75;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1"
d="m 581.471,513.808 h -41.754 v 21.458 h 83.508 v -21.458 z" /></g><g
id="g276"><text
id="text274"
style="font-variant:normal;font-weight:normal;font-size:13.01099968px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,564.208,519.987)"><tspan
id="tspan272"
y="0"
x="0 8.6913481 17.30463 25.917912">ESAK</tspan></text>
</g><g
id="g282"><text
id="text280"
style="font-variant:normal;font-weight:normal;font-size:10.00599957px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,572.287,537.392)"><tspan
id="tspan278"
y="0"
x="0 5.5033002 11.0066 16.509899">128b</tspan></text>
</g><path
id="path284"
style="fill:#ffffff;fill-opacity:1;fill-rule:evenodd;stroke:none"
d="m 511.88,250.186 h -54.595 v 21.458 h 109.162 v -21.458 z" /><g
id="g288"><path
id="path286"
style="fill:none;stroke:#000000;stroke-width:0.75;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1"
d="m 511.88,250.186 h -54.595 v 21.458 h 109.162 v -21.458 z" /></g><g
id="g294"><text
id="text292"
style="font-variant:normal;font-weight:normal;font-size:13.01099968px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,498.614,256.394)"><tspan
id="tspan290"
y="0"
x="0 9.302865 17.994213">DEK</tspan></text>
</g><g
id="g300"><text
id="text298"
style="font-variant:normal;font-weight:normal;font-size:10.00599957px;font-family:'Liberation Sans';-inkscape-font-specification:LiberationSans;writing-mode:lr-tb;fill:#000000;fill-opacity:1;fill-rule:nonzero;stroke:none"
transform="matrix(1,0,0,-1,500.91,239.811)"><tspan
id="tspan296"
y="0"
x="0 5.5033002 11.0066 16.599955">256b</tspan></text>
</g><path
id="path302"
style="fill:none;stroke:#000000;stroke-width:0.1;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1"
d="m 603.071,307.106 v -10.63 h 3.855 v -16.725" /><path
id="path304"
style="fill:#000000;fill-opacity:1;fill-rule:evenodd;stroke:none"
d="m 606.926,271.616 2.835,8.504 h -5.67 z" /><g
id="g308"><path
id="path306"
style="fill:none;stroke:#000000;stroke-width:0.75;stroke-linecap:butt;stroke-linejoin:round;stroke-miterlimit:10;stroke-dasharray:none;stroke-opacity:1"
d="m 581.471,513.78 v -31.777 h 40.138 V 464.4" /></g></g></g></g></g></g></g></svg>

After

Width:  |  Height:  |  Size: 27 KiB

562
storage/norcow.c Normal file
View File

@ -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 <http://www.gnu.org/licenses/>.
*/
#include <string.h>
#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;
}

82
storage/norcow.h Normal file
View File

@ -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 <http://www.gnu.org/licenses/>.
*/
#ifndef __NORCOW_H__
#define __NORCOW_H__
#include <stdint.h>
#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

1286
storage/storage.c Normal file

File diff suppressed because it is too large Load Diff

44
storage/storage.h Normal file
View File

@ -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 <http://www.gnu.org/licenses/>.
*/
#ifndef __STORAGE_H__
#define __STORAGE_H__
#include <stdint.h>
#include <stddef.h>
#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