pax_global_header00006660000000000000000000000064145333156540014523gustar00rootroot0000000000000052 comment=8e48784ecdf36dae229a56a128ccadede98bbfcf nullboot-0.5.0/000077500000000000000000000000001453331565400133635ustar00rootroot00000000000000nullboot-0.5.0/.github/000077500000000000000000000000001453331565400147235ustar00rootroot00000000000000nullboot-0.5.0/.github/dependabot.yml000066400000000000000000000003161453331565400175530ustar00rootroot00000000000000version: 2 updates: - package-ecosystem: "gomod" directory: "/" schedule: interval: "daily" - package-ecosystem: "github-actions" directory: "/" schedule: interval: "daily" nullboot-0.5.0/.github/workflows/000077500000000000000000000000001453331565400167605ustar00rootroot00000000000000nullboot-0.5.0/.github/workflows/ci.yml000066400000000000000000000022361453331565400201010ustar00rootroot00000000000000name: CI tests on: - push - pull_request jobs: pre-commit: strategy: fail-fast: false matrix: go: - 1.18.x os: - ubuntu-20.04 - ubuntu-22.04 runs-on: ${{ matrix.os }} steps: - name: Checkout code uses: actions/checkout@v4 - name: Install Go uses: actions/setup-go@v4 with: go-version: ${{ matrix.go }} - name: Setup dependencies run: | sudo apt install libefivar-dev libefiboot-dev python3-pip golint pip3 install pre-commit - name: Run pre-commit run: | go get . ~/.local/bin/pre-commit run -a - name: Coverage run: go test -v -coverprofile=profile.cov ./... - name: Send coverage to Coveralls (parallel) uses: shogo82148/actions-goveralls@v1 with: path-to-profile: profile.cov parallel: true flag-name: ${{ matrix.os }}-go-${{ matrix.go }} finish: needs: pre-commit if: ${{ always() }} runs-on: ubuntu-latest steps: - name: Coveralls finished uses: shogo82148/actions-goveralls@v1 with: parallel-finished: true nullboot-0.5.0/.github/workflows/codeql-analysis.yml000066400000000000000000000044321453331565400225760ustar00rootroot00000000000000# For most projects, this workflow file will not need changing; you simply need # to commit it to your repository. # # You may wish to alter this file to override the set of languages analyzed, # or to provide custom queries or build logic. # # ******** NOTE ******** # We have attempted to detect the languages in your repository. Please check # the `language` matrix defined below to confirm you have the correct set of # supported CodeQL languages. # name: "CodeQL" on: push: branches: [ main ] pull_request: # The branches below must be a subset of the branches above branches: [ main ] schedule: - cron: '16 10 * * 0' jobs: analyze: name: Analyze runs-on: ubuntu-latest permissions: actions: read contents: read security-events: write strategy: fail-fast: false matrix: language: [ 'go' ] # CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ] # Learn more about CodeQL language support at https://git.io/codeql-language-support steps: - name: Checkout repository uses: actions/checkout@v4 # Initializes the CodeQL tools for scanning. - name: Initialize CodeQL uses: github/codeql-action/init@v2 with: languages: ${{ matrix.language }} # If you wish to specify custom queries, you can do so here or in a config file. # By default, queries listed here will override any specified in a config file. # Prefix the list here with "+" to use these queries and those in the config file. # queries: ./path/to/local/query, your-org/your-repo/queries@main # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). # If this step fails, then you should remove it and run the build manually (see below) - name: Autobuild uses: github/codeql-action/autobuild@v2 # â„šī¸ Command-line programs to run using the OS shell. # 📚 https://git.io/JvXDl # âœī¸ If the Autobuild fails above, remove it and uncomment the following three lines # and modify them (or add more) to build your code if your project # uses a compiled language #- run: | # make bootstrap # make release - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v2 nullboot-0.5.0/.pre-commit-config.yaml000066400000000000000000000003701453331565400176440ustar00rootroot00000000000000repos: - repo: https://github.com/dnephin/pre-commit-golang rev: v0.4.0 hooks: - id: go-fmt - id: go-vet - id: go-lint - id: validate-toml - id: no-go-testing - id: go-unit-tests - id: go-build - id: go-mod-tidy nullboot-0.5.0/COPYING000066400000000000000000001045131453331565400144220ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . nullboot-0.5.0/README.md000066400000000000000000000014651453331565400146500ustar00rootroot00000000000000A boot manager that isn't ========================= nullboot is a boot manager for environments that do not need a boot manager. Instead of running a boot manager at boot, it directly manages the UEFI boot entries for you. Licensing --------- This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License version 3, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . nullboot-0.5.0/cmd/000077500000000000000000000000001453331565400141265ustar00rootroot00000000000000nullboot-0.5.0/cmd/nullbootctl/000077500000000000000000000000001453331565400164675ustar00rootroot00000000000000nullboot-0.5.0/cmd/nullbootctl/main.go000066400000000000000000000071031453331565400177430ustar00rootroot00000000000000// This file is part of nullboot // Copyright 2021 Canonical Ltd. // SPDX-License-Identifier: GPL-3.0-only package main import "github.com/canonical/nullboot/efibootmgr" import "flag" import "log" import "os" var noTPM = flag.Bool("no-tpm", false, "Do not do any resealing with the TPM") var noEfivars = flag.Bool("no-efivars", false, "Do not use or update the EFI variables") var outputJSON = flag.String("output-json", "", "JSON file to write (also disables writing real EFI variables)") func main() { var assets *efibootmgr.TrustedAssets var err error flag.Parse() const ( esp = "/boot/efi" shimSourceDir = "/usr/lib/nullboot/shim" kernelSourceDir = "/usr/lib/linux/efi" vendor = "ubuntu" ) // FIXME: Let's actually add some arg parsing and stuff? if !*noTPM { assets, err = efibootmgr.ReadTrustedAssets() if err != nil { log.Println("cannot read trusted asset hashes:", err) os.Exit(1) } for _, p := range []string{shimSourceDir, kernelSourceDir} { if err := assets.TrustNewFromDir(p); err != nil { log.Println("cannot add new assets from", p, ":", err) os.Exit(1) } } if err := efibootmgr.TrustCurrentBoot(assets, esp); err != nil { log.Println("cannot trust boot assets used for current boot:", err) os.Exit(1) } } var maybeBm *efibootmgr.BootManager var efivars efibootmgr.EFIVariables if *outputJSON != "" { efivars = &efibootmgr.MockEFIVariables{} } else { efivars = efibootmgr.RealEFIVariables{} } if !*noEfivars { if bm, err := efibootmgr.NewBootManagerForVariables(efivars); err != nil { log.Println("cannot load efi boot variables:", err) os.Exit(1) } else { maybeBm = &bm } } km, err := efibootmgr.NewKernelManager(esp, kernelSourceDir, vendor, maybeBm) if err != nil { log.Print(err) os.Exit(1) } if assets != nil { if err := assets.Save(); err != nil { log.Println("cannot update list of trusted boot assets:", err) os.Exit(1) } // Initial reseal against new assets if err := efibootmgr.ResealKey(assets, km, esp, shimSourceDir, vendor); err != nil { log.Println("initial reseal failed:", err) os.Exit(1) } } // Install the shim updatedShim, err := efibootmgr.InstallShim(esp, shimSourceDir, vendor) if err != nil { log.Print(err) os.Exit(1) } if updatedShim { log.Print("Updated shim") } // Install new kernels and commit to bootloader config. This // way if err = km.InstallKernels(); err != nil { log.Print(err) os.Exit(1) } if err = km.CommitToBootLoader(); err != nil { log.Print(err) os.Exit(1) } // Cleanup old entries if err = km.RemoveObsoleteKernels(); err != nil { log.Print(err) os.Exit(1) } if err = km.CommitToBootLoader(); err != nil { log.Print(err) os.Exit(1) } if assets != nil { assets.RemoveObsolete() if err := assets.Save(); err != nil { log.Println("cannot update list of trusted boot assets:", err) os.Exit(1) } // Final reseal to remove obsolete assets from profile if err := efibootmgr.ResealKey(assets, km, esp, shimSourceDir, vendor); err != nil { log.Println("final reseal failed:", err) os.Exit(1) } } if jsonEfivars, ok := efivars.(*efibootmgr.MockEFIVariables); ok { json, err := jsonEfivars.JSON() if err != nil { log.Println("cannot write json:", err) os.Exit(2) } f, err := os.Create(*outputJSON) if err != nil { log.Printf("Could not open JSON output file %s: %v", *outputJSON, err) os.Exit(1) } defer f.Close() _, err = f.Write(json) if err != nil { log.Printf("Could not write JSON output file %s: %v", *outputJSON, err) os.Exit(1) } } } nullboot-0.5.0/doc.go000066400000000000000000000003231453331565400144550ustar00rootroot00000000000000// This file is part of nullboot // Copyright 2021 Canonical Ltd. // SPDX-License-Identifier: GPL-3.0-only // Package nullboot provides the nullboot experience // Most of it is in subpackages. package nullboot nullboot-0.5.0/efibootmgr/000077500000000000000000000000001453331565400155205ustar00rootroot00000000000000nullboot-0.5.0/efibootmgr/assets.go000066400000000000000000000176411453331565400173620ustar00rootroot00000000000000// This file is part of nullboot // Copyright 2021 Canonical Ltd. // SPDX-License-Identifier: GPL-3.0-only package efibootmgr import ( "bytes" "crypto" _ "crypto/sha256" // ensure that sha256 is linked in "encoding/json" "errors" "fmt" "io" "os" "path/filepath" ) const ( hashBlockSize = 4096 trustedAssetsPath = "/var/lib/nullboot/assets" ) func computeRootHash(alg crypto.Hash, hashes [][]byte) []byte { if len(hashes) == 0 { panic("no hashes supplied!") } for len(hashes) != 1 { // Loop until we get to a single hash var next [][]byte for len(hashes) > 0 { // Loop whilst we still have hashes var block [hashBlockSize]byte for i := 0; hashBlockSize-i >= alg.Size() && len(hashes) > 0; i += alg.Size() { // Loop until we've filled a block or run out of hashes. copy(block[i:], hashes[0]) hashes = hashes[1:] } // Hash the current block and save it for the next // outer loop iteration. h := alg.New() h.Write(block[:]) next = append(next, h.Sum(nil)) } // Process the hashes created on this loop iteration hashes = next } return hashes[0] } type hashAlg struct { crypto.Hash } func (a hashAlg) MarshalJSON() ([]byte, error) { var s string switch a.Hash { case crypto.SHA256: s = "sha256" //case crypto.SHA384: // s = "sha384" //case crypto.SHA512: // s = "sha512" default: return nil, fmt.Errorf("unsupported hash algorithm: %v", a.Hash) } return json.Marshal(s) } func (a *hashAlg) UnmarshalJSON(b []byte) error { var s string if err := json.Unmarshal(b, &s); err != nil { return err } switch s { case "sha256": a.Hash = crypto.SHA256 //case "sha384": // a.Hash = crypto.SHA384 //case "sha512": // a.Hash = crypto.SHA512 default: return fmt.Errorf("unsupported hash algorithm: %s", s) } return nil } type loadedTrustedAssets struct { Alg hashAlg `json:"alg"` Hashes [][]byte `json:"hashes"` } // TrustedAssets keeps a record of boot asset hashes that are trusted for the // purpose of computing PCR profiles. New hashes are added by adding a directory // that is trusted using TrustNewFromDir - the directory will be one inside the // encrypted container, writable by root and managed by the package manager). // // Boot assets may be copied outside of a trusted directory, eg, to the ESP. // Assets loaded from outside of a trusted directory in order to compute a PCR // profile must be checked against one of the trusted hashes, to avoid tricking // the resealing code into adding a malicious asset to a PCR profile. // // Snapd achieves the same thing by keeping a cache of trusted assets inside // the encrypted data partition. This avoids having to do that. // // Note that the hashes are not constructed by hashing the file contents in // a single pass, as this would require keeping entire PE images in memory // after verifying their hashes in order to avoid TOCTOU type bugs. Files // are hashed by producing a hash tree with a 4k block size. If a file's // size is not a multiple of 4k, the last block is padded with zeros. // // The hash tree is not stored anywhere - only the root hash is stored. // In order to verify that a file's contents are trusted, the leaf hashes // are constructed when the file is read and then closed (see hashedFile) // and the rest of the hash tree is reconstructed by calling checkLeafHashes. // In order to verify any blocks, the entire file has to eventually be read // in order to reconstruct the entire hash tree. This is a tradeoff between // having to read an entire file in order to verify a few blocks, and not // having to read an entire file in order to verify a few blocks, but having // to store the entire hash tree somewhere. // // Use newCheckedHashedFile to have a file checked against the set of trusted // boot assets. type TrustedAssets struct { loaded loadedTrustedAssets newAssets [][]byte } func (t *TrustedAssets) alg() crypto.Hash { return t.loaded.Alg.Hash } func (t *TrustedAssets) checkLeafHashes(hashes [][]byte) bool { d := computeRootHash(t.alg(), hashes) for _, a := range t.loaded.Hashes { if bytes.Equal(d, a) { return true } } return false } func (t *TrustedAssets) maybeAddHash(d []byte) { for _, a := range t.loaded.Hashes { if bytes.Equal(d, a) { return } } t.loaded.Hashes = append(t.loaded.Hashes, d) } func (t *TrustedAssets) trustLeafHashes(hashes [][]byte) { d := computeRootHash(t.alg(), hashes) t.maybeAddHash(d) t.newAssets = append(t.newAssets, d) } func (t *TrustedAssets) trustFile(path string) error { f, err := appFs.Open(path) if err != nil { return err } defer f.Close() var hashes [][]byte h := t.alg().New() for { var block [hashBlockSize]byte _, err := io.ReadFull(f, block[:]) if err == io.EOF { break } if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) { return err } h.Reset() h.Write(block[:]) hashes = append(hashes, h.Sum(nil)) if err != nil { break } } t.trustLeafHashes(hashes) return nil } func (t *TrustedAssets) trustDir(path string) error { dirents, err := appFs.ReadDir(path) if err != nil { return err } for _, e := range dirents { p := filepath.Join(path, e.Name()) if err := t.trustPath(p); err != nil { return fmt.Errorf("cannot process path %s: %w", p, err) } } return nil } func (t *TrustedAssets) trustPath(path string) error { fi, err := appFs.Stat(path) if err != nil { return err } if fi.IsDir() { return t.trustDir(path) } return t.trustFile(path) } // TrustNewFromDir adds hashes of the files under the specified path to the list // of trusted hashes for the purpose of computing PCR profiles. The path should // be within the encrypted container, writable only by root and managed by the // package manager. func (t *TrustedAssets) TrustNewFromDir(path string) error { if !filepath.IsAbs(path) { return errors.New("path is not absolute") } return t.trustDir(filepath.Clean(path)) } // RemoveObsolete drops all asset hashes that haven't been added in this context // via a call to TrustNewFromDir. This should be called after newly trusted assets // have been properly committed and obsolete assets have been removed. func (t *TrustedAssets) RemoveObsolete() { t.loaded.Hashes = nil for _, d := range t.newAssets { t.maybeAddHash(d) } } // Save persists the list of trusted hashes to disk. func (t *TrustedAssets) Save() (err error) { if err := appFs.MkdirAll(filepath.Dir(trustedAssetsPath), 0600); err != nil { return fmt.Errorf("cannot make directory: %v", err) } f, err := appFs.TempFile(filepath.Dir(trustedAssetsPath), "."+filepath.Base(trustedAssetsPath)+".") if err != nil { return err } defer func() { name := f.Name() f.Close() if err == nil { return } os.Remove(name) }() if err := json.NewEncoder(f).Encode(t.loaded); err != nil { return err } return appFs.Rename(f.Name(), trustedAssetsPath) } func newTrustedAssets() *TrustedAssets { return &TrustedAssets{loaded: loadedTrustedAssets{Alg: hashAlg{Hash: crypto.SHA256}}} } // ReadTrustedAssets loads the list of previously trusted hashes from // disk. func ReadTrustedAssets() (*TrustedAssets, error) { f, err := appFs.Open(trustedAssetsPath) switch { case os.IsNotExist(err): // Ignore this. return newTrustedAssets(), nil case err != nil: return nil, err } defer f.Close() assets := new(TrustedAssets) if err := json.NewDecoder(f).Decode(&assets.loaded); err != nil { return nil, err } if !assets.loaded.Alg.Available() { return nil, fmt.Errorf("digest algorithm %v is not available", assets.loaded.Alg) } return assets, nil } // newCheckedHashedFile wraps a file handle and calls the supplied // closeNotify callback when the file is closed with an indication // as to whether the file's contents are included in the supplied set // of trusted boot assets func newCheckedHashedFile(f File, assets *TrustedAssets, closeNotify func(bool)) (*hashedFile, error) { return newHashedFile(f, assets.alg(), func(leafHashes [][]byte) { closeNotify(assets.checkLeafHashes(leafHashes)) }) } nullboot-0.5.0/efibootmgr/assets_test.go000066400000000000000000000164521453331565400204200ustar00rootroot00000000000000// This file is part of nullboot // Copyright 2021 Canonical Ltd. // SPDX-License-Identifier: GPL-3.0-only package efibootmgr import ( "crypto" "gopkg.in/check.v1" ) type assetsSuite struct { mapFsMixin } var _ = check.Suite(&assetsSuite{}) func (s *assetsSuite) TestNewTrustedAssets(c *check.C) { assets := newTrustedAssets() c.Check(assets, check.NotNil) c.Check(assets.loaded.Alg, check.Equals, hashAlg{Hash: crypto.SHA256}) c.Check(assets.loaded.Hashes, check.DeepEquals, [][]byte(nil)) c.Check(assets.newAssets, check.DeepEquals, [][]byte(nil)) } func (s *assetsSuite) TestReadTrustedAssets(c *check.C) { payload := []byte(` { "alg": "sha256", "hashes": [ "tbudgBSg+bHWHiHnlteNzN8TUvI80ygS9IULh4rklEw=", "fYZelZskZpGMmGOvypQtD7idfJrAyZuvw3SVBN7ZdzA=" ] }`) c.Check(s.fs.WriteFile(trustedAssetsPath, payload, 0644), check.IsNil) assets, err := ReadTrustedAssets() c.Assert(err, check.IsNil) c.Check(assets.loaded.Alg, check.Equals, hashAlg{Hash: crypto.SHA256}) c.Check(assets.loaded.Hashes, check.DeepEquals, [][]byte{ decodeHexString(c, "b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c"), decodeHexString(c, "7d865e959b2466918c9863afca942d0fb89d7c9ac0c99bafc3749504ded97730"), }) c.Check(assets.newAssets, check.DeepEquals, [][]byte(nil)) } func (s *assetsSuite) TestReadTrustedAssetsNoFile(c *check.C) { assets, err := ReadTrustedAssets() c.Assert(err, check.IsNil) c.Check(assets.loaded.Alg, check.Equals, hashAlg{Hash: crypto.SHA256}) c.Check(assets.loaded.Hashes, check.DeepEquals, [][]byte(nil)) c.Check(assets.newAssets, check.DeepEquals, [][]byte(nil)) } func (s *assetsSuite) TestReadTrustedAssetsMissingAlg(c *check.C) { payload := []byte(` { "hashes": [ "tbudgBSg+bHWHiHnlteNzN8TUvI80ygS9IULh4rklEw=", "fYZelZskZpGMmGOvypQtD7idfJrAyZuvw3SVBN7ZdzA=" ] }`) c.Check(s.fs.WriteFile(trustedAssetsPath, payload, 0644), check.IsNil) _, err := ReadTrustedAssets() c.Assert(err, check.ErrorMatches, "digest algorithm unknown hash value 0 is not available") } func (s *assetsSuite) TestReadTrustedAssetsInvalidAlg(c *check.C) { payload := []byte(` { "alg": "foo", "hashes": [ "tbudgBSg+bHWHiHnlteNzN8TUvI80ygS9IULh4rklEw=", "fYZelZskZpGMmGOvypQtD7idfJrAyZuvw3SVBN7ZdzA=" ] }`) c.Check(s.fs.WriteFile(trustedAssetsPath, payload, 0644), check.IsNil) _, err := ReadTrustedAssets() c.Assert(err, check.ErrorMatches, "unsupported hash algorithm: foo") } func (s *assetsSuite) TestTrustNewFromDir(c *check.C) { // Write some files with a repeating payload to test file hashing - the // payload size is selected to not repeat on block boundaries and not // produce a total size that is a multiple of the block size (to test // the padding behaviour). // Write a file that is just under 10 blocks long to produce a hash tree // with a depth of 2. s.writeFile(c, "/foo/1", 0, 199, 200) // Write a file that is just over 170 blocks long to produce a hash tree // with a depth of 3. The middle level of the tree has 2 blocks, with the // last block only partially filled. s.writeFile(c, "/foo/2", 0, 199, 3500) assets, err := ReadTrustedAssets() c.Assert(err, check.IsNil) assets.loaded.Hashes = [][]byte{ decodeHexString(c, "b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c"), decodeHexString(c, "7d865e959b2466918c9863afca942d0fb89d7c9ac0c99bafc3749504ded97730"), } c.Check(assets.TrustNewFromDir("/foo"), check.IsNil) c.Check(assets.loaded.Hashes, check.DeepEquals, [][]byte{ decodeHexString(c, "b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c"), decodeHexString(c, "7d865e959b2466918c9863afca942d0fb89d7c9ac0c99bafc3749504ded97730"), decodeHexString(c, "73e60cb7e2d9c8ba47a507c647f9b388900f5a5dc33c24d4a95f84f4dd85dcec"), decodeHexString(c, "6c05c5017b4e584ce0e4e77b42e7399c0392407216803f24233def5c038adc7c"), }) c.Check(assets.newAssets, check.DeepEquals, [][]byte{ decodeHexString(c, "73e60cb7e2d9c8ba47a507c647f9b388900f5a5dc33c24d4a95f84f4dd85dcec"), decodeHexString(c, "6c05c5017b4e584ce0e4e77b42e7399c0392407216803f24233def5c038adc7c"), }) } func (s *assetsSuite) TestTrustNewFromDirDeDup(c *check.C) { c.Check(s.fs.WriteFile("/foo/1", []byte("some contents"), 0644), check.IsNil) assets, err := ReadTrustedAssets() c.Assert(err, check.IsNil) assets.loaded.Hashes = [][]byte{ decodeHexString(c, "b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c"), decodeHexString(c, "7d865e959b2466918c9863afca942d0fb89d7c9ac0c99bafc3749504ded97730"), decodeHexString(c, "8c3bb60fb858eccd3e85ba8fd3a85d9014f468defbdf6bc0c46891b2049eca46"), } c.Check(assets.TrustNewFromDir("/foo"), check.IsNil) c.Check(assets.loaded.Hashes, check.DeepEquals, [][]byte{ decodeHexString(c, "b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c"), decodeHexString(c, "7d865e959b2466918c9863afca942d0fb89d7c9ac0c99bafc3749504ded97730"), decodeHexString(c, "8c3bb60fb858eccd3e85ba8fd3a85d9014f468defbdf6bc0c46891b2049eca46"), }) c.Check(assets.newAssets, check.DeepEquals, [][]byte{ decodeHexString(c, "8c3bb60fb858eccd3e85ba8fd3a85d9014f468defbdf6bc0c46891b2049eca46"), }) } func (s *assetsSuite) TestRemoveObsolete(c *check.C) { assets, err := ReadTrustedAssets() c.Assert(err, check.IsNil) assets.loaded.Hashes = [][]byte{ decodeHexString(c, "b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c"), decodeHexString(c, "7d865e959b2466918c9863afca942d0fb89d7c9ac0c99bafc3749504ded97730"), decodeHexString(c, "73e60cb7e2d9c8ba47a507c647f9b388900f5a5dc33c24d4a95f84f4dd85dcec"), decodeHexString(c, "6c05c5017b4e584ce0e4e77b42e7399c0392407216803f24233def5c038adc7c"), } assets.newAssets = [][]byte{ decodeHexString(c, "73e60cb7e2d9c8ba47a507c647f9b388900f5a5dc33c24d4a95f84f4dd85dcec"), decodeHexString(c, "6c05c5017b4e584ce0e4e77b42e7399c0392407216803f24233def5c038adc7c"), decodeHexString(c, "6c05c5017b4e584ce0e4e77b42e7399c0392407216803f24233def5c038adc7c"), } assets.RemoveObsolete() c.Check(assets.loaded.Hashes, check.DeepEquals, [][]byte{ decodeHexString(c, "73e60cb7e2d9c8ba47a507c647f9b388900f5a5dc33c24d4a95f84f4dd85dcec"), decodeHexString(c, "6c05c5017b4e584ce0e4e77b42e7399c0392407216803f24233def5c038adc7c"), }) c.Check(assets.newAssets, check.DeepEquals, [][]byte{ decodeHexString(c, "73e60cb7e2d9c8ba47a507c647f9b388900f5a5dc33c24d4a95f84f4dd85dcec"), decodeHexString(c, "6c05c5017b4e584ce0e4e77b42e7399c0392407216803f24233def5c038adc7c"), decodeHexString(c, "6c05c5017b4e584ce0e4e77b42e7399c0392407216803f24233def5c038adc7c"), }) } func (s *assetsSuite) TestSave(c *check.C) { assets, err := ReadTrustedAssets() c.Assert(err, check.IsNil) assets.loaded.Hashes = [][]byte{ decodeHexString(c, "b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c"), decodeHexString(c, "7d865e959b2466918c9863afca942d0fb89d7c9ac0c99bafc3749504ded97730"), decodeHexString(c, "73e60cb7e2d9c8ba47a507c647f9b388900f5a5dc33c24d4a95f84f4dd85dcec"), decodeHexString(c, "6c05c5017b4e584ce0e4e77b42e7399c0392407216803f24233def5c038adc7c"), } c.Check(assets.Save(), check.IsNil) data, err := s.fs.ReadFile(trustedAssetsPath) c.Check(err, check.IsNil) c.Check(data, check.DeepEquals, []byte(`{"alg":"sha256","hashes":["tbudgBSg+bHWHiHnlteNzN8TUvI80ygS9IULh4rklEw=","fYZelZskZpGMmGOvypQtD7idfJrAyZuvw3SVBN7ZdzA=","c+YMt+LZyLpHpQfGR/mziJAPWl3DPCTUqV+E9N2F3Ow=","bAXFAXtOWEzg5Od7Quc5nAOSQHIWgD8kIz3vXAOK3Hw="]} `)) } nullboot-0.5.0/efibootmgr/bootmgr.go000066400000000000000000000161761453331565400175330ustar00rootroot00000000000000// This file is part of nullboot // Copyright 2021 Canonical Ltd. // SPDX-License-Identifier: GPL-3.0-only // Package efibootmgr contains a boot management library package efibootmgr import ( "bytes" "encoding/binary" "fmt" "log" "path" "github.com/canonical/go-efilib" efi_linux "github.com/canonical/go-efilib/linux" ) const ( maxBootEntries = 65535 // Maximum number of boot entries we can hold ) // BootEntryVariable defines a boot entry variable type BootEntryVariable struct { BootNumber int // number of the Boot variable, for example, for Boot0004 this is 4 Data []byte // the data of the variable Attributes efi.VariableAttributes // any attributes set on the variable LoadOption *efi.LoadOption // the data of the variable parsed as a load option, if it is a valid load option } // BootManager manages the boot device selection menu entries (Boot0000...BootFFFF). type BootManager struct { efivars EFIVariables // EFIVariables implementation entries map[int]BootEntryVariable // The Boot variables bootOrder []int // The BootOrder variable, parsed bootOrderAttrs efi.VariableAttributes // The attributes of BootOrder variable } // NewBootManagerFromSystem returns a new BootManager object, initialized with the system state. func NewBootManagerFromSystem() (BootManager, error) { return NewBootManagerForVariables(RealEFIVariables{}) } // NewBootManagerForVariables returns a boot manager for the given EFIVariables manager func NewBootManagerForVariables(efivars EFIVariables) (BootManager, error) { var err error bm := BootManager{} bm.efivars = efivars if !VariablesSupported(efivars) { return BootManager{}, fmt.Errorf("Variables not supported") } bootOrderBytes, bootOrderAttrs, err := bm.efivars.GetVariable(efi.GlobalVariable, "BootOrder") if err != nil { log.Println("Could not read BootOrder variable, populating with default, error was:", err) bootOrderBytes = nil bootOrderAttrs = efi.AttributeNonVolatile | efi.AttributeBootserviceAccess | efi.AttributeRuntimeAccess } bm.bootOrder = make([]int, len(bootOrderBytes)/2) bm.bootOrderAttrs = bootOrderAttrs for i := 0; i < len(bootOrderBytes); i += 2 { // FIXME: It's probably not valid to assume little-endian here? bm.bootOrder[i/2] = int(binary.LittleEndian.Uint16(bootOrderBytes[i : i+2])) } bm.entries = make(map[int]BootEntryVariable) names, err := GetVariableNames(bm.efivars, efi.GlobalVariable) if err != nil { return BootManager{}, fmt.Errorf("cannot obtain list of global variables: %v", err) } for _, name := range names { var entry BootEntryVariable if parsed, err := fmt.Sscanf(name, "Boot%04X", &entry.BootNumber); len(name) != 8 || parsed != 1 || err != nil { continue } entry.Data, entry.Attributes, err = bm.efivars.GetVariable(efi.GlobalVariable, name) if err != nil { return BootManager{}, fmt.Errorf("cannot read %s: %v", name, err) } entry.LoadOption, err = efi.ReadLoadOption(bytes.NewReader(entry.Data)) if err != nil { log.Printf("Invalid boot entry Boot%04X: %s\n", entry.BootNumber, err) } bm.entries[entry.BootNumber] = entry } return bm, nil } // NextFreeEntry returns the number of the next free Boot variable. func (bm *BootManager) NextFreeEntry() (int, error) { for i := 0; i < maxBootEntries; i++ { if _, ok := bm.entries[i]; !ok { return i, nil } } return -1, fmt.Errorf("Maximum number of boot entries exceeded") } // FindOrCreateEntry finds a matching entry in the boot device selection menu, // or creates one if it is missing. // // It returns the number of the entry created, or -1 on failure, with error set. // // The argument relativeTo specifies the directory entry.Filename is in. func (bm *BootManager) FindOrCreateEntry(entry BootEntry, relativeTo string) (int, error) { bootNext, err := bm.NextFreeEntry() if err != nil { return -1, err } variable := fmt.Sprintf("Boot%04X", bootNext) dp, err := bm.efivars.NewFileDevicePath(path.Join(relativeTo, entry.Filename), efi_linux.ShortFormPathHD) if err != nil { return -1, err } optionalData := new(bytes.Buffer) binary.Write(optionalData, binary.LittleEndian, efi.ConvertUTF8ToUCS2(entry.Options+"\x00")) loadoption := &efi.LoadOption{ Attributes: efi.LoadOptionActive, Description: entry.Label, FilePath: dp, OptionalData: optionalData.Bytes()} loadoptionBytes, err := loadoption.Bytes() if err != nil { return -1, fmt.Errorf("cannot encode load option: %v", err) } entryVar := BootEntryVariable{ BootNumber: bootNext, Data: loadoptionBytes, Attributes: efi.AttributeNonVolatile | efi.AttributeBootserviceAccess | efi.AttributeRuntimeAccess, LoadOption: loadoption, } // Detect duplicates and ignore for _, existingVar := range bm.entries { if bytes.Equal(existingVar.Data, entryVar.Data) && existingVar.Attributes == entryVar.Attributes { return existingVar.BootNumber, nil } } if err := bm.efivars.SetVariable(efi.GlobalVariable, variable, entryVar.Data, entryVar.Attributes); err != nil { return -1, err } bm.entries[bootNext] = entryVar return bootNext, nil } // DeleteEntry deletes an entry and updates the cached boot order. // // The boot order still needs to be committed afterwards. It is not written back immediately, // as there will usually be multiple places to update boot order, and we can coalesce those // writes. We still have to update the boot order though, such that when we delete an entry // and then create a new one with the same number we don't accidentally have the new one in // the order. func (bm *BootManager) DeleteEntry(bootNum int) error { variable := fmt.Sprintf("Boot%04X", bootNum) if _, ok := bm.entries[bootNum]; !ok { return fmt.Errorf("Tried deleting a non-existing variable %s", variable) } if err := DelVariable(bm.efivars, efi.GlobalVariable, variable); err != nil { return err } delete(bm.entries, bootNum) var newOrder []int for _, orderEntry := range bm.bootOrder { if orderEntry != bootNum { newOrder = append(newOrder, orderEntry) } } bm.bootOrder = newOrder return nil } // PrependAndSetBootOrder commits a new boot order or returns an error. // // The boot order specified is prepended to the existing one, and the order // is deduplicated before committing. func (bm *BootManager) PrependAndSetBootOrder(head []int) error { var newOrder []int // Combine head with existing boot order, filter out duplicates and non-existing entries for _, num := range append(append([]int(nil), head...), bm.bootOrder...) { isDuplicate := false for _, otherNum := range newOrder { if otherNum == num { isDuplicate = true } } if _, ok := bm.entries[num]; ok && !isDuplicate { newOrder = append(newOrder, num) } } // Encode the boot order to bytes var output []byte for _, num := range newOrder { var numBytes [2]byte binary.LittleEndian.PutUint16(numBytes[0:], uint16(num)) output = append(output, numBytes[0], numBytes[1]) } // Set the boot order and update our cache if err := bm.efivars.SetVariable(efi.GlobalVariable, "BootOrder", output, bm.bootOrderAttrs); err != nil { return err } bm.bootOrder = newOrder return nil } nullboot-0.5.0/efibootmgr/bootmgr_test.go000066400000000000000000000237321453331565400205660ustar00rootroot00000000000000// This file is part of nullboot // Copyright 2021 Canonical Ltd. // SPDX-License-Identifier: GPL-3.0-only package efibootmgr import ( "bytes" "encoding/json" "reflect" "testing" "github.com/canonical/go-efilib" "github.com/spf13/afero" ) func TestBootManager_mocked(t *testing.T) { memFs := afero.NewMemMapFs() appFs = MapFS{memFs} afero.WriteFile(memFs, "path", []byte("file a"), 0644) afero.WriteFile(memFs, "path2", []byte("file b"), 0644) mockvars := MockEFIVariables{ map[efi.VariableDescriptor]mockEFIVariable{ {GUID: efi.GlobalVariable, Name: "BootOrder"}: {[]byte{1, 0, 2, 0, 3, 0}, 123}, {GUID: efi.GlobalVariable, Name: "Boot0001"}: {UsbrBootCdromOptBytes, 42}, }, } bm, err := NewBootManagerForVariables(&mockvars) if err != nil { t.Fatalf("Unexpected error: %v", err) } if len(bm.entries) != 1 { t.Fatalf("Could not parse an entry") } if want := []int{1, 2, 3}; !reflect.DeepEqual(bm.bootOrder, want) { t.Fatalf("Expected %v, got: %v", want, bm.bootOrder) } want := BootEntryVariable{1, UsbrBootCdromOptBytes, 42, UsbrBootCdromOpt} if !reflect.DeepEqual(bm.entries[1], want) { t.Fatalf("\n"+ "expected: %+v\n"+ "got: %+v", want, bm.entries[1]) } // This creates entry Boot0000 got, err := bm.FindOrCreateEntry(BootEntry{Filename: "path", Label: "desc", Options: "arg1 arg2"}, "") if err != nil { t.Fatalf("could not create next boot entry, error: %v", err) } if want := 0; got != want { t.Fatalf("expected to create Boot%04X, created Boot%04X", want, got) } boot0000, ok := mockvars.store[efi.VariableDescriptor{GUID: efi.GlobalVariable, Name: "Boot0000"}] if !ok { t.Fatal("Variable Boot0000 does not exist") } if want := efi.AttributeNonVolatile | efi.AttributeBootserviceAccess | efi.AttributeRuntimeAccess; want != boot0000.attrs { t.Fatalf("Expected attributes %v, got %v", want, boot0000.attrs) } optGot, err := efi.ReadLoadOption(bytes.NewReader(boot0000.data)) if err != nil { t.Fatalf("Cannot decode load option: %v", err) } descGot := optGot.Description if want := "desc"; want != descGot { t.Fatalf("Expected desc %v, got %v", want, descGot) } // This is our mock path pathGot := optGot.FilePath if want := (efi.DevicePath{efi.NewFilePathDevicePathNode("path")}); !reflect.DeepEqual(want, pathGot) { t.Fatalf("Expected path %v, got %v", want, pathGot) } // This creates entry Boot0002 got, err = bm.FindOrCreateEntry(BootEntry{Filename: "path2", Label: "desc2", Options: "arg3 arg4"}, "") if want := 2; got != want { t.Fatalf("expected to create Boot%04X, created Boot%04X", want, got) } if err != nil { t.Fatalf("could not create next boot entry, error: %v", err) } boot0002, ok := mockvars.store[efi.VariableDescriptor{GUID: efi.GlobalVariable, Name: "Boot0002"}] if !ok { t.Fatal("Variable Boot0002 does not exist") } if want := efi.AttributeNonVolatile | efi.AttributeBootserviceAccess | efi.AttributeRuntimeAccess; want != boot0002.attrs { t.Fatalf("Expected attributes %v, got %v", want, boot0002.attrs) } optGot, err = efi.ReadLoadOption(bytes.NewReader(boot0002.data)) if err != nil { t.Fatalf("Cannot decode load option: %v", err) } descGot = optGot.Description if want := "desc2"; want != descGot { t.Fatalf("Expected desc %v, got %v", want, descGot) } // This is our mock path pathGot = optGot.FilePath if want := (efi.DevicePath{efi.NewFilePathDevicePathNode("path2")}); !reflect.DeepEqual(want, pathGot) { t.Fatalf("Expected path %v, got %v", want, pathGot) } // Check that the existing entry is not recreated got, err = bm.FindOrCreateEntry(BootEntry{Filename: "path2", Label: "desc2", Options: "arg3 arg4"}, "") if want := 2; got != want { t.Fatalf("expected to create Boot%04X, created Boot%04X", want, got) } if err != nil { t.Fatalf("could not create next boot entry, error: %v", err) } } func TestBootManagerDeleteEntry(t *testing.T) { mockvars := MockEFIVariables{ map[efi.VariableDescriptor]mockEFIVariable{ {GUID: efi.GlobalVariable, Name: "BootOrder"}: {[]byte{1, 0, 2, 0, 3, 0}, 123}, {GUID: efi.GlobalVariable, Name: "Boot0001"}: {UsbrBootCdromOptBytes, 42}, {GUID: efi.GlobalVariable, Name: "Boot0002"}: {UsbrBootCdromOptBytes, 43}, }, } bm, err := NewBootManagerForVariables(&mockvars) if err != nil { t.Fatalf("Could not create boot manager: %v", err) } if err := bm.DeleteEntry(1); err != nil { t.Errorf("Expected successful deletion, got %v", err) } if !reflect.DeepEqual(bm.bootOrder, []int{2, 3}) { t.Errorf("Expected boot order to be 2, 3 got %v", bm.bootOrder) } if !bytes.Equal(mockvars.store[efi.VariableDescriptor{GUID: efi.GlobalVariable, Name: "BootOrder"}].data, []byte{1, 0, 2, 0, 3, 0}) { t.Errorf("Expected actual boot order to not be changed, got %v.", mockvars.store[efi.VariableDescriptor{GUID: efi.GlobalVariable, Name: "BootOrder"}]) } if err := bm.DeleteEntry(1); err == nil { t.Errorf("Expected failure in deletion") } delete(mockvars.store, efi.VariableDescriptor{GUID: efi.GlobalVariable, Name: "Boot0002"}) if err := bm.DeleteEntry(2); err == nil { t.Errorf("Expected failure in deletion") } } func TestBootManagerSetBootOrder(t *testing.T) { mockvars := MockEFIVariables{ map[efi.VariableDescriptor]mockEFIVariable{ {GUID: efi.GlobalVariable, Name: "BootOrder"}: {[]byte{1, 0, 2, 0, 3, 0}, 123}, {GUID: efi.GlobalVariable, Name: "Boot0001"}: {UsbrBootCdromOptBytes, 42}, {GUID: efi.GlobalVariable, Name: "Boot0002"}: {UsbrBootCdromOptBytes, 43}, }, } bm, err := NewBootManagerForVariables(&mockvars) if err != nil { t.Fatalf("Could not create boot manager: %v", err) } if err := bm.PrependAndSetBootOrder([]int{2}); err != nil { t.Errorf("Failed to commit boot order: %v", err) } if !reflect.DeepEqual(bm.bootOrder, []int{2, 1}) { t.Errorf("Expected boot order to be 2, 1 got %v", bm.bootOrder) } if !bytes.Equal(mockvars.store[efi.VariableDescriptor{GUID: efi.GlobalVariable, Name: "BootOrder"}].data, []byte{2, 0, 1, 0}) { t.Errorf("Expected actual boot order to not be changed, got %v.", mockvars.store[efi.VariableDescriptor{GUID: efi.GlobalVariable, Name: "BootOrder"}]) } } func TestBootManager_json(t *testing.T) { memFs := afero.NewMemMapFs() appFs = MapFS{memFs} afero.WriteFile(memFs, "/boot/efi/path", []byte("file a"), 0644) afero.WriteFile(memFs, "/boot/efi/path2", []byte("file b"), 0644) mockvars := MockEFIVariables{ map[efi.VariableDescriptor]mockEFIVariable{}, } bm, err := NewBootManagerForVariables(&mockvars) if err != nil { t.Fatalf("Unexpected error: %v", err) } // This creates entry Boot0000 got, err := bm.FindOrCreateEntry(BootEntry{Filename: "/boot/efi/path", Label: "desc", Options: "arg1 arg2"}, "") boot0000, ok := mockvars.store[efi.VariableDescriptor{GUID: efi.GlobalVariable, Name: "Boot0000"}] if !ok { t.Fatal("Variable Boot0000 does not exist") } if want := efi.AttributeNonVolatile | efi.AttributeBootserviceAccess | efi.AttributeRuntimeAccess; want != boot0000.attrs { t.Fatalf("Expected attributes %v, got %v", want, boot0000.attrs) } optGot, err := efi.ReadLoadOption(bytes.NewReader(boot0000.data)) if err != nil { t.Fatalf("Cannot decode load option: %v", err) } descGot := optGot.Description if want := "desc"; want != descGot { t.Fatalf("Expected desc %v, got %v", want, descGot) } // This is our mock path pathGot := optGot.FilePath if want := (efi.DevicePath{efi.NewFilePathDevicePathNode("/path")}); !reflect.DeepEqual(want, pathGot) { t.Fatalf("Expected path %v, got %v", want, pathGot) } // This creates entry Boot0001 got, err = bm.FindOrCreateEntry(BootEntry{Filename: "/boot/efi/path2", Label: "desc2", Options: "arg3 arg4"}, "") if want := 1; got != want { t.Fatalf("expected to create Boot%04X, created Boot%04X", want, got) } if err != nil { t.Fatalf("could not create next boot entry, error: %v", err) } boot0001, ok := mockvars.store[efi.VariableDescriptor{GUID: efi.GlobalVariable, Name: "Boot0001"}] if !ok { t.Fatal("Variable Boot0002 does not exist") } if want := efi.AttributeNonVolatile | efi.AttributeBootserviceAccess | efi.AttributeRuntimeAccess; want != boot0001.attrs { t.Fatalf("Expected attributes %v, got %v", want, boot0001.attrs) } optGot, err = efi.ReadLoadOption(bytes.NewReader(boot0001.data)) if err != nil { t.Fatalf("Cannot decode load option: %v", err) } descGot = optGot.Description if want := "desc2"; want != descGot { t.Fatalf("Expected desc %v, got %v", want, descGot) } // This is our mock path pathGot = optGot.FilePath if want := (efi.DevicePath{efi.NewFilePathDevicePathNode("/path2")}); !reflect.DeepEqual(want, pathGot) { t.Fatalf("Expected path %v, got %v", want, pathGot) } if err := bm.PrependAndSetBootOrder([]int{0, 1}); err != nil { t.Errorf("Failed to commit boot order: %v", err) } if !reflect.DeepEqual(bm.bootOrder, []int{0, 1}) { t.Errorf("Expected boot order to be 0, 1 got %v", bm.bootOrder) } jsonBytes, err := mockvars.JSON() if err != nil { t.Fatalf("Expected JSON, received err %v", err) } want := map[string]map[string]string{ "Boot0000": { "attributes": "BwA=", "guid": "Yd/ki8qT0hGqDQDgmAMrjA==", "value": "AQAAABQAZABlAHMAYwAAAAQEEABcAHAAYQB0AGgAAAB//wQAYQByAGcAMQAgAGEAcgBnADIAAAA=", }, "Boot0001": { "attributes": "BwA=", "guid": "Yd/ki8qT0hGqDQDgmAMrjA==", "value": "AQAAABYAZABlAHMAYwAyAAAABAQSAFwAcABhAHQAaAAyAAAAf/8EAGEAcgBnADMAIABhAHIAZwA0AAAA", }, "BootOrder": { "attributes": "BwA=", "guid": "Yd/ki8qT0hGqDQDgmAMrjA==", "value": "AAABAA==", }, } gotJSON := make(map[string]map[string]string) if err := json.Unmarshal(jsonBytes, &gotJSON); err != nil { t.Fatalf("Unable to unmarshal JSON: %v", err) } if !reflect.DeepEqual(want, gotJSON) { t.Fatalf("Expected\n%v\ngot\n%v\nerr: %v", want, gotJSON, err) } } func TestBootManager_unsupported(t *testing.T) { mockvars := NoEFIVariables{} _, err := NewBootManagerForVariables(&mockvars) if err == nil { t.Fatalf("Unexpected success") } if err.Error() != "Variables not supported" { t.Fatalf("Unexpected error: %v", err) } } nullboot-0.5.0/efibootmgr/efibootmgr_test.go000066400000000000000000000007651453331565400212530ustar00rootroot00000000000000// This file is part of nullboot // Copyright 2021 Canonical Ltd. // SPDX-License-Identifier: GPL-3.0-only package efibootmgr import ( "encoding/hex" "testing" "gopkg.in/check.v1" ) func decodeHexStringT(t *testing.T, str string) []byte { h, err := hex.DecodeString(str) if err != nil { t.Fatal(err) } return h } func decodeHexString(c *check.C, str string) []byte { h, err := hex.DecodeString(str) c.Assert(err, check.IsNil) return h } func Test(t *testing.T) { check.TestingT(t) } nullboot-0.5.0/efibootmgr/efivars.go000066400000000000000000000116701453331565400175130ustar00rootroot00000000000000// This file is part of nullboot // Copyright 2021 Canonical Ltd. // SPDX-License-Identifier: GPL-3.0-only package efibootmgr import ( "encoding/base64" "encoding/binary" "encoding/json" "strings" //"errors" "github.com/canonical/go-efilib" efi_linux "github.com/canonical/go-efilib/linux" ) // EFIVariables abstracts away the host-specific bits of the efivars module type EFIVariables interface { ListVariables() ([]efi.VariableDescriptor, error) GetVariable(guid efi.GUID, name string) (data []byte, attrs efi.VariableAttributes, err error) SetVariable(guid efi.GUID, name string, data []byte, attrs efi.VariableAttributes) error NewFileDevicePath(filepath string, mode efi_linux.FileDevicePathMode) (efi.DevicePath, error) } // RealEFIVariables provides the real implementation of efivars type RealEFIVariables struct{} // ListVariables proxy func (RealEFIVariables) ListVariables() ([]efi.VariableDescriptor, error) { return efi.ListVariables() } // GetVariable proxy func (RealEFIVariables) GetVariable(guid efi.GUID, name string) (data []byte, attrs efi.VariableAttributes, err error) { return efi.ReadVariable(name, guid) } // SetVariable proxy func (RealEFIVariables) SetVariable(guid efi.GUID, name string, data []byte, attrs efi.VariableAttributes) error { return efi.WriteVariable(name, guid, attrs, data) } // NewFileDevicePath proxy func (RealEFIVariables) NewFileDevicePath(filepath string, mode efi_linux.FileDevicePathMode) (efi.DevicePath, error) { return efi_linux.NewFileDevicePath(filepath, mode) } type mockEFIVariable struct { data []byte attrs efi.VariableAttributes } // MockEFIVariables implements an in-memory variable store. type MockEFIVariables struct { store map[efi.VariableDescriptor]mockEFIVariable } // ListVariables implements EFIVariables func (m MockEFIVariables) ListVariables() (out []efi.VariableDescriptor, err error) { for k := range m.store { out = append(out, k) } return out, nil } // GetVariable implements EFIVariables func (m MockEFIVariables) GetVariable(guid efi.GUID, name string) (data []byte, attrs efi.VariableAttributes, err error) { out, ok := m.store[efi.VariableDescriptor{Name: name, GUID: guid}] if !ok { return nil, 0, efi.ErrVarNotExist } return out.data, out.attrs, nil } // SetVariable implements EFIVariables func (m *MockEFIVariables) SetVariable(guid efi.GUID, name string, data []byte, attrs efi.VariableAttributes) error { if m.store == nil { m.store = make(map[efi.VariableDescriptor]mockEFIVariable) } if len(data) == 0 { delete(m.store, efi.VariableDescriptor{Name: name, GUID: guid}) } else { m.store[efi.VariableDescriptor{Name: name, GUID: guid}] = mockEFIVariable{data, attrs} } return nil } // NewFileDevicePath implements EFIVariables func (m MockEFIVariables) NewFileDevicePath(filepath string, mode efi_linux.FileDevicePathMode) (efi.DevicePath, error) { file, err := appFs.Open(filepath) if err != nil { return nil, err } file.Close() const espLocation = "/boot/efi/" if strings.HasPrefix(filepath, espLocation) { filepath = filepath[len(espLocation):] } return efi.DevicePath{ efi.NewFilePathDevicePathNode(filepath), }, nil } // JSON renders the MockEFIVariables as an Azure JSON config func (m MockEFIVariables) JSON() ([]byte, error) { payload := make(map[string]map[string]string) var numBytes [2]byte for key, entry := range m.store { entryID := key.Name entryBase64 := base64.StdEncoding.EncodeToString(entry.data) guidBase64 := base64.StdEncoding.EncodeToString(key.GUID[0:]) binary.LittleEndian.PutUint16(numBytes[0:], uint16(entry.attrs)) entryAttrBase64 := base64.StdEncoding.EncodeToString(numBytes[0:]) payload[entryID] = map[string]string{ "guid": guidBase64, "attributes": entryAttrBase64, "value": entryBase64, } } return json.MarshalIndent(payload, "", " ") } // VariablesSupported indicates whether variables can be accessed. func VariablesSupported(efiVars EFIVariables) bool { _, err := efiVars.ListVariables() return err == nil } // GetVariableNames returns the names of every variable with the specified GUID. func GetVariableNames(efiVars EFIVariables, filterGUID efi.GUID) (names []string, err error) { vars, err := efiVars.ListVariables() if err != nil { return nil, err } for _, entry := range vars { if entry.GUID != filterGUID { continue } names = append(names, entry.Name) } return names, nil } // DelVariable deletes the non-authenticated variable with the specified name. func DelVariable(efivars EFIVariables, guid efi.GUID, name string) error { _, attrs, err := efivars.GetVariable(guid, name) if err != nil { return err } // XXX: Update tests to not set these attributes in mock variables //if attrs&(efi.AttributeAuthenticatedWriteAccess|efi.AttributeTimeBasedAuthenticatedWriteAccess|efi.AttributeEnhancedAuthenticatedAccess) != 0 { // return errors.New("variable must be deleted by setting an authenticated empty payload") //} return efivars.SetVariable(guid, name, nil, attrs) } nullboot-0.5.0/efibootmgr/efivars_test.go000066400000000000000000000026431453331565400205520ustar00rootroot00000000000000// This file is part of nullboot // Copyright 2021 Canonical Ltd. // SPDX-License-Identifier: GPL-3.0-only // This file does not contain actual tests, but contains mock implementations of EFIVariables package efibootmgr import ( "errors" "github.com/canonical/go-efilib" efi_linux "github.com/canonical/go-efilib/linux" ) type NoEFIVariables struct{} func (NoEFIVariables) ListVariables() ([]efi.VariableDescriptor, error) { return nil, efi.ErrVarsUnavailable } func (NoEFIVariables) GetVariable(guid efi.GUID, name string) ([]byte, efi.VariableAttributes, error) { return nil, 0, efi.ErrVarsUnavailable } func (NoEFIVariables) SetVariable(guid efi.GUID, name string, data []byte, attrs efi.VariableAttributes) error { return efi.ErrVarsUnavailable } func (NoEFIVariables) NewFileDevicePath(filepath string, mode efi_linux.FileDevicePathMode) (efi.DevicePath, error) { return nil, errors.New("Cannot access") } var ( UsbrBootCdromOpt = &efi.LoadOption{ Attributes: efi.LoadOptionActive | efi.LoadOptionHidden, Description: "USBR BOOT CDROM", FilePath: efi.DevicePath{ &efi.ACPIDevicePathNode{HID: 0x0a0341d0}, &efi.PCIDevicePathNode{Device: 0x14, Function: 0}, &efi.USBDevicePathNode{ParentPortNumber: 0xb, InterfaceNumber: 0x1}}, OptionalData: []byte{}} UsbrBootCdromOptBytes []byte ) func init() { var err error UsbrBootCdromOptBytes, err = UsbrBootCdromOpt.Bytes() if err != nil { panic(err) } } nullboot-0.5.0/efibootmgr/fs.go000066400000000000000000000102701453331565400164570ustar00rootroot00000000000000// This file is part of nullboot // Copyright 2021 Canonical Ltd. // SPDX-License-Identifier: GPL-3.0-only package efibootmgr import ( "bytes" "crypto/sha256" "fmt" "io" "io/ioutil" "os" "path/filepath" ) // File abstracts an open file. type File interface { io.Closer io.Writer io.Reader io.ReaderAt io.Seeker Name() string Stat() (os.FileInfo, error) } // FS abstracts away the filesystem. // // So we really wanted to use afero because it does all the magic for us, but it doubles // our binary size, so that seems a tad much. type FS interface { // Create behaves like os.Create() Create(path string) (File, error) // MkdirAll behaves like os.MkdirAll() MkdirAll(path string, perm os.FileMode) error // Open behaves like os.Open() Open(path string) (File, error) // ReadDir behaves like os.ReadDir() ReadDir(path string) ([]os.DirEntry, error) // Readlink behaves like os.Readlink() Readlink(path string) (string, error) // Remove behaves like os.Remove() Remove(path string) error // Rename behaves like os.Rename() Rename(oldname, newname string) error // Stat behaves like os.Stat() Stat(path string) (os.FileInfo, error) // TempFile behaves like ioutil.TempFile() TempFile(dir, prefix string) (File, error) } // realFS implements FS using the os package type realFS struct{} func (realFS) Create(path string) (File, error) { return os.Create(path) } func (realFS) MkdirAll(path string, perm os.FileMode) error { return os.MkdirAll(path, perm) } func (realFS) Open(path string) (File, error) { return os.Open(path) } func (realFS) ReadDir(path string) ([]os.DirEntry, error) { return os.ReadDir(path) } func (realFS) Readlink(path string) (string, error) { return os.Readlink(path) } func (realFS) Remove(path string) error { return os.Remove(path) } func (realFS) Rename(oldname, newname string) error { return os.Rename(oldname, newname) } func (realFS) Stat(path string) (os.FileInfo, error) { return os.Stat(path) } func (realFS) TempFile(dir, prefix string) (File, error) { return ioutil.TempFile(dir, prefix) } // appFs is our default FS var appFs FS = realFS{} // MaybeUpdateFile copies src to dest if they are different // It returns true if the destination file was successfully updated. If the return value // is false, the state of the destination is unspecified. It might not exist, exist // with partial data or exist with old data, amongst others. func MaybeUpdateFile(dst string, src string) (updated bool, err error) { srcFile, err := appFs.Open(src) if err != nil { return false, fmt.Errorf("Could not open source file: %w", err) } defer srcFile.Close() if needUpdate, err := needUpdateFile(dst, src, srcFile); !needUpdate { return false, err } dstFile, err := appFs.TempFile(filepath.Dir(dst), "."+filepath.Base(dst)+".") if err != nil { return false, fmt.Errorf("Could not open %s for writing: %w", dst, err) } defer func() { name := dstFile.Name() dstFile.Close() if err != nil { appFs.Remove(name) } }() if _, err := io.Copy(dstFile, srcFile); err != nil { return false, fmt.Errorf("Could not copy %s to %s: %w", src, dst, err) } if err := appFs.Rename(dstFile.Name(), dst); err != nil { return false, fmt.Errorf("cannot rename %s to %s: %w", dstFile.Name(), dst, err) } return true, nil } func needUpdateFile(dst string, src string, srcFile File) (bool, error) { // To keep things simple, but not have the files in memory, just hash them dstHash := sha256.New() srcHash := sha256.New() dstFile, err := appFs.Open(dst) if err != nil { if os.IsNotExist(err) { return true, nil } return false, fmt.Errorf("Could not open destination file: %w", err) } defer dstFile.Close() if _, err := io.Copy(dstHash, dstFile); err != nil { return false, fmt.Errorf("Could not hash destination file %s: %w", dst, err) } if _, err := io.Copy(srcHash, srcFile); err != nil { return false, fmt.Errorf("Could not hash source file %s: %w", src, err) } if bytes.Equal(dstHash.Sum(nil), srcHash.Sum(nil)) { return false, nil } if _, err := srcFile.Seek(0, io.SeekStart); err != nil { return false, fmt.Errorf("Could not seek in source file %s: %w", src, err) } return true, nil } nullboot-0.5.0/efibootmgr/fs_test.go000066400000000000000000000141441453331565400175220ustar00rootroot00000000000000// This file is part of nullboot // Copyright 2021 Canonical Ltd. // SPDX-License-Identifier: GPL-3.0-only package efibootmgr import ( "bytes" "errors" "fmt" "io" "os" "syscall" "testing" "github.com/spf13/afero" "github.com/spf13/afero/mem" "gopkg.in/check.v1" ) type MapFS struct { p afero.Fs } type dirEntry struct { os.FileInfo } func (d dirEntry) Info() (os.FileInfo, error) { return os.FileInfo(d), nil } func (d dirEntry) Type() os.FileMode { return d.Mode().Type() } func (m MapFS) Create(path string) (File, error) { return m.p.Create(path) } func (m MapFS) MkdirAll(path string, perm os.FileMode) error { return m.p.MkdirAll(path, perm) } func (m MapFS) Open(path string) (File, error) { return m.p.Open(path) } func (m MapFS) ReadDir(path string) ([]os.DirEntry, error) { var out []os.DirEntry fis, err := afero.ReadDir(m.p, path) if err != nil { return nil, err } for _, fi := range fis { out = append(out, dirEntry{fi}) } return out, nil } func (m MapFS) Readlink(path string) (target string, err error) { defer func() { fmt.Println("readlink path:", path, "target:", target, "err:", err) var e *os.PathError if errors.As(err, &e) && e.Op != "readlink" { err = &os.PathError{Op: "readlink", Path: path, Err: e.Err} } }() fi, err := m.p.Stat(path) if err != nil { return "", err } if fi.Mode()&os.ModeSymlink == 0 { return "", &os.PathError{Op: "readlink", Path: path, Err: syscall.EINVAL} } tgt, err := afero.ReadFile(m.p, path) return string(tgt), err } func (m MapFS) Remove(path string) error { return m.p.Remove(path) } func (m MapFS) Rename(oldname, newname string) error { return m.p.Rename(oldname, newname) } func (m MapFS) Stat(path string) (os.FileInfo, error) { return m.p.Stat(path) } func (m MapFS) TempFile(dir, prefix string) (File, error) { return afero.TempFile(m.p, dir, prefix) } type mapFsMixin struct { restoreFs func() fs afero.Afero } func (m *mapFsMixin) SetUpTest(c *check.C) { m.restoreFs = m.mockFs(afero.NewMemMapFs()) } func (m *mapFsMixin) TearDownTest(c *check.C) { if m.restoreFs != nil { m.restoreFs() m.restoreFs = nil } } func (m *mapFsMixin) mockFs(fs afero.Fs) (restore func()) { origAppFs := appFs origMockFs := m.fs appFs = MapFS{fs} m.fs = afero.Afero{Fs: fs} return func() { appFs = origAppFs m.fs = origMockFs } } // writeFile writes n repeatable sequences of blockSz bytes to path. Select blockSz // as a prime number to reduce the number of repeated blocks. func (m *mapFsMixin) writeFile(c *check.C, path string, firstByte, blockSz uint8, n int) { data := make([]byte, 0, blockSz) for i := uint8(0); i < blockSz; i++ { data = append(data, i+firstByte) } w := new(bytes.Buffer) for ; n > 0; n-- { w.Write(data) } c.Check(m.fs.WriteFile(path, w.Bytes(), 0644), check.IsNil) } func (m *mapFsMixin) symlink(c *check.C, oldname, newname string) { f, err := m.fs.OpenFile(newname, os.O_WRONLY|os.O_CREATE, 0777) c.Assert(err, check.IsNil) defer f.Close() _, err = io.WriteString(f, oldname) c.Check(err, check.IsNil) mem.SetMode(f.(*mem.File).Data(), os.ModeSymlink|0777) } func TestMaybeUpdateFile_missingSrc(t *testing.T) { memFs := afero.NewMemMapFs() appFs = MapFS{memFs} updated, err := MaybeUpdateFile("dst", "src") if err == nil { t.Errorf("Expected error") } if updated { t.Errorf("File was unexpectedly updated") } if _, err := memFs.Stat("dst"); !os.IsNotExist(err) { t.Errorf("file \"%s\" exists or something\n", "dst") } if _, err := memFs.Stat("src"); !os.IsNotExist(err) { t.Errorf("file \"%s\" exists or something\n", "src") } } func TestMaybeUpdateFile_newFile(t *testing.T) { memFs := afero.NewMemMapFs() appFs = MapFS{memFs} afero.WriteFile(memFs, "src", []byte("file b"), 0644) updated, err := MaybeUpdateFile("dst", "src") if err != nil { t.Errorf("Could not update file: %v", err) } if !updated { t.Errorf("Did not update") } srcBytes, err := afero.ReadFile(memFs, "src") if err != nil { t.Errorf("Could not read src: %v", err) } dstBytes, err := afero.ReadFile(memFs, "dst") if err != nil { t.Errorf("Could not read dst: %v", err) } if !bytes.Equal(srcBytes, dstBytes) { t.Errorf("Expected: %v, got: %v", srcBytes, dstBytes) } } func TestMaybeUpdateFile_updateFile(t *testing.T) { memFs := afero.NewMemMapFs() appFs = MapFS{memFs} afero.WriteFile(memFs, "src", []byte("file b"), 0644) afero.WriteFile(memFs, "dst", []byte("file a"), 0644) updated, err := MaybeUpdateFile("dst", "src") if err != nil { t.Errorf("Could not update file: %v", err) } if !updated { t.Errorf("Did not update") } srcBytes, err := afero.ReadFile(memFs, "src") if err != nil { t.Errorf("Could not read src: %v", err) } dstBytes, err := afero.ReadFile(memFs, "dst") if err != nil { t.Errorf("Could not read dst: %v", err) } if !bytes.Equal(srcBytes, dstBytes) { t.Errorf("Expected: %v, got: %v", srcBytes, dstBytes) } // XXX: Need to check that updating is done in an atomic way, // possibly by verifying that it's a new file. But that needs // a real filesystem. } func TestMaybeUpdateFile_readOnlyTarget(t *testing.T) { memFs := afero.NewMemMapFs() appFs = MapFS{memFs} afero.WriteFile(memFs, "src", []byte("file b"), 0644) afero.WriteFile(memFs, "dst", []byte("file a"), 0644) appFs = MapFS{afero.NewReadOnlyFs(memFs)} updated, err := MaybeUpdateFile("dst", "src") if err == nil { t.Errorf("Expected errro") } if !errors.Is(err, os.ErrPermission) { t.Errorf("Expected to fail with permission error, got: %v", err) } if updated { t.Errorf("Expected not to have updated, but somehow did") } } func TestMaybeUpdateFile_sameFile(t *testing.T) { memFs := afero.NewMemMapFs() appFs = MapFS{memFs} afero.WriteFile(memFs, "src", []byte("file b"), 0644) afero.WriteFile(memFs, "dst", []byte("file b"), 0644) appFs = MapFS{afero.NewReadOnlyFs(memFs)} updated, err := MaybeUpdateFile("dst", "src") if err != nil { t.Errorf("Could not update file: %v", err) } if updated { t.Errorf("Rewrote existing file") } if _, err := memFs.Stat("dst"); os.IsNotExist(err) { t.Errorf("file \"%s\" does not exist.\n", "dst") } } nullboot-0.5.0/efibootmgr/hashed_file.go000066400000000000000000000073251453331565400203110ustar00rootroot00000000000000// This file is part of nullboot // Copyright 2021 Canonical Ltd. // SPDX-License-Identifier: GPL-3.0-only package efibootmgr import ( "bytes" "crypto" "errors" "fmt" "io" ) // hashedFile wraps a file handle and builds a list of per-block hashes for // each block of data read from the file. // // During read operations, hashes are computed on a block-by-block basis. If a // block's hash hasn't previously been computed, then it is recorded. If it // has previously been computed, then the hash is compared against the previously // recorded one and an error returns if it is different. // // During close, any previously unread blocks are read in order to compute their // hashes. A notify function is then called with the list of hashes for external // code to verify. This allows verification to be performed without the risk of // TOCTOU type bugs and without having to read and keep the entire file in // memory whilst it is being used. type hashedFile struct { file File sz int64 alg crypto.Hash closeNotify func([][]byte) leafHashes [][]byte cachedBlockIndex int64 cachedBlock []byte } // newHashedFile creates a new hashedFile from the supplied file handle. When the // file is closed, the supplied closeNotify callback will be called with a list // of per-block hashes from the file. func newHashedFile(f File, alg crypto.Hash, closeNotify func([][]byte)) (*hashedFile, error) { info, err := f.Stat() if err != nil { return nil, err } return &hashedFile{ file: f, sz: info.Size(), alg: alg, closeNotify: closeNotify, leafHashes: make([][]byte, (info.Size()+(hashBlockSize-1))/hashBlockSize), cachedBlockIndex: -1}, nil } func (f *hashedFile) readAndCacheBlock(i int64) error { if i == f.cachedBlockIndex { // Reading from the cached block return nil } if i >= int64(len(f.leafHashes)) { // Huh, out of range return io.EOF } // Read the whole block r := io.NewSectionReader(f.file, i*hashBlockSize, hashBlockSize) var block [hashBlockSize]byte n, err := io.ReadFull(r, block[:]) if err != nil && !errors.Is(err, io.ErrUnexpectedEOF) { // Handle io.ErrUnexpectedEOF later. return err } // Cache this block to speed up small reads f.cachedBlockIndex = i f.cachedBlock = block[:n] // Hash the block h := f.alg.New() h.Write(block[:]) if len(f.leafHashes[i]) == 0 { // This is the first time we read this block. f.leafHashes[i] = h.Sum(nil) } else if !bytes.Equal(h.Sum(nil), f.leafHashes[i]) { // We've read this block before, and it has changed. return fmt.Errorf("hash check fail for block %d", i) } return err } func (f *hashedFile) ReadAt(p []byte, off int64) (n int, err error) { // Calculate the starting block and number of blocks. start := ((off + hashBlockSize) / hashBlockSize) - 1 end := ((off + int64(len(p)) + hashBlockSize) / hashBlockSize) num := end - start // Read and hash each block. for i := start; i < start+num; i++ { if err := f.readAndCacheBlock(i); err != nil && !errors.Is(err, io.ErrUnexpectedEOF) { break } data := f.cachedBlock if n == 0 { off0 := off - (start * hashBlockSize) data = data[off0:] } sz := len(p) - n if sz < len(data) { data = data[:sz] } copy(p[n:], data) n += len(data) if err != nil { break } } if n == 0 { return 0, io.EOF } return n, nil } func (f *hashedFile) Close() error { // Loop over missing leaf hashes. for i, d := range f.leafHashes { if len(d) > 0 { continue } // Hash missing block. if err := f.readAndCacheBlock(int64(i)); err != nil { break } } if f.closeNotify != nil { f.closeNotify(f.leafHashes) } return f.file.Close() } func (f *hashedFile) Size() int64 { return f.sz } nullboot-0.5.0/efibootmgr/hashed_file_test.go000066400000000000000000000046541453331565400213520ustar00rootroot00000000000000// This file is part of nullboot // Copyright 2021 Canonical Ltd. // SPDX-License-Identifier: GPL-3.0-only package efibootmgr import ( "crypto" "errors" "io" "gopkg.in/check.v1" ) type hashedFileSuite struct { mapFsMixin } var _ = check.Suite(&hashedFileSuite{}) type testHashedFileReadBlock struct { off int64 sz int64 n int64 } func (s *hashedFileSuite) testHashedFile(c *check.C, path string, blocks []testHashedFileReadBlock) { f, err := appFs.Open(path) c.Assert(err, check.IsNil) defer f.Close() var leafHashes [][]byte for { var data [hashBlockSize]byte n, err := f.Read(data[:]) if n > 0 { h := crypto.SHA256.New() h.Write(data[:]) leafHashes = append(leafHashes, h.Sum(nil)) } if err != nil { break } } h := crypto.SHA256.New() for _, leaf := range leafHashes { h.Write(leaf) } expectedHash := h.Sum(nil) leafHashes = nil hf, err := newHashedFile(f, crypto.SHA256, func(hashes [][]byte) { leafHashes = hashes }) c.Assert(err, check.IsNil) for _, block := range blocks { total := block.sz * block.n expected := make([]byte, total) data := make([]byte, total) for i := int64(0); i < total; { n, err := f.ReadAt(expected[i:i+block.sz], i+block.off) if err == io.EOF || errors.Is(err, io.ErrUnexpectedEOF) || int64(n) < block.sz { break } c.Check(err, check.IsNil) i += int64(n) } for i := int64(0); i < total; { n, err := hf.ReadAt(data[i:i+block.sz], i+block.off) if err == io.EOF || errors.Is(err, io.ErrUnexpectedEOF) || int64(n) < block.sz { break } c.Check(err, check.IsNil) i += int64(n) } c.Check(data, check.DeepEquals, expected) } c.Check(hf.Close(), check.IsNil) h = crypto.SHA256.New() for _, leaf := range leafHashes { h.Write(leaf) } c.Check(h.Sum(nil), check.DeepEquals, expectedHash) } func (s *hashedFileSuite) TestHashedFileReadFullSmallReads(c *check.C) { s.writeFile(c, "/foo", 0, 199, 3500) s.testHashedFile(c, "/foo", []testHashedFileReadBlock{ {off: 0, sz: 10, n: 69650}, }) } func (s *hashedFileSuite) TestHashedFileReadFullLargeReads(c *check.C) { s.writeFile(c, "/foo", 0, 199, 3500) s.testHashedFile(c, "/foo", []testHashedFileReadBlock{ {off: 0, sz: 69650, n: 10}, }) } func (s *hashedFileSuite) TestHashedFileReadSparse(c *check.C) { s.writeFile(c, "/foo", 0, 199, 3500) s.testHashedFile(c, "/foo", []testHashedFileReadBlock{ {off: 500, sz: 10, n: 100}, {off: 20000, sz: 500, n: 20}, }) } nullboot-0.5.0/efibootmgr/kernel.go000066400000000000000000000137551453331565400173420ustar00rootroot00000000000000// This file is part of nullboot // Copyright 2021 Canonical Ltd. // SPDX-License-Identifier: GPL-3.0-only package efibootmgr import ( "fmt" "io/ioutil" "log" "path" "sort" "strings" "github.com/knqyf263/go-deb-version" ) // KernelManager manages kernels in an SP vendor directory. // // It will update or install shim, copy in any new kernels, // remove old kernels, and configure boot in shim and BDS. type KernelManager struct { sourceDir string // sourceDir is the location to copy kernels from targetDir string // targetDir is a vendor directory on the ESP sourceKernels []string // kernels in sourceDir targetKernels []string // kernels in targetDir bootEntries []BootEntry // boot entries filled by InstallKernels kernelOptions string // options to pass to kernel bootManager *BootManager // The EFI boot manager } // NewKernelManager returns a new kernel manager managing kernels in the host system func NewKernelManager(esp, sourceDir, vendor string, bootManager *BootManager) (*KernelManager, error) { var km KernelManager var err error km.sourceDir = sourceDir km.targetDir = path.Join(esp, "EFI", vendor) km.bootManager = bootManager if file, err := appFs.Open("/etc/kernel/cmdline"); err == nil { defer file.Close() data, err := ioutil.ReadAll(file) if err != nil { return nil, fmt.Errorf("Cannot read kernel command line: %w", err) } km.kernelOptions = strings.TrimSpace(string(data)) } km.sourceKernels, err = km.readKernels(km.sourceDir) if err != nil { return nil, err } km.targetKernels, err = km.readKernels(km.targetDir) if err != nil { return nil, err } return &km, nil } // readKernels returns a list of all kernels in the func (km *KernelManager) readKernels(dir string) ([]string, error) { var kernels []string entries, err := appFs.ReadDir(dir) if err != nil { return nil, fmt.Errorf("Could not determine kernels: %w", err) } for _, e := range entries { if strings.HasPrefix(e.Name(), "kernel.efi-") { kernels = append(kernels, e.Name()) } } // Sort descending sort.Slice(kernels, func(i, j int) bool { a, e := version.NewVersion(kernels[i][len("kernel.efi-"):]) if e != nil { err = fmt.Errorf("Could not parse kernel version of %s: %w", kernels[i], e) return false } b, e := version.NewVersion(kernels[j][len("kernel.efi-"):]) if e != nil { err = fmt.Errorf("Could not parse kernel version of %s: %w", kernels[j], e) return false } return a.GreaterThan(b) }) return kernels, err } // getKernelABI returns the kernel ABI part of the kernel filename func getKernelABI(kernel string) string { return kernel[len("kernel.efi-"):] } // InstallKernels installs the kernels to the ESP and builds up the boot entries // to commit using CommitToBootLoader() func (km *KernelManager) InstallKernels() error { km.bootEntries = nil for _, sk := range km.sourceKernels { updated, err := MaybeUpdateFile(path.Join(km.targetDir, sk), path.Join(km.sourceDir, sk)) if err != nil { log.Printf("Could not install kernel %s: %v", sk, err) continue } if updated { log.Printf("Installed or updated kernel %s", sk) } // It is worth pointing out that the argument for shim should start with \ // which here somehow denotes it is in the same directory rather than the root. // FIXME: Extract vendor name out into config file skVersion := getKernelABI(sk) options := "\\" + sk if km.kernelOptions != "" { options += " " + km.kernelOptions } km.bootEntries = append(km.bootEntries, BootEntry{ Filename: "shim" + GetEfiArchitecture() + ".efi", Label: fmt.Sprintf("Ubuntu with kernel %s", skVersion), Options: options, Description: fmt.Sprintf("Ubuntu entry for kernel %s", skVersion), }) } return nil } // IsObsoleteKernel checks whether a kernel is obsolete. func (km *KernelManager) isObsoleteKernel(k string) bool { for _, sk := range km.sourceKernels { if sk == k { return false } } return true } // RemoveObsoleteKernels removes old kernels in the ESP vendor directory func (km *KernelManager) RemoveObsoleteKernels() error { var remaining []string for _, tk := range km.targetKernels { if !km.isObsoleteKernel(tk) { continue } if err := appFs.Remove(path.Join(km.targetDir, tk)); err != nil { log.Printf("Could not remove kernel %s: %v", tk, err) remaining = append(remaining, tk) continue } log.Printf("Removed kernel %s", tk) } km.targetKernels = remaining return nil } // CommitToBootLoader updates the firmware BDS entries and shim's boot.csv func (km *KernelManager) CommitToBootLoader() error { log.Print("Configuring shim fallback loader") // We completely own the shim fallback file, so just write it if err := WriteShimFallbackToFile(path.Join(km.targetDir, "BOOT"+strings.ToUpper(GetEfiArchitecture())+".CSV"), km.bootEntries); err != nil { log.Printf("Failed to configure shim fallback loader: %v", err) } if km.bootManager == nil { return nil } log.Print("Configuring UEFI boot device selection") // This will become the head of the new boot order var ourBootOrder []int // Add new entries, find existing ones and build target boot order for _, entry := range km.bootEntries { bootNum, err := km.bootManager.FindOrCreateEntry(entry, km.targetDir) if err != nil { return fmt.Errorf("Failure to add boot entry for %s: %w", entry.Label, err) } ourBootOrder = append(ourBootOrder, bootNum) } // Delete any obsolete kernels for _, ev := range km.bootManager.entries { if !strings.HasPrefix(ev.LoadOption.Description, "Ubuntu ") { continue } isObsolete := true for _, num := range ourBootOrder { if num == ev.BootNumber { isObsolete = false } } if !isObsolete { continue } if err := km.bootManager.DeleteEntry(ev.BootNumber); err != nil { log.Printf("Could not delete Boot%04X: %v", ev.BootNumber, err) } } // Set the boot order if err := km.bootManager.PrependAndSetBootOrder(ourBootOrder); err != nil { return fmt.Errorf("Could not set boot order: %w", err) } return nil } nullboot-0.5.0/efibootmgr/kernel_test.go000066400000000000000000000211321453331565400203650ustar00rootroot00000000000000// This file is part of nullboot // Copyright 2021 Canonical Ltd. // SPDX-License-Identifier: GPL-3.0-only package efibootmgr import ( "bytes" "fmt" "io/ioutil" "reflect" "strings" "testing" "github.com/canonical/go-efilib" "github.com/spf13/afero" "golang.org/x/text/encoding/unicode" "golang.org/x/text/transform" ) func CheckFilesEqual(fs afero.Fs, want string, got string) error { wantBytes, err := afero.ReadFile(fs, want) if err != nil { return fmt.Errorf("Could not read want: %v", err) } gotBytes, err := afero.ReadFile(fs, got) if err != nil { return fmt.Errorf("Could not read got: %v", err) } if !bytes.Equal(wantBytes, gotBytes) { return fmt.Errorf("Expected: %v, got: %v", string(wantBytes), string(gotBytes)) } return nil } func TestKernelManagerNewAndInstallKernels(t *testing.T) { appArchitecture = "x64" memFs := afero.NewMemMapFs() appFs = MapFS{memFs} afero.WriteFile(memFs, "/usr/lib/linux/kernel.efi-1.0-12-generic", []byte("1.0-12-generic"), 0644) afero.WriteFile(memFs, "/usr/lib/linux/kernel.efi-1.0-1-generic", []byte("1.0-1-generic"), 0644) afero.WriteFile(memFs, "/boot/efi/EFI/ubuntu/", []byte(""), 0644) afero.WriteFile(memFs, "/etc/kernel/cmdline", []byte("root=magic"), 0644) afero.WriteFile(memFs, "/boot/efi/EFI/ubuntu/shimx64.efi", []byte("file a"), 0644) mockvars := MockEFIVariables{ map[efi.VariableDescriptor]mockEFIVariable{ {GUID: efi.GlobalVariable, Name: "BootOrder"}: {[]byte{1, 0, 2, 0, 3, 0}, 123}, {GUID: efi.GlobalVariable, Name: "Boot0001"}: {UsbrBootCdromOptBytes, 42}, }, } // Create an obsolete Boot0000 entry that we want to collect at the end. bm, _ := NewBootManagerForVariables(&mockvars) if _, err := bm.FindOrCreateEntry(BootEntry{Filename: "shimx64.efi", Label: "Ubuntu with obsolete kernel", Options: ""}, "/boot/efi/EFI/ubuntu"); err != nil { t.Fatal(err) } km, err := NewKernelManager("/boot/efi", "/usr/lib/linux", "ubuntu", &bm) if err != nil { t.Fatalf("Could not create kernel manager: %v", err) } wantSourceKernels := []string{"kernel.efi-1.0-12-generic", "kernel.efi-1.0-1-generic"} if !reflect.DeepEqual(km.sourceKernels, wantSourceKernels) { t.Fatalf("Expected %v, got %v", wantSourceKernels, km.sourceKernels) } var wantTargetKernels []string if !reflect.DeepEqual(km.targetKernels, wantTargetKernels) { t.Fatalf("Expected %v, got %v", wantTargetKernels, km.targetKernels) } if err := km.InstallKernels(); err != nil { t.Errorf("Could not install kernels: %v", err) } if err := CheckFilesEqual(memFs, "/usr/lib/linux/kernel.efi-1.0-12-generic", "/boot/efi/EFI/ubuntu/kernel.efi-1.0-12-generic"); err != nil { t.Error(err) } if err := CheckFilesEqual(memFs, "/usr/lib/linux/kernel.efi-1.0-1-generic", "/boot/efi/EFI/ubuntu/kernel.efi-1.0-1-generic"); err != nil { t.Error(err) } if err := km.CommitToBootLoader(); err != nil { t.Errorf("Could not commit to bootloader: %v", err) } file, err := memFs.Open("/boot/efi/EFI/ubuntu/BOOT" + strings.ToUpper(GetEfiArchitecture()) + ".CSV") if err != nil { t.Fatalf("Could not open boot.csv: %v", err) } reader := transform.NewReader(file, unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM).NewDecoder()) data, err := ioutil.ReadAll(reader) if err != nil { t.Fatalf("Could not read boot.csv: %v", err) } want := ("shim" + GetEfiArchitecture() + ".efi,Ubuntu with kernel 1.0-1-generic,\\kernel.efi-1.0-1-generic root=magic ,Ubuntu entry for kernel 1.0-1-generic\n" + "shim" + GetEfiArchitecture() + ".efi,Ubuntu with kernel 1.0-12-generic,\\kernel.efi-1.0-12-generic root=magic ,Ubuntu entry for kernel 1.0-12-generic\n") if want != string(data) { t.Errorf("Boot entry mismatch:\nExpected:\n%v\nGot:\n%v", want, string(data)) } // Validate we have actually written the EFI stuff we want bm, err = NewBootManagerForVariables(&mockvars) if err != nil { t.Fatalf("Could not create boot manager: %v", err) } // So we already had 1 populated with a foreign boot entry, this should be preserved. if !reflect.DeepEqual(bm.bootOrder, []int{2, 3, 1}) { t.Fatalf("Unexpected boot order %v", bm.bootOrder) } for i, desc := range map[int]string{2: "Ubuntu with kernel 1.0-12-generic", 3: "Ubuntu with kernel 1.0-1-generic", 1: "USBR BOOT CDROM"} { if bm.entries[i].LoadOption.Description != desc { t.Errorf("Expected boot entry %d Description %s, got %s", i, desc, bm.entries[i].LoadOption.Description) } } } func TestKernelManager_noCmdLine(t *testing.T) { appArchitecture = "x64" memFs := afero.NewMemMapFs() appFs = MapFS{memFs} afero.WriteFile(memFs, "/usr/lib/linux/kernel.efi-1.0-12-generic", []byte("1.0-12-generic"), 0644) afero.WriteFile(memFs, "/usr/lib/linux/kernel.efi-1.0-1-generic", []byte("1.0-1-generic"), 0644) afero.WriteFile(memFs, "/boot/efi/EFI/ubuntu/", []byte(""), 0644) afero.WriteFile(memFs, "/boot/efi/EFI/ubuntu/shimx64.efi", []byte("file a"), 0644) mockvars := MockEFIVariables{ map[efi.VariableDescriptor]mockEFIVariable{ {GUID: efi.GlobalVariable, Name: "BootOrder"}: {[]byte{1, 0, 2, 0, 3, 0}, 123}, {GUID: efi.GlobalVariable, Name: "Boot0001"}: {UsbrBootCdromOptBytes, 42}, }, } // Create an obsolete Boot0000 entry that we want to collect at the end. bm, _ := NewBootManagerForVariables(&mockvars) if _, err := bm.FindOrCreateEntry(BootEntry{Filename: "shimx64.efi", Label: "Ubuntu with obsolete kernel", Options: ""}, "/boot/efi/EFI/ubuntu"); err != nil { t.Fatal(err) } km, err := NewKernelManager("/boot/efi", "/usr/lib/linux", "ubuntu", &bm) if err := km.InstallKernels(); err != nil { t.Errorf("Could not install kernels: %v", err) } if err := km.CommitToBootLoader(); err != nil { t.Errorf("Could not commit to bootloader: %v", err) } file, err := memFs.Open("/boot/efi/EFI/ubuntu/BOOT" + strings.ToUpper(GetEfiArchitecture()) + ".CSV") if err != nil { t.Fatalf("Could not open boot.csv: %v", err) } reader := transform.NewReader(file, unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM).NewDecoder()) data, err := ioutil.ReadAll(reader) if err != nil { t.Fatalf("Could not read boot.csv: %v", err) } want := ("shim" + GetEfiArchitecture() + ".efi,Ubuntu with kernel 1.0-1-generic,\\kernel.efi-1.0-1-generic ,Ubuntu entry for kernel 1.0-1-generic\n" + "shim" + GetEfiArchitecture() + ".efi,Ubuntu with kernel 1.0-12-generic,\\kernel.efi-1.0-12-generic ,Ubuntu entry for kernel 1.0-12-generic\n") if want != string(data) { t.Errorf("Boot entry mismatch:\nExpected:\n%v\nGot:\n%v", want, string(data)) } // Validate we have actually written the EFI stuff we want bm, err = NewBootManagerForVariables(&mockvars) if err != nil { t.Fatalf("Could not create boot manager: %v", err) } // So we already had 1 populated with a foreign boot entry, this should be preserved. if !reflect.DeepEqual(bm.bootOrder, []int{2, 3, 1}) { t.Fatalf("Unexpected boot order %v", bm.bootOrder) } for i, desc := range map[int]string{2: "Ubuntu with kernel 1.0-12-generic", 3: "Ubuntu with kernel 1.0-1-generic", 1: "USBR BOOT CDROM"} { if bm.entries[i].LoadOption.Description != desc { t.Errorf("Expected boot entry %d Description %s, got %s", i, desc, bm.entries[i].LoadOption.Description) } } } func TestKernelManagerRemoveObsoleteKernels(t *testing.T) { appArchitecture = "x64" memFs := afero.NewMemMapFs() appFs = MapFS{memFs} afero.WriteFile(memFs, "/usr/lib/linux/kernel.efi-1.0-12-generic", []byte("1.0-12-generic"), 0644) afero.WriteFile(memFs, "/boot/efi/EFI/ubuntu/kernel.efi-1.0-12-generic", []byte("1.0-12-generic"), 0644) afero.WriteFile(memFs, "/boot/efi/EFI/ubuntu/kernel.efi-1.0-1-generic", []byte("1.0-1-generic"), 0644) afero.WriteFile(memFs, "/boot/efi/EFI/ubuntu/BOOTX64.CSV", []byte(""), 0644) afero.WriteFile(memFs, "/etc/kernel/cmdline", []byte("root=magic"), 0644) mockvars := MockEFIVariables{ map[efi.VariableDescriptor]mockEFIVariable{ {GUID: efi.GlobalVariable, Name: "BootOrder"}: {[]byte{}, 123}, }, } bm, err := NewBootManagerForVariables(&mockvars) if err != nil { t.Fatalf("Could not create boot manager: %v", err) } km, err := NewKernelManager("/boot/efi", "/usr/lib/linux", "ubuntu", &bm) if err != nil { t.Fatalf("Could not create kernel manager: %v", err) } if err := km.RemoveObsoleteKernels(); err != nil { t.Errorf("Failed to remove obsolete kernels: %v", err) } if _, err := memFs.Stat("/boot/efi/EFI/ubuntu/kernel.efi-1.0-12-generic"); err != nil { t.Errorf("missing file: %v\n", err) } if _, err := memFs.Stat("/boot/efi/EFI/ubuntu/kernel.efi-1.0-1-generic"); err == nil { t.Errorf("did not expect obsolete kernel to be present") } if km.targetKernels != nil { t.Errorf("expected list of target kernels to be empty now, got: %v", km.targetKernels) } } nullboot-0.5.0/efibootmgr/reseal.go000066400000000000000000000250731453331565400173310ustar00rootroot00000000000000// This file is part of nullboot // Copyright 2021 Canonical Ltd. // SPDX-License-Identifier: GPL-3.0-only package efibootmgr import ( "bytes" "crypto" "encoding/binary" "errors" "fmt" "io" "log" "os" "path/filepath" "strings" "syscall" "github.com/canonical/go-efilib" "github.com/canonical/go-tpm2" "github.com/canonical/tcglog-parser" "github.com/snapcore/secboot" secboot_efi "github.com/snapcore/secboot/efi" secboot_tpm2 "github.com/snapcore/secboot/tpm2" "golang.org/x/sys/unix" ) const ( keyFilePath = "device/fde/cloudimg-rootfs.sealed-key" keyringPrefix = "ubuntu-fde" rootfsLabel = "cloudimg-rootfs-enc" ) var ( efiComputePeImageDigest = efi.ComputePeImageDigest sbefiAddBootManagerProfile = secboot_efi.AddBootManagerProfile sbefiAddSecureBootPolicyProfile = secboot_efi.AddSecureBootPolicyProfile sbGetAuxiliaryKeyFromKernel = secboot.GetAuxiliaryKeyFromKernel sbtpmConnectToDefaultTPM = secboot_tpm2.ConnectToDefaultTPM sbtpmReadSealedKeyObjectFromFile = secboot_tpm2.ReadSealedKeyObjectFromFile sbtpmSealedKeyObjectUpdatePCRProtectionPolicy = (*secboot_tpm2.SealedKeyObject).UpdatePCRProtectionPolicy sbtpmSealedKeyObjectWriteAtomic = (*secboot_tpm2.SealedKeyObject).WriteAtomic unixKeyctlInt = unix.KeyctlInt ) type pcrProfileComputeContext struct { nOpen int failedPaths []string } // trustedEFIImage is an implementation of secboot_efi.Image that makes // use of hashedFile in order to ensure that boot assets added to a PCR // profile are trusted. type trustedEFIImage struct { assets *TrustedAssets context *pcrProfileComputeContext path string } func (i *trustedEFIImage) String() string { return i.path } func (i *trustedEFIImage) Open() (file interface { io.ReaderAt io.Closer Size() int64 }, err error) { f, err := appFs.Open(i.path) if err != nil { return nil, err } i.context.nOpen++ defer func() { if err != nil { f.Close() i.context.nOpen-- } }() return newCheckedHashedFile(f, i.assets, func(trusted bool) { if !trusted { i.context.failedPaths = append(i.context.failedPaths, i.path) } i.context.nOpen-- }) } func newTrustedEFIImage(assets *TrustedAssets, context *pcrProfileComputeContext, path string) *trustedEFIImage { return &trustedEFIImage{assets, context, path} } func resolveLink(path string) (string, error) { path = filepath.Clean(path) for { tgtPath, err := appFs.Readlink(path) if errors.Is(err, syscall.EINVAL) { return path, nil } if err != nil { return "", err } if !filepath.IsAbs(tgtPath) { tgtPath = filepath.Clean(filepath.Join(filepath.Dir(path), tgtPath)) } path = tgtPath } } func getPolicyAuthKeyFromKernel() (secboot_tpm2.PolicyAuthKey, error) { devPath, err := resolveLink(filepath.Join("/dev/disk/by-label", rootfsLabel)) if err != nil { return nil, fmt.Errorf("cannot resolve devive symlink: %w", err) } // By default, system services get their own session keyring that doesn't have // the user keyring linked to it. This means that attempting to read a key from // the user keyring will fail if the key only permits possessor read. Link the // user keyring into our process keyring so that we can read such keys from the // user keyring. if _, err := unixKeyctlInt(unix.KEYCTL_LINK, -4, -2, 0, 0); err != nil { return nil, fmt.Errorf("cannot link user keyring into process keyring: %w", err) } key, err := sbGetAuxiliaryKeyFromKernel(keyringPrefix, devPath, false) if err != nil { if err == secboot.ErrKernelKeyNotFound { // Work around a secboot bug ents, err2 := appFs.ReadDir("/dev/disk/by-partuuid") if err2 == nil { for _, ent := range ents { path := filepath.Join("/dev/disk/by-partuuid", ent.Name()) devPath2, err2 := resolveLink(path) if err2 != nil { continue } if devPath2 == devPath { key, err = sbGetAuxiliaryKeyFromKernel(keyringPrefix, path, false) break } } } } if err != nil { return nil, fmt.Errorf("cannot read key from kernel: %w", err) } } return secboot_tpm2.PolicyAuthKey(key), nil } func computePCRProtectionProfile(loadChains []*secboot_efi.ImageLoadEvent) (*secboot_tpm2.PCRProtectionProfile, error) { profile := secboot_tpm2.NewPCRProtectionProfile() pcr4Params := secboot_efi.BootManagerProfileParams{ PCRAlgorithm: tpm2.HashAlgorithmSHA256, LoadSequences: loadChains} if err := sbefiAddBootManagerProfile(profile, &pcr4Params); err != nil { return nil, fmt.Errorf("cannot add EFI boot manager profile: %w", err) } pcr7Params := secboot_efi.SecureBootPolicyProfileParams{ PCRAlgorithm: tpm2.HashAlgorithmSHA256, LoadSequences: loadChains} if err := sbefiAddSecureBootPolicyProfile(profile, &pcr7Params); err != nil { return nil, fmt.Errorf("cannot add EFI secure boot policy profile: %w", err) } profile.AddPCRValue(tpm2.HashAlgorithmSHA256, 12, make([]byte, tpm2.HashAlgorithmSHA256.Size())) // snap-bootstrap measures an epoch h := crypto.SHA256.New() binary.Write(h, binary.LittleEndian, uint32(0)) profile.ExtendPCR(tpm2.HashAlgorithmSHA256, 12, h.Sum(nil)) // XXX: The kernel EFI stub has a compiled-in commandline which isn't measured. log.Println("Computed PCR profile:", profile) pcrValues, err := profile.ComputePCRValues(nil) if err != nil { return nil, fmt.Errorf("cannot compute PCR values: %w", err) } log.Println("Computed PCR values:") for i, values := range pcrValues { log.Printf(" branch %d:\n", i) for alg := range values { for pcr := range values[alg] { log.Printf(" PCR%d,%v: %x\n", pcr, alg, values[alg][pcr]) } } } pcrs, digests, err := profile.ComputePCRDigests(nil, tpm2.HashAlgorithmSHA256) if err != nil { return nil, fmt.Errorf("cannot compute PCR digests: %w", err) } log.Println("PCR selection:", pcrs) log.Println("Computed PCR digests:") for _, digest := range digests { log.Printf(" %x\n", digest) } return profile, nil } // ResealKey updates the PCR profile for the disk encryption key to incorporate // the boot assets installed directly by the package manager and those assets // copied by this package to the ESP. func ResealKey(assets *TrustedAssets, km *KernelManager, esp, shimSource, vendor string) error { _, err := appFs.Stat(filepath.Join(esp, keyFilePath)) if os.IsNotExist(err) { // Assume that this file being missing means there is nothing to do. return nil } context := new(pcrProfileComputeContext) shimBase := "shim" + GetEfiArchitecture() + ".efi" var roots []*secboot_efi.ImageLoadEvent for _, path := range []string{ filepath.Join(shimSource, shimBase+".signed"), filepath.Join(esp, "EFI", vendor, shimBase)} { _, err := appFs.Stat(path) if os.IsNotExist(err) { continue } roots = append(roots, &secboot_efi.ImageLoadEvent{ Source: secboot_efi.Firmware, Image: newTrustedEFIImage(assets, context, path)}) } var kernels []*secboot_efi.ImageLoadEvent for _, x := range []struct { dir string files []string }{ { dir: km.sourceDir, files: km.sourceKernels, }, { dir: km.targetDir, files: km.targetKernels, }, } { for _, n := range x.files { path := filepath.Join(x.dir, n) kernels = append(kernels, &secboot_efi.ImageLoadEvent{ Source: secboot_efi.Shim, Image: newTrustedEFIImage(assets, context, path)}) } } for _, root := range roots { root.Next = kernels } authKey, err := getPolicyAuthKeyFromKernel() if err != nil { return fmt.Errorf("cannot obtain auth key from kernel: %w", err) } pcrProfile, err := computePCRProtectionProfile(roots) if err != nil { return fmt.Errorf("cannot compute PCR profile: %w", err) } if context.nOpen != 0 { return errors.New("leaked open files from computing PCR profile") } if len(context.failedPaths) > 0 { return fmt.Errorf("some assets failed an integrity check: %v", context.failedPaths) } k, err := sbtpmReadSealedKeyObjectFromFile(filepath.Join(esp, keyFilePath)) if err != nil { return fmt.Errorf("cannot read sealed key file: %w", err) } // XXX: Connection is required because we do integrity checks // on the key data. Should probably switch to using the /dev/tpmrm0 // device here. tpm, err := sbtpmConnectToDefaultTPM() if err != nil { return err } defer tpm.Close() if err := sbtpmSealedKeyObjectUpdatePCRProtectionPolicy(k, tpm, authKey, pcrProfile); err != nil { return fmt.Errorf("cannot update PCR profile: %w", err) } w := secboot_tpm2.NewFileSealedKeyObjectWriter(filepath.Join(esp, keyFilePath)) if err := sbtpmSealedKeyObjectWriteAtomic(k, w); err != nil { return fmt.Errorf("cannot write updated sealed key object: %w", err) } return nil } // TrustCurrentBoot adds the assets used in the current boot to the list of boot // assets trusted for adding to PCR profiles with ResealKey. It works by mapping // EV_EFI_BOOT_SERVICES_APPLICATION events from the TCG log to files stored in the // ESP. func TrustCurrentBoot(assets *TrustedAssets, esp string) error { f, err := appFs.Open("/sys/kernel/security/tpm0/binary_bios_measurements") if err != nil { return err } defer f.Close() eventLog, err := tcglog.ReadLog(f, &tcglog.LogOptions{}) if err != nil { return fmt.Errorf("cannot read TCG log: %v", err) } for _, event := range eventLog.Events { if event.PCRIndex != 4 { continue } if event.EventType != tcglog.EventTypeEFIBootServicesApplication { continue } data, ok := event.Data.(*tcglog.EFIImageLoadEvent) if !ok { log.Println("Invalid event data for EV_EFI_BOOT_SERVICES_APPLICATION event") continue } fpdp, ok := data.DevicePath[len(data.DevicePath)-1].(efi.FilePathDevicePathNode) if !ok { // Ignore application not stored in a filesystem continue } components := strings.Split(string(fpdp), "\\") path := strings.Join(components, string(os.PathSeparator)) err := func() error { f, err := appFs.Open(filepath.Join(esp, path)) switch { case os.IsNotExist(err): log.Println("Missing file:", filepath.Join(esp, path)) return nil case err != nil: return err } peHashMatch := false hf, err := newHashedFile(f, assets.alg(), func(leafHashes [][]byte) { if !peHashMatch { return } assets.trustLeafHashes(leafHashes) }) if err != nil { f.Close() return err } defer hf.Close() digest, err := efiComputePeImageDigest(crypto.SHA256, hf, hf.Size()) if err != nil { return fmt.Errorf("cannot compute PE image hash: %v", err) } if bytes.Equal(digest, event.Digests[tpm2.HashAlgorithmSHA256]) { peHashMatch = true } return nil }() if err != nil { return err } } return nil } nullboot-0.5.0/efibootmgr/reseal_test.go000066400000000000000000001037531453331565400203720ustar00rootroot00000000000000// This file is part of nullboot // Copyright 2021 Canonical Ltd. // SPDX-License-Identifier: GPL-3.0-only package efibootmgr import ( "bytes" "crypto" "io" "io/ioutil" "os" "github.com/canonical/go-efilib" "github.com/canonical/go-tpm2" "github.com/canonical/go-tpm2/linux" "github.com/canonical/tcglog-parser" "github.com/snapcore/secboot" secboot_efi "github.com/snapcore/secboot/efi" secboot_tpm2 "github.com/snapcore/secboot/tpm2" "golang.org/x/sys/unix" "gopkg.in/check.v1" ) type resealSuite struct { mapFsMixin } func (*resealSuite) mockSbefiAddBootManagerProfile(fn func(profile *secboot_tpm2.PCRProtectionProfile, params *secboot_efi.BootManagerProfileParams) error) (restore func()) { orig := sbefiAddBootManagerProfile sbefiAddBootManagerProfile = fn return func() { sbefiAddBootManagerProfile = orig } } func (*resealSuite) mockSbefiAddSecureBootPolicyProfile(fn func(profile *secboot_tpm2.PCRProtectionProfile, params *secboot_efi.SecureBootPolicyProfileParams) error) (restore func()) { orig := sbefiAddSecureBootPolicyProfile sbefiAddSecureBootPolicyProfile = fn return func() { sbefiAddSecureBootPolicyProfile = orig } } func (*resealSuite) mockSbGetAuxiliaryKeyFromKernel(fn func(prefix, devicePath string, remove bool) (secboot.AuxiliaryKey, error)) (restore func()) { orig := sbGetAuxiliaryKeyFromKernel sbGetAuxiliaryKeyFromKernel = fn return func() { sbGetAuxiliaryKeyFromKernel = orig } } func (*resealSuite) mockSbtpmConnectToDefaultTPM(fn func() (*secboot_tpm2.Connection, error)) (restore func()) { orig := sbtpmConnectToDefaultTPM sbtpmConnectToDefaultTPM = fn return func() { sbtpmConnectToDefaultTPM = orig } } func (*resealSuite) mockSbtpmReadSealedKeyObjectFromFile(fn func(path string) (*secboot_tpm2.SealedKeyObject, error)) (restore func()) { orig := sbtpmReadSealedKeyObjectFromFile sbtpmReadSealedKeyObjectFromFile = fn return func() { sbtpmReadSealedKeyObjectFromFile = orig } } func (*resealSuite) mockSbtpmSealedKeyObjectUpdatePCRProtectionPolicy(fn func(k *secboot_tpm2.SealedKeyObject, tpm *secboot_tpm2.Connection, authKey secboot_tpm2.PolicyAuthKey, profile *secboot_tpm2.PCRProtectionProfile) error) (restore func()) { orig := sbtpmSealedKeyObjectUpdatePCRProtectionPolicy sbtpmSealedKeyObjectUpdatePCRProtectionPolicy = fn return func() { sbtpmSealedKeyObjectUpdatePCRProtectionPolicy = orig } } func (*resealSuite) mockSbtpmSealedKeyObjectWriteAtomic(fn func(k *secboot_tpm2.SealedKeyObject, w secboot.KeyDataWriter) error) (restore func()) { orig := sbtpmSealedKeyObjectWriteAtomic sbtpmSealedKeyObjectWriteAtomic = fn return func() { sbtpmSealedKeyObjectWriteAtomic = orig } } func (*resealSuite) mockUnixKeyctlInt(fn func(cmd, arg2, arg3, arg4, arg5 int) (int, error)) (restore func()) { orig := unixKeyctlInt unixKeyctlInt = fn return func() { unixKeyctlInt = orig } } func (*resealSuite) mockEfiArch(arch string) (restore func()) { orig := appArchitecture appArchitecture = arch return func() { appArchitecture = orig } } var _ = check.Suite(&resealSuite{}) func (s *resealSuite) TestTrustedEfiImageOk(c *check.C) { s.writeFile(c, "/foo", 0, 43, 50) assets, err := ReadTrustedAssets() c.Assert(err, check.IsNil) c.Check(assets.TrustNewFromDir("/"), check.IsNil) context := new(pcrProfileComputeContext) img := newTrustedEFIImage(assets, context, "/foo") f, err := img.Open() c.Assert(err, check.IsNil) c.Check(f.Close(), check.IsNil) c.Check(context.nOpen, check.Equals, 0) c.Check(context.failedPaths, check.IsNil) } func (s *resealSuite) TestTrustedEfiImageBad(c *check.C) { s.writeFile(c, "/foo", 0, 43, 50) assets, err := ReadTrustedAssets() c.Assert(err, check.IsNil) context := new(pcrProfileComputeContext) img := newTrustedEFIImage(assets, context, "/foo") f, err := img.Open() c.Assert(err, check.IsNil) c.Check(f.Close(), check.IsNil) c.Check(context.nOpen, check.Equals, 0) c.Check(context.failedPaths, check.DeepEquals, []string{"/foo"}) } type testResealKeyData struct { arch string auxiliaryKey []byte devicePaths []string shims [][]byte kernels [][]byte } func (s *resealSuite) testResealKey(c *check.C, data *testResealKeyData) { var ( expectedSko *secboot_tpm2.SealedKeyObject = nil expectedTpm *secboot_tpm2.Connection = nil userKeyringLinkedFromProcessKeyring = false ) restore := s.mockEfiArch(data.arch) defer restore() restore = s.mockSbefiAddBootManagerProfile(func(profile *secboot_tpm2.PCRProtectionProfile, params *secboot_efi.BootManagerProfileParams) error { c.Assert(profile, check.NotNil) c.Check(params.PCRAlgorithm, check.Equals, tpm2.HashAlgorithmSHA256) c.Assert(params.LoadSequences, check.HasLen, len(data.shims)) for i, e := range params.LoadSequences { f, err := e.Image.Open() c.Assert(err, check.IsNil) r := io.NewSectionReader(f, 0, 1<<63-1) b, err := ioutil.ReadAll(r) c.Check(err, check.IsNil) f.Close() c.Check(b, check.DeepEquals, data.shims[i]) c.Assert(e.Next, check.HasLen, len(data.kernels)) for i, e := range e.Next { f, err := e.Image.Open() c.Assert(err, check.IsNil) r := io.NewSectionReader(f, 0, 1<<63-1) b, err := ioutil.ReadAll(r) c.Check(err, check.IsNil) f.Close() c.Check(b, check.DeepEquals, data.kernels[i]) } } profile.AddPCRValue(tpm2.HashAlgorithmSHA256, 4, make([]byte, 32)) return nil }) defer restore() restore = s.mockSbefiAddSecureBootPolicyProfile(func(profile *secboot_tpm2.PCRProtectionProfile, params *secboot_efi.SecureBootPolicyProfileParams) error { c.Assert(profile, check.NotNil) c.Check(params.PCRAlgorithm, check.Equals, tpm2.HashAlgorithmSHA256) c.Assert(params.LoadSequences, check.HasLen, len(data.shims)) for i, e := range params.LoadSequences { c.Check(e.Source, check.Equals, secboot_efi.Firmware) f, err := e.Image.Open() c.Assert(err, check.IsNil) r := io.NewSectionReader(f, 0, 1<<63-1) b, err := ioutil.ReadAll(r) c.Check(err, check.IsNil) f.Close() c.Check(b, check.DeepEquals, data.shims[i]) c.Assert(e.Next, check.HasLen, len(data.kernels)) for i, e := range e.Next { c.Check(e.Source, check.Equals, secboot_efi.Shim) f, err := e.Image.Open() c.Assert(err, check.IsNil) r := io.NewSectionReader(f, 0, 1<<63-1) b, err := ioutil.ReadAll(r) c.Check(err, check.IsNil) f.Close() c.Check(b, check.DeepEquals, data.kernels[i]) } } profile.AddPCRValue(tpm2.HashAlgorithmSHA256, 7, make([]byte, 32)) return nil }) defer restore() n := 0 restore = s.mockSbGetAuxiliaryKeyFromKernel(func(prefix, devicePath string, remove bool) (secboot.AuxiliaryKey, error) { c.Check(prefix, check.Equals, "ubuntu-fde") c.Check(devicePath, check.Equals, data.devicePaths[n]) c.Check(remove, check.Equals, false) c.Check(userKeyringLinkedFromProcessKeyring, check.Equals, true) n++ if n < len(data.devicePaths) { return nil, secboot.ErrKernelKeyNotFound } return data.auxiliaryKey, nil }) defer restore() restore = s.mockSbtpmConnectToDefaultTPM(func() (*secboot_tpm2.Connection, error) { c.Check(expectedTpm, check.IsNil) tcti, err := linux.OpenDevice("/dev/null") c.Assert(err, check.IsNil) expectedTpm = &secboot_tpm2.Connection{TPMContext: tpm2.NewTPMContext(tcti)} return expectedTpm, nil }) defer restore() restore = s.mockSbtpmReadSealedKeyObjectFromFile(func(path string) (*secboot_tpm2.SealedKeyObject, error) { c.Check(expectedSko, check.IsNil) c.Check(path, check.Equals, "/boot/efi/device/fde/cloudimg-rootfs.sealed-key") expectedSko = &secboot_tpm2.SealedKeyObject{} return expectedSko, nil }) defer restore() restore = s.mockSbtpmSealedKeyObjectUpdatePCRProtectionPolicy(func(k *secboot_tpm2.SealedKeyObject, tpm *secboot_tpm2.Connection, authKey secboot_tpm2.PolicyAuthKey, profile *secboot_tpm2.PCRProtectionProfile) error { c.Check(k, check.Equals, expectedSko) c.Check(tpm, check.Equals, expectedTpm) c.Check(authKey, check.DeepEquals, secboot_tpm2.PolicyAuthKey(data.auxiliaryKey)) c.Assert(profile, check.NotNil) pcrs, _, err := profile.ComputePCRDigests(nil, tpm2.HashAlgorithmSHA256) c.Check(err, check.IsNil) c.Check(pcrs.Equal(tpm2.PCRSelectionList{{Hash: tpm2.HashAlgorithmSHA256, Select: []int{4, 7, 12}}}), check.Equals, true) return nil }) defer restore() restore = s.mockSbtpmSealedKeyObjectWriteAtomic(func(k *secboot_tpm2.SealedKeyObject, w secboot.KeyDataWriter) error { c.Check(k, check.Equals, expectedSko) fw, ok := w.(*secboot_tpm2.FileSealedKeyObjectWriter) c.Check(ok, check.Equals, true) c.Check(fw, check.NotNil) return nil }) defer restore() restore = s.mockUnixKeyctlInt(func(cmd, arg2, arg3, arg4, arg5 int) (int, error) { if cmd == unix.KEYCTL_LINK && arg2 == -4 && arg3 == -2 && arg4 == 0 && arg5 == 0 { userKeyringLinkedFromProcessKeyring = true } return 0, nil }) defer restore() mockvars := MockEFIVariables{map[efi.VariableDescriptor]mockEFIVariable{{GUID: efi.GlobalVariable, Name: "BootOrder"}: {[]byte{1, 0, 2, 0, 3, 0}, 123}}} assets, err := ReadTrustedAssets() c.Assert(err, check.IsNil) c.Check(assets.TrustNewFromDir("/boot/efi/EFI/ubuntu"), check.IsNil) c.Check(assets.TrustNewFromDir("/usr/lib/nullboot/shim"), check.IsNil) c.Check(assets.TrustNewFromDir("/usr/lib/linux"), check.IsNil) bm, err := NewBootManagerForVariables(&mockvars) c.Assert(err, check.IsNil) km, err := NewKernelManager("/boot/efi", "/usr/lib/linux", "ubuntu", &bm) c.Assert(err, check.IsNil) c.Check(ResealKey(assets, km, "/boot/efi", "/usr/lib/nullboot/shim", "ubuntu"), check.IsNil) } func (s *resealSuite) TestResealKeyNoFDE(c *check.C) { c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/shimx64.efi", []byte("shim1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/nullboot/shim/shimx64.efi.signed", []byte("shim1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/kernel.efi-1.0-1-generic", []byte("kernel1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/linux/kernel-efi.1.0-2-generic", []byte("kernel2"), 0600), check.IsNil) s.testResealKey(c, &testResealKeyData{}) } func (s *resealSuite) TestResealKeyBeforeNewKernel(c *check.C) { c.Check(s.fs.WriteFile("/dev/sda1", nil, os.ModeDevice|0660), check.IsNil) s.symlink(c, "/dev/sda1", "/dev/disk/by-label/cloudimg-rootfs-enc") c.Check(s.fs.WriteFile("/boot/efi/device/fde/cloudimg-rootfs.sealed-key", []byte("key data"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/shimx64.efi", []byte("shim1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/nullboot/shim/shimx64.efi.signed", []byte("shim1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/kernel.efi-1.0-1-generic", []byte("kernel1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/linux/kernel.efi-1.0-1-generic", []byte("kernel1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/linux/kernel.efi-1.0-2-generic", []byte("kernel2"), 0600), check.IsNil) s.testResealKey(c, &testResealKeyData{ arch: "x64", auxiliaryKey: []byte{1, 2, 3, 4, 5, 6}, devicePaths: []string{"/dev/sda1"}, shims: [][]byte{ []byte("shim1"), []byte("shim1"), }, kernels: [][]byte{ []byte("kernel2"), []byte("kernel1"), []byte("kernel1"), }, }) } func (s *resealSuite) TestResealKeyAfterNewKernel(c *check.C) { c.Check(s.fs.WriteFile("/dev/sda1", nil, os.ModeDevice|0660), check.IsNil) s.symlink(c, "/dev/sda1", "/dev/disk/by-label/cloudimg-rootfs-enc") c.Check(s.fs.WriteFile("/boot/efi/device/fde/cloudimg-rootfs.sealed-key", []byte("key data"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/shimx64.efi", []byte("shim1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/nullboot/shim/shimx64.efi.signed", []byte("shim1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/kernel.efi-1.0-1-generic", []byte("kernel1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/kernel.efi-1.0-2-generic", []byte("kernel2"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/linux/kernel.efi-1.0-1-generic", []byte("kernel1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/linux/kernel.efi-1.0-2-generic", []byte("kernel2"), 0600), check.IsNil) s.testResealKey(c, &testResealKeyData{ arch: "x64", auxiliaryKey: []byte{1, 2, 3, 4, 5, 6}, devicePaths: []string{"/dev/sda1"}, shims: [][]byte{ []byte("shim1"), []byte("shim1"), }, kernels: [][]byte{ []byte("kernel2"), []byte("kernel1"), []byte("kernel2"), []byte("kernel1"), }, }) } func (s *resealSuite) TestResealKeyBeforeNewShim(c *check.C) { c.Check(s.fs.WriteFile("/dev/sda1", nil, os.ModeDevice|0660), check.IsNil) s.symlink(c, "/dev/sda1", "/dev/disk/by-label/cloudimg-rootfs-enc") c.Check(s.fs.WriteFile("/boot/efi/device/fde/cloudimg-rootfs.sealed-key", []byte("key data"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/shimx64.efi", []byte("shim1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/nullboot/shim/shimx64.efi.signed", []byte("shim2"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/kernel.efi-1.0-1-generic", []byte("kernel1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/linux/kernel.efi-1.0-1-generic", []byte("kernel1"), 0600), check.IsNil) s.testResealKey(c, &testResealKeyData{ arch: "x64", auxiliaryKey: []byte{1, 2, 3, 4, 5, 6}, devicePaths: []string{"/dev/sda1"}, shims: [][]byte{ []byte("shim2"), []byte("shim1"), }, kernels: [][]byte{ []byte("kernel1"), []byte("kernel1"), }, }) } func (s *resealSuite) TestResealKeyAfterNewShim(c *check.C) { c.Check(s.fs.WriteFile("/dev/sda1", nil, os.ModeDevice|0660), check.IsNil) s.symlink(c, "/dev/sda1", "/dev/disk/by-label/cloudimg-rootfs-enc") c.Check(s.fs.WriteFile("/boot/efi/device/fde/cloudimg-rootfs.sealed-key", []byte("key data"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/shimx64.efi", []byte("shim2"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/nullboot/shim/shimx64.efi.signed", []byte("shim2"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/kernel.efi-1.0-1-generic", []byte("kernel1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/linux/kernel.efi-1.0-1-generic", []byte("kernel1"), 0600), check.IsNil) s.testResealKey(c, &testResealKeyData{ arch: "x64", auxiliaryKey: []byte{1, 2, 3, 4, 5, 6}, devicePaths: []string{"/dev/sda1"}, shims: [][]byte{ []byte("shim2"), []byte("shim2"), }, kernels: [][]byte{ []byte("kernel1"), []byte("kernel1"), }, }) } func (s *resealSuite) TestResealKeyBeforeRemoveKernel(c *check.C) { c.Check(s.fs.WriteFile("/dev/sda1", nil, os.ModeDevice|0660), check.IsNil) s.symlink(c, "/dev/sda1", "/dev/disk/by-label/cloudimg-rootfs-enc") c.Check(s.fs.WriteFile("/boot/efi/device/fde/cloudimg-rootfs.sealed-key", []byte("key data"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/shimx64.efi", []byte("shim1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/nullboot/shim/shimx64.efi.signed", []byte("shim1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/kernel.efi-1.0-1-generic", []byte("kernel1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/kernel.efi-1.0-2-generic", []byte("kernel2"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/linux/kernel.efi-1.0-2-generic", []byte("kernel2"), 0600), check.IsNil) s.testResealKey(c, &testResealKeyData{ arch: "x64", auxiliaryKey: []byte{1, 2, 3, 4, 5, 6}, devicePaths: []string{"/dev/sda1"}, shims: [][]byte{ []byte("shim1"), []byte("shim1"), }, kernels: [][]byte{ []byte("kernel2"), []byte("kernel2"), []byte("kernel1"), }, }) } func (s *resealSuite) TestResealKeyAfterRemoveKernel(c *check.C) { c.Check(s.fs.WriteFile("/dev/sda1", nil, os.ModeDevice|0660), check.IsNil) s.symlink(c, "/dev/sda1", "/dev/disk/by-label/cloudimg-rootfs-enc") c.Check(s.fs.WriteFile("/boot/efi/device/fde/cloudimg-rootfs.sealed-key", []byte("key data"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/shimx64.efi", []byte("shim1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/nullboot/shim/shimx64.efi.signed", []byte("shim1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/kernel.efi-1.0-2-generic", []byte("kernel2"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/linux/kernel.efi-1.0-2-generic", []byte("kernel2"), 0600), check.IsNil) s.testResealKey(c, &testResealKeyData{ arch: "x64", auxiliaryKey: []byte{1, 2, 3, 4, 5, 6}, devicePaths: []string{"/dev/sda1"}, shims: [][]byte{ []byte("shim1"), []byte("shim1"), }, kernels: [][]byte{ []byte("kernel2"), []byte("kernel2"), }, }) } func (s *resealSuite) TestResealKeyDifferentAuxiliaryKey(c *check.C) { c.Check(s.fs.WriteFile("/dev/sda1", nil, os.ModeDevice|0660), check.IsNil) s.symlink(c, "/dev/sda1", "/dev/disk/by-label/cloudimg-rootfs-enc") c.Check(s.fs.WriteFile("/boot/efi/device/fde/cloudimg-rootfs.sealed-key", []byte("key data"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/shimx64.efi", []byte("shim1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/nullboot/shim/shimx64.efi.signed", []byte("shim2"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/kernel.efi-1.0-1-generic", []byte("kernel1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/linux/kernel.efi-1.0-1-generic", []byte("kernel1"), 0600), check.IsNil) s.testResealKey(c, &testResealKeyData{ arch: "x64", auxiliaryKey: []byte{5, 6, 7, 8, 9}, devicePaths: []string{"/dev/sda1"}, shims: [][]byte{ []byte("shim2"), []byte("shim1"), }, kernels: [][]byte{ []byte("kernel1"), []byte("kernel1"), }, }) } func (s *resealSuite) TestResealKeyDifferentBlockDevice(c *check.C) { c.Check(s.fs.WriteFile("/dev/vda14", nil, os.ModeDevice|0660), check.IsNil) s.symlink(c, "/dev/vda14", "/dev/disk/by-label/cloudimg-rootfs-enc") c.Check(s.fs.WriteFile("/boot/efi/device/fde/cloudimg-rootfs.sealed-key", []byte("key data"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/shimx64.efi", []byte("shim1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/nullboot/shim/shimx64.efi.signed", []byte("shim2"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/kernel.efi-1.0-1-generic", []byte("kernel1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/linux/kernel.efi-1.0-1-generic", []byte("kernel1"), 0600), check.IsNil) s.testResealKey(c, &testResealKeyData{ arch: "x64", auxiliaryKey: []byte{1, 2, 3, 4, 5, 6}, devicePaths: []string{"/dev/vda14"}, shims: [][]byte{ []byte("shim2"), []byte("shim1"), }, kernels: [][]byte{ []byte("kernel1"), []byte("kernel1"), }, }) } func (s *resealSuite) TestResealKeyDifferentArch(c *check.C) { c.Check(s.fs.WriteFile("/dev/sda1", nil, os.ModeDevice|0660), check.IsNil) s.symlink(c, "/dev/sda1", "/dev/disk/by-label/cloudimg-rootfs-enc") c.Check(s.fs.WriteFile("/boot/efi/device/fde/cloudimg-rootfs.sealed-key", []byte("key data"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/shimaa64.efi", []byte("shim1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/nullboot/shim/shimaa64.efi.signed", []byte("shim1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/kernel.efi-1.0-1-generic", []byte("kernel1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/linux/kernel.efi-1.0-1-generic", []byte("kernel1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/linux/kernel.efi-1.0-2-generic", []byte("kernel2"), 0600), check.IsNil) s.testResealKey(c, &testResealKeyData{ arch: "aa64", auxiliaryKey: []byte{1, 2, 3, 4, 5, 6}, devicePaths: []string{"/dev/sda1"}, shims: [][]byte{ []byte("shim1"), []byte("shim1"), }, kernels: [][]byte{ []byte("kernel2"), []byte("kernel1"), []byte("kernel1"), }, }) } func (s *resealSuite) TestResealKeyGetAuxiliaryKeyFromKernelBug(c *check.C) { c.Check(s.fs.WriteFile("/dev/sda1", nil, os.ModeDevice|0660), check.IsNil) c.Check(s.fs.WriteFile("/dev/sda15", nil, os.ModeDevice|0660), check.IsNil) s.symlink(c, "/dev/sda1", "/dev/disk/by-label/cloudimg-rootfs-enc") s.symlink(c, "/dev/sda1", "/dev/disk/by-partuuid/94725587-885d-4bde-bc61-078e0010057d") s.symlink(c, "/dev/sda15", "/dev/disk/by-partuuid/848b8304-0f20-42e9-9806-b447ce344d85") c.Check(s.fs.WriteFile("/boot/efi/device/fde/cloudimg-rootfs.sealed-key", []byte("key data"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/shimx64.efi", []byte("shim1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/nullboot/shim/shimx64.efi.signed", []byte("shim2"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/kernel.efi-1.0-1-generic", []byte("kernel1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/linux/kernel.efi-1.0-1-generic", []byte("kernel1"), 0600), check.IsNil) s.testResealKey(c, &testResealKeyData{ arch: "x64", auxiliaryKey: []byte{1, 2, 3, 4, 5, 6}, devicePaths: []string{"/dev/sda1", "/dev/disk/by-partuuid/94725587-885d-4bde-bc61-078e0010057d"}, shims: [][]byte{ []byte("shim2"), []byte("shim1"), }, kernels: [][]byte{ []byte("kernel1"), []byte("kernel1"), }, }) } type testResealKeyUnhappyData struct { noAuxKey bool fileLeak bool untrustedAssets bool noTpm bool } func (s *resealSuite) testResealKeyUnhappy(c *check.C, data *testResealKeyUnhappyData) error { c.Check(s.fs.WriteFile("/dev/sda1", nil, os.ModeDevice|0660), check.IsNil) s.symlink(c, "/dev/sda1", "/dev/disk/by-label/cloudimg-rootfs-enc") c.Check(s.fs.WriteFile("/boot/efi/device/fde/cloudimg-rootfs.sealed-key", []byte("key data"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/shimx64.efi", []byte("shim1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/nullboot/shim/shimx64.efi.signed", []byte("shim2"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/kernel.efi-1.0-1-generic", []byte("kernel1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/usr/lib/linux/kernel.efi-1.0-1-generic", []byte("kernel1"), 0600), check.IsNil) restore := s.mockEfiArch("x64") defer restore() restore = s.mockSbefiAddBootManagerProfile(func(profile *secboot_tpm2.PCRProtectionProfile, params *secboot_efi.BootManagerProfileParams) error { if data.fileLeak { params.LoadSequences[0].Image.Open() } for _, e := range params.LoadSequences { f, err := e.Image.Open() c.Assert(err, check.IsNil) f.Close() for _, e := range e.Next { f, err := e.Image.Open() c.Assert(err, check.IsNil) f.Close() } } return nil }) defer restore() restore = s.mockSbefiAddSecureBootPolicyProfile(func(profile *secboot_tpm2.PCRProtectionProfile, params *secboot_efi.SecureBootPolicyProfileParams) error { for _, e := range params.LoadSequences { f, err := e.Image.Open() c.Assert(err, check.IsNil) f.Close() for _, e := range e.Next { f, err := e.Image.Open() c.Assert(err, check.IsNil) f.Close() } } return nil }) defer restore() restore = s.mockSbGetAuxiliaryKeyFromKernel(func(prefix, devicePath string, remove bool) (secboot.AuxiliaryKey, error) { if data.noAuxKey { return nil, secboot.ErrKernelKeyNotFound } return nil, nil }) defer restore() restore = s.mockSbtpmConnectToDefaultTPM(func() (*secboot_tpm2.Connection, error) { if data.noTpm { return nil, secboot_tpm2.ErrNoTPM2Device } tcti, err := linux.OpenDevice("/dev/null") c.Assert(err, check.IsNil) return &secboot_tpm2.Connection{TPMContext: tpm2.NewTPMContext(tcti)}, nil }) defer restore() restore = s.mockSbtpmReadSealedKeyObjectFromFile(func(path string) (*secboot_tpm2.SealedKeyObject, error) { return &secboot_tpm2.SealedKeyObject{}, nil }) defer restore() restore = s.mockSbtpmSealedKeyObjectUpdatePCRProtectionPolicy(func(k *secboot_tpm2.SealedKeyObject, tpm *secboot_tpm2.Connection, authKey secboot_tpm2.PolicyAuthKey, profile *secboot_tpm2.PCRProtectionProfile) error { return nil }) defer restore() restore = s.mockSbtpmSealedKeyObjectWriteAtomic(func(k *secboot_tpm2.SealedKeyObject, w secboot.KeyDataWriter) error { return nil }) defer restore() restore = s.mockUnixKeyctlInt(func(cmd, arg2, arg3, arg4, arg5 int) (int, error) { return 0, nil }) defer restore() mockvars := MockEFIVariables{map[efi.VariableDescriptor]mockEFIVariable{{GUID: efi.GlobalVariable, Name: "BootOrder"}: {[]byte{1, 0, 2, 0, 3, 0}, 123}}} assets, err := ReadTrustedAssets() c.Assert(err, check.IsNil) if !data.untrustedAssets { c.Check(assets.TrustNewFromDir("/boot/efi/EFI/ubuntu"), check.IsNil) } c.Check(assets.TrustNewFromDir("/usr/lib/nullboot/shim"), check.IsNil) c.Check(assets.TrustNewFromDir("/usr/lib/linux"), check.IsNil) bm, err := NewBootManagerForVariables(&mockvars) c.Assert(err, check.IsNil) km, err := NewKernelManager("/boot/efi", "/usr/lib/linux", "ubuntu", &bm) c.Assert(err, check.IsNil) return ResealKey(assets, km, "/boot/efi", "/usr/lib/nullboot/shim", "ubuntu") } func (s *resealSuite) TestResealKeyUnhappyNoAuxiliaryKey(c *check.C) { err := s.testResealKeyUnhappy(c, &testResealKeyUnhappyData{ noAuxKey: true, }) c.Check(err, check.ErrorMatches, "cannot obtain auth key from kernel: cannot read key from kernel: cannot find key in kernel keyring") } func (s *resealSuite) TestResealKeyUnhappyFileLeak(c *check.C) { err := s.testResealKeyUnhappy(c, &testResealKeyUnhappyData{ fileLeak: true, }) c.Check(err, check.ErrorMatches, "leaked open files from computing PCR profile") } func (s *resealSuite) TestResealKeyUnhappyUntrustedAssets(c *check.C) { err := s.testResealKeyUnhappy(c, &testResealKeyUnhappyData{ untrustedAssets: true, }) c.Check(err, check.ErrorMatches, "some assets failed an integrity check: \\[/boot/efi/EFI/ubuntu/shimx64.efi /boot/efi/EFI/ubuntu/shimx64.efi\\]") } func (s *resealSuite) TestResealKeyUnhappyNoTPM(c *check.C) { err := s.testResealKeyUnhappy(c, &testResealKeyUnhappyData{ noTpm: true, }) c.Check(err, check.ErrorMatches, "no TPM2 device is available") } // The TCG log writing code is borrowed from github.com:snapcore/secboot tools/make-efi-testdata/logs.go // to avoid checking in a binary log type event struct { PCRIndex tcglog.PCRIndex EventType tcglog.EventType Data tcglog.EventData } type eventData interface { Write(w io.Writer) error } type bytesData []byte func (d bytesData) Write(w io.Writer) error { _, err := w.Write(d) return err } type logWriter struct { algs []tpm2.HashAlgorithmId events []*tcglog.Event } func newCryptoAgileLogWriter() *logWriter { event := &tcglog.Event{ PCRIndex: 0, EventType: tcglog.EventTypeNoAction, Digests: tcglog.DigestMap{tpm2.HashAlgorithmSHA1: make(tcglog.Digest, tpm2.HashAlgorithmSHA1.Size())}, Data: &tcglog.SpecIdEvent03{ SpecVersionMajor: 2, UintnSize: 2, DigestSizes: []tcglog.EFISpecIdEventAlgorithmSize{ {AlgorithmId: tpm2.HashAlgorithmSHA1, DigestSize: uint16(tpm2.HashAlgorithmSHA1.Size())}, {AlgorithmId: tpm2.HashAlgorithmSHA256, DigestSize: uint16(tpm2.HashAlgorithmSHA256.Size())}}}} return &logWriter{ algs: []tpm2.HashAlgorithmId{tpm2.HashAlgorithmSHA1, tpm2.HashAlgorithmSHA256}, events: []*tcglog.Event{event}} } func (w *logWriter) hashLogExtendEvent(data eventData, event *event) { ev := &tcglog.Event{ PCRIndex: event.PCRIndex, EventType: event.EventType, Digests: make(tcglog.DigestMap), Data: event.Data} for _, alg := range w.algs { h := alg.NewHash() if err := data.Write(h); err != nil { panic(err) } ev.Digests[alg] = h.Sum(nil) } w.events = append(w.events, ev) } func (s *resealSuite) writeMockTcglog(c *check.C) { w := newCryptoAgileLogWriter() { data := &tcglog.SeparatorEventData{Value: tcglog.SeparatorEventNormalValue} w.hashLogExtendEvent(data, &event{ PCRIndex: 7, EventType: tcglog.EventTypeSeparator, Data: data}) } { data := tcglog.EFICallingEFIApplicationEvent w.hashLogExtendEvent(data, &event{ PCRIndex: 4, EventType: tcglog.EventTypeEFIAction, Data: data}) } for _, pcr := range []tcglog.PCRIndex{0, 1, 2, 3, 4, 5, 6} { data := &tcglog.SeparatorEventData{Value: tcglog.SeparatorEventNormalValue} w.hashLogExtendEvent(data, &event{ PCRIndex: pcr, EventType: tcglog.EventTypeSeparator, Data: data}) } { pe := bytesData("mock shim PE") data := &tcglog.EFIImageLoadEvent{ LocationInMemory: 0x6556c018, LengthInMemory: 955072, DevicePath: efi.DevicePath{ &efi.ACPIDevicePathNode{ HID: 0x0a0341d0, UID: 0x0}, &efi.PCIDevicePathNode{ Function: 0x0, Device: 0x1d}, &efi.PCIDevicePathNode{ Function: 0x0, Device: 0x0}, &efi.NVMENamespaceDevicePathNode{ NamespaceID: 0x1, NamespaceUUID: 0x0}, &efi.HardDriveDevicePathNode{ PartitionNumber: 1, PartitionStart: 0x800, PartitionSize: 0x100000, Signature: efi.GUIDHardDriveSignature(efi.MakeGUID(0x66de947b, 0xfdb2, 0x4525, 0xb752, [...]uint8{0x30, 0xd6, 0x6b, 0xb2, 0xb9, 0x60})), MBRType: efi.GPT}, efi.FilePathDevicePathNode("\\EFI\\ubuntu\\shimx64.efi")}} w.hashLogExtendEvent(pe, &event{ PCRIndex: 4, EventType: tcglog.EventTypeEFIBootServicesApplication, Data: data}) } { pe := bytesData("mock kernel PE") data := &tcglog.EFIImageLoadEvent{ DevicePath: efi.DevicePath{efi.FilePathDevicePathNode("\\EFI\\ubuntu\\kernel.efi-1.0-1-generic")}} w.hashLogExtendEvent(pe, &event{ PCRIndex: 4, EventType: tcglog.EventTypeEFIBootServicesApplication, Data: data}) } f, err := s.fs.OpenFile("/sys/kernel/security/tpm0/binary_bios_measurements", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0644) c.Assert(err, check.IsNil) defer f.Close() c.Check(tcglog.WriteLog(f, w.events), check.IsNil) } func (s *resealSuite) mockEfiComputePeImageDigest(fn func(alg crypto.Hash, r io.ReaderAt, sz int64) ([]byte, error)) (restore func()) { orig := efiComputePeImageDigest efiComputePeImageDigest = fn return func() { efiComputePeImageDigest = orig } } func (s *resealSuite) TestTrustCurrentBoot(c *check.C) { c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/shimx64.efi", []byte("shim1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/kernel.efi-1.0-1-generic", []byte("kernel1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/kernel.efi-1.0-2-generic", []byte("kernel2"), 0600), check.IsNil) s.writeMockTcglog(c) restore := s.mockEfiComputePeImageDigest(func(alg crypto.Hash, r io.ReaderAt, sz int64) ([]byte, error) { r2 := io.NewSectionReader(r, 0, sz) b, err := ioutil.ReadAll(r2) c.Check(err, check.IsNil) switch { case bytes.Equal(b, []byte("shim1")): return decodeHexString(c, "93c294bd9d372cf76e3cfd6f66a93fd2586aeb0406677ea0df104349b2ec093d"), nil case bytes.Equal(b, []byte("kernel1")): return decodeHexString(c, "54a5737f95928a359ba326bda6405a8e91fd06869cdb76f7f53aae83c1050308"), nil default: c.Fatal("invalid file") } return nil, nil }) defer restore() assets := newTrustedAssets() c.Check(TrustCurrentBoot(assets, "/boot/efi"), check.IsNil) c.Check(assets.loaded.Hashes, check.DeepEquals, [][]byte{ decodeHexString(c, "efbef08d5d3787d609ec6b55fabc36c7f212140b97a88606a39dc8f732368147"), decodeHexString(c, "7e8c4310bd1e228888917fb5f87920426dbecd64ea7d6c2256740f80e39dcf6f")}) c.Check(assets.newAssets, check.DeepEquals, [][]byte{ decodeHexString(c, "efbef08d5d3787d609ec6b55fabc36c7f212140b97a88606a39dc8f732368147"), decodeHexString(c, "7e8c4310bd1e228888917fb5f87920426dbecd64ea7d6c2256740f80e39dcf6f")}) } func (s *resealSuite) TestTrustCurrentBootRejectPeHashMismatch(c *check.C) { c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/shimx64.efi", []byte("shim1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/kernel.efi-1.0-1-generic", []byte("kernel1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/kernel.efi-1.0-2-generic", []byte("kernel2"), 0600), check.IsNil) s.writeMockTcglog(c) restore := s.mockEfiComputePeImageDigest(func(alg crypto.Hash, r io.ReaderAt, sz int64) ([]byte, error) { r2 := io.NewSectionReader(r, 0, sz) b, err := ioutil.ReadAll(r2) c.Check(err, check.IsNil) switch { case bytes.Equal(b, []byte("shim1")): return decodeHexString(c, "93c294bd9d372cf76e3cfd6f66a93fd2586aeb0406677ea0df104349b2ec093f"), nil case bytes.Equal(b, []byte("kernel1")): return decodeHexString(c, "54a5737f95928a359ba326bda6405a8e91fd06869cdb76f7f53aae83c1050308"), nil default: c.Fatal("invalid file") } return nil, nil }) defer restore() assets := newTrustedAssets() c.Check(TrustCurrentBoot(assets, "/boot/efi"), check.IsNil) c.Check(assets.loaded.Hashes, check.DeepEquals, [][]byte{ decodeHexString(c, "7e8c4310bd1e228888917fb5f87920426dbecd64ea7d6c2256740f80e39dcf6f")}) c.Check(assets.newAssets, check.DeepEquals, [][]byte{ decodeHexString(c, "7e8c4310bd1e228888917fb5f87920426dbecd64ea7d6c2256740f80e39dcf6f")}) } func (s *resealSuite) TestTrustCurrentBootRejectMissing(c *check.C) { c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/shimx64.efi", []byte("shim1"), 0600), check.IsNil) c.Check(s.fs.WriteFile("/boot/efi/EFI/ubuntu/kernel.efi-1.0-2-generic", []byte("kernel2"), 0600), check.IsNil) s.writeMockTcglog(c) restore := s.mockEfiComputePeImageDigest(func(alg crypto.Hash, r io.ReaderAt, sz int64) ([]byte, error) { r2 := io.NewSectionReader(r, 0, sz) b, err := ioutil.ReadAll(r2) c.Check(err, check.IsNil) switch { case bytes.Equal(b, []byte("shim1")): return decodeHexString(c, "93c294bd9d372cf76e3cfd6f66a93fd2586aeb0406677ea0df104349b2ec093d"), nil case bytes.Equal(b, []byte("kernel1")): return decodeHexString(c, "54a5737f95928a359ba326bda6405a8e91fd06869cdb76f7f53aae83c1050308"), nil default: c.Fatal("invalid file") } return nil, nil }) defer restore() assets := newTrustedAssets() c.Check(TrustCurrentBoot(assets, "/boot/efi"), check.IsNil) c.Check(assets.loaded.Hashes, check.DeepEquals, [][]byte{ decodeHexString(c, "efbef08d5d3787d609ec6b55fabc36c7f212140b97a88606a39dc8f732368147")}) c.Check(assets.newAssets, check.DeepEquals, [][]byte{ decodeHexString(c, "efbef08d5d3787d609ec6b55fabc36c7f212140b97a88606a39dc8f732368147")}) } nullboot-0.5.0/efibootmgr/shim.go000066400000000000000000000100611453331565400170050ustar00rootroot00000000000000// This file is part of nullboot // Copyright 2021 Canonical Ltd. // SPDX-License-Identifier: GPL-3.0-only package efibootmgr import ( "fmt" "golang.org/x/text/encoding/unicode" "golang.org/x/text/transform" "io" "path" "path/filepath" "runtime" "strings" ) // BootEntry is a boot entry. type BootEntry struct { Filename string Label string Options string Description string } // architectureMaps maps from GOARCH to host var architectureMap = map[string]string{ "386": "ia32", "amd64": "x64", "arm": "arm", "arm64": "aa64", "riscv": "riscv32", "riscv64": "riscv64", "riscv128": "riscv128", } // appArchitecture can be overriden in a test case for testing purposes var appArchitecture = "" // GetEfiArchitecture returns the EFI architecture for the target system func GetEfiArchitecture() string { if appArchitecture != "" { return appArchitecture } return architectureMap[runtime.GOARCH] } // WriteShimFallbackToFile opens the specified path in UTF-16LE and then calls WriteShimFallback func WriteShimFallbackToFile(path string, entries []BootEntry) error { file, err := appFs.TempFile(filepath.Dir(path), "."+filepath.Base(path)+".") if err != nil { return fmt.Errorf("could not open %s: %w", path, err) } defer func() { name := file.Name() file.Close() if err != nil { appFs.Remove(name) } }() writer := transform.NewWriter(file, unicode.UTF16(unicode.LittleEndian, unicode.IgnoreBOM).NewEncoder()) if err = WriteShimFallback(writer, entries); err != nil { return err } if err := appFs.Rename(file.Name(), path); err != nil { return err } return err } // WriteShimFallback writes out a BOOT*.CSV for the shim fallback loader to the specified writer. // The output of this function is unencoded, use a transformed UTF-16 writer. func WriteShimFallback(w io.Writer, entries []BootEntry) error { // sigh, fallback prepends entries to the boot order so last line comes first, so we // need to write out the lines in reverse boot order. for i := len(entries); i > 0; i-- { entry := entries[i-1] if strings.Contains(entry.Filename, ",") || strings.Contains(entry.Label, ",") || strings.Contains(entry.Options, ",") || strings.Contains(entry.Description, ",") { return fmt.Errorf("entry '%s' contains ',' in one of the attributes, this is not supported", entry.Label) } // We have an empty space after Options, because if there is no space in the options, shim // does not seem to parse them at all. var options = entry.Options if options != "" { options += " " } _, err := fmt.Fprintf(w, "%s,%s,%s,%s\n", entry.Filename, entry.Label, options, entry.Description) if err != nil { return fmt.Errorf("Could not write entry '%s' to file: %w", entry.Label, err) } } return nil } // InstallShim installs the shim into the given ESP for the given vendor // It returns true if it installed the shim. func InstallShim(esp string, source string, vendor string) (bool, error) { if err := appFs.MkdirAll(path.Join(esp, "EFI", "BOOT"), 0644); err != nil { return false, fmt.Errorf("Could not create BOOT directory on ESP: %w", err) } if err := appFs.MkdirAll(path.Join(esp, "EFI", vendor), 0644); err != nil { return false, fmt.Errorf("Could not create vendor directory on ESP: %w", err) } updatedAny := false shim := "shim" + GetEfiArchitecture() + ".efi" fb := "fb" + GetEfiArchitecture() + ".efi" mm := "mm" + GetEfiArchitecture() + ".efi" removable := "BOOT" + strings.ToUpper(GetEfiArchitecture()) + ".EFI" copies := map[string]string{ path.Join(esp, "EFI", "BOOT", removable): shim + ".signed", path.Join(esp, "EFI", "BOOT", fb): fb, path.Join(esp, "EFI", "BOOT", mm): mm, path.Join(esp, "EFI", vendor, shim): shim + ".signed", path.Join(esp, "EFI", vendor, fb): fb, path.Join(esp, "EFI", vendor, mm): mm, } for dst, src := range copies { updated, err := MaybeUpdateFile(dst, path.Join(source, src)) if err != nil { return false, fmt.Errorf("Could not update file: %v", err) } updatedAny = updatedAny || updated } return updatedAny, nil } nullboot-0.5.0/efibootmgr/shim_test.go000066400000000000000000000057741453331565400200630ustar00rootroot00000000000000// This file is part of nullboot // Copyright 2021 Canonical Ltd. // SPDX-License-Identifier: GPL-3.0-only package efibootmgr import ( "github.com/spf13/afero" "bytes" "runtime" "testing" ) func TestGetEfiArchitecture(t *testing.T) { appArchitecture = "" arch := GetEfiArchitecture() if arch == "" { t.Fatalf("Unknown architecture: '%s'", runtime.GOARCH) } } func TestWriteShimFallback(t *testing.T) { appArchitecture = "x64" tests := []struct { label string input []BootEntry want string }{ {"basic", []BootEntry{{"shimx64.efi", "ubuntu", "", "This is the boot entry for ubuntu"}}, "shimx64.efi,ubuntu,,This is the boot entry for ubuntu\n"}, {"fwupd", []BootEntry{ {"shimx64.efi", "ubuntu", "", "This is the boot entry for ubuntu"}, {"shimx64.efi", "Linux-Firmware-Updater", "\\fwupdx64.efi", "This is the boot entry for Linux-Firmware-Updater"}, }, "shimx64.efi,Linux-Firmware-Updater,\\fwupdx64.efi ,This is the boot entry for Linux-Firmware-Updater\n" + "shimx64.efi,ubuntu,,This is the boot entry for ubuntu\n", }, } for _, tc := range tests { t.Run(tc.label, func(t *testing.T) { var w bytes.Buffer if err := WriteShimFallback(&w, tc.input); err != nil { t.Fatalf("error: %v", err) } got := w.String() if tc.want != got { t.Fatalf("Output does not match.\nexpected: %v\ngot:\n%v", tc.want, got) } }) } } func TestInstallShim_NoKernelsAvailable(t *testing.T) { appArchitecture = "x64" memFs := afero.NewMemMapFs() appFs = MapFS{memFs} updated, err := InstallShim("/boot/efi", "/usr/lib/nullboot/shim-signed", "ubuntu") if updated { t.Errorf("Unexpected update") } if err == nil { t.Errorf("Unexpected success") } } func TestInstallShim_BasicUpdate(t *testing.T) { appArchitecture = "x64" memFs := afero.NewMemMapFs() appFs = MapFS{memFs} afero.WriteFile(memFs, "/usr/lib/nullboot/shim-signed/shimx64.efi.signed", []byte("shim"), 0644) afero.WriteFile(memFs, "/usr/lib/nullboot/shim-signed/fbx64.efi", []byte("fb"), 0644) afero.WriteFile(memFs, "/usr/lib/nullboot/shim-signed/mmx64.efi", []byte("mm"), 0644) afero.WriteFile(memFs, "/boot/efi/EFI/BOOT/BOOTX64.EFI", []byte("old shim"), 0644) updated, err := InstallShim("/boot/efi", "/usr/lib/nullboot/shim-signed", "ubuntu") if err != nil { t.Errorf("Expected success, got error: %v", err) } if !updated { t.Errorf("Expected successful update") } copies := map[string]string{ "/boot/efi/EFI/BOOT/BOOTX64.EFI": "/usr/lib/nullboot/shim-signed/shimx64.efi.signed", "/boot/efi/EFI/BOOT/fbx64.efi": "/usr/lib/nullboot/shim-signed/fbx64.efi", "/boot/efi/EFI/BOOT/mmx64.efi": "/usr/lib/nullboot/shim-signed/mmx64.efi", "/boot/efi/EFI/ubuntu/shimx64.efi": "/usr/lib/nullboot/shim-signed/shimx64.efi.signed", "/boot/efi/EFI/ubuntu/fbx64.efi": "/usr/lib/nullboot/shim-signed/fbx64.efi", "/boot/efi/EFI/ubuntu/mmx64.efi": "/usr/lib/nullboot/shim-signed/mmx64.efi", } for dst, src := range copies { if err := CheckFilesEqual(memFs, dst, src); err != nil { t.Error(err) } } } nullboot-0.5.0/go.mod000066400000000000000000000026641453331565400145010ustar00rootroot00000000000000module github.com/canonical/nullboot go 1.18 require ( github.com/canonical/go-efilib v0.3.1-0.20220815143333-7e5151412e93 github.com/canonical/go-tpm2 v0.1.0 github.com/canonical/tcglog-parser v0.0.0-20220314144800-471071956aa1 github.com/knqyf263/go-deb-version v0.0.0-20230223133812-3ed183d23422 github.com/snapcore/secboot v0.0.0-20230623151406-4d331d24f830 github.com/spf13/afero v1.11.0 golang.org/x/sys v0.15.0 golang.org/x/text v0.14.0 gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c ) require ( github.com/canonical/go-sp800.108-kdf v0.0.0-20210315104021-ead800bbf9a0 // indirect github.com/canonical/go-sp800.90a-drbg v0.0.0-20210314144037-6eeb1040d6c3 // indirect github.com/godbus/dbus v4.1.0+incompatible // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect github.com/rogpeppe/go-internal v1.11.0 // indirect github.com/snapcore/go-gettext v0.0.0-20201130093759-38740d1bd3d2 // indirect github.com/snapcore/snapd v0.0.0-20231013114329-a9c308a6cdb9 // indirect go.mozilla.org/pkcs7 v0.0.0-20210826202110-33d05740a352 // indirect golang.org/x/crypto v0.16.0 // indirect golang.org/x/net v0.19.0 // indirect golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028 // indirect gopkg.in/retry.v1 v1.0.3 // indirect gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637 // indirect gopkg.in/yaml.v2 v2.4.0 // indirect maze.io/x/crypto v0.0.0-20190131090603-9b94c9afe066 // indirect ) nullboot-0.5.0/go.sum000066400000000000000000000217761453331565400145330ustar00rootroot00000000000000github.com/bsiegert/ranges v0.0.0-20111221115336-19303dc7aa63/go.mod h1:8z71/aZjDHLs4ihK/5nD5wZVQxm/W4eRDnxQZcJmVD4= github.com/canonical/go-efilib v0.3.1-0.20220314143719-95d50e8afc82/go.mod h1:9b2PNAuPcZsB76x75/uwH99D8CyH/A2y4rq1/+bvplg= github.com/canonical/go-efilib v0.3.1-0.20220815143333-7e5151412e93 h1:F0bRDzPy/j2IX/iIWqCEA23S1nal+f7A+/vLyj6Ye+4= github.com/canonical/go-efilib v0.3.1-0.20220815143333-7e5151412e93/go.mod h1:9b2PNAuPcZsB76x75/uwH99D8CyH/A2y4rq1/+bvplg= github.com/canonical/go-sp800.108-kdf v0.0.0-20210314145419-a3359f2d21b9/go.mod h1:Zrs3YjJr+w51u0R/dyLh/oWt/EcBVdLPCVFYC4daW5s= github.com/canonical/go-sp800.108-kdf v0.0.0-20210315104021-ead800bbf9a0 h1:ZE2XMRFHcwlib3uU9is37+pKkkMloVoEPWmgQ6GK1yo= github.com/canonical/go-sp800.108-kdf v0.0.0-20210315104021-ead800bbf9a0/go.mod h1:Zrs3YjJr+w51u0R/dyLh/oWt/EcBVdLPCVFYC4daW5s= github.com/canonical/go-sp800.90a-drbg v0.0.0-20210314144037-6eeb1040d6c3 h1:oe6fCvaEpkhyW3qAicT0TnGtyht/UrgvOwMcEgLb7Aw= github.com/canonical/go-sp800.90a-drbg v0.0.0-20210314144037-6eeb1040d6c3/go.mod h1:qdP0gaj0QtgX2RUZhnlVrceJ+Qln8aSlDyJwelLLFeM= github.com/canonical/go-tpm2 v0.1.0 h1:2mXU+Hy+zYSxmuYys2NtPEO6NwT3Qr9Sygwtops7NYk= github.com/canonical/go-tpm2 v0.1.0/go.mod h1:vG41hdbBjV4+/fkubTT1ENBBqSkLwLr7mCeW9Y6kpZY= github.com/canonical/tcglog-parser v0.0.0-20220314144800-471071956aa1 h1:JSg9RHT1AMIFIiYEM7hMUe3oI+hhnLpjcFwG+hcOUqE= github.com/canonical/tcglog-parser v0.0.0-20220314144800-471071956aa1/go.mod h1:AoJVV7tUwDDGPZkKqwqAMGdPiH7x45JLNmxFrxfoxcs= github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4= github.com/creack/pty v1.1.9/go.mod h1:oKZEueFk5CKHvIhNR5MUki03XCEU+Q6VDXinZuGJ33E= github.com/frankban/quicktest v1.2.2 h1:xfmOhhoH5fGPgbEAlhLpJH9p0z/0Qizio9osmvn9IUY= github.com/frankban/quicktest v1.2.2/go.mod h1:Qh/WofXFeiAFII1aEBu529AtJo6Zg2VHscnEsbBnJ20= github.com/godbus/dbus v4.1.0+incompatible h1:WqqLRTsQic3apZUK9qC5sGNfXthmPXzUZ7nQPrNITa4= github.com/godbus/dbus v4.1.0+incompatible/go.mod h1:/YcGZj5zSblfDWMMoOzV4fas9FZnQYTkDnsGvmh2Grw= github.com/google/go-cmp v0.2.1-0.20190312032427-6f77996f0c42 h1:q3pnF5JFBNRz8sRD+IRj7Y6DMyYGTNqnZ9axTbSfoNI= github.com/google/go-cmp v0.2.1-0.20190312032427-6f77996f0c42/go.mod h1:8QqcDgzrUqlUb/G2PQTWiueGozuR1884gddMywk6iLU= github.com/gorilla/mux v1.8.0/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So= github.com/jessevdk/go-flags v1.5.0/go.mod h1:Fw0T6WPc1dYxT4mKEZRfG5kJhaTDP9pj1c2EWnYs/m4= github.com/knqyf263/go-deb-version v0.0.0-20230223133812-3ed183d23422 h1:PPPlUUqPP6fLudIK4n0l0VU4KT2cQGnheW9x8pNiCHI= github.com/knqyf263/go-deb-version v0.0.0-20230223133812-3ed183d23422/go.mod h1:ijAmSS4jErO6+KRzcK6ixsm3Vt96hMhJ+W+x+VmbrQA= github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo= github.com/kr/pretty v0.2.1/go.mod h1:ipq/a2n7PKx3OHsz4KJII5eveXtPO4qwEXGdVfWzfnI= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ= github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/mvo5/goconfigparser v0.0.0-20201015074339-50f22f44deb5/go.mod h1:xmt4k1xLDl8Tdan+0S/jmMK2uSUBSzTc18+5GN5Vea8= github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/pkg/diff v0.0.0-20210226163009-20ebb0f2a09e/go.mod h1:pJLUxLENpZxwdsKMEsNbx1VGcRFpLqf3715MtcvvzbA= github.com/rogpeppe/clock v0.0.0-20190514195947-2896927a307a h1:3QH7VyOaaiUHNrA9Se4YQIRkDTCw1EJls9xTUCaCeRM= github.com/rogpeppe/clock v0.0.0-20190514195947-2896927a307a/go.mod h1:4r5QyqhjIWCcK8DO4KMclc5Iknq5qVBAlbYYzAbUScQ= github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/rogpeppe/go-internal v1.11.0 h1:cWPaGQEPrBb5/AsnsZesgZZ9yb1OQ+GOISoDNXVBh4M= github.com/rogpeppe/go-internal v1.11.0/go.mod h1:ddIwULY96R17DhadqLgMfk9H9tvdUzkipdSkR5nkCZA= github.com/snapcore/go-gettext v0.0.0-20191107141714-82bbea49e785/go.mod h1:D3SsWAXK7wCCBZu+Vk5hc1EuKj/L3XN1puEMXTU4LrQ= github.com/snapcore/go-gettext v0.0.0-20201130093759-38740d1bd3d2 h1:nETXPg0CiJrMAwC2gqkcam9BiBWYGvTsSYRfrjOz2Kg= github.com/snapcore/go-gettext v0.0.0-20201130093759-38740d1bd3d2/go.mod h1:D3SsWAXK7wCCBZu+Vk5hc1EuKj/L3XN1puEMXTU4LrQ= github.com/snapcore/secboot v0.0.0-20211207204151-239d06c34009/go.mod h1:72paVOkm4sJugXt+v9ItmnjXgO921D8xqsbH2OekouY= github.com/snapcore/secboot v0.0.0-20230623151406-4d331d24f830 h1:SCJ9Uiekv6uMqzMGP50Y0KBxkLP7IzPW35aI3Po6iyM= github.com/snapcore/secboot v0.0.0-20230623151406-4d331d24f830/go.mod h1:72paVOkm4sJugXt+v9ItmnjXgO921D8xqsbH2OekouY= github.com/snapcore/snapd v0.0.0-20201005140838-501d14ac146e/go.mod h1:3xrn7QDDKymcE5VO2rgWEQ5ZAUGb9htfwlXnoel6Io8= github.com/snapcore/snapd v0.0.0-20231013114329-a9c308a6cdb9 h1:oM8l+Azz0El37TxPafA9gsrufD0rUbqbBfoLaMxha4U= github.com/snapcore/snapd v0.0.0-20231013114329-a9c308a6cdb9/go.mod h1:M+wSEB8eBfffw7I69nDtilqKfbdkmCNbtXY1wMJV1v0= github.com/snapcore/squashfuse v0.0.0-20171220165323-319f6d41a041/go.mod h1:8loYitFPSdoeCXBs/XjO0fyGcpgLAybOHLUsGwgMq90= github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8= github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY= go.mozilla.org/pkcs7 v0.0.0-20200128120323-432b2356ecb1/go.mod h1:SNgMg+EgDFwmvSmLRTNKC5fegJjB7v23qTQ0XLGUNHk= go.mozilla.org/pkcs7 v0.0.0-20210826202110-33d05740a352 h1:CCriYyAfq1Br1aIYettdHZTy8mBTIPo7We18TuO/bak= go.mozilla.org/pkcs7 v0.0.0-20210826202110-33d05740a352/go.mod h1:SNgMg+EgDFwmvSmLRTNKC5fegJjB7v23qTQ0XLGUNHk= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto= golang.org/x/crypto v0.16.0 h1:mMMrFzRSCF0GvB7Ne27XVtVAaXLrPmgPC7/v0tkwHaY= golang.org/x/crypto v0.16.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg= golang.org/x/net v0.0.0-20201002202402-0a1ea396d57c/go.mod h1:iQL9McJNjoIa5mjH6nYTCTZXUN6RP+XW3eib7Ya3XcI= golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c= golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U= golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210320140829-1e4c9ba3b0c4/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210324051608-47abb6519492/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210908233432-aa78b53d3365/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028 h1:+cNy6SZtPcJQH3LJVLOSmiC7MMxXNOb3PU/VUEz+EhU= golang.org/x/xerrors v0.0.0-20231012003039-104605ab7028/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q= gopkg.in/retry.v1 v1.0.3 h1:a9CArYczAVv6Qs6VGoLMio99GEs7kY9UzSF9+LD+iGs= gopkg.in/retry.v1 v1.0.3/go.mod h1:FJkXmWiMaAo7xB+xhvDF59zhfjDWyzmyAxiT4dB688g= gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637 h1:yiW+nvdHb9LVqSHQBXfZCieqV4fzYhNBql77zY0ykqs= gopkg.in/tomb.v2 v2.0.0-20161208151619-d5d1b5820637/go.mod h1:BHsqpu/nsuzkT5BpiH1EMZPLyqSMM8JbIavyFACoFNk= gopkg.in/yaml.v2 v2.3.0/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= maze.io/x/crypto v0.0.0-20190131090603-9b94c9afe066 h1:UrD21H1Ue5Nl8f2x/NQJBRdc49YGmla3mRStinH8CCE= maze.io/x/crypto v0.0.0-20190131090603-9b94c9afe066/go.mod h1:DEvumi+swYmlKxSlnsvPwS15tRjoypCCeJFXswU5FfQ=