diff options
author | Victor Hsieh <victorhsieh@google.com> | 2018-10-04 12:54:01 -0700 |
---|---|---|
committer | android-build-merger <android-build-merger@google.com> | 2018-10-04 12:54:01 -0700 |
commit | b82bb92be8de0fed376ec3db9b996a4bd2301080 (patch) | |
tree | 131f4a358839b50ffbedc1dfe90c16f34c677b37 | |
parent | cff71472ac10415c3c4d147ef389f7ca51b33546 (diff) | |
parent | 5bcd0f9063089e14b86165b346e54d44f7f7d592 (diff) | |
download | fsverity-utils-b82bb92be8de0fed376ec3db9b996a4bd2301080.tar.gz |
Merge remote-tracking branch 'aosp/upstream_master' into init
am: 5bcd0f9063
Change-Id: I542eda1bf72d9bca0f3737c929c9a3433939d027
-rw-r--r-- | .gitignore | 5 | ||||
-rw-r--r-- | COPYING | 339 | ||||
-rw-r--r-- | LICENSE | 339 | ||||
-rw-r--r-- | METADATA | 19 | ||||
-rw-r--r-- | MODULE_LICENSE_GPL | 0 | ||||
-rw-r--r-- | Makefile | 22 | ||||
-rw-r--r-- | NOTICE | 339 | ||||
-rw-r--r-- | README.md | 162 | ||||
-rw-r--r-- | cmd_enable.c | 37 | ||||
-rw-r--r-- | cmd_measure.c | 72 | ||||
-rw-r--r-- | cmd_setup.c | 565 | ||||
-rw-r--r-- | commands.h | 20 | ||||
-rw-r--r-- | crc32c_table.h | 72 | ||||
-rw-r--r-- | debian/changelog | 5 | ||||
-rw-r--r-- | debian/compat | 1 | ||||
-rw-r--r-- | debian/control | 14 | ||||
-rw-r--r-- | debian/copyright | 7 | ||||
-rwxr-xr-x | debian/rules | 8 | ||||
-rw-r--r-- | elide_patch.c | 307 | ||||
-rw-r--r-- | fsverity.c | 148 | ||||
-rw-r--r-- | fsverity_uapi.h | 112 | ||||
-rw-r--r-- | fsveritysetup.h | 43 | ||||
-rw-r--r-- | hash_algs.c | 218 | ||||
-rw-r--r-- | hash_algs.h | 64 | ||||
-rw-r--r-- | scripts/gen_crc32c_table.c | 62 | ||||
-rw-r--r-- | sign.c | 552 | ||||
-rw-r--r-- | util.c | 362 | ||||
-rw-r--r-- | util.h | 160 |
28 files changed, 4054 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..95457ca --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +fsverity +*.o +tags +cscope.* +ncscope.* @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) 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 +this service 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 make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. 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. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the 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 a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE 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. + + 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 +convey 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 2 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, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision 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, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + <signature of Ty Coon>, 1 April 1989 + Ty Coon, President of Vice + +This 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. @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) 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 +this service 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 make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. 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. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the 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 a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE 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. + + 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 +convey 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 2 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, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision 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, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + <signature of Ty Coon>, 1 April 1989 + Ty Coon, President of Vice + +This 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. diff --git a/METADATA b/METADATA new file mode 100644 index 0000000..a9d6066 --- /dev/null +++ b/METADATA @@ -0,0 +1,19 @@ +name: "fsverity-utils" +description: + "This is `fsverity`, a userspace utility for fs-verity. fs-verity is " + "a Linux kernel feature that does transparent on-demand " + "integrity/authenticity verification of the contents of read-only " + "files, using a Merkle tree (hash tree) hidden after the end of the " + "file. The mechanism is similar to dm-verity, but implemented at the " + "file level rather than at the block device level. The `fsverity` " + "utility allows you to set up fs-verity protected files." + +third_party { + url { + type: GIT + value: "https://git.kernel.org/pub/scm/linux/kernel/git/ebiggers/fsverity-utils.git" + } + version: "bdebc45b4527d64109723ad5753fa514bac47c9f" + last_upgrade_date { year: 2018 month: 10 day: 4 } + license_type: RESTRICTED +} diff --git a/MODULE_LICENSE_GPL b/MODULE_LICENSE_GPL new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/MODULE_LICENSE_GPL diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..b9c09b9 --- /dev/null +++ b/Makefile @@ -0,0 +1,22 @@ +EXE := fsverity +CFLAGS := -O2 -Wall +CPPFLAGS := -D_FILE_OFFSET_BITS=64 +LDLIBS := -lcrypto +DESTDIR := /usr/local +SRC := $(wildcard *.c) +OBJ := $(SRC:.c=.o) +HDRS := $(wildcard *.h) + +all:$(EXE) + +$(EXE):$(OBJ) + +$(OBJ): %.o: %.c $(HDRS) + +clean: + rm -f $(EXE) $(OBJ) + +install:all + install -Dm755 -t $(DESTDIR)/bin $(EXE) + +.PHONY: all clean install @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) 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 +this service 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 make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. 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. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +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 +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the 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 a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE 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. + + 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 +convey 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 2 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, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision 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, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + <signature of Ty Coon>, 1 April 1989 + Ty Coon, President of Vice + +This 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. diff --git a/README.md b/README.md new file mode 100644 index 0000000..be2a251 --- /dev/null +++ b/README.md @@ -0,0 +1,162 @@ +# Introduction + +This is `fsverity`, a userspace utility for fs-verity. fs-verity is +a Linux kernel feature that does transparent on-demand +integrity/authenticity verification of the contents of read-only +files, using a Merkle tree (hash tree) hidden after the end of the +file. The mechanism is similar to dm-verity, but implemented at the +file level rather than at the block device level. The `fsverity` +utility allows you to set up fs-verity protected files. + +fs-verity will initially be supported by the ext4 and f2fs +filesystems, but it may later be supported by other filesystems too. + +# Building and installing + +The `fsverity` utility uses the OpenSSL library, so you first must +install the needed development files. For example, on Debian-based +systems, run: + +```bash + sudo apt-get install libssl-dev +``` + +OpenSSL must be version 1.0.0 or later. + +Then, to build and install: + +```bash + make + sudo make install +``` + +# Examples + +## Basic use + +```bash + mkfs.f2fs -O verity /dev/vdc + mount /dev/vdc /vdc + cd /vdc + + # Create a test file + head -c 1000000 /dev/urandom > file + md5sum file + + # Append the Merkle tree and other metadata to the file: + fsverity setup file + + # Enable fs-verity on the file + fsverity enable file + + # Should show the same hash that 'fsverity setup' printed. + # This hash can be logged, or compared to a trusted value. + fsverity measure file + + # Contents are now transparently verified and should match the + # original file contents, i.e. the metadata is hidden. + md5sum file +``` + +Note that in the above example, the file isn't signed. Therefore, to +get any authenticity protection (as opposed to just integrity +protection), the output of `fsverity measure` needs to be compared +against a trusted value. + +## Using builtin signatures + +With `CONFIG_FS_VERITY_BUILTIN_SIGNATURES=y`, the filesystem supports +automatically verifying a signed file measurement that has been +included in the fs-verity metadata. The signature is verified against +the set of X.509 certificates that have been loaded into the +".fs-verity" kernel keyring. Here's an example: + +```bash + # Generate a new certificate and private key: + openssl req -newkey rsa:4096 -nodes -keyout key.pem -x509 -out cert.pem + + # Convert the certificate from PEM to DER format: + openssl x509 -in cert.pem -out cert.der -outform der + + # Load the certificate into the fs-verity keyring: + keyctl padd asymmetric '' %keyring:.fs-verity < cert.der + + # Optionally, lock the keyring so that no more keys can be added + # (requires keyctl v1.5.11 or later): + keyctl restrict_keyring %keyring:.fs-verity + + # Optionally, require that all fs-verity files be signed: + sysctl fs.verity.require_signatures=1 + + # Now set up fs-verity on a test file: + md5sum file + fsverity setup file --signing-key=key.pem --signing-cert=cert.pem + fsverity enable file + md5sum file +``` + +By default, it's not required that fs-verity files have a signature. +This can be changed with `sysctl fs.verity.require_signatures=1`. +When set, it's guaranteed that the contents of every fs-verity file +has been signed by one of the certificates in the keyring. + +Note: applications generally still need to check whether the file +they're accessing really is a fs-verity file, since an attacker could +replace a fs-verity file with a regular one. + +## With IMA + +IMA support for fs-verity is planned. + +# Notices + +This project is provided under the terms of the GNU General Public +License, version 2; or at your option, any later version. A copy of the +GPLv2 can be found in the file named [COPYING](COPYING). + +Permission to link to OpenSSL (libcrypto) is granted. + +Send questions and bug reports to linux-fscrypt@vger.kernel.org. + +# Submitting patches + +Send patches to linux-fscrypt@vger.kernel.org. Patches should follow +the Linux kernel's coding style. Additionally, like the Linux kernel +itself, patches require the following "sign-off" procedure: + +The sign-off is a simple line at the end of the explanation for the +patch, which certifies that you wrote it or otherwise have the right +to pass it on as an open-source patch. The rules are pretty simple: +if you can certify the below: + +Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + + (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + + (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + + (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + + (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. + +then you just add a line saying:: + + Signed-off-by: Random J Developer <random@developer.example.org> + +using your real name (sorry, no pseudonyms or anonymous contributions.) diff --git a/cmd_enable.c b/cmd_enable.c new file mode 100644 index 0000000..ed092f0 --- /dev/null +++ b/cmd_enable.c @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * The 'fsverity enable' command + * + * Copyright (C) 2018 Google LLC + * + * Written by Eric Biggers. + */ + +#include <fcntl.h> +#include <sys/ioctl.h> + +#include "commands.h" +#include "fsverity_uapi.h" + +int fsverity_cmd_enable(const struct fsverity_command *cmd, + int argc, char *argv[]) +{ + struct filedes file; + + if (argc != 2) { + usage(cmd, stderr); + return 2; + } + + if (!open_file(&file, argv[1], O_RDONLY, 0)) + return 1; + if (ioctl(file.fd, FS_IOC_ENABLE_VERITY, NULL) != 0) { + error_msg_errno("FS_IOC_ENABLE_VERITY failed on '%s'", + file.name); + filedes_close(&file); + return 1; + } + if (!filedes_close(&file)) + return 1; + return 0; +} diff --git a/cmd_measure.c b/cmd_measure.c new file mode 100644 index 0000000..a5480a6 --- /dev/null +++ b/cmd_measure.c @@ -0,0 +1,72 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * The 'fsverity measure' command + * + * Copyright (C) 2018 Google LLC + * + * Written by Eric Biggers. + */ + +#include <fcntl.h> +#include <stdlib.h> +#include <sys/ioctl.h> + +#include "commands.h" +#include "fsverity_uapi.h" +#include "hash_algs.h" + +int fsverity_cmd_measure(const struct fsverity_command *cmd, + int argc, char *argv[]) +{ + struct fsverity_digest *d = NULL; + struct filedes file; + char digest_hex[FS_VERITY_MAX_DIGEST_SIZE * 2 + 1]; + const struct fsverity_hash_alg *hash_alg; + char _hash_alg_name[32]; + const char *hash_alg_name; + int status; + int i; + + if (argc < 2) + goto out_usage; + + d = xzalloc(sizeof(*d) + FS_VERITY_MAX_DIGEST_SIZE); + + for (i = 1; i < argc; i++) { + d->digest_size = FS_VERITY_MAX_DIGEST_SIZE; + + if (!open_file(&file, argv[i], O_RDONLY, 0)) + goto out_err; + if (ioctl(file.fd, FS_IOC_MEASURE_VERITY, d) != 0) { + error_msg_errno("FS_IOC_MEASURE_VERITY failed on '%s'", + file.name); + filedes_close(&file); + goto out_err; + } + filedes_close(&file); + + ASSERT(d->digest_size <= FS_VERITY_MAX_DIGEST_SIZE); + bin2hex(d->digest, d->digest_size, digest_hex); + hash_alg = find_hash_alg_by_num(d->digest_algorithm); + if (hash_alg) { + hash_alg_name = hash_alg->name; + } else { + sprintf(_hash_alg_name, "ALG_%u", d->digest_algorithm); + hash_alg_name = _hash_alg_name; + } + printf("%s:%s %s\n", hash_alg_name, digest_hex, argv[i]); + } + status = 0; +out: + free(d); + return status; + +out_err: + status = 1; + goto out; + +out_usage: + usage(cmd, stderr); + status = 2; + goto out; +} diff --git a/cmd_setup.c b/cmd_setup.c new file mode 100644 index 0000000..c598a71 --- /dev/null +++ b/cmd_setup.c @@ -0,0 +1,565 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * The 'fsverity setup' command + * + * Copyright (C) 2018 Google LLC + * + * Written by Eric Biggers. + */ + +#include <fcntl.h> +#include <getopt.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> + +#include "commands.h" +#include "fsverity_uapi.h" +#include "fsveritysetup.h" +#include "hash_algs.h" + +enum { + OPT_HASH, + OPT_SALT, + OPT_BLOCKSIZE, + OPT_SIGNING_KEY, + OPT_SIGNING_CERT, + OPT_SIGNATURE, + OPT_ELIDE, + OPT_PATCH, +}; + +static const struct option longopts[] = { + {"hash", required_argument, NULL, OPT_HASH}, + {"salt", required_argument, NULL, OPT_SALT}, + {"blocksize", required_argument, NULL, OPT_BLOCKSIZE}, + {"signing-key", required_argument, NULL, OPT_SIGNING_KEY}, + {"signing-cert", required_argument, NULL, OPT_SIGNING_CERT}, + {"signature", required_argument, NULL, OPT_SIGNATURE}, + {"elide", required_argument, NULL, OPT_ELIDE}, + {"patch", required_argument, NULL, OPT_PATCH}, + {NULL, 0, NULL, 0} +}; + +/* Parse the --blocksize=BLOCKSIZE option */ +static bool parse_blocksize_option(const char *opt, int *blocksize_ret) +{ + char *end; + unsigned long n = strtoul(opt, &end, 10); + + if (n <= 0 || n >= INT32_MAX || *end || !is_power_of_2(n)) { + error_msg("Invalid block size: %s. Must be power of 2", opt); + return false; + } + *blocksize_ret = n; + return true; +} + +#define FS_VERITY_MAX_LEVELS 64 + +/* + * Calculate the depth of the Merkle tree, then create a map from level to the + * block offset at which that level's hash blocks start. Level 'depth - 1' is + * the root and is stored first in the file, in the first block following the + * original data. Level 0 is the "leaf" level: it's directly "above" the data + * blocks and is stored last in the file. + */ +static void compute_tree_layout(u64 data_size, u64 tree_offset, int blockbits, + unsigned int hashes_per_block, + u64 hash_lvl_region_idx[FS_VERITY_MAX_LEVELS], + int *depth_ret, u64 *tree_end_ret) +{ + u64 blocks = data_size >> blockbits; + u64 offset = tree_offset >> blockbits; + int depth = 0; + int i; + + ASSERT(data_size > 0); + ASSERT(data_size % (1 << blockbits) == 0); + ASSERT(tree_offset % (1 << blockbits) == 0); + ASSERT(hashes_per_block >= 2); + + while (blocks > 1) { + ASSERT(depth < FS_VERITY_MAX_LEVELS); + blocks = DIV_ROUND_UP(blocks, hashes_per_block); + hash_lvl_region_idx[depth++] = blocks; + } + for (i = depth - 1; i >= 0; i--) { + u64 next_count = hash_lvl_region_idx[i]; + + hash_lvl_region_idx[i] = offset; + offset += next_count; + } + *depth_ret = depth; + *tree_end_ret = offset << blockbits; +} + +/* + * Build a Merkle tree (hash tree) over the data of a file. + * + * @params: Block size, hashes per block, and salt + * @hash: Handle for the hash algorithm + * @data_file: input data file + * @data_size: size of data file in bytes; must be aligned to ->blocksize + * @tree_file: output tree file + * @tree_offset: byte offset in tree file at which to write the tree; + * must be aligned to ->blocksize + * @tree_end_ret: On success, the byte offset in the tree file of the end of the + * tree is written here + * @root_hash_ret: On success, the Merkle tree root hash is written here + * + * Return: exit status code (0 on success, nonzero on failure) + */ +static int build_merkle_tree(const struct fsveritysetup_params *params, + struct hash_ctx *hash, + struct filedes *data_file, u64 data_size, + struct filedes *tree_file, u64 tree_offset, + u64 *tree_end_ret, u8 *root_hash_ret) +{ + const unsigned int digest_size = hash->alg->digest_size; + int depth; + u64 hash_lvl_region_idx[FS_VERITY_MAX_LEVELS]; + u8 *data_to_hash = NULL; + u8 *pending_hashes = NULL; + unsigned int pending_hash_bytes; + u64 nr_hashes_at_this_lvl; + int lvl; + int status; + + compute_tree_layout(data_size, tree_offset, params->blockbits, + params->hashes_per_block, hash_lvl_region_idx, + &depth, tree_end_ret); + + /* Allocate block buffers */ + data_to_hash = xmalloc(params->blocksize); + pending_hashes = xmalloc(params->blocksize); + pending_hash_bytes = 0; + nr_hashes_at_this_lvl = data_size >> params->blockbits; + + /* + * Generate each level of the Merkle tree, starting at the leaf level + * ('lvl == 0') and ascending to the root node ('lvl == depth - 1'). + * Then at the end ('lvl == depth'), calculate the root node's hash. + */ + for (lvl = 0; lvl <= depth; lvl++) { + u64 i; + + for (i = 0; i < nr_hashes_at_this_lvl; i++) { + struct filedes *file; + u64 blk_idx; + + hash_init(hash); + hash_update(hash, params->salt, params->saltlen); + + if (lvl == 0) { + /* Leaf: hashing a data block */ + file = data_file; + blk_idx = i; + } else { + /* Non-leaf: hashing a hash block */ + file = tree_file; + blk_idx = hash_lvl_region_idx[lvl - 1] + i; + } + if (!full_pread(file, data_to_hash, params->blocksize, + blk_idx << params->blockbits)) + goto out_err; + hash_update(hash, data_to_hash, params->blocksize); + + hash_final(hash, &pending_hashes[pending_hash_bytes]); + pending_hash_bytes += digest_size; + + if (lvl == depth) { + /* Root hash */ + ASSERT(nr_hashes_at_this_lvl == 1); + ASSERT(pending_hash_bytes == digest_size); + memcpy(root_hash_ret, pending_hashes, + digest_size); + status = 0; + goto out; + } + + if (pending_hash_bytes + digest_size > params->blocksize + || i + 1 == nr_hashes_at_this_lvl) { + /* Flush the pending hash block */ + memset(&pending_hashes[pending_hash_bytes], 0, + params->blocksize - pending_hash_bytes); + blk_idx = hash_lvl_region_idx[lvl] + + (i / params->hashes_per_block); + if (!full_pwrite(tree_file, + pending_hashes, + params->blocksize, + blk_idx << params->blockbits)) + goto out_err; + pending_hash_bytes = 0; + } + } + + nr_hashes_at_this_lvl = DIV_ROUND_UP(nr_hashes_at_this_lvl, + params->hashes_per_block); + } + ASSERT(0); /* unreachable; should exit via "Root hash" case above */ +out_err: + status = 1; +out: + free(data_to_hash); + free(pending_hashes); + return status; +} + +/* + * Append to the buffer @*buf_p an extension (variable-length metadata) item of + * type @type, containing the data @ext of length @extlen bytes. + */ +void fsverity_append_extension(void **buf_p, int type, + const void *ext, size_t extlen) +{ + void *buf = *buf_p; + struct fsverity_extension *hdr = buf; + + hdr->type = cpu_to_le16(type); + hdr->length = cpu_to_le32(sizeof(*hdr) + extlen); + hdr->reserved = 0; + buf += sizeof(*hdr); + memcpy(buf, ext, extlen); + buf += extlen; + memset(buf, 0, -extlen & 7); + buf += -extlen & 7; + ASSERT(buf - *buf_p == FSVERITY_EXTLEN(extlen)); + *buf_p = buf; +} + +/* + * Append the authenticated portion of the fs-verity descriptor to 'out', in the + * process updating 'hash' with the data written. + */ +static int append_fsverity_descriptor(const struct fsveritysetup_params *params, + u64 filesize, const u8 *root_hash, + struct filedes *out, + struct hash_ctx *hash) +{ + size_t desc_auth_len; + void *buf; + struct fsverity_descriptor *desc; + u16 auth_ext_count; + int status; + + desc_auth_len = sizeof(*desc); + desc_auth_len += FSVERITY_EXTLEN(params->hash_alg->digest_size); + if (params->saltlen) + desc_auth_len += FSVERITY_EXTLEN(params->saltlen); + desc_auth_len += total_elide_patch_ext_length(params); + desc = buf = xzalloc(desc_auth_len); + + memcpy(desc->magic, FS_VERITY_MAGIC, sizeof(desc->magic)); + desc->major_version = 1; + desc->minor_version = 0; + desc->log_data_blocksize = params->blockbits; + desc->log_tree_blocksize = params->blockbits; + desc->data_algorithm = cpu_to_le16(params->hash_alg - + fsverity_hash_algs); + desc->tree_algorithm = desc->data_algorithm; + desc->orig_file_size = cpu_to_le64(filesize); + + auth_ext_count = 1; /* root hash */ + if (params->saltlen) + auth_ext_count++; + auth_ext_count += params->num_elisions_and_patches; + desc->auth_ext_count = cpu_to_le16(auth_ext_count); + + buf += sizeof(*desc); + fsverity_append_extension(&buf, FS_VERITY_EXT_ROOT_HASH, + root_hash, params->hash_alg->digest_size); + if (params->saltlen) + fsverity_append_extension(&buf, FS_VERITY_EXT_SALT, + params->salt, params->saltlen); + append_elide_patch_exts(&buf, params); + ASSERT(buf - (void *)desc == desc_auth_len); + + hash_update(hash, desc, desc_auth_len); + if (!full_write(out, desc, desc_auth_len)) + goto out_err; + status = 0; +out: + free(desc); + return status; + +out_err: + status = 1; + goto out; +} + +/* + * Append any needed unauthenticated extension items: currently, just possibly a + * PKCS7_SIGNATURE item containing the signed file measurement. + */ +static int +append_unauthenticated_extensions(struct filedes *out, + const struct fsveritysetup_params *params, + const u8 *measurement) +{ + u16 unauth_ext_count = 0; + struct { + __le16 unauth_ext_count; + __le16 pad[3]; + } hdr; + bool have_sig = params->signing_key_file || params->signature_file; + + if (have_sig) + unauth_ext_count++; + + ASSERT(sizeof(hdr) % 8 == 0); + memset(&hdr, 0, sizeof(hdr)); + hdr.unauth_ext_count = cpu_to_le16(unauth_ext_count); + + if (!full_write(out, &hdr, sizeof(hdr))) + return 1; + + if (have_sig) + return append_signed_measurement(out, params, measurement); + + return 0; +} + +static int append_footer(struct filedes *out, u64 desc_offset) +{ + struct fsverity_footer ftr; + u32 offset = (out->pos + sizeof(ftr)) - desc_offset; + + ftr.desc_reverse_offset = cpu_to_le32(offset); + memcpy(ftr.magic, FS_VERITY_MAGIC, sizeof(ftr.magic)); + + if (!full_write(out, &ftr, sizeof(ftr))) + return 1; + return 0; +} + +static int fsveritysetup(const char *infile, const char *outfile, + const struct fsveritysetup_params *params) +{ + struct filedes _in = { .fd = -1 }; + struct filedes _out = { .fd = -1 }; + struct filedes _tmp = { .fd = -1 }; + struct hash_ctx *hash = NULL; + struct filedes *in = &_in, *out = &_out, *src; + u64 filesize; + u64 aligned_filesize; + u64 src_filesize; + u64 tree_end_offset; + u8 root_hash[FS_VERITY_MAX_DIGEST_SIZE]; + u8 measurement[FS_VERITY_MAX_DIGEST_SIZE]; + char hash_hex[FS_VERITY_MAX_DIGEST_SIZE * 2 + 1]; + int status; + + if (!open_file(in, infile, (infile == outfile ? O_RDWR : O_RDONLY), 0)) + goto out_err; + + if (!get_file_size(in, &filesize)) + goto out_err; + + if (filesize <= 0) { + error_msg("input file is empty: '%s'", infile); + goto out_err; + } + + if (infile == outfile) { + /* + * Invoked with one file argument: we're appending verity + * metadata to an existing file. + */ + out = in; + if (!filedes_seek(out, filesize, SEEK_SET)) + goto out_err; + } else { + /* + * Invoked with two file arguments: we're copying the first file + * to the second file, then appending verity metadata to it. + */ + if (!open_file(out, outfile, O_RDWR|O_CREAT|O_TRUNC, 0644)) + goto out_err; + if (!copy_file_data(in, out, filesize)) + goto out_err; + } + + /* Zero-pad the output file to the next block boundary */ + aligned_filesize = ALIGN(filesize, params->blocksize); + if (!write_zeroes(out, aligned_filesize - filesize)) + goto out_err; + + if (params->num_elisions_and_patches) { + /* Merkle tree is built over temporary elided/patched file */ + src = &_tmp; + if (!apply_elisions_and_patches(params, in, filesize, + src, &src_filesize)) + goto out_err; + } else { + /* Merkle tree is built over original file */ + src = out; + src_filesize = aligned_filesize; + } + + hash = hash_create(params->hash_alg); + + /* Build the file's Merkle tree and calculate its root hash */ + status = build_merkle_tree(params, hash, src, src_filesize, + out, aligned_filesize, + &tree_end_offset, root_hash); + if (status) + goto out; + if (!filedes_seek(out, tree_end_offset, SEEK_SET)) + goto out_err; + + /* Append the additional needed metadata */ + + hash_init(hash); + status = append_fsverity_descriptor(params, filesize, root_hash, + out, hash); + if (status) + goto out; + hash_final(hash, measurement); + + status = append_unauthenticated_extensions(out, params, measurement); + if (status) + goto out; + + status = append_footer(out, tree_end_offset); + if (status) + goto out; + + bin2hex(measurement, params->hash_alg->digest_size, hash_hex); + printf("File measurement: %s:%s\n", params->hash_alg->name, hash_hex); + status = 0; +out: + hash_free(hash); + if (status != 0 && out->fd >= 0) { + /* Error occurred; undo what we wrote */ + if (in == out) + (void)ftruncate(out->fd, filesize); + else + out->autodelete = true; + } + filedes_close(&_in); + filedes_close(&_tmp); + if (!filedes_close(&_out) && status == 0) + status = 1; + return status; + +out_err: + status = 1; + goto out; +} + +int fsverity_cmd_setup(const struct fsverity_command *cmd, + int argc, char *argv[]) +{ + struct fsveritysetup_params params = { + .hash_alg = DEFAULT_HASH_ALG, + }; + STRING_LIST(elide_opts); + STRING_LIST(patch_opts); + int c; + int status; + + while ((c = getopt_long(argc, argv, "", longopts, NULL)) != -1) { + switch (c) { + case OPT_HASH: + params.hash_alg = find_hash_alg_by_name(optarg); + if (!params.hash_alg) + goto out_usage; + break; + case OPT_SALT: + if (params.salt) { + error_msg("--salt can only be specified once"); + goto out_usage; + } + params.saltlen = strlen(optarg) / 2; + params.salt = xmalloc(params.saltlen); + if (!hex2bin(optarg, params.salt, params.saltlen)) { + error_msg("salt is not a valid hex string"); + goto out_usage; + } + break; + case OPT_BLOCKSIZE: + if (!parse_blocksize_option(optarg, ¶ms.blocksize)) + goto out_usage; + break; + case OPT_SIGNING_KEY: + params.signing_key_file = optarg; + break; + case OPT_SIGNING_CERT: + params.signing_cert_file = optarg; + break; + case OPT_SIGNATURE: + params.signature_file = optarg; + break; + case OPT_ELIDE: + string_list_append(&elide_opts, optarg); + break; + case OPT_PATCH: + string_list_append(&patch_opts, optarg); + break; + default: + goto out_usage; + } + } + + argv += optind; + argc -= optind; + + if (argc != 1 && argc != 2) + goto out_usage; + + ASSERT(params.hash_alg->digest_size <= FS_VERITY_MAX_DIGEST_SIZE); + + if (params.blocksize == 0) { + params.blocksize = sysconf(_SC_PAGESIZE); + if (params.blocksize <= 0 || !is_power_of_2(params.blocksize)) { + fprintf(stderr, + "Warning: invalid _SC_PAGESIZE (%d). Assuming 4K blocks.\n", + params.blocksize); + params.blocksize = 4096; + } + } + params.blockbits = ilog2(params.blocksize); + + params.hashes_per_block = params.blocksize / + params.hash_alg->digest_size; + if (params.hashes_per_block < 2) { + error_msg("block size of %d bytes is too small for %s hash", + params.blocksize, params.hash_alg->name); + goto out_err; + } + + if (params.signing_cert_file && !params.signing_key_file) { + error_msg("--signing-cert was given, but --signing-key was not.\n" +" You must provide the certificate's private key file using --signing-key."); + goto out_err; + } + + if ((params.signing_key_file || params.signature_file) && + !params.hash_alg->cryptographic) { + error_msg("Signing a file using '%s' checksums does not make sense\n" + " because '%s' is not a cryptographically secure hash algorithm.", + params.hash_alg->name, params.hash_alg->name); + goto out_err; + } + + if (!load_elisions_and_patches(&elide_opts, &patch_opts, ¶ms)) + goto out_err; + + status = fsveritysetup(argv[0], argv[argc - 1], ¶ms); +out: + free(params.salt); + free_elisions_and_patches(¶ms); + string_list_destroy(&elide_opts); + string_list_destroy(&patch_opts); + return status; + +out_err: + status = 1; + goto out; + +out_usage: + usage(cmd, stderr); + status = 2; + goto out; +} diff --git a/commands.h b/commands.h new file mode 100644 index 0000000..cc87368 --- /dev/null +++ b/commands.h @@ -0,0 +1,20 @@ +/* SPDX-License-Identifier: GPL-2.0+ */ +#ifndef COMMANDS_H +#define COMMANDS_H + +#include <stdio.h> + +#include "util.h" + +struct fsverity_command; + +void usage(const struct fsverity_command *cmd, FILE *fp); + +int fsverity_cmd_enable(const struct fsverity_command *cmd, + int argc, char *argv[]); +int fsverity_cmd_setup(const struct fsverity_command *cmd, + int argc, char *argv[]); +int fsverity_cmd_measure(const struct fsverity_command *cmd, + int argc, char *argv[]); + +#endif /* COMMANDS_H */ diff --git a/crc32c_table.h b/crc32c_table.h new file mode 100644 index 0000000..4c3dafb --- /dev/null +++ b/crc32c_table.h @@ -0,0 +1,72 @@ +/* + * crc32c_table.h - data table to accelerate CRC-32C computation + * + * This file was automatically generated by scripts/gen_crc32c_table.c + */ + +static const u32 crc32c_table[] = { + 0x00000000, 0xf26b8303, 0xe13b70f7, 0x1350f3f4, + 0xc79a971f, 0x35f1141c, 0x26a1e7e8, 0xd4ca64eb, + 0x8ad958cf, 0x78b2dbcc, 0x6be22838, 0x9989ab3b, + 0x4d43cfd0, 0xbf284cd3, 0xac78bf27, 0x5e133c24, + 0x105ec76f, 0xe235446c, 0xf165b798, 0x030e349b, + 0xd7c45070, 0x25afd373, 0x36ff2087, 0xc494a384, + 0x9a879fa0, 0x68ec1ca3, 0x7bbcef57, 0x89d76c54, + 0x5d1d08bf, 0xaf768bbc, 0xbc267848, 0x4e4dfb4b, + 0x20bd8ede, 0xd2d60ddd, 0xc186fe29, 0x33ed7d2a, + 0xe72719c1, 0x154c9ac2, 0x061c6936, 0xf477ea35, + 0xaa64d611, 0x580f5512, 0x4b5fa6e6, 0xb93425e5, + 0x6dfe410e, 0x9f95c20d, 0x8cc531f9, 0x7eaeb2fa, + 0x30e349b1, 0xc288cab2, 0xd1d83946, 0x23b3ba45, + 0xf779deae, 0x05125dad, 0x1642ae59, 0xe4292d5a, + 0xba3a117e, 0x4851927d, 0x5b016189, 0xa96ae28a, + 0x7da08661, 0x8fcb0562, 0x9c9bf696, 0x6ef07595, + 0x417b1dbc, 0xb3109ebf, 0xa0406d4b, 0x522bee48, + 0x86e18aa3, 0x748a09a0, 0x67dafa54, 0x95b17957, + 0xcba24573, 0x39c9c670, 0x2a993584, 0xd8f2b687, + 0x0c38d26c, 0xfe53516f, 0xed03a29b, 0x1f682198, + 0x5125dad3, 0xa34e59d0, 0xb01eaa24, 0x42752927, + 0x96bf4dcc, 0x64d4cecf, 0x77843d3b, 0x85efbe38, + 0xdbfc821c, 0x2997011f, 0x3ac7f2eb, 0xc8ac71e8, + 0x1c661503, 0xee0d9600, 0xfd5d65f4, 0x0f36e6f7, + 0x61c69362, 0x93ad1061, 0x80fde395, 0x72966096, + 0xa65c047d, 0x5437877e, 0x4767748a, 0xb50cf789, + 0xeb1fcbad, 0x197448ae, 0x0a24bb5a, 0xf84f3859, + 0x2c855cb2, 0xdeeedfb1, 0xcdbe2c45, 0x3fd5af46, + 0x7198540d, 0x83f3d70e, 0x90a324fa, 0x62c8a7f9, + 0xb602c312, 0x44694011, 0x5739b3e5, 0xa55230e6, + 0xfb410cc2, 0x092a8fc1, 0x1a7a7c35, 0xe811ff36, + 0x3cdb9bdd, 0xceb018de, 0xdde0eb2a, 0x2f8b6829, + 0x82f63b78, 0x709db87b, 0x63cd4b8f, 0x91a6c88c, + 0x456cac67, 0xb7072f64, 0xa457dc90, 0x563c5f93, + 0x082f63b7, 0xfa44e0b4, 0xe9141340, 0x1b7f9043, + 0xcfb5f4a8, 0x3dde77ab, 0x2e8e845f, 0xdce5075c, + 0x92a8fc17, 0x60c37f14, 0x73938ce0, 0x81f80fe3, + 0x55326b08, 0xa759e80b, 0xb4091bff, 0x466298fc, + 0x1871a4d8, 0xea1a27db, 0xf94ad42f, 0x0b21572c, + 0xdfeb33c7, 0x2d80b0c4, 0x3ed04330, 0xccbbc033, + 0xa24bb5a6, 0x502036a5, 0x4370c551, 0xb11b4652, + 0x65d122b9, 0x97baa1ba, 0x84ea524e, 0x7681d14d, + 0x2892ed69, 0xdaf96e6a, 0xc9a99d9e, 0x3bc21e9d, + 0xef087a76, 0x1d63f975, 0x0e330a81, 0xfc588982, + 0xb21572c9, 0x407ef1ca, 0x532e023e, 0xa145813d, + 0x758fe5d6, 0x87e466d5, 0x94b49521, 0x66df1622, + 0x38cc2a06, 0xcaa7a905, 0xd9f75af1, 0x2b9cd9f2, + 0xff56bd19, 0x0d3d3e1a, 0x1e6dcdee, 0xec064eed, + 0xc38d26c4, 0x31e6a5c7, 0x22b65633, 0xd0ddd530, + 0x0417b1db, 0xf67c32d8, 0xe52cc12c, 0x1747422f, + 0x49547e0b, 0xbb3ffd08, 0xa86f0efc, 0x5a048dff, + 0x8ecee914, 0x7ca56a17, 0x6ff599e3, 0x9d9e1ae0, + 0xd3d3e1ab, 0x21b862a8, 0x32e8915c, 0xc083125f, + 0x144976b4, 0xe622f5b7, 0xf5720643, 0x07198540, + 0x590ab964, 0xab613a67, 0xb831c993, 0x4a5a4a90, + 0x9e902e7b, 0x6cfbad78, 0x7fab5e8c, 0x8dc0dd8f, + 0xe330a81a, 0x115b2b19, 0x020bd8ed, 0xf0605bee, + 0x24aa3f05, 0xd6c1bc06, 0xc5914ff2, 0x37faccf1, + 0x69e9f0d5, 0x9b8273d6, 0x88d28022, 0x7ab90321, + 0xae7367ca, 0x5c18e4c9, 0x4f48173d, 0xbd23943e, + 0xf36e6f75, 0x0105ec76, 0x12551f82, 0xe03e9c81, + 0x34f4f86a, 0xc69f7b69, 0xd5cf889d, 0x27a40b9e, + 0x79b737ba, 0x8bdcb4b9, 0x988c474d, 0x6ae7c44e, + 0xbe2da0a5, 0x4c4623a6, 0x5f16d052, 0xad7d5351, +}; diff --git a/debian/changelog b/debian/changelog new file mode 100644 index 0000000..a2e894d --- /dev/null +++ b/debian/changelog @@ -0,0 +1,5 @@ +fsverity-utils (0.1-1) experimental; urgency=low + + * Experimental: debian package for xfstests test appliances + + -- Eric Biggers <ebiggers@google.com> Mon, 02 Apr 2018 10:18:21 -0700 diff --git a/debian/compat b/debian/compat new file mode 100644 index 0000000..f599e28 --- /dev/null +++ b/debian/compat @@ -0,0 +1 @@ +10 diff --git a/debian/control b/debian/control new file mode 100644 index 0000000..aaa4ac3 --- /dev/null +++ b/debian/control @@ -0,0 +1,14 @@ +Source: fsverity-utils +Priority: optional +Maintainer: Eric Biggers <ebiggers@google.com> +Build-Depends: debhelper (>= 10), libssl-dev (>= 1.0.0) +Standards-Version: 4.0.0 +Vcs-Git: git://git.kernel.org/pub/scm/linux/kernel/git/mhalcrow/fsverity + +Package: fsverity-utils +Section: utils +Architecture: any +Depends: ${shlibs:Depends}, ${misc:Depends} +Description: fs-verity userspace utility. This program allows you to set up + read-only, integrity and/or authenticity-protected files when supported by the + underlying filesystem. diff --git a/debian/copyright b/debian/copyright new file mode 100644 index 0000000..a728656 --- /dev/null +++ b/debian/copyright @@ -0,0 +1,7 @@ +Format: http://dep.debian.net/deps/dep5 +Upstream-Name: fsverity +Source: git://git.kernel.org/pub/scm/linux/kernel/git/mhalcrow/fsverity + +Files: * +Copyright: 2018 Google LLC +License: GPL-2+ diff --git a/debian/rules b/debian/rules new file mode 100755 index 0000000..9b694a1 --- /dev/null +++ b/debian/rules @@ -0,0 +1,8 @@ +#!/usr/bin/make -f + +export DH_VERBOSE=1 + +include /usr/share/dpkg/default.mk + +%: + dh $@ diff --git a/elide_patch.c b/elide_patch.c new file mode 100644 index 0000000..3eed416 --- /dev/null +++ b/elide_patch.c @@ -0,0 +1,307 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * Elide and patch handling for 'fsverity setup' + * + * Copyright (C) 2018 Google LLC + * + * Written by Eric Biggers. + */ + +#include <errno.h> +#include <fcntl.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "fsverity_uapi.h" +#include "fsveritysetup.h" + +/* An elision or a patch */ +struct fsverity_elide_patch { + u64 offset; /* byte offset within the original data */ + u64 length; /* length in bytes */ + bool patch; /* false if elision, true if patch */ + u8 data[]; /* replacement data (if patch=true) */ +}; + +/* Maximum supported patch size, in bytes */ +#define FS_VERITY_MAX_PATCH_SIZE 255 + +/* Parse an --elide=OFFSET,LENGTH option */ +static struct fsverity_elide_patch *parse_elide_option(const char *optarg) +{ + struct fsverity_elide_patch *ext = NULL; + char *sep, *end; + unsigned long long offset; + unsigned long long length; + + sep = strchr(optarg, ','); + if (!sep || sep == optarg) + goto invalid; + errno = 0; + *sep = '\0'; + offset = strtoull(optarg, &end, 10); + *sep = ','; + if (errno || end != sep) + goto invalid; + length = strtoull(sep + 1, &end, 10); + if (errno || *end) + goto invalid; + if (length <= 0 || length > UINT64_MAX - offset) { + error_msg("Invalid length in '--elide=%s'", optarg); + return NULL; + } + ext = xzalloc(sizeof(*ext)); + ext->offset = offset; + ext->length = length; + ext->patch = false; + return ext; + +invalid: + error_msg("Invalid --elide option: '%s'. Must be formatted as OFFSET,LENGTH", + optarg); + return NULL; +} + +/* Parse a --patch=OFFSET,PATCHFILE option */ +static struct fsverity_elide_patch *parse_patch_option(const char *optarg) +{ + struct fsverity_elide_patch *ext = NULL; + struct filedes patchfile = { .fd = -1 }; + char *sep, *end; + unsigned long long offset; + u64 length; + + sep = strchr(optarg, ','); + if (!sep || sep == optarg) + goto invalid; + errno = 0; + *sep = '\0'; + offset = strtoull(optarg, &end, 10); + *sep = ','; + if (errno || end != sep) + goto invalid; + if (!open_file(&patchfile, sep + 1, O_RDONLY, 0)) + goto out; + if (!get_file_size(&patchfile, &length)) + goto out; + if (length <= 0) { + error_msg("patch file '%s' is empty", patchfile.name); + goto out; + } + if (length > FS_VERITY_MAX_PATCH_SIZE) { + error_msg("Patch file '%s' is too long. Max patch size is %d bytes.", + patchfile.name, FS_VERITY_MAX_PATCH_SIZE); + goto out; + } + ext = xzalloc(sizeof(*ext) + length); + ext->offset = offset; + ext->length = length; + ext->patch = true; + if (!full_read(&patchfile, ext->data, length)) { + free(ext); + ext = NULL; + } +out: + filedes_close(&patchfile); + return ext; + +invalid: + error_msg("Invalid --patch option: '%s'. Must be formatted as OFFSET,PATCHFILE", + optarg); + goto out; +} + +/* Sort by increasing offset */ +static int cmp_elide_patch_exts(const void *_p1, const void *_p2) +{ + const struct fsverity_elide_patch *ext1, *ext2; + + ext1 = *(const struct fsverity_elide_patch **)_p1; + ext2 = *(const struct fsverity_elide_patch **)_p2; + + if (ext1->offset > ext2->offset) + return 1; + if (ext1->offset < ext2->offset) + return -1; + return 0; +} + +/* + * Given the lists of --elide and --patch options, validate and load the + * elisions and patches into @params. + */ +bool load_elisions_and_patches(const struct string_list *elide_opts, + const struct string_list *patch_opts, + struct fsveritysetup_params *params) +{ + const size_t num_exts = elide_opts->length + patch_opts->length; + struct fsverity_elide_patch **exts; + size_t i, j; + + if (num_exts == 0) /* Normal case: no elisions or patches */ + return true; + params->num_elisions_and_patches = num_exts; + exts = xzalloc(num_exts * sizeof(exts[0])); + params->elisions_and_patches = exts; + j = 0; + + /* Parse the --elide options */ + for (i = 0; i < elide_opts->length; i++) { + exts[j] = parse_elide_option(elide_opts->strings[i]); + if (!exts[j++]) + return false; + } + + /* Parse the --patch options */ + for (i = 0; i < patch_opts->length; i++) { + exts[j] = parse_patch_option(patch_opts->strings[i]); + if (!exts[j++]) + return false; + } + + /* Sort the elisions and patches by increasing offset */ + qsort(exts, num_exts, sizeof(exts[0]), cmp_elide_patch_exts); + + /* Verify that no elisions or patches overlap */ + for (j = 1; j < num_exts; j++) { + if (exts[j]->offset < + exts[j - 1]->offset + exts[j - 1]->length) { + error_msg("%s at [%"PRIu64", %"PRIu64") overlaps " + "%s at [%"PRIu64", %"PRIu64")", + exts[j - 1]->patch ? "Patch" : "Elision", + exts[j - 1]->offset, + exts[j - 1]->offset + exts[j - 1]->length, + exts[j]->patch ? "patch" : "elision", + exts[j]->offset, + exts[j]->offset + exts[j]->length); + return false; + } + } + return true; +} + +void free_elisions_and_patches(struct fsveritysetup_params *params) +{ + size_t i; + + for (i = 0; i < params->num_elisions_and_patches; i++) + free(params->elisions_and_patches[i]); + free(params->elisions_and_patches); +} + +/* + * Given the original file @in of length @in_length bytes, create a temporary + * file @out_ret and write to it the data with the elisions and patches applied, + * with the end zero-padded to the next block boundary. Returns in + * @out_length_ret the length of the elided/patched file in bytes. + */ +bool apply_elisions_and_patches(const struct fsveritysetup_params *params, + struct filedes *in, u64 in_length, + struct filedes *out_ret, u64 *out_length_ret) +{ + struct fsverity_elide_patch **exts = params->elisions_and_patches; + struct filedes *out = out_ret; + size_t i; + + for (i = 0; i < params->num_elisions_and_patches; i++) { + if (exts[i]->offset + exts[i]->length > in_length) { + error_msg("%s at [%"PRIu64", %"PRIu64") extends beyond end of input file", + exts[i]->patch ? "Patch" : "Elision", + exts[i]->offset, + exts[i]->offset + exts[i]->length); + return false; + } + } + + if (!filedes_seek(in, 0, SEEK_SET)) + return false; + + if (!open_tempfile(out)) + return false; + + for (i = 0; i < params->num_elisions_and_patches; i++) { + printf("Applying %s: offset=%"PRIu64", length=%"PRIu64"\n", + exts[i]->patch ? "patch" : "elision", + exts[i]->offset, exts[i]->length); + + if (!copy_file_data(in, out, exts[i]->offset - in->pos)) + return false; + + if (exts[i]->patch && + !full_write(out, exts[i]->data, exts[i]->length)) + return false; + + if (!filedes_seek(in, exts[i]->length, SEEK_CUR)) + return false; + } + if (!copy_file_data(in, out, in_length - in->pos)) + return false; + if (!write_zeroes(out, ALIGN(out->pos, params->blocksize) - out->pos)) + return false; + *out_length_ret = out->pos; + return true; +} + +/* Calculate the size the elisions and patches will take up when serialized */ +size_t total_elide_patch_ext_length(const struct fsveritysetup_params *params) +{ + size_t total = 0; + size_t i; + + for (i = 0; i < params->num_elisions_and_patches; i++) { + const struct fsverity_elide_patch *ext = + params->elisions_and_patches[i]; + size_t inner_len; + + if (ext->patch) { + inner_len = sizeof(struct fsverity_extension_patch) + + ext->length; + } else { + inner_len = sizeof(struct fsverity_extension_elide); + } + total += FSVERITY_EXTLEN(inner_len); + } + return total; +} + +/* + * Append the elide and patch extensions (if any) to the given buffer. + * The buffer must have enough space; call total_elide_patch_ext_length() first. + */ +void append_elide_patch_exts(void **buf_p, + const struct fsveritysetup_params *params) +{ + void *buf = *buf_p; + size_t i; + union { + struct { + struct fsverity_extension_patch hdr; + u8 data[FS_VERITY_MAX_PATCH_SIZE]; + } patch; + struct fsverity_extension_elide elide; + } u; + + for (i = 0; i < params->num_elisions_and_patches; i++) { + const struct fsverity_elide_patch *ext = + params->elisions_and_patches[i]; + int type; + size_t extlen; + + if (ext->patch) { + type = FS_VERITY_EXT_PATCH; + u.patch.hdr.offset = cpu_to_le64(ext->offset); + ASSERT(ext->length <= sizeof(u.patch.data)); + memcpy(u.patch.data, ext->data, ext->length); + extlen = sizeof(u.patch.hdr) + ext->length; + } else { + type = FS_VERITY_EXT_ELIDE; + u.elide.offset = cpu_to_le64(ext->offset), + u.elide.length = cpu_to_le64(ext->length); + extlen = sizeof(u.elide); + } + fsverity_append_extension(&buf, type, &u, extlen); + } + + *buf_p = buf; +} diff --git a/fsverity.c b/fsverity.c new file mode 100644 index 0000000..a463c7f --- /dev/null +++ b/fsverity.c @@ -0,0 +1,148 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * fs-verity userspace tool + * + * Copyright (C) 2018 Google LLC + * + * Written by Eric Biggers. + */ + +#include <stdlib.h> +#include <string.h> + +#include "commands.h" +#include "hash_algs.h" + +static const struct fsverity_command { + const char *name; + int (*func)(const struct fsverity_command *cmd, int argc, char *argv[]); + const char *short_desc; + const char *usage_str; +} fsverity_commands[] = { + { + .name = "enable", + .func = fsverity_cmd_enable, + .short_desc = +"Enable fs-verity on a file with verity metadata", + .usage_str = +" fsverity enable FILE\n" + }, { + .name = "measure", + .func = fsverity_cmd_measure, + .short_desc = +"Display the measurement of the given fs-verity file(s)", + .usage_str = +" fsverity measure FILE...\n" + }, { + .name = "setup", + .func = fsverity_cmd_setup, + .short_desc = "Create the verity metadata for a file", + .usage_str = +" fsverity setup INFILE [OUTFILE]\n" +" [--hash=HASH_ALG] [--salt=SALT] [--signing-key=KEYFILE]\n" +" [--signing-cert=CERTFILE] [--signature=SIGFILE]\n" +" [--patch=OFFSET,PATCHFILE] [--elide=OFFSET,LENGTH]\n" + } +}; + +static void usage_all(FILE *fp) +{ + int i; + + fputs("Usage:\n", fp); + for (i = 0; i < ARRAY_SIZE(fsverity_commands); i++) + fprintf(fp, " %s:\n%s\n", fsverity_commands[i].short_desc, + fsverity_commands[i].usage_str); + fputs( +" Standard options:\n" +" fsverity --help\n" +" fsverity --version\n" +"\n" +"Available hash algorithms: ", fp); + show_all_hash_algs(fp); + fputs("\nSee `man fsverity` for more details.\n", fp); +} + +static void usage_cmd(const struct fsverity_command *cmd, FILE *fp) +{ + fprintf(fp, "Usage:\n%s", cmd->usage_str); +} + +void usage(const struct fsverity_command *cmd, FILE *fp) +{ + if (cmd) + usage_cmd(cmd, fp); + else + usage_all(fp); +} + +#define PACKAGE_VERSION "v0.0-alpha" +#define PACKAGE_BUGREPORT "linux-fscrypt@vger.kernel.org" + +static void show_version(void) +{ + static const char * const str = +"fsverity " PACKAGE_VERSION "\n" +"Copyright (C) 2018 Google LLC\n" +"License GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl.html>.\n" +"This is free software: you are free to change and redistribute it.\n" +"There is NO WARRANTY, to the extent permitted by law.\n" +"\n" +"Report bugs to " PACKAGE_BUGREPORT ".\n"; + fputs(str, stdout); +} + +static void handle_common_options(int argc, char *argv[], + const struct fsverity_command *cmd) +{ + int i; + + for (i = 1; i < argc; i++) { + const char *arg = argv[i]; + + if (*arg++ != '-') + continue; + if (*arg++ != '-') + continue; + if (!strcmp(arg, "help")) { + usage(cmd, stdout); + exit(0); + } else if (!strcmp(arg, "version")) { + show_version(); + exit(0); + } else if (!*arg) /* reached "--", no more options */ + return; + } +} + +static const struct fsverity_command *find_command(const char *name) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(fsverity_commands); i++) + if (!strcmp(name, fsverity_commands[i].name)) + return &fsverity_commands[i]; + return NULL; +} + +int main(int argc, char *argv[]) +{ + const struct fsverity_command *cmd; + + if (argc < 2) { + error_msg("no command specified"); + usage_all(stderr); + return 2; + } + + cmd = find_command(argv[1]); + + handle_common_options(argc, argv, cmd); + + if (!cmd) { + error_msg("unrecognized command: '%s'", argv[1]); + usage_all(stderr); + return 2; + } + return cmd->func(cmd, argc - 1, argv + 1); +} diff --git a/fsverity_uapi.h b/fsverity_uapi.h new file mode 100644 index 0000000..00c64f9 --- /dev/null +++ b/fsverity_uapi.h @@ -0,0 +1,112 @@ +/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ +/* + * fs-verity (file-based verity) support + * + * Copyright (C) 2018 Google LLC + */ +#ifndef _UAPI_LINUX_FSVERITY_H +#define _UAPI_LINUX_FSVERITY_H + +#include <linux/limits.h> +#include <linux/ioctl.h> +#include <linux/types.h> + +/* ========== Ioctls ========== */ + +struct fsverity_digest { + __u16 digest_algorithm; + __u16 digest_size; /* input/output */ + __u8 digest[]; +}; + +#define FS_IOC_ENABLE_VERITY _IO('f', 133) +#define FS_IOC_MEASURE_VERITY _IOWR('f', 134, struct fsverity_digest) + +/* ========== On-disk format ========== */ + +#define FS_VERITY_MAGIC "FSVerity" + +/* Supported hash algorithms */ +#define FS_VERITY_ALG_SHA256 1 +#define FS_VERITY_ALG_SHA512 2 +#define FS_VERITY_ALG_CRC32C 3 /* for integrity only */ + +/* Metadata stored near the end of fs-verity files, after the Merkle tree */ +/* This structure is 64 bytes long */ +struct fsverity_descriptor { + __u8 magic[8]; /* must be FS_VERITY_MAGIC */ + __u8 major_version; /* must be 1 */ + __u8 minor_version; /* must be 0 */ + __u8 log_data_blocksize;/* log2(data-bytes-per-hash), e.g. 12 for 4KB */ + __u8 log_tree_blocksize;/* log2(tree-bytes-per-hash), e.g. 12 for 4KB */ + __le16 data_algorithm; /* hash algorithm for data blocks */ + __le16 tree_algorithm; /* hash algorithm for tree blocks */ + __le32 flags; /* flags */ + __le32 reserved1; /* must be 0 */ + __le64 orig_file_size; /* size of the original, unpadded data */ + __le16 auth_ext_count; /* number of authenticated extensions */ + __u8 reserved2[30]; /* must be 0 */ +}; +/* followed by list of 'auth_ext_count' authenticated extensions */ +/* + * then followed by '__le16 unauth_ext_count' padded to next 8-byte boundary, + * then a list of 'unauth_ext_count' (may be 0) unauthenticated extensions + */ + +/* Extension types */ +#define FS_VERITY_EXT_ROOT_HASH 1 +#define FS_VERITY_EXT_SALT 2 +#define FS_VERITY_EXT_PKCS7_SIGNATURE 3 +#define FS_VERITY_EXT_ELIDE 4 +#define FS_VERITY_EXT_PATCH 5 + +/* Header of each extension (variable-length metadata item) */ +struct fsverity_extension { + /* + * Length in bytes, including this header but excluding padding to next + * 8-byte boundary that is applied when advancing to the next extension. + */ + __le32 length; + __le16 type; /* Type of this extension (see codes above) */ + __le16 reserved; /* Reserved, must be 0 */ +}; +/* followed by the payload of 'length - 8' bytes */ + +/* Extension payload formats */ + +/* + * FS_VERITY_EXT_ROOT_HASH payload is just a byte array, with size equal to the + * digest size of the hash algorithm given in the fsverity_descriptor + */ + +/* FS_VERITY_EXT_SALT payload is just a byte array, any size */ + +/* + * FS_VERITY_EXT_PKCS7_SIGNATURE payload is a DER-encoded PKCS#7 message + * containing the signed file measurement in the following format: + */ +struct fsverity_digest_disk { + __le16 digest_algorithm; + __le16 digest_size; + __u8 digest[]; +}; + +/* FS_VERITY_EXT_ELIDE payload */ +struct fsverity_extension_elide { + __le64 offset; + __le64 length; +}; + +/* FS_VERITY_EXT_PATCH payload */ +struct fsverity_extension_patch { + __le64 offset; + /* followed by variable-length patch data */ +}; + +/* Fields stored at the very end of the file */ +struct fsverity_footer { + __le32 desc_reverse_offset; /* distance to fsverity_descriptor */ + __u8 magic[8]; /* FS_VERITY_MAGIC */ +} __attribute__((packed)); + +#endif /* _UAPI_LINUX_FSVERITY_H */ diff --git a/fsveritysetup.h b/fsveritysetup.h new file mode 100644 index 0000000..282aabd --- /dev/null +++ b/fsveritysetup.h @@ -0,0 +1,43 @@ +/* SPDX-License-Identifier: GPL-2.0+ */ +#ifndef FSVERITYSETUP_H +#define FSVERITYSETUP_H + +#include "util.h" + +struct fsveritysetup_params { + const struct fsverity_hash_alg *hash_alg; + u8 *salt; + size_t saltlen; + int blocksize; + int blockbits; /* ilog2(blocksize) */ + unsigned int hashes_per_block; /* blocksize / digest_size */ + const char *signing_key_file; + const char *signing_cert_file; + const char *signature_file; + struct fsverity_elide_patch **elisions_and_patches; + size_t num_elisions_and_patches; +}; + +void fsverity_append_extension(void **buf_p, int type, + const void *ext, size_t extlen); + +#define FSVERITY_EXTLEN(inner_len) \ + ALIGN(sizeof(struct fsverity_extension) + (inner_len), 8) + +/* elide_patch.c */ +bool load_elisions_and_patches(const struct string_list *elide_opts, + const struct string_list *patch_opts, + struct fsveritysetup_params *params); +void free_elisions_and_patches(struct fsveritysetup_params *params); +bool apply_elisions_and_patches(const struct fsveritysetup_params *params, + struct filedes *in, u64 in_length, + struct filedes *out_ret, u64 *out_length_ret); +size_t total_elide_patch_ext_length(const struct fsveritysetup_params *params); +void append_elide_patch_exts(void **buf_p, + const struct fsveritysetup_params *params); +/* sign.c */ +int append_signed_measurement(struct filedes *out, + const struct fsveritysetup_params *params, + const u8 *measurement); + +#endif /* FSVERITYSETUP_H */ diff --git a/hash_algs.c b/hash_algs.c new file mode 100644 index 0000000..1e46924 --- /dev/null +++ b/hash_algs.c @@ -0,0 +1,218 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * fs-verity hash algorithms + * + * Copyright (C) 2018 Google LLC + * + * Written by Eric Biggers. + */ + +#include <openssl/evp.h> +#include <stdlib.h> +#include <string.h> + +#include "fsverity_uapi.h" +#include "hash_algs.h" + +static void free_hash_ctx(struct hash_ctx *ctx) +{ + free(ctx); +} + +/* ========== libcrypto (OpenSSL) wrappers ========== */ + +struct openssl_hash_ctx { + struct hash_ctx base; /* must be first */ + EVP_MD_CTX *md_ctx; + const EVP_MD *md; +}; + +static void openssl_digest_init(struct hash_ctx *_ctx) +{ + struct openssl_hash_ctx *ctx = (void *)_ctx; + + if (EVP_DigestInit_ex(ctx->md_ctx, ctx->md, NULL) != 1) + fatal_error("EVP_DigestInit_ex() failed for algorithm '%s'", + ctx->base.alg->name); +} + +static void openssl_digest_update(struct hash_ctx *_ctx, + const void *data, size_t size) +{ + struct openssl_hash_ctx *ctx = (void *)_ctx; + + if (EVP_DigestUpdate(ctx->md_ctx, data, size) != 1) + fatal_error("EVP_DigestUpdate() failed for algorithm '%s'", + ctx->base.alg->name); +} + +static void openssl_digest_final(struct hash_ctx *_ctx, u8 *digest) +{ + struct openssl_hash_ctx *ctx = (void *)_ctx; + + if (EVP_DigestFinal_ex(ctx->md_ctx, digest, NULL) != 1) + fatal_error("EVP_DigestFinal_ex() failed for algorithm '%s'", + ctx->base.alg->name); +} + +static void openssl_digest_ctx_free(struct hash_ctx *_ctx) +{ + struct openssl_hash_ctx *ctx = (void *)_ctx; + + /* + * OpenSSL 1.1.0 renamed EVP_MD_CTX_destroy() to EVP_MD_CTX_free() but + * kept the old name as a macro. Use the old name for compatibility + * with older OpenSSL versions. + */ + EVP_MD_CTX_destroy(ctx->md_ctx); + free(ctx); +} + +static struct hash_ctx * +openssl_digest_ctx_create(const struct fsverity_hash_alg *alg, const EVP_MD *md) +{ + struct openssl_hash_ctx *ctx; + + ctx = xzalloc(sizeof(*ctx)); + ctx->base.alg = alg; + ctx->base.init = openssl_digest_init; + ctx->base.update = openssl_digest_update; + ctx->base.final = openssl_digest_final; + ctx->base.free = openssl_digest_ctx_free; + /* + * OpenSSL 1.1.0 renamed EVP_MD_CTX_create() to EVP_MD_CTX_new() but + * kept the old name as a macro. Use the old name for compatibility + * with older OpenSSL versions. + */ + ctx->md_ctx = EVP_MD_CTX_create(); + if (!ctx->md_ctx) + fatal_error("out of memory"); + + ctx->md = md; + ASSERT(EVP_MD_size(md) == alg->digest_size); + + return &ctx->base; +} + +static struct hash_ctx *create_sha256_ctx(const struct fsverity_hash_alg *alg) +{ + return openssl_digest_ctx_create(alg, EVP_sha256()); +} + +static struct hash_ctx *create_sha512_ctx(const struct fsverity_hash_alg *alg) +{ + return openssl_digest_ctx_create(alg, EVP_sha512()); +} + +/* ========== CRC-32C ========== */ + +/* + * There are faster ways to calculate CRC's, but for now we just use the + * 256-entry table method as it's portable and not too complex. + */ + +#include "crc32c_table.h" + +struct crc32c_hash_ctx { + struct hash_ctx base; /* must be first */ + u32 remainder; +}; + +static void crc32c_init(struct hash_ctx *_ctx) +{ + struct crc32c_hash_ctx *ctx = (void *)_ctx; + + ctx->remainder = ~0; +} + +static void crc32c_update(struct hash_ctx *_ctx, const void *data, size_t size) +{ + struct crc32c_hash_ctx *ctx = (void *)_ctx; + const u8 *p = data; + u32 r = ctx->remainder; + + while (size--) + r = (r >> 8) ^ crc32c_table[(u8)r ^ *p++]; + + ctx->remainder = r; +} + +static void crc32c_final(struct hash_ctx *_ctx, u8 *digest) +{ + struct crc32c_hash_ctx *ctx = (void *)_ctx; + __le32 remainder = cpu_to_le32(~ctx->remainder); + + memcpy(digest, &remainder, sizeof(remainder)); +} + +static struct hash_ctx *create_crc32c_ctx(const struct fsverity_hash_alg *alg) +{ + struct crc32c_hash_ctx *ctx = xzalloc(sizeof(*ctx)); + + ctx->base.alg = alg; + ctx->base.init = crc32c_init; + ctx->base.update = crc32c_update; + ctx->base.final = crc32c_final; + ctx->base.free = free_hash_ctx; + return &ctx->base; +} + +/* ========== Hash algorithm definitions ========== */ + +const struct fsverity_hash_alg fsverity_hash_algs[] = { + [FS_VERITY_ALG_SHA256] = { + .name = "sha256", + .digest_size = 32, + .cryptographic = true, + .create_ctx = create_sha256_ctx, + }, + [FS_VERITY_ALG_SHA512] = { + .name = "sha512", + .digest_size = 64, + .cryptographic = true, + .create_ctx = create_sha512_ctx, + }, + [FS_VERITY_ALG_CRC32C] = { + .name = "crc32c", + .digest_size = 4, + .create_ctx = create_crc32c_ctx, + }, +}; + +const struct fsverity_hash_alg *find_hash_alg_by_name(const char *name) +{ + int i; + + for (i = 0; i < ARRAY_SIZE(fsverity_hash_algs); i++) { + if (fsverity_hash_algs[i].name && + !strcmp(name, fsverity_hash_algs[i].name)) + return &fsverity_hash_algs[i]; + } + error_msg("unknown hash algorithm: '%s'", name); + fputs("Available hash algorithms: ", stderr); + show_all_hash_algs(stderr); + putc('\n', stderr); + return NULL; +} + +const struct fsverity_hash_alg *find_hash_alg_by_num(unsigned int num) +{ + if (num < ARRAY_SIZE(fsverity_hash_algs) && + fsverity_hash_algs[num].name) + return &fsverity_hash_algs[num]; + + return NULL; +} + +void show_all_hash_algs(FILE *fp) +{ + int i; + const char *sep = ""; + + for (i = 0; i < ARRAY_SIZE(fsverity_hash_algs); i++) { + if (fsverity_hash_algs[i].name) { + fprintf(fp, "%s%s", sep, fsverity_hash_algs[i].name); + sep = ", "; + } + } +} diff --git a/hash_algs.h b/hash_algs.h new file mode 100644 index 0000000..3cb0a98 --- /dev/null +++ b/hash_algs.h @@ -0,0 +1,64 @@ +/* SPDX-License-Identifier: GPL-2.0+ */ +#ifndef HASH_ALGS_H +#define HASH_ALGS_H + +#include <stdio.h> + +#include "util.h" + +struct fsverity_hash_alg { + const char *name; + unsigned int digest_size; + bool cryptographic; + struct hash_ctx *(*create_ctx)(const struct fsverity_hash_alg *alg); +}; + +extern const struct fsverity_hash_alg fsverity_hash_algs[]; + +struct hash_ctx { + const struct fsverity_hash_alg *alg; + void (*init)(struct hash_ctx *ctx); + void (*update)(struct hash_ctx *ctx, const void *data, size_t size); + void (*final)(struct hash_ctx *ctx, u8 *out); + void (*free)(struct hash_ctx *ctx); +}; + +const struct fsverity_hash_alg *find_hash_alg_by_name(const char *name); +const struct fsverity_hash_alg *find_hash_alg_by_num(unsigned int num); +void show_all_hash_algs(FILE *fp); +#define DEFAULT_HASH_ALG (&fsverity_hash_algs[FS_VERITY_ALG_SHA256]) + +/* + * Largest digest size among all hash algorithms supported by fs-verity. + * This can be increased if needed. + */ +#define FS_VERITY_MAX_DIGEST_SIZE 64 + +static inline struct hash_ctx *hash_create(const struct fsverity_hash_alg *alg) +{ + return alg->create_ctx(alg); +} + +static inline void hash_init(struct hash_ctx *ctx) +{ + ctx->init(ctx); +} + +static inline void hash_update(struct hash_ctx *ctx, + const void *data, size_t size) +{ + ctx->update(ctx, data, size); +} + +static inline void hash_final(struct hash_ctx *ctx, u8 *digest) +{ + ctx->final(ctx, digest); +} + +static inline void hash_free(struct hash_ctx *ctx) +{ + if (ctx) + ctx->free(ctx); +} + +#endif /* HASH_ALGS_H */ diff --git a/scripts/gen_crc32c_table.c b/scripts/gen_crc32c_table.c new file mode 100644 index 0000000..1c5af88 --- /dev/null +++ b/scripts/gen_crc32c_table.c @@ -0,0 +1,62 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * Generate a table for CRC-32C calculation. + * + * Copyright (C) 2018 Google LLC + * + * Written by Eric Biggers. + */ + +#include <stdint.h> +#include <stdio.h> + +/* + * This is the CRC-32C (Castagnoli) polynomial: x^32+x^28+x^27+x^26+x^25+x^23+ + * x^22+x^20+x^19+x^18+x^14+x^13+x^11+x^10+x^9+x^8+x^6+x^0, with the polynomial + * coefficients mapped to bits using the "little endian" convention. + */ +#define CRC32C_POLY_LE 0x82F63B78 + +static uint32_t crc32c_update_bit(uint32_t remainder, uint8_t bit) +{ + return (remainder >> 1) ^ + (((remainder ^ bit) & 1) ? CRC32C_POLY_LE : 0); +} + +static uint32_t crc32c_update_byte(uint32_t remainder, uint8_t byte) +{ + int bit; + + for (bit = 0; bit < 8; bit++, byte >>= 1) + remainder = crc32c_update_bit(remainder, byte & 1); + return remainder; +} + +static uint32_t crc32c_table[256]; + +int main(void) +{ + int i, j; + + for (i = 0; i < 256; i++) + crc32c_table[i] = crc32c_update_byte(0, i); + + printf("/*\n"); + printf(" * crc32c_table.h - data table to accelerate CRC-32C computation\n"); + printf(" *\n"); + printf(" * This file was automatically generated by scripts/gen_crc32c_table.c\n"); + printf(" */\n"); + printf("\n"); + printf("static const u32 crc32c_table[] = {\n"); + for (i = 0; i < 64; i++) { + printf("\t"); + for (j = 0; j < 4; j++) { + printf("0x%08x,", crc32c_table[i * 4 + j]); + if (j != 3) + printf(" "); + } + printf("\n"); + } + printf("};\n"); + return 0; +} @@ -0,0 +1,552 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * Signature support for 'fsverity setup' + * + * Copyright (C) 2018 Google LLC + * + * Written by Eric Biggers. + */ + +#include <fcntl.h> +#include <limits.h> +#include <openssl/bio.h> +#include <openssl/err.h> +#include <openssl/pem.h> +#include <openssl/pkcs7.h> +#include <stdlib.h> +#include <string.h> + +#include "fsverity_uapi.h" +#include "fsveritysetup.h" +#include "hash_algs.h" + +static void __printf(1, 2) __cold +error_msg_openssl(const char *format, ...) +{ + va_list va; + + va_start(va, format); + do_error_msg(format, va, 0); + va_end(va); + + if (ERR_peek_error() == 0) + return; + + fprintf(stderr, "OpenSSL library errors:\n"); + ERR_print_errors_fp(stderr); +} + +/* Read a PEM PKCS#8 formatted private key */ +static EVP_PKEY *read_private_key(const char *keyfile) +{ + BIO *bio; + EVP_PKEY *pkey; + + bio = BIO_new_file(keyfile, "r"); + if (!bio) { + error_msg_openssl("can't open '%s' for reading", keyfile); + return NULL; + } + + pkey = PEM_read_bio_PrivateKey(bio, NULL, NULL, NULL); + if (!pkey) { + error_msg_openssl("Failed to parse private key file '%s'.\n" + " Note: it must be in PEM PKCS#8 format.", + keyfile); + } + BIO_free(bio); + return pkey; +} + +/* Read a PEM X.509 formatted certificate */ +static X509 *read_certificate(const char *certfile) +{ + BIO *bio; + X509 *cert; + + bio = BIO_new_file(certfile, "r"); + if (!bio) { + error_msg_openssl("can't open '%s' for reading", certfile); + return NULL; + } + cert = PEM_read_bio_X509(bio, NULL, NULL, NULL); + if (!cert) { + error_msg_openssl("Failed to parse X.509 certificate file '%s'.\n" + " Note: it must be in PEM format.", + certfile); + } + BIO_free(bio); + return cert; +} + +/* + * Check that the given data is a valid 'struct fsverity_digest_disk' that + * matches the given @expected_digest and @hash_alg. + * + * Return: NULL if the digests match, else a string describing the difference. + */ +static const char * +compare_fsverity_digest(const void *data, size_t size, + const u8 *expected_digest, + const struct fsverity_hash_alg *hash_alg) +{ + const struct fsverity_digest_disk *d = data; + + if (size != sizeof(*d) + hash_alg->digest_size) + return "unexpected length"; + + if (le16_to_cpu(d->digest_algorithm) != hash_alg - fsverity_hash_algs) + return "unexpected hash algorithm"; + + if (le16_to_cpu(d->digest_size) != hash_alg->digest_size) + return "wrong digest size for hash algorithm"; + + if (memcmp(expected_digest, d->digest, hash_alg->digest_size)) + return "wrong digest"; + + return NULL; +} + +#ifdef OPENSSL_IS_BORINGSSL + +static bool sign_pkcs7(const void *data_to_sign, size_t data_size, + EVP_PKEY *pkey, X509 *cert, const EVP_MD *md, + void **sig_ret, int *sig_size_ret) +{ + CBB out, outer_seq, wrapped_seq, seq, digest_algos_set, digest_algo, + null, content_info, issuer_and_serial, signed_data, + wrapped_signed_data, signer_infos, signer_info, sign_algo, + signature; + EVP_MD_CTX md_ctx; + u8 *name_der = NULL, *sig = NULL, *pkcs7_data = NULL; + size_t pkcs7_data_len, sig_len; + int name_der_len, sig_nid; + bool ok = false; + + EVP_MD_CTX_init(&md_ctx); + BIGNUM *serial = ASN1_INTEGER_to_BN(X509_get_serialNumber(cert), NULL); + + if (!CBB_init(&out, 1024)) { + error_msg("out of memory"); + goto out; + } + + name_der_len = i2d_X509_NAME(X509_get_subject_name(cert), &name_der); + if (name_der_len < 0) { + error_msg_openssl("i2d_X509_NAME failed"); + goto out; + } + + if (!EVP_DigestSignInit(&md_ctx, NULL, md, NULL, pkey)) { + error_msg_openssl("EVP_DigestSignInit failed"); + goto out; + } + + sig_len = EVP_PKEY_size(pkey); + sig = xmalloc(sig_len); + if (!EVP_DigestSign(&md_ctx, sig, &sig_len, data_to_sign, data_size)) { + error_msg_openssl("EVP_DigestSign failed"); + goto out; + } + + sig_nid = EVP_PKEY_id(pkey); + /* To mirror OpenSSL behaviour, always use |NID_rsaEncryption| with RSA + * rather than the combined hash+pkey NID. */ + if (sig_nid != NID_rsaEncryption) { + OBJ_find_sigid_by_algs(&sig_nid, EVP_MD_type(md), + EVP_PKEY_id(pkey)); + } + + // See https://tools.ietf.org/html/rfc2315#section-7 + if (!CBB_add_asn1(&out, &outer_seq, CBS_ASN1_SEQUENCE) || + !OBJ_nid2cbb(&outer_seq, NID_pkcs7_signed) || + !CBB_add_asn1(&outer_seq, &wrapped_seq, CBS_ASN1_CONTEXT_SPECIFIC | + CBS_ASN1_CONSTRUCTED | 0) || + // See https://tools.ietf.org/html/rfc2315#section-9.1 + !CBB_add_asn1(&wrapped_seq, &seq, CBS_ASN1_SEQUENCE) || + !CBB_add_asn1_uint64(&seq, 1 /* version */) || + !CBB_add_asn1(&seq, &digest_algos_set, CBS_ASN1_SET) || + !CBB_add_asn1(&digest_algos_set, &digest_algo, CBS_ASN1_SEQUENCE) || + !OBJ_nid2cbb(&digest_algo, EVP_MD_type(md)) || + !CBB_add_asn1(&digest_algo, &null, CBS_ASN1_NULL) || + !CBB_add_asn1(&seq, &content_info, CBS_ASN1_SEQUENCE) || + !OBJ_nid2cbb(&content_info, NID_pkcs7_data) || + !CBB_add_asn1( + &content_info, &signed_data, + CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) || + !CBB_add_asn1(&signed_data, &wrapped_signed_data, + CBS_ASN1_OCTETSTRING) || + !CBB_add_bytes(&wrapped_signed_data, (const u8 *)data_to_sign, + data_size) || + !CBB_add_asn1(&seq, &signer_infos, CBS_ASN1_SET) || + !CBB_add_asn1(&signer_infos, &signer_info, CBS_ASN1_SEQUENCE) || + !CBB_add_asn1_uint64(&signer_info, 1 /* version */) || + !CBB_add_asn1(&signer_info, &issuer_and_serial, + CBS_ASN1_SEQUENCE) || + !CBB_add_bytes(&issuer_and_serial, name_der, name_der_len) || + !BN_marshal_asn1(&issuer_and_serial, serial) || + !CBB_add_asn1(&signer_info, &digest_algo, CBS_ASN1_SEQUENCE) || + !OBJ_nid2cbb(&digest_algo, EVP_MD_type(md)) || + !CBB_add_asn1(&digest_algo, &null, CBS_ASN1_NULL) || + !CBB_add_asn1(&signer_info, &sign_algo, CBS_ASN1_SEQUENCE) || + !OBJ_nid2cbb(&sign_algo, sig_nid) || + !CBB_add_asn1(&sign_algo, &null, CBS_ASN1_NULL) || + !CBB_add_asn1(&signer_info, &signature, CBS_ASN1_OCTETSTRING) || + !CBB_add_bytes(&signature, sig, sig_len) || + !CBB_finish(&out, &pkcs7_data, &pkcs7_data_len)) { + error_msg_openssl("failed to construct PKCS#7 data"); + goto out; + } + + *sig_ret = xmemdup(pkcs7_data, pkcs7_data_len); + *sig_size_ret = pkcs7_data_len; + ok = true; +out: + BN_free(serial); + EVP_MD_CTX_cleanup(&md_ctx); + CBB_cleanup(&out); + free(sig); + OPENSSL_free(name_der); + OPENSSL_free(pkcs7_data); + return ok; +} + +static const char * +compare_fsverity_digest_pkcs7(const void *sig, size_t sig_len, + const u8 *expected_measurement, + const struct fsverity_hash_alg *hash_alg) +{ + CBS in, content_info, content_type, wrapped_signed_data, signed_data, + content, wrapped_data, data; + u64 version; + + CBS_init(&in, sig, sig_len); + if (!CBS_get_asn1(&in, &content_info, CBS_ASN1_SEQUENCE) || + !CBS_get_asn1(&content_info, &content_type, CBS_ASN1_OBJECT) || + (OBJ_cbs2nid(&content_type) != NID_pkcs7_signed) || + !CBS_get_asn1( + &content_info, &wrapped_signed_data, + CBS_ASN1_CONTEXT_SPECIFIC | CBS_ASN1_CONSTRUCTED | 0) || + !CBS_get_asn1(&wrapped_signed_data, &signed_data, + CBS_ASN1_SEQUENCE) || + !CBS_get_asn1_uint64(&signed_data, &version) || + (version < 1) || + !CBS_get_asn1(&signed_data, NULL /* digests */, CBS_ASN1_SET) || + !CBS_get_asn1(&signed_data, &content, CBS_ASN1_SEQUENCE) || + !CBS_get_asn1(&content, &content_type, CBS_ASN1_OBJECT) || + (OBJ_cbs2nid(&content_type) != NID_pkcs7_data) || + !CBS_get_asn1(&content, &wrapped_data, CBS_ASN1_CONTEXT_SPECIFIC | + CBS_ASN1_CONSTRUCTED | 0) || + !CBS_get_asn1(&wrapped_data, &data, CBS_ASN1_OCTETSTRING)) { + return "invalid PKCS#7 data"; + } + + return compare_fsverity_digest(CBS_data(&data), CBS_len(&data), + expected_measurement, hash_alg); +} + +#else /* OPENSSL_IS_BORINGSSL */ + +static BIO *new_mem_buf(const void *buf, size_t size) +{ + BIO *bio; + + ASSERT(size <= INT_MAX); + /* + * Prior to OpenSSL 1.1.0, BIO_new_mem_buf() took a non-const pointer, + * despite still marking the resulting bio as read-only. So cast away + * the const to avoid a compiler warning with older OpenSSL versions. + */ + bio = BIO_new_mem_buf((void *)buf, size); + if (!bio) + error_msg_openssl("out of memory"); + return bio; +} + +static bool sign_pkcs7(const void *data_to_sign, size_t data_size, + EVP_PKEY *pkey, X509 *cert, const EVP_MD *md, + void **sig_ret, int *sig_size_ret) +{ + /* + * PKCS#7 signing flags: + * + * - PKCS7_BINARY signing binary data, so skip MIME translation + * + * - PKCS7_NOATTR omit extra authenticated attributes, such as + * SMIMECapabilities + * + * - PKCS7_NOCERTS omit the signer's certificate + * + * - PKCS7_PARTIAL PKCS7_sign() creates a handle only, then + * PKCS7_sign_add_signer() can add a signer later. + * This is necessary to change the message digest + * algorithm from the default of SHA-1. Requires + * OpenSSL 1.0.0 or later. + */ + int pkcs7_flags = PKCS7_BINARY | PKCS7_NOATTR | PKCS7_NOCERTS | + PKCS7_PARTIAL; + void *sig; + int sig_size; + BIO *bio = NULL; + PKCS7 *p7 = NULL; + bool ok = false; + + bio = new_mem_buf(data_to_sign, data_size); + if (!bio) + goto out; + + p7 = PKCS7_sign(NULL, NULL, NULL, bio, pkcs7_flags); + if (!p7) { + error_msg_openssl("failed to initialize PKCS#7 signature object"); + goto out; + } + + if (!PKCS7_sign_add_signer(p7, cert, pkey, md, pkcs7_flags)) { + error_msg_openssl("failed to add signer to PKCS#7 signature object"); + goto out; + } + + if (PKCS7_final(p7, bio, pkcs7_flags) != 1) { + error_msg_openssl("failed to finalize PKCS#7 signature"); + goto out; + } + + BIO_free(bio); + bio = BIO_new(BIO_s_mem()); + if (!bio) { + error_msg_openssl("out of memory"); + goto out; + } + + if (i2d_PKCS7_bio(bio, p7) != 1) { + error_msg_openssl("failed to DER-encode PKCS#7 signature object"); + goto out; + } + + sig_size = BIO_get_mem_data(bio, &sig); + *sig_ret = xmemdup(sig, sig_size); + *sig_size_ret = sig_size; + ok = true; +out: + PKCS7_free(p7); + BIO_free(bio); + return ok; +} + +static const char * +compare_fsverity_digest_pkcs7(const void *sig, size_t sig_len, + const u8 *expected_measurement, + const struct fsverity_hash_alg *hash_alg) +{ + BIO *bio = NULL; + PKCS7 *p7 = NULL; + const char *reason = NULL; + + bio = new_mem_buf(sig, sig_len); + if (!bio) + return "out of memory"; + + p7 = d2i_PKCS7_bio(bio, NULL); + if (!p7) { + reason = "failed to decode PKCS#7 signature"; + goto out; + } + + if (OBJ_obj2nid(p7->type) != NID_pkcs7_signed || + OBJ_obj2nid(p7->d.sign->contents->type) != NID_pkcs7_data) { + reason = "unexpected PKCS#7 content type"; + } else { + const ASN1_OCTET_STRING *o = p7->d.sign->contents->d.data; + + reason = compare_fsverity_digest(o->data, o->length, + expected_measurement, + hash_alg); + } +out: + BIO_free(bio); + PKCS7_free(p7); + return reason; +} + +#endif /* !OPENSSL_IS_BORINGSSL */ + +/* + * Sign the specified @data_to_sign of length @data_size bytes using the private + * key in @keyfile, the certificate in @certfile, and the hash algorithm + * @hash_alg. Returns the DER-formatted PKCS#7 signature, with the signed data + * included (not detached), in @sig_ret and @sig_size_ret. + */ +static bool sign_data(const void *data_to_sign, size_t data_size, + const char *keyfile, const char *certfile, + const struct fsverity_hash_alg *hash_alg, + void **sig_ret, int *sig_size_ret) +{ + EVP_PKEY *pkey = NULL; + X509 *cert = NULL; + const EVP_MD *md; + bool ok = false; + + pkey = read_private_key(keyfile); + if (!pkey) + goto out; + + cert = read_certificate(certfile); + if (!cert) + goto out; + + OpenSSL_add_all_digests(); + ASSERT(hash_alg->cryptographic); + md = EVP_get_digestbyname(hash_alg->name); + if (!md) { + fprintf(stderr, + "Warning: '%s' algorithm not found in OpenSSL library.\n" + " Falling back to SHA-256 signature.\n", + hash_alg->name); + md = EVP_sha256(); + } + + ok = sign_pkcs7(data_to_sign, data_size, pkey, cert, md, + sig_ret, sig_size_ret); +out: + EVP_PKEY_free(pkey); + X509_free(cert); + return ok; +} + +/* + * Read a file measurement signature in PKCS#7 DER format from @signature_file, + * validate that the signed data matches the expected measurement, then return + * the PKCS#7 DER message in @sig_ret and @sig_size_ret. + */ +static bool read_signature(const char *signature_file, + const u8 *expected_measurement, + const struct fsverity_hash_alg *hash_alg, + void **sig_ret, int *sig_size_ret) +{ + struct filedes file = { .fd = -1 }; + u64 filesize; + void *sig = NULL; + bool ok = false; + const char *reason; + + if (!open_file(&file, signature_file, O_RDONLY, 0)) + goto out; + if (!get_file_size(&file, &filesize)) + goto out; + if (filesize <= 0) { + error_msg("signature file '%s' is empty", signature_file); + goto out; + } + if (filesize > 1000000) { + error_msg("signature file '%s' is too large", signature_file); + goto out; + } + sig = xmalloc(filesize); + if (!full_read(&file, sig, filesize)) + goto out; + + reason = compare_fsverity_digest_pkcs7(sig, filesize, + expected_measurement, hash_alg); + if (reason) { + error_msg("signed file measurement from '%s' is invalid (%s)", + signature_file, reason); + goto out; + } + + printf("Using existing signed file measurement from '%s'\n", + signature_file); + *sig_ret = sig; + *sig_size_ret = filesize; + sig = NULL; + ok = true; +out: + filedes_close(&file); + free(sig); + return ok; +} + +static bool write_signature(const char *signature_file, + const void *sig, int sig_size) +{ + struct filedes file; + bool ok; + + if (!open_file(&file, signature_file, O_WRONLY|O_CREAT|O_TRUNC, 0644)) + return false; + ok = full_write(&file, sig, sig_size); + ok &= filedes_close(&file); + if (ok) + printf("Wrote signed file measurement to '%s'\n", + signature_file); + return ok; +} + +/* + * Append the signed file measurement to the output file as a PKCS7_SIGNATURE + * extension item. + * + * Return: exit status code (0 on success, nonzero on failure) + */ +int append_signed_measurement(struct filedes *out, + const struct fsveritysetup_params *params, + const u8 *measurement) +{ + struct fsverity_digest_disk *data_to_sign = NULL; + void *sig = NULL; + void *extbuf = NULL; + void *tmp; + int sig_size; + int status; + + if (params->signing_key_file) { + size_t data_size = sizeof(*data_to_sign) + + params->hash_alg->digest_size; + + /* Sign the file measurement using the given key */ + + data_to_sign = xzalloc(data_size); + data_to_sign->digest_algorithm = + cpu_to_le16(params->hash_alg - fsverity_hash_algs); + data_to_sign->digest_size = + cpu_to_le16(params->hash_alg->digest_size); + memcpy(data_to_sign->digest, measurement, + params->hash_alg->digest_size); + + ASSERT(compare_fsverity_digest(data_to_sign, data_size, + measurement, params->hash_alg) == NULL); + + if (!sign_data(data_to_sign, data_size, + params->signing_key_file, + params->signing_cert_file ?: + params->signing_key_file, + params->hash_alg, + &sig, &sig_size)) + goto out_err; + + if (params->signature_file && + !write_signature(params->signature_file, sig, sig_size)) + goto out_err; + } else { + /* Using a signature that was already created */ + if (!read_signature(params->signature_file, measurement, + params->hash_alg, &sig, &sig_size)) + goto out_err; + } + + tmp = extbuf = xzalloc(FSVERITY_EXTLEN(sig_size)); + fsverity_append_extension(&tmp, FS_VERITY_EXT_PKCS7_SIGNATURE, + sig, sig_size); + ASSERT(tmp == extbuf + FSVERITY_EXTLEN(sig_size)); + if (!full_write(out, extbuf, FSVERITY_EXTLEN(sig_size))) + goto out_err; + status = 0; +out: + free(data_to_sign); + free(sig); + free(extbuf); + return status; + +out_err: + status = 1; + goto out; +} @@ -0,0 +1,362 @@ +// SPDX-License-Identifier: GPL-2.0+ +/* + * Utility functions for the 'fsverity' program + * + * Copyright (C) 2018 Google LLC + * + * Written by Eric Biggers. + */ + +#include <errno.h> +#include <fcntl.h> +#include <limits.h> +#include <stdarg.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <sys/stat.h> +#include <unistd.h> + +#include "util.h" + +/* ========== Memory allocation ========== */ + +void *xmalloc(size_t size) +{ + void *p = malloc(size); + + if (!p) + fatal_error("out of memory"); + return p; +} + +void *xzalloc(size_t size) +{ + return memset(xmalloc(size), 0, size); +} + +void *xmemdup(const void *mem, size_t size) +{ + return memcpy(xmalloc(size), mem, size); +} + +char *xstrdup(const char *s) +{ + return xmemdup(s, strlen(s) + 1); +} + +char *xasprintf(const char *format, ...) +{ + va_list va1, va2; + int size; + char *s; + + va_start(va1, format); + + va_copy(va2, va1); + size = vsnprintf(NULL, 0, format, va2); + va_end(va2); + + ASSERT(size >= 0); + s = xmalloc(size + 1); + vsprintf(s, format, va1); + + va_end(va1); + return s; +} + +/* ========== Error messages and assertions ========== */ + +void do_error_msg(const char *format, va_list va, int err) +{ + fputs("ERROR: ", stderr); + vfprintf(stderr, format, va); + if (err) + fprintf(stderr, ": %s", strerror(err)); + putc('\n', stderr); +} + +void error_msg(const char *format, ...) +{ + va_list va; + + va_start(va, format); + do_error_msg(format, va, 0); + va_end(va); +} + +void error_msg_errno(const char *format, ...) +{ + va_list va; + + va_start(va, format); + do_error_msg(format, va, errno); + va_end(va); +} + +__noreturn void fatal_error(const char *format, ...) +{ + va_list va; + + va_start(va, format); + do_error_msg(format, va, 0); + va_end(va); + abort(); +} + +__noreturn void assertion_failed(const char *expr, const char *file, int line) +{ + fatal_error("Assertion failed: %s at %s:%d", expr, file, line); +} + +/* ========== File utilities ========== */ + +bool open_file(struct filedes *file, const char *filename, int flags, int mode) +{ + file->fd = open(filename, flags, mode); + if (file->fd < 0) { + error_msg_errno("can't open '%s' for %s", filename, + (flags & O_ACCMODE) == O_RDONLY ? "reading" : + (flags & O_ACCMODE) == O_WRONLY ? "writing" : + "reading and writing"); + return false; + } + file->autodelete = false; + file->name = xstrdup(filename); + file->pos = 0; + return true; +} + +bool open_tempfile(struct filedes *file) +{ + const char *tmpdir = getenv("TMPDIR") ?: P_tmpdir; + char *name = xasprintf("%s/fsverity-XXXXXX", tmpdir); + + file->fd = mkstemp(name); + if (file->fd < 0) { + error_msg_errno("can't create temporary file"); + free(name); + return false; + } + file->autodelete = true; + file->name = name; + file->pos = 0; + return true; +} + +bool get_file_size(struct filedes *file, u64 *size_ret) +{ + struct stat stbuf; + + if (fstat(file->fd, &stbuf) != 0) { + error_msg_errno("can't stat file '%s'", file->name); + return false; + } + *size_ret = stbuf.st_size; + return true; +} + +bool filedes_seek(struct filedes *file, u64 pos, int whence) +{ + off_t res; + + res = lseek(file->fd, pos, whence); + if (res < 0) { + error_msg_errno("seek error on '%s'", file->name); + return false; + } + file->pos = res; + return true; +} + +bool full_read(struct filedes *file, void *buf, size_t count) +{ + while (count) { + int n = read(file->fd, buf, min(count, INT_MAX)); + + if (n < 0) { + error_msg_errno("reading from '%s'", file->name); + return false; + } + if (n == 0) { + error_msg("unexpected end-of-file on '%s'", file->name); + return false; + } + buf += n; + count -= n; + file->pos += n; + } + return true; +} + +bool full_pread(struct filedes *file, void *buf, size_t count, u64 offset) +{ + while (count) { + int n = pread(file->fd, buf, min(count, INT_MAX), offset); + + if (n < 0) { + error_msg_errno("reading from '%s'", file->name); + return false; + } + if (n == 0) { + error_msg("unexpected end-of-file on '%s'", file->name); + return false; + } + buf += n; + count -= n; + offset += n; + } + return true; +} + +bool full_write(struct filedes *file, const void *buf, size_t count) +{ + while (count) { + int n = write(file->fd, buf, min(count, INT_MAX)); + + if (n < 0) { + error_msg_errno("writing to '%s'", file->name); + return false; + } + buf += n; + count -= n; + file->pos += n; + } + return true; +} + +bool full_pwrite(struct filedes *file, const void *buf, size_t count, + u64 offset) +{ + while (count) { + int n = pwrite(file->fd, buf, min(count, INT_MAX), offset); + + if (n < 0) { + error_msg_errno("writing to '%s'", file->name); + return false; + } + buf += n; + count -= n; + offset += n; + } + return true; +} + +/* Copy 'count' bytes of data from 'src' to 'dst' */ +bool copy_file_data(struct filedes *src, struct filedes *dst, u64 count) +{ + char buf[4096]; + + while (count) { + size_t n = min(count, sizeof(buf)); + + if (!full_read(src, buf, n)) + return false; + if (!full_write(dst, buf, n)) + return false; + count -= n; + } + return true; +} + +/* Write 'count' bytes of zeroes to the file */ +bool write_zeroes(struct filedes *file, u64 count) +{ + char buf[4096]; + + memset(buf, 0, min(count, sizeof(buf))); + + while (count) { + size_t n = min(count, sizeof(buf)); + + if (!full_write(file, buf, n)) + return false; + count -= n; + } + return true; +} + +bool filedes_close(struct filedes *file) +{ + int res; + + if (file->fd < 0) + return true; + res = close(file->fd); + if (res != 0) + error_msg_errno("closing '%s'", file->name); + if (file->autodelete) + (void)unlink(file->name); + file->fd = -1; + free(file->name); + file->name = NULL; + return res == 0; +} + +/* ========== String utilities ========== */ + +static int hex2bin_char(char c) +{ + if (c >= '0' && c <= '9') + return c - '0'; + if (c >= 'a' && c <= 'f') + return 10 + (c - 'a'); + if (c >= 'A' && c <= 'F') + return 10 + (c - 'A'); + return -1; +} + +bool hex2bin(const char *hex, u8 *bin, size_t bin_len) +{ + if (strlen(hex) != 2 * bin_len) + return false; + + while (bin_len--) { + int hi = hex2bin_char(*hex++); + int lo = hex2bin_char(*hex++); + + if (hi < 0 || lo < 0) + return false; + *bin++ = (hi << 4) | lo; + } + return true; +} + +static char bin2hex_char(u8 nibble) +{ + ASSERT(nibble <= 0xf); + + if (nibble < 10) + return '0' + nibble; + return 'a' + (nibble - 10); +} + +void bin2hex(const u8 *bin, size_t bin_len, char *hex) +{ + while (bin_len--) { + *hex++ = bin2hex_char(*bin >> 4); + *hex++ = bin2hex_char(*bin & 0xf); + bin++; + } + *hex = '\0'; +} + +void string_list_append(struct string_list *list, char *string) +{ + ASSERT(list->length <= list->capacity); + if (list->length == list->capacity) { + list->capacity = (list->capacity * 2) + 4; + list->strings = realloc(list->strings, + sizeof(list->strings[0]) * + list->capacity); + if (!list->strings) + fatal_error("out of memory"); + } + list->strings[list->length++] = string; +} + +void string_list_destroy(struct string_list *list) +{ + free(list->strings); + memset(list, 0, sizeof(*list)); +} @@ -0,0 +1,160 @@ +/* SPDX-License-Identifier: GPL-2.0+ */ +/* + * Utility functions and macros for the 'fsverity' program + * + * Copyright (C) 2018 Google LLC + */ +#ifndef UTIL_H +#define UTIL_H + +#include <inttypes.h> +#include <stdarg.h> +#include <stdbool.h> +#include <stddef.h> + +typedef uint8_t u8; +typedef uint16_t u16; +typedef uint32_t u32; +typedef uint64_t u64; + +#ifndef __force +# ifdef __CHECKER__ +# define __force __attribute__((force)) +# else +# define __force +# endif +#endif + +#ifndef __printf +# define __printf(fmt_idx, vargs_idx) \ + __attribute__((format(printf, fmt_idx, vargs_idx))) +#endif + +#ifndef __noreturn +# define __noreturn __attribute__((noreturn)) +#endif + +#ifndef __cold +# define __cold __attribute__((cold)) +#endif + +#define min(a, b) ({ \ + __typeof__(a) _a = (a); \ + __typeof__(b) _b = (b); \ + _a < _b ? _a : _b; \ +}) +#define max(a, b) ({ \ + __typeof__(a) _a = (a); \ + __typeof__(b) _b = (b); \ + _a > _b ? _a : _b; \ +}) + +#define ARRAY_SIZE(A) (sizeof(A) / sizeof((A)[0])) + +#define DIV_ROUND_UP(n, d) (((n) + (d) - 1) / (d)) + +/* + * Round 'v' up to the next 'alignment'-byte aligned boundary. + * 'alignment' must be a power of 2. + */ +#define ALIGN(v, alignment) (((v) + ((alignment) - 1)) & ~((alignment) - 1)) + +static inline bool is_power_of_2(unsigned long n) +{ + return n != 0 && ((n & (n - 1)) == 0); +} + +static inline int ilog2(unsigned long n) +{ + return (8 * sizeof(n) - 1) - __builtin_clzl(n); +} + +/* ========== Endianness conversion ========== */ + +#if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ +# define cpu_to_le16(v) ((__force __le16)(u16)(v)) +# define le16_to_cpu(v) ((__force u16)(__le16)(v)) +# define cpu_to_le32(v) ((__force __le32)(u32)(v)) +# define le32_to_cpu(v) ((__force u32)(__le32)(v)) +# define cpu_to_le64(v) ((__force __le64)(u64)(v)) +# define le64_to_cpu(v) ((__force u64)(__le64)(v)) +# define cpu_to_be16(v) ((__force __be16)__builtin_bswap16(v)) +# define be16_to_cpu(v) (__builtin_bswap16((__force u16)(v))) +# define cpu_to_be32(v) ((__force __be32)__builtin_bswap32(v)) +# define be32_to_cpu(v) (__builtin_bswap32((__force u32)(v))) +# define cpu_to_be64(v) ((__force __be64)__builtin_bswap64(v)) +# define be64_to_cpu(v) (__builtin_bswap64((__force u64)(v))) +#else +# define cpu_to_le16(v) ((__force __le16)__builtin_bswap16(v)) +# define le16_to_cpu(v) (__builtin_bswap16((__force u16)(v))) +# define cpu_to_le32(v) ((__force __le32)__builtin_bswap32(v)) +# define le32_to_cpu(v) (__builtin_bswap32((__force u32)(v))) +# define cpu_to_le64(v) ((__force __le64)__builtin_bswap64(v)) +# define le64_to_cpu(v) (__builtin_bswap64((__force u64)(v))) +# define cpu_to_be16(v) ((__force __be16)(u16)(v)) +# define be16_to_cpu(v) ((__force u16)(__be16)(v)) +# define cpu_to_be32(v) ((__force __be32)(u32)(v)) +# define be32_to_cpu(v) ((__force u32)(__be32)(v)) +# define cpu_to_be64(v) ((__force __be64)(u64)(v)) +# define be64_to_cpu(v) ((__force u64)(__be64)(v)) +#endif + +/* ========== Memory allocation ========== */ + +void *xmalloc(size_t size); +void *xzalloc(size_t size); +void *xmemdup(const void *mem, size_t size); +char *xstrdup(const char *s); +__printf(1, 2) char *xasprintf(const char *format, ...); + +/* ========== Error messages and assertions ========== */ + +__cold void do_error_msg(const char *format, va_list va, int err); +__printf(1, 2) __cold void error_msg(const char *format, ...); +__printf(1, 2) __cold void error_msg_errno(const char *format, ...); +__printf(1, 2) __cold __noreturn void fatal_error(const char *format, ...); +__cold __noreturn void assertion_failed(const char *expr, + const char *file, int line); + +#define ASSERT(e) ({ if (!(e)) assertion_failed(#e, __FILE__, __LINE__); }) + +/* ========== File utilities ========== */ + +struct filedes { + int fd; + bool autodelete; /* unlink when closed? */ + char *name; /* filename, for logging or error messages */ + u64 pos; /* lseek() position */ +}; + +bool open_file(struct filedes *file, const char *filename, int flags, int mode); +bool open_tempfile(struct filedes *file); +bool get_file_size(struct filedes *file, u64 *size_ret); +bool filedes_seek(struct filedes *file, u64 pos, int whence); +bool full_read(struct filedes *file, void *buf, size_t count); +bool full_pread(struct filedes *file, void *buf, size_t count, u64 offset); +bool full_write(struct filedes *file, const void *buf, size_t count); +bool full_pwrite(struct filedes *file, const void *buf, size_t count, + u64 offset); +bool copy_file_data(struct filedes *src, struct filedes *dst, u64 length); +bool write_zeroes(struct filedes *file, u64 length); +bool filedes_close(struct filedes *file); + +/* ========== String utilities ========== */ + +bool hex2bin(const char *hex, u8 *bin, size_t bin_len); +void bin2hex(const u8 *bin, size_t bin_len, char *hex); + +struct string_list { + char **strings; + size_t length; + size_t capacity; +}; + +#define STRING_LIST_INITIALIZER { .strings = NULL, .length = 0, .capacity = 0 } +#define STRING_LIST(_list) struct string_list _list = STRING_LIST_INITIALIZER + +void string_list_append(struct string_list *list, char *string); +void string_list_destroy(struct string_list *list); + +#endif /* UTIL_H */ |