pax_global_header00006660000000000000000000000064152102460240014506gustar00rootroot0000000000000052 comment=ec869c79ea10741e8bd0c8043e4f2c0c5b740ce2 ukiboot-0.2.1+git20260604.ec869c7/000077500000000000000000000000001521024602400156545ustar00rootroot00000000000000ukiboot-0.2.1+git20260604.ec869c7/.clang-format000066400000000000000000000025331521024602400202320ustar00rootroot00000000000000--- AlignAfterOpenBracket: 'Align' AlignConsecutiveAssignments: 'false' AlignConsecutiveDeclarations: 'false' AlignConsecutiveMacros: 'true' AlignOperands: 'true' AlignTrailingComments: 'true' AllowAllArgumentsOnNextLine: 'false' AllowAllParametersOfDeclarationOnNextLine: 'false' AllowShortBlocksOnASingleLine: 'false' AllowShortCaseLabelsOnASingleLine: 'false' AllowShortFunctionsOnASingleLine: 'Inline' AllowShortIfStatementsOnASingleLine: 'false' AlwaysBreakAfterReturnType: 'All' BinPackParameters: 'false' BinPackArguments: 'false' BreakBeforeBraces: 'Linux' ColumnLimit: '100' DerivePointerAlignment: 'false' IndentCaseLabels: 'false' IndentWidth: '4' KeepEmptyLinesAtTheStartOfBlocks: 'false' Language: 'Cpp' MaxEmptyLinesToKeep: '1' PointerAlignment: 'Right' SortIncludes: 'true' SpaceAfterCStyleCast: 'false' SpaceBeforeAssignmentOperators : 'true' SpaceBeforeParens: 'ControlStatements' SpaceInEmptyParentheses: 'false' SpacesInSquareBrackets: 'false' TabWidth: '8' UseTab: 'Always' PenaltyBreakAssignment: '3' PenaltyBreakBeforeFirstCallParameter: '15' IncludeCategories: - Regex: '^"config.h"$' Priority: '0' - Regex: '' Priority: '1' - Regex: '^<' Priority: '2' - Regex: 'fwupd' Priority: '3' - Regex: '.*' Priority: '4' ... ukiboot-0.2.1+git20260604.ec869c7/.gitlab-ci.yml000066400000000000000000000011371521024602400203120ustar00rootroot00000000000000# .gitlab-ci.yml # Define the stages for the CI/CD pipeline stages: - test # Define the test job meson-test: stage: test image: fedora:latest before_script: - dnf update -y - dnf install -y gnu-efi-devel meson ninja-build gcc systemd systemd-devel ukify clang-tools-extra openssl-devel sbsigntools clang lld qemu-system-x86-core edk2-ovmf dosfstools mtools util-linux script: - clang-format -Werror --dry-run --verbose -- *.[ch] efi/*.[ch] - meson build - cd build - ninja - meson test artifacts: when: always paths: - build/meson-logs/testlog.txt ukiboot-0.2.1+git20260604.ec869c7/COPYING.LIB000066400000000000000000000636421521024602400173270ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. [This is the first released version of the Lesser GPL. It also counts as the successor of the GNU Library Public License, version 2, hence the version number 2.1.] Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public Licenses are intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This license, the Lesser General Public License, applies to some specially designated software packages--typically libraries--of the Free Software Foundation and other authors who decide to use it. You can use it too, but we suggest you first think carefully about whether this license or the ordinary General Public License is the better strategy to use in any particular case, based on the explanations below. When we speak of free software, we are referring to freedom of use, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish); that you receive source code or can get it if you want it; that you can change the software and use pieces of it in new free programs; and that you are informed that you can do these things. To protect your rights, we need to make restrictions that forbid distributors to deny you these rights or to ask you to surrender these rights. These restrictions translate to certain responsibilities for you if you distribute copies of the library or if you modify it. For example, if you distribute copies of the library, whether gratis or for a fee, you must give the recipients all the rights that we gave you. You must make sure that they, too, receive or can get the source code. If you link other code with the library, you must provide complete object files to the recipients, so that they can relink them with the library after making changes to the library and recompiling it. And you must show them these terms so they know their rights. We protect your rights with a two-step method: (1) we copyright the library, and (2) we offer you this license, which gives you legal permission to copy, distribute and/or modify the library. To protect each distributor, we want to make it very clear that there is no warranty for the free library. Also, if the library is modified by someone else and passed on, the recipients should know that what they have is not the original version, so that the original author's reputation will not be affected by problems that might be introduced by others. Finally, software patents pose a constant threat to the existence of any free program. We wish to make sure that a company cannot effectively restrict the users of a free program by obtaining a restrictive license from a patent holder. Therefore, we insist that any patent license obtained for a version of the library must be consistent with the full freedom of use specified in this license. Most GNU software, including some libraries, is covered by the ordinary GNU General Public License. This license, the GNU Lesser General Public License, applies to certain designated libraries, and is quite different from the ordinary General Public License. We use this license for certain libraries in order to permit linking those libraries into non-free programs. When a program is linked with a library, whether statically or using a shared library, the combination of the two is legally speaking a combined work, a derivative of the original library. The ordinary General Public License therefore permits such linking only if the entire combination fits its criteria of freedom. The Lesser General Public License permits more lax criteria for linking other code with the library. We call this license the "Lesser" General Public License because it does Less to protect the user's freedom than the ordinary General Public License. It also provides other free software developers Less of an advantage over competing non-free programs. These disadvantages are the reason we use the ordinary General Public License for many libraries. However, the Lesser license provides advantages in certain special circumstances. For example, on rare occasions, there may be a special need to encourage the widest possible use of a certain library, so that it becomes a de-facto standard. To achieve this, non-free programs must be allowed to use the library. A more frequent case is that a free library does the same job as widely used non-free libraries. In this case, there is little to gain by limiting the free library to free software only, so we use the Lesser General Public License. In other cases, permission to use a particular library in non-free programs enables a greater number of people to use a large body of free software. For example, permission to use the GNU C Library in non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less protective of the users' freedom, it does ensure that the user of a program that is linked with the Library has the freedom and the wherewithal to run that program using a modified version of the Library. The precise terms and conditions for copying, distribution and modification follow. Pay close attention to the difference between a "work based on the library" and a "work that uses the library". The former contains code derived from the library, whereas the latter must be combined with the library in order to run. GNU LESSER GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License Agreement applies to any software library or other program which contains a notice placed by the copyright holder or other authorized party saying it may be distributed under the terms of this Lesser General Public License (also called "this License"). Each licensee is addressed as "you". A "library" means a collection of software functions and/or data prepared so as to be conveniently linked with application programs (which use some of those functions and data) to form executables. The "Library", below, refers to any such software library or work which has been distributed under these terms. A "work based on the Library" means either the Library or any derivative work under copyright law: that is to say, a work containing the Library or a portion of it, either verbatim or with modifications and/or translated straightforwardly into another language. (Hereinafter, translation is included without limitation in the term "modification".) "Source code" for a work means the preferred form of the work for making modifications to it. For a library, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the library. Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running a program using the Library is not restricted, and output from such a program is covered only if its contents constitute a work based on the Library (independent of the use of the Library in a tool for writing it). Whether that is true depends on what the Library does and what the program that uses the Library does. 1. You may copy and distribute verbatim copies of the Library's complete source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and distribute a copy of this License along with the Library. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Library or any portion of it, thus forming a work based on the Library, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) The modified work must itself be a software library. b) You must cause the files modified to carry prominent notices stating that you changed the files and the date of any change. c) You must cause the whole of the work to be licensed at no charge to all third parties under the terms of this License. d) If a facility in the modified Library refers to a function or a table of data to be supplied by an application program that uses the facility, other than as an argument passed when the facility is invoked, then you must make a good faith effort to ensure that, in the event an application does not supply such function or table, the facility still operates, and performs whatever part of its purpose remains meaningful. (For example, a function in a library to compute square roots has a purpose that is entirely well-defined independent of the application. Therefore, Subsection 2d requires that any application-supplied function or table used by this function must be optional: if the application does not supply it, the square root function must still compute square roots.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Library, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Library, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Library. In addition, mere aggregation of another work not based on the Library with the Library (or with a work based on the Library) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may opt to apply the terms of the ordinary GNU General Public License instead of this License to a given copy of the Library. To do this, you must alter all the notices that refer to this License, so that they refer to the ordinary GNU General Public License, version 2, instead of to this License. (If a newer version than version 2 of the ordinary GNU General Public License has appeared, then you can specify that version instead if you wish.) Do not make any other change in these notices. Once this change is made in a given copy, it is irreversible for that copy, so the ordinary GNU General Public License applies to all subsequent copies and derivative works made from that copy. This option is useful when you wish to copy part of the code of the Library into a program that is not a library. 4. You may copy and distribute the Library (or a portion or derivative of it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange. If distribution of object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place satisfies the requirement to distribute the source code, even though third parties are not compelled to copy the source along with the object code. 5. A program that contains no derivative of any portion of the Library, but is designed to work with the Library by being compiled or linked with it, is called a "work that uses the Library". Such a work, in isolation, is not a derivative work of the Library, and therefore falls outside the scope of this License. However, linking a "work that uses the Library" with the Library creates an executable that is a derivative of the Library (because it contains portions of the Library), rather than a "work that uses the library". The executable is therefore covered by this License. Section 6 states terms for distribution of such executables. When a "work that uses the Library" uses material from a header file that is part of the Library, the object code for the work may be a derivative work of the Library even though the source code is not. Whether this is true is especially significant if the work can be linked without the Library, or if the work is itself a library. The threshold for this to be true is not precisely defined by law. If such an object file uses only numerical parameters, data structure layouts and accessors, and small macros and small inline functions (ten lines or less in length), then the use of the object file is unrestricted, regardless of whether it is legally a derivative work. (Executables containing this object code plus portions of the Library will still fall under Section 6.) Otherwise, if the work is a derivative of the Library, you may distribute the object code for the work under the terms of Section 6. Any executables containing that work also fall under Section 6, whether or not they are linked directly with the Library itself. 6. As an exception to the Sections above, you may also combine or link a "work that uses the Library" with the Library to produce a work containing portions of the Library, and distribute that work under terms of your choice, provided that the terms permit modification of the work for the customer's own use and reverse engineering for debugging such modifications. You must give prominent notice with each copy of the work that the Library is used in it and that the Library and its use are covered by this License. You must supply a copy of this License. If the work during execution displays copyright notices, you must include the copyright notice for the Library among them, as well as a reference directing the user to the copy of this License. Also, you must do one of these things: a) Accompany the work with the complete corresponding machine-readable source code for the Library including whatever changes were used in the work (which must be distributed under Sections 1 and 2 above); and, if the work is an executable linked with the Library, with the complete machine-readable "work that uses the Library", as object code and/or source code, so that the user can modify the Library and then relink to produce a modified executable containing the modified Library. (It is understood that the user who changes the contents of definitions files in the Library will not necessarily be able to recompile the application to use the modified definitions.) b) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (1) uses at run time a copy of the library already present on the user's computer system, rather than copying library functions into the executable, and (2) will operate properly with a modified version of the library, if the user installs one, as long as the modified version is interface-compatible with the version that the work was made with. c) Accompany the work with a written offer, valid for at least three years, to give the same user the materials specified in Subsection 6a, above, for a charge no more than the cost of performing this distribution. d) If distribution of the work is made by offering access to copy from a designated place, offer equivalent access to copy the above specified materials from the same place. e) Verify that the user has already received a copy of these materials or that you have already sent this user a copy. For an executable, the required form of the "work that uses the Library" must include any data and utility programs needed for reproducing the executable from it. However, as a special exception, the materials to be distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. It may happen that this requirement contradicts the license restrictions of other proprietary libraries that do not normally accompany the operating system. Such a contradiction means you cannot use both them and the Library together in an executable that you distribute. 7. You may place library facilities that are a work based on the Library side-by-side in a single library together with other library facilities not covered by this License, and distribute such a combined library, provided that the separate distribution of the work based on the Library and of the other library facilities is otherwise permitted, and provided that you do these two things: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities. This must be distributed under the terms of the Sections above. b) Give prominent notice with the combined library of the fact that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 8. You may not copy, modify, sublicense, link with, or distribute the Library except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense, link with, or distribute the Library is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 9. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Library or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Library (or any work based on the Library), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Library or works based on it. 10. Each time you redistribute the Library (or any work based on the Library), the recipient automatically receives a license from the original licensor to copy, distribute, link with or modify the Library subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties with this License. 11. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Library at all. For example, if a patent license would not permit royalty-free redistribution of the Library by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Library. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply, and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 12. If the distribution and/or use of the Library is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Library under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 13. The Free Software Foundation may publish revised and/or new versions of the Lesser 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 Library specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Library does not specify a license version number, you may choose any version ever published by the Free Software Foundation. 14. If you wish to incorporate parts of the Library into other free programs whose distribution conditions are incompatible with these, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE LIBRARY "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 LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE LIBRARY 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 LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Libraries If you develop a new library, and you want it to be of the greatest possible use to the public, we recommend making it free software that everyone can redistribute and change. You can do so by permitting redistribution under these terms (or, alternatively, under the terms of the ordinary General Public License). To apply these terms, attach the following notices to the library. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Also add information on how to contact you by electronic and paper mail. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the library, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the library `Frob' (a library for tweaking knobs) written by James Random Hacker. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! ukiboot-0.2.1+git20260604.ec869c7/README.md000066400000000000000000000143361521024602400171420ustar00rootroot00000000000000UKIBoot ============ This is an implementation of a UEFI based A/B boot protocol, that is very similar to android boot. If you install this very small boot loader as EFI/BOOT/BOOTX64.EFI, then that will be loaded at boot by the UEFI firmware, and it will then chain load another UEFI binary from either the `ukiboot_a`, or the `ukiboot_b` partition, depending on what is the active boot slot. The chain loaded binaries can be anything, but the primary idea is that they would be Unified Kernel Images per: https://uapi-group.org/specifications/specs/unified_kernel_image/ Such images contain a kernel, an initrd, and a set of kernel commandlines, and this allows booting a (optionally signed with SecureBoot) complete linux kernel, which would then find the remaining userspace. The implementation used here is very much modeled on android verified boot v2, in particular the way it is implemented in uboot: https://lore.kernel.org/all/CAModR+XkH1P6ZWcRyfDDua9_X4k6OQc5Wk-=PqzxLdOPdqqRGg@mail.gmail.com/T/#e896d728bde04a96c3ed35230f7d72048c7dcd9e5 Technical details ================= The GPT has 3 partitions, `ukiboot_a`, `ukiboot_b` and `ukibootctl`. The first two, with partition type `DF331E4D-BE00-463F-B4A7-8B43E18FB53A`, contain raw (i.e. not on a filesystem) UKI UEFI binaries. The `uki_bootctl` partition, type `FEFD9070-346F-4C9A-85E6-17F07F922773`, is used to track which partitions are valid, active, and what the current boot count is. The layout of this partition is this, with all field being little endian: ``` typedef struct { UINT8 priority; UINT8 tries_remaining; UINT8 successful_boot; UINT8 reserved; } UkiBootSlotInfo; #define UKI_BOOT_CTRL_MAGIC 1420550408 typedef struct { UINT32 magic; UkiBootSlotInfo slots[2]; UINT8 reserved[8]; UINT32 CRC32; } UkiBootCtrl; ``` Under the MBR scheme, the partitions are structured as logical partitions within an extended partition. Each is assigned a unique MBR identifier: `ukiboot_a` has the MBR id `0x46`, `ukiboot_b` has the MBR id `0x47`, and `ukiboot_ctl` has the MBR id `0x48`. A slot is valid either if `successful_boot` is set, or if `tries_remaining` is larger than 0. The former means that this partition was successfully booted before, and the later means that we are testing boot of this partition. When booting, the valid slot that has the highest priority is chosen. And, if the chosen slot doesn't have `successful_boot` set, then `tries_remaining` will be decreased by one each boot, until it reaches zero, and the slot is considered invalid. When this happens for a newly installed slot, what typically happens is that the other slot has `successful_boot` set (being the previous working version), but with a lower priority, so it will instead be booted. If at boot, the `ukibootctl` partition is uninitilized (or corrupted), then it will be initialized with a default setup that marks both partitions as valid, with a boot count of 7, and with the first slot having higher priority. When the UKI is booted, the kernel commandline is extended with a custom commandline option `androidboot.slot_suffix` with the value `_a` or `_b`, depending on what the current active slot is. This is the same key as android boot uses, which means most code that integrates with it can work with ukiboot with few or no modifications. The kernel commandline extension is implemented using two systemd stub addons, one called `ukiboot_a.efi.extra.d/slot_a.addon.efi` and one called `ukiboot_b.efi.extra.d/slot_b.addon.efi`. We then start the UKI as either `ukiboot_a.efi` or `ukiboot_b.efi` which causes the UKI stub to load the expected addon. Implementing updates ==================== When userspace is implementing a version update, these are the steps that are needed: * Look at the kernel commandline to find the current active slot * Rewrite the `ukibootctl partition with the following changes: * current slot: Set `successful_boot` to 1, and `tries_remaining` to 0, keeping the current priority. This ensures the fallback is marked as working. Normally this isn't needed, as this should already be marked successfully booted. * next slot: Set `successful_boot`, `tries_remaining` and `priority` to zero. This marks the slot as invalid, so it will not be used until writing the partition is completed. * Perform the update, doing whatever updates that are needed, as well as writing the new UKI to the next slot (`ukiboot_a` or `ukiboot_b`). * Rewrite the `ukibootctl partition with the following changes: * current slot: Set `priority` to 14, keep the rest as is. * next slot: Set ``tries_remaining` to 7, and `priority` to 15. This will cause ukiboot to try to boot the new slot 7 times and then fall back to the old slot. * Reboot, which should boot the new version * If boot completes sucessfully, mark the boot successful by rewriting the `ukibootctl` partition, setting `successful_boot` to 1, and `tries_remaining` to 0 (for the booted partition, as per the kernel commandline option). ### Firmware Requirements To support UKIBoot, the firmware must comply with the UEFI 2.x specification. In particular, it must implement the following Protocols and Boot Services: #### Required UEFI Protocols * `EFI_BLOCK_IO_PROTOCOL`: Required on partition handles to read/write raw disk sectors (for the `ukibootctl` data and UKI images). * `EFI_PARTITION_INFO_PROTOCOL`: Required on partition handles. UKIBoot relies on the firmware to parse the GPT/MBR table and provide this protocol to identify partitions by Type GUID or ID. * `EFI_LOADED_IMAGE_DEVICE_PATH_PROTOCOL`: Required on the handle of the running image. UKIBoot uses this to determine the device path of the boot media. #### Required UEFI Boot Services * `LoadImage`: The firmware must support loading a PE/COFF image directly from a source buffer (RAM) rather than just from a file path. * `StartImage`: Required to transfer control to the chain-loaded UKI images. * `OpenProtocol`: The firmware must support opening protocols in exclusive mode prevent race conditions during partition access. * `CalculateCrc32`: Required to validate the checksum of the `ukibootctl` metadata. ukiboot-0.2.1+git20260604.ec869c7/bootctl.h000066400000000000000000000046061521024602400175010ustar00rootroot00000000000000/* Shared UkiBootCtrl definitions Copyright (C) 2025 Alexander Larsson This file is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This file 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ #include "utils.h" typedef struct attr_packed { uint8_t priority; uint8_t tries_remaining; uint8_t successful_boot; uint8_t reserved; } UkiBootSlotInfo; #define UKI_BOOT_CTRL_MAGIC 1420550408 typedef struct attr_packed { uint32_t magic; UkiBootSlotInfo slots[2]; uint8_t reserved[8]; uint32_t CRC32; } UkiBootCtrl; static inline bool bootctl_slot_valid(UkiBootSlotInfo *slot) { return slot->successful_boot != 0 || slot->tries_remaining > 0; } static inline bool bootctl_validate(UkiBootCtrl *bootctl) { if (le32toh(bootctl->magic) != UKI_BOOT_CTRL_MAGIC) { verbose("Invalid bootctl magic value\n"); return false; } uint32_t crc = crc32((uint8_t *)bootctl, sizeof(UkiBootCtrl) - sizeof(uint32_t)); if (le32toh(bootctl->CRC32) != crc) { verbose("Invalid bootctl crc32\n"); return false; } return true; } static inline bool bootctl_find_active_slot(UkiBootCtrl *bootctl, uint32_t *out_slot) { int32_t active_slot = -1; for (int32_t i = 0; i < 2; i++) { if (bootctl_slot_valid(&bootctl->slots[i])) { if (active_slot == -1) { active_slot = i; } else { if (bootctl->slots[i].priority > bootctl->slots[active_slot].priority) { active_slot = i; } } } } if (active_slot != -1) { *out_slot = active_slot; return true; } return false; } static inline void bootctl_init_default(UkiBootCtrl *bootctl) { memset(bootctl, 0, sizeof(UkiBootCtrl)); bootctl->magic = htole32(UKI_BOOT_CTRL_MAGIC); bootctl->slots[0].priority = 15; bootctl->slots[0].tries_remaining = 7; bootctl->slots[1].priority = 14; bootctl->slots[1].tries_remaining = 7; } ukiboot-0.2.1+git20260604.ec869c7/efi/000077500000000000000000000000001521024602400164175ustar00rootroot00000000000000ukiboot-0.2.1+git20260604.ec869c7/efi/bootloader.c000066400000000000000000000045331521024602400207220ustar00rootroot00000000000000#include #include #include #include #include "bootloader.h" #include "ukiboot-efi.h" /* This adds minimal support for the boot loader interface defined in * https://systemd.io/BOOT_LOADER_INTERFACE/. * * At the moment we only set Loasystemd-gpt-auto-generatorderDevicePartUUID, which is enough to * allow systemd-gpt-auto-generator to auto-find all mountpoints. */ /* Defined in */ #define BOOT_LOADER_INTERFACE_VENDOR_UUID \ {0x4a67b082, 0x0a4c, 0x41cf, {0xb6, 0xc7, 0x44, 0x0b, 0x29, 0xbb, 0x8c, 0x4f}} static EFI_STATUS set_efivar(const EFI_GUID *vendor, const CHAR16 *name, const VOID *buf, size_t size, UINT32 flags) { flags |= EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS; return uefi_call_wrapper(RT->SetVariable, 5, (CHAR16 *)name, (EFI_GUID *)vendor, flags, size, (VOID *)buf); } static EFI_STATUS set_efivar_str(const EFI_GUID *vendor, const CHAR16 *name, const CHAR16 *value, UINT32 flags) { return set_efivar(vendor, name, value, value ? (StrLen(value) + 1) * sizeof(CHAR16) : 0, flags); } static EFI_GUID * device_path_find_partition_guid(EFI_DEVICE_PATH_PROTOCOL *dp) { while (!IsDevicePathEnd(dp)) { if (DevicePathType(dp) == MEDIA_DEVICE_PATH && DevicePathSubType(dp) == MEDIA_HARDDRIVE_DP) { HARDDRIVE_DEVICE_PATH *Hd = (HARDDRIVE_DEVICE_PATH *)dp; if (Hd->SignatureType == SIGNATURE_TYPE_GUID) { return (EFI_GUID *)Hd->Signature; } } dp = NextDevicePathNode(dp); } return NULL; } EFI_STATUS bootloader_interface_init(EFI_HANDLE loaded_image_handle) { EFI_STATUS rc; _cleanup_protocol Protocol proto = PROTOCOL_INIT; EFI_GUID lidpp = EFI_LOADED_IMAGE_DEVICE_PATH_PROTOCOL_GUID; EFI_GUID boot_loader_iface = BOOT_LOADER_INTERFACE_VENDOR_UUID; rc = efi_open_protocol_exclusive(loaded_image_handle, &lidpp, loaded_image_handle, &proto); if (EFI_ERROR(rc)) { log(L"Could not open loaded_image devicepath protocol"); return rc; } EFI_DEVICE_PATH_PROTOCOL *dp = proto.iface; EFI_GUID *guid = device_path_find_partition_guid(dp); if (guid != NULL) { CHAR16 guid_str[64]; GuidToString(guid_str, guid); set_efivar_str(&boot_loader_iface, L"LoaderDevicePartUUID", guid_str, 0); } return EFI_SUCCESS; } ukiboot-0.2.1+git20260604.ec869c7/efi/bootloader.h000066400000000000000000000001151521024602400207170ustar00rootroot00000000000000extern EFI_STATUS bootloader_interface_init(EFI_HANDLE loaded_image_handle); ukiboot-0.2.1+git20260604.ec869c7/efi/generate_binary.py000066400000000000000000000050411521024602400221270ustar00rootroot00000000000000#!/usr/bin/env python3 # # Copyright (C) 2021 Javier Martinez Canillas # Copyright (C) 2021 Richard Hughes # # SPDX-License-Identifier: LGPL-2.1+ # # pylint: disable=missing-docstring, invalid-name import subprocess import sys import argparse def _run_objcopy(args): argv = [ args.objcopy, "-j", ".text", "-j", ".sbat", "-j", ".sbom", "-j", ".sdata", "-j", ".data", "-j", ".dynamic", "-j", ".rodata", "-j", ".areloc", "-j", ".rel*", args.infile, args.outfile, ] # older objcopy for Aarch64, ARM32 and RISC-V are not EFI capable. # Use "binary" instead, and add required symbols manually. if args.objcopy_manualsymbols: argv.extend(["-O", "binary"]) else: argv.extend(["--output-target", "efi-app-{}".format(args.arch)]) try: subprocess.run(argv, check=True) except FileNotFoundError as e: print(str(e)) sys.exit(1) def _run_genpeimg(args): if not args.genpeimg: return argv = [args.genpeimg, "-d", "+d", "-d", "+n", "-d", "+s", args.outfile] try: subprocess.run(argv, check=True) except FileNotFoundError as e: print(str(e)) sys.exit(1) def _add_nx_pefile(args): # unnecessary if we have genpeimg if args.genpeimg: return try: import pefile except ImportError: print("Unable to add NX support to binaries without genpeimg or python3-pefile") sys.exit(1) pe = pefile.PE(args.outfile) pe.OPTIONAL_HEADER.DllCharacteristics |= pefile.DLL_CHARACTERISTICS[ "IMAGE_DLLCHARACTERISTICS_NX_COMPAT" ] pe.write(args.outfile) if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument( "--objcopy", default="objcopy", help="Binary file to use for objcopy" ) parser.add_argument("--genpeimg", help="Binary file to use for genpeimg") parser.add_argument("--arch", default="x86_64", help="EFI architecture") parser.add_argument("--os", help="OS type") parser.add_argument( "--objcopy-manualsymbols", action="store_true", help="whether adding symbols direct to binary", ) parser.add_argument("infile", help="Input file") parser.add_argument("outfile", help="Output file") _args = parser.parse_args() _run_objcopy(_args) _run_genpeimg(_args) _add_nx_pefile(_args) sys.exit(0) ukiboot-0.2.1+git20260604.ec869c7/efi/meson.build000066400000000000000000000227761521024602400205770ustar00rootroot00000000000000generate_binary = [python3, files('generate_binary.py')] host_cpu = host_machine.cpu_family() if host_cpu == 'x86' EFI_MACHINE_TYPE_NAME = 'ia32' gnu_efi_arch = 'ia32' elif host_cpu == 'x86_64' EFI_MACHINE_TYPE_NAME = 'x64' gnu_efi_arch = 'x86_64' elif host_cpu == 'arm' EFI_MACHINE_TYPE_NAME = 'arm' gnu_efi_arch = 'arm' elif host_cpu == 'aarch64' EFI_MACHINE_TYPE_NAME = 'aa64' gnu_efi_arch = 'aarch64' elif host_cpu == 'loongarch64' EFI_MACHINE_TYPE_NAME = 'loongarch64' gnu_efi_arch = 'loongarch64' elif host_cpu == 'riscv64' EFI_MACHINE_TYPE_NAME = 'riscv64' gnu_efi_arch = 'riscv64' else error('Unknown host_cpu ' + host_cpu) endif gnu_efi_path_arch = '' foreach name : [gnu_efi_arch, EFI_MACHINE_TYPE_NAME] if (gnu_efi_path_arch == '' and name != '' and cc.has_header('@0@/@1@/efibind.h'.format(efi_incdir, name))) gnu_efi_path_arch = name endif endforeach if gnu_efi_path_arch != '' and EFI_MACHINE_TYPE_NAME == '' error('gnu-efi is available, but EFI_MACHINE_TYPE_NAME is unknown') endif if efi_libdir == '' fs = import('fs') multi = run_command(cc.cmd_array(), '-print-multi-os-directory', check: true).stdout().strip() efi_libdir = join_paths('/usr/lib/', multi) if not fs.is_dir(join_paths(efi_libdir, 'gnuefi')) efi_libdir = '/usr/lib' endif endif lds_os = '' if host_cpu == 'x86_64' and host_machine.system() == 'freebsd' lds_os = '_fbsd' endif arch_lds = 'efi.lds' arch_crt = 'crt0.o' if efi_ldsdir == '' efi_ldsdir = join_paths(efi_libdir, 'gnuefi', gnu_efi_path_arch) cmd = run_command('test', '-f', join_paths(efi_ldsdir, arch_lds), check: false) if cmd.returncode() != 0 arch_lds = 'elf_@0@@1@_efi.lds'.format(gnu_efi_path_arch, lds_os) arch_crt = 'crt0-efi-@0@.o'.format(gnu_efi_path_arch) efi_ldsdir = join_paths(efi_libdir, 'gnuefi') cmd = run_command('test', '-f', join_paths(efi_ldsdir, arch_lds), check: false) endif if cmd.returncode() != 0 efi_ldsdir = efi_libdir cmd = run_command('test', '-f', join_paths(efi_ldsdir, arch_lds), check: false) if cmd.returncode() != 0 error('Cannot find @0@'.format(arch_lds)) endif endif else cmd = run_command('test', '-f', join_paths(efi_ldsdir, arch_lds), check: false) if cmd.returncode() != 0 arch_lds = 'elf_@0@@1@_efi.lds'.format(gnu_efi_path_arch, lds_os) arch_crt = 'crt0-efi-@0@.o'.format(gnu_efi_path_arch) cmd = run_command('test', '-f', join_paths(efi_ldsdir, arch_lds), check: false) endif if cmd.returncode() != 0 error('Cannot find @0@'.format(arch_lds)) endif endif efi_crtdir = efi_ldsdir # If using objcopy, crt0 must not include the PE/COFF header if run_command('grep', '-q', 'coff_header', join_paths(efi_crtdir, arch_crt), check: false).returncode() == 0 coff_header_in_crt0 = true else coff_header_in_crt0 = false endif # older objcopy for Aarch64, ARM32 and RISC-V are not EFI capable. # Use 'binary' instead, and add required symbols manually. if host_cpu == 'arm' or host_cpu == 'riscv64' or (host_cpu == 'aarch64' and coff_header_in_crt0) objcopy_manualsymbols = true generate_binary_extra = ['--objcopy-manualsymbols'] elif host_cpu == 'loongarch64' and (objcopy_version.version_compare ('< 2.41') or coff_header_in_crt0) objcopy_manualsymbols = true generate_binary_extra = ['--objcopy-manualsymbols'] else objcopy_manualsymbols = false generate_binary_extra = [] endif # Check aligned lds and crt0 on ARM64 this breaks otherwise if host_cpu == 'aarch64' and not objcopy_manualsymbols if efi_ldsdir == join_paths(meson.current_source_dir(), 'lds') arch_lds = 'elf_@0@@1@_efi_system.lds'.format(gnu_efi_arch, lds_os) endif endif message('efi-libdir: "@0@"'.format(efi_libdir)) message('efi-ldsdir: "@0@"'.format(efi_ldsdir)) message('efi-crtdir: "@0@"'.format(efi_crtdir)) message('efi-includedir: "@0@"'.format(efi_incdir)) debugdir = join_paths (libdir, 'debug') compile_args = ['-Og', '-g3', '--param=ssp-buffer-size=4', '-fexceptions', '-Wall', '-Wextra', '-Wvla', '-std=gnu11', '-fpic', '-funsigned-char', '-fshort-wchar', '-ffreestanding', '-fno-strict-aliasing', '-fno-stack-protector', '-fno-stack-check', '-fno-merge-all-constants', '-Wsign-compare', '-Wno-missing-field-initializers', '-Wno-address-of-packed-member', '-grecord-gcc-switches', '-DDEBUGDIR="@0@"'.format(debugdir), '-I.', '-isystem', efi_incdir, '-isystem', join_paths(efi_incdir, gnu_efi_path_arch)] # clang only has fno-merge-all-constants compile_args += cc.first_supported_argument('-fno-merge-constants') if get_option('werror') compile_args += '-Werror' endif if host_cpu == 'x86_64' compile_args += ['-mno-red-zone', '-mno-sse', '-mno-mmx', '-DEFI_FUNCTION_WRAPPER', '-DGNU_EFI_USE_MS_ABI'] elif host_cpu == 'x86' compile_args += ['-mno-sse', '-mno-mmx', '-mno-red-zone', '-m32'] # no special cases for aarch64 or arm endif efi_ldflags = ['-T', join_paths(efi_ldsdir, arch_lds), '-shared', '-Bsymbolic', '-nostdlib', '-znocombreloc', '-znorelro', '-L', efi_crtdir, '-L', efi_libdir, join_paths(efi_crtdir, arch_crt)] if host_cpu == 'aarch64' or host_cpu == 'arm' # Don't use 64KiB pages efi_ldflags += ['-z', 'common-page-size=4096'] efi_ldflags += ['-z', 'max-page-size=4096'] endif if objcopy_manualsymbols # older objcopy for Aarch64, ARM32 and RISC-V are not EFI capable. # Use 'binary' instead, and add required symbols manually. if efi_crtdir != join_paths(meson.current_build_dir(), 'crt0') # Using system so without crt0 generator efi_ldflags += ['--defsym=EFI_SUBSYSTEM=0xa'] endif efi_format = ['-O', 'binary'] else efi_format = ['--output-target=efi-app-@0@'.format(gnu_efi_arch)] endif libgcc_file_name = run_command(cc.cmd_array(), '-print-libgcc-file-name', check: true).stdout().strip() efi_name = 'ukiboot@0@.efi'.format(EFI_MACHINE_TYPE_NAME) # GNU-EFI 4.0 changed how CompareGuid works (to align with EDK2) # Keep GNU-EFI 3.0 support for a while if not gnuefi.found() or gnuefi.version().version_compare('>=4.0.0') compile_args += ['-DGNU_EFI_3_0_COMPAT'] endif o_files = [] o_files += custom_target('ukiboot.o', input : 'ukiboot.c', output : 'ukiboot.o', command : [cc.cmd_array(), '-c', '@INPUT@', '-o', '@OUTPUT@'] + compile_args) o_files += custom_target('pe_parser.o', input : 'pe_parser.c', output : 'pe_parser.o', command : [cc.cmd_array(), '-c', '@INPUT@', '-o', '@OUTPUT@'] + compile_args) o_files += custom_target('bootloader.o', input : 'bootloader.c', output : 'bootloader.o', command : [cc.cmd_array(), '-c', '@INPUT@', '-o', '@OUTPUT@'] + compile_args) o_files += custom_target('ukiboot-efi.o', input : 'ukiboot-efi.c', output : 'ukiboot-efi.o', command : [cc.cmd_array(), '-c', '@INPUT@', '-o', '@OUTPUT@'] + compile_args) efi_cc_ldflags = [] foreach flag : efi_ldflags efi_cc_ldflags += ['-Wl,' + flag] endforeach so = custom_target('ukiboot.so', input : o_files, output : 'ukiboot.so', command : [cc.cmd_array(), '-nostdlib', '-o', '@OUTPUT@'] + efi_cc_ldflags + ['@INPUT@'] + ['-lefi', '-lgnuefi', libgcc_file_name], depends: []) app = custom_target(efi_name, input : so, output : efi_name, command : [ generate_binary, '@INPUT@', '@OUTPUT@', '--arch', gnu_efi_arch, '--os', host_machine.system(), '--objcopy', objcopy, ] + generate_binary_extra, install : true, install_dir : efi_app_location) dbg = custom_target('efi_debug', input : so, output : efi_name + '.debug', command : [objcopy, '-j', '.text', '-j', '.sdata', '-j', '.data', '-j', '.dynamic', '-j', '.rodata', '-j', '.rel*', '-j', '.rela*', '-j', '.reloc', '-j', '.eh_frame', '-j', '.debug*', '-j', '.note.gnu.build-id'] + efi_format + ['@INPUT@', '@OUTPUT@'], install : false, install_dir : debugdir) ukiboot-0.2.1+git20260604.ec869c7/efi/pe_parser.c000066400000000000000000000136641521024602400205550ustar00rootroot00000000000000#include #include #include #include "pe_parser.h" #include "ukiboot-efi.h" #define IMAGE_DOS_SIGNATURE 23117 #define IMAGE_NT_SIGNATURE 17744 typedef struct _IMAGE_DOS_HEADER { UINT16 e_magic; UINT16 e_cblp; UINT16 e_cp; UINT16 e_crlc; UINT16 e_cparhdr; UINT16 e_minalloc; UINT16 e_maxalloc; UINT16 e_ss; UINT16 e_sp; UINT16 e_csum; UINT16 e_ip; UINT16 e_cs; UINT16 e_lfarlc; UINT16 e_ovno; UINT16 e_res[4]; UINT16 e_oemid; UINT16 e_oeminfo; UINT16 e_res2[10]; INT32 e_lfanew; } IMAGE_DOS_HEADER; typedef struct _IMAGE_FILE_HEADER { UINT16 Machine; UINT16 NumberOfSections; UINT32 TimeDateStamp; UINT32 PointerToSymbolTable; UINT32 NumberOfSymbols; UINT16 SizeOfOptionalHeader; UINT16 Characteristics; } IMAGE_FILE_HEADER; typedef struct _IMAGE_NT_HEADERS { UINT32 Signature; IMAGE_FILE_HEADER FileHeader; } IMAGE_NT_HEADERS; #define IMAGE_SIZEOF_SHORT_NAME 8 typedef struct _IMAGE_SECTION_HEADER { UINT8 Name[IMAGE_SIZEOF_SHORT_NAME]; union { UINT32 PhysicalAddress; UINT32 VirtualSize; } Misc; UINT32 VirtualAddress; UINT32 SizeOfRawData; UINT32 PointerToRawData; UINT32 PointerToRelocations; UINT32 PointerToLinenumbers; UINT16 NumberOfRelocations; UINT16 NumberOfLinenumbers; UINT32 Characteristics; } IMAGE_SECTION_HEADER; #define IMAGE_DIRECTORY_ENTRY_SECURITY 4 typedef struct _IMAGE_DATA_DIRECTORY { UINT32 VirtualAddress; UINT32 Size; } IMAGE_DATA_DIRECTORY; #define IMAGE_NUMBEROF_DIRECTORY_ENTRIES 16 #define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b typedef struct _IMAGE_OPTIONAL_HEADER64 { UINT16 Magic; UINT8 MajorLinkerVersion; UINT8 MinorLinkerVersion; UINT32 SizeOfCode; UINT32 SizeOfInitializedData; UINT32 SizeOfUninitializedData; UINT32 AddressOfEntryPoint; UINT32 BaseOfCode; UINT64 ImageBase; UINT32 SectionAlignment; UINT32 FileAlignment; UINT16 MajorOperatingSystemVersion; UINT16 MinorOperatingSystemVersion; UINT16 MajorImageVersion; UINT16 MinorImageVersion; UINT16 MajorSubsystemVersion; UINT16 MinorSubsystemVersion; UINT32 Win32VersionValue; UINT32 SizeOfImage; UINT32 SizeOfHeaders; UINT32 CheckSum; UINT16 Subsystem; UINT16 DllCharacteristics; UINT64 SizeOfStackReserve; UINT64 SizeOfStackCommit; UINT64 SizeOfHeapReserve; UINT64 SizeOfHeapCommit; UINT32 LoaderFlags; UINT32 NumberOfRvaAndSizes; IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; } IMAGE_OPTIONAL_HEADER64; EFI_STATUS get_pe_size(UINT8 *buffer, UINTN size, UINTN *size_out) { if (size < sizeof(IMAGE_DOS_HEADER)) { return EFI_INVALID_PARAMETER; } IMAGE_DOS_HEADER *dos_header = (IMAGE_DOS_HEADER *)buffer; if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) { log(L"Invalid DOS header"); return EFI_INVALID_PARAMETER; } if (dos_header->e_lfanew < (INT32)sizeof(IMAGE_DOS_HEADER)) { log(L"Invalid e_lfanew"); return EFI_INVALID_PARAMETER; } UINTN nt_header_start = dos_header->e_lfanew; UINTN nt_header_size = sizeof(IMAGE_NT_HEADERS); if (nt_header_start >= size || nt_header_size > size - nt_header_start) { log(L"Buffer too small for NT header"); return EFI_INVALID_PARAMETER; } IMAGE_NT_HEADERS *nt_header = (IMAGE_NT_HEADERS *)(buffer + nt_header_start); if (nt_header->Signature != IMAGE_NT_SIGNATURE) { log(L"Invalid NT header"); return EFI_INVALID_PARAMETER; } UINTN optional_header_size = nt_header->FileHeader.SizeOfOptionalHeader; UINTN num_sections = nt_header->FileHeader.NumberOfSections; if (num_sections > 96) { log(L"Too many PE sections"); return EFI_INVALID_PARAMETER; } UINTN headers_end = nt_header_start + nt_header_size; if (optional_header_size > size - headers_end) { log(L"Buffer too small for optional header"); return EFI_INVALID_PARAMETER; } IMAGE_OPTIONAL_HEADER64 *optional_header = (IMAGE_OPTIONAL_HEADER64 *)(buffer + headers_end); if (optional_header->Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) { log(L"Wrong optional nt header"); return EFI_INVALID_PARAMETER; } UINTN sections_start = headers_end + optional_header_size; UINTN section_entry_size = sizeof(IMAGE_SECTION_HEADER); UINTN sections_total = num_sections * section_entry_size; if (sections_total > size - sections_start) { log(L"Buffer too small for section table"); return EFI_INVALID_PARAMETER; } UINTN end_of_file = sections_start + sections_total; for (UINTN i = 0; i < num_sections; i++) { IMAGE_SECTION_HEADER *section = (IMAGE_SECTION_HEADER *)(buffer + sections_start + i * section_entry_size); UINTN raw_offset = section->PointerToRawData; UINTN raw_size = section->SizeOfRawData; if (raw_size > 0 && raw_offset > (UINTN)-1 - raw_size) { log(L"PE section offset + size overflow"); return EFI_INVALID_PARAMETER; } UINTN section_end = raw_offset + raw_size; if (section_end > end_of_file) { end_of_file = section_end; } } /* The Attribute Certificate is referenced by IMAGE_DIRECTORY_ENTRY_SECURITY * in the optional header. Other entries in the data directory are refering * to addresses inside the sections, but the certificates are actually * file offsets outside of the regular sections. So we need to extend the file * size to fit the certificates as well. */ IMAGE_DATA_DIRECTORY *security_dir = &optional_header->DataDirectory[IMAGE_DIRECTORY_ENTRY_SECURITY]; if (security_dir->VirtualAddress != 0) { UINTN sec_start = security_dir->VirtualAddress; UINTN sec_size = security_dir->Size; if (sec_size > 0 && sec_start > (UINTN)-1 - sec_size) { log(L"Security directory offset + size overflow"); return EFI_INVALID_PARAMETER; } UINTN sec_end = sec_start + sec_size; if (sec_end > end_of_file) { end_of_file = sec_end; } } *size_out = end_of_file; return EFI_SUCCESS; } ukiboot-0.2.1+git20260604.ec869c7/efi/pe_parser.h000066400000000000000000000001641521024602400205510ustar00rootroot00000000000000#define PE_FILE_HEADER_BUFFER_SIZE 1024 extern EFI_STATUS get_pe_size(UINT8 *buffer, UINTN size, UINTN *size_out); ukiboot-0.2.1+git20260604.ec869c7/efi/ukiboot-efi.c000066400000000000000000000005611521024602400210020ustar00rootroot00000000000000#include #include #include #include "ukiboot-efi.h" VOID log(CHAR16 *fmt, ...) { va_list args; _cleanup_free CHAR16 *tmp = NULL; va_start(args, fmt); tmp = VPoolPrint(fmt, args); va_end(args); if (tmp == NULL) { Print(L"fwupdate: Allocation for debug log failed!\n"); return; } Print(L"%s\n", tmp); } ukiboot-0.2.1+git20260604.ec869c7/efi/ukiboot-efi.h000066400000000000000000000075311521024602400210130ustar00rootroot00000000000000extern VOID log(CHAR16 *fmt, ...); #define UNUSED __attribute__((__unused__)) #define PACKED __attribute__((packed)) #define _DEFINE_CLEANUP_FUNCTION0(Type, name, func) \ static inline VOID name(VOID *v) \ { \ if (*(Type *)v) \ func(*(Type *)v); \ } _DEFINE_CLEANUP_FUNCTION0(VOID *, _FreePool_p, FreePool) #define _cleanup_free __attribute__((cleanup(_FreePool_p))) static inline VOID * _steal_pointer(VOID *pp) { VOID **ptr = (VOID **)pp; VOID *ref = *ptr; *ptr = NULL; return ref; } static inline EFI_STATUS efi_calculate_crc32(VOID *data, UINTN size, UINT32 *out) { return uefi_call_wrapper(BS->CalculateCrc32, 3, data, size, out); } static inline EFI_STATUS efi_open_protocol(EFI_HANDLE handle, EFI_GUID *guid, VOID *iface, EFI_HANDLE agent, EFI_HANDLE controller, UINT32 attrs) { return uefi_call_wrapper(BS->OpenProtocol, 6, handle, guid, iface, agent, controller, attrs); } static inline EFI_STATUS efi_close_protocol(EFI_HANDLE handle, EFI_GUID *guid, EFI_HANDLE agent) { return uefi_call_wrapper(BS->CloseProtocol, 4, handle, guid, agent, 0); } static inline EFI_STATUS efi_read_blocks(EFI_BLOCK_IO_PROTOCOL *blockio, UINT32 start, UINT32 size, UINT8 *buffer) { return uefi_call_wrapper(blockio->ReadBlocks, 5, blockio, blockio->Media->MediaId, start, size, buffer); } static inline EFI_STATUS efi_write_blocks(EFI_BLOCK_IO_PROTOCOL *blockio, UINT32 start, UINT32 size, UINT8 *buffer) { return uefi_call_wrapper(blockio->WriteBlocks, 5, blockio, blockio->Media->MediaId, start, size, buffer); } typedef struct { EFI_HANDLE handle; EFI_GUID *guid; EFI_HANDLE agent; VOID *iface; } Protocol; #define PROTOCOL_INIT {0} static inline VOID cleanup_protocol_p(VOID *v) { Protocol *protocol = v; if (protocol->handle != 0) { EFI_STATUS rc; rc = efi_close_protocol(protocol->handle, protocol->guid, protocol->agent); if (EFI_ERROR(rc)) { log(L"Could not close protocol"); } protocol->handle = 0; } } #define _cleanup_protocol __attribute__((cleanup(cleanup_protocol_p))) static inline EFI_STATUS efi_open_protocol_exclusive(EFI_HANDLE handle, EFI_GUID *guid, EFI_HANDLE agent, Protocol *protocol) { EFI_STATUS rc; VOID *iface; SetMem(protocol, sizeof(Protocol), 0); rc = efi_open_protocol(handle, guid, &iface, agent, 0, EFI_OPEN_PROTOCOL_EXCLUSIVE); if (EFI_ERROR(rc)) { return rc; } protocol->handle = handle; protocol->guid = guid; protocol->agent = agent; protocol->iface = iface; return EFI_SUCCESS; } #define EFI_PARTITION_INFO_PROTOCOL_GUID \ {0x8cf2f62c, 0xbc9b, 0x4821, {0x80, 0x8d, 0xec, 0x9e, 0xc4, 0x21, 0xa1, 0xa0}} #define PARTITION_INFO_PROTOCOL EFI_PARTITION_INFO_PROTOCOL_GUID #define EFI_PARTITION_INFO_PROTOCOL_REVISION 0x0001000 #define PARTITION_TYPE_OTHER 0x00 #define PARTITION_TYPE_MBR 0x01 #define PARTITION_TYPE_GPT 0x02 #pragma pack(1) typedef struct { UINT32 Revision; UINT32 Type; UINT8 System; UINT8 Reserved[7]; union { MBR_PARTITION_RECORD Mbr; EFI_PARTITION_ENTRY Gpt; } Info; } EFI_PARTITION_INFO_PROTOCOL; #pragma pack() #ifndef EFI_LOADED_IMAGE_DEVICE_PATH_PROTOCOL_GUID #define EFI_LOADED_IMAGE_DEVICE_PATH_PROTOCOL_GUID \ {0xbc62157e, 0x3e33, 0x4fec, {0x99, 0x20, 0x2d, 0x3b, 0x36, 0xd7, 0x50, 0xdf}} #endif ukiboot-0.2.1+git20260604.ec869c7/efi/ukiboot.c000066400000000000000000000345601521024602400202470ustar00rootroot00000000000000#include "config.h" #include #include #include #include "bootloader.h" #include "pe_parser.h" #include "ukiboot-efi.h" #define UKIBOOTCTL_PARTITION_TYPE_UUID \ {0xfefd9070, 0x346f, 0x4c9a, {0x85, 0xe6, 0x17, 0xf0, 0x7f, 0x92, 0x27, 0x73}} #define UKIBOOT_PARTITION_TYPE_UUID \ {0xdf331e4d, 0xbe00, 0x463f, {0xb4, 0xa7, 0x8b, 0x43, 0xe1, 0x8f, 0xb5, 0x3a}} #define UKIBOOT_PARTITION_TYPE_MBR_IDS {0x46, 0x47} #define UKIBOOTCTL_PARTITION_TYPE_MBR_ID 0x48 typedef struct PACKED { UINT8 priority; UINT8 tries_remaining; UINT8 successful_boot; UINT8 reserved; } UkiBootSlotInfo; #define UKI_BOOT_CTRL_MAGIC 1420550408 /* * The size (in bytes) of the EFI_DEVICE_PATH_PROTOCOL header, which consists of three * fields: Type (1 byte), SubType (1 byte), and Length (2 bytes). So, the header i * always 4 bytes. */ #define DEVICE_PATH_HEADER_SIZE 4 typedef struct PACKED { UINT32 magic; UkiBootSlotInfo slots[2]; UINT8 reserved[8]; UINT32 CRC32; } UkiBootCtrl; CHAR16 *slot_names[] = { L"A", L"B", }; CHAR16 *slot_partition_names[] = { L"ukiboot_a", L"ukiboot_b", }; CHAR16 *slot_efi_name[] = { L"ukiboot_a.efi", L"ukiboot_b.efi", }; UINT32 bootctl_slot_other(UINT32 slot) { if (slot == 0) { return 1; } return 0; } BOOLEAN bootctl_slot_valid(UkiBootSlotInfo *slot) { return slot->successful_boot != 0 || slot->tries_remaining > 0; } EFI_STATUS bootctl_update_crc32(UkiBootCtrl *bootctl) { UINT32 crc; EFI_STATUS rc; rc = efi_calculate_crc32(bootctl, sizeof(UkiBootCtrl) - sizeof(UINT32), &crc); if (EFI_ERROR(rc)) { log(L"Can't compute CRC32"); return rc; } bootctl->CRC32 = crc; return EFI_SUCCESS; } EFI_STATUS bootctl_init(UkiBootCtrl *bootctl) { SetMem(bootctl, sizeof(UkiBootCtrl), 0); bootctl->magic = UKI_BOOT_CTRL_MAGIC; bootctl->slots[0].priority = 15; bootctl->slots[0].tries_remaining = 7; bootctl->slots[0].successful_boot = 0; bootctl->slots[1].priority = 14; bootctl->slots[1].tries_remaining = 7; bootctl->slots[1].successful_boot = 0; return bootctl_update_crc32(bootctl); } EFI_STATUS bootctl_validate(UkiBootCtrl *bootctl) { EFI_STATUS rc; if (bootctl->magic != UKI_BOOT_CTRL_MAGIC) { return EFI_INVALID_PARAMETER; } UINT32 crc; rc = efi_calculate_crc32(bootctl, sizeof(UkiBootCtrl) - sizeof(UINT32), &crc); if (EFI_ERROR(rc)) { log(L"Can't compute CRC32"); return rc; } if (bootctl->CRC32 != crc) { log(L"Invalid bootctrl CRC"); return EFI_INVALID_PARAMETER; } return EFI_SUCCESS; } EFI_STATUS bootctl_find_active_slot(UkiBootCtrl *bootctl, UINT32 *out_slot) { INT32 active_slot = -1; for (INT32 i = 0; i < 2; i++) { if (bootctl_slot_valid(&bootctl->slots[i])) { if (active_slot == -1) { active_slot = i; } else { if (bootctl->slots[i].priority > bootctl->slots[active_slot].priority) { active_slot = i; } } } } if (active_slot != -1) { *out_slot = active_slot; return EFI_SUCCESS; } return EFI_NOT_FOUND; } EFI_STATUS find_partition(EFI_HANDLE loaded_image, EFI_GUID *partition_type, CHAR16 *name, UINT8 mbr_partition_type, EFI_HANDLE *partition_out) { UINTN n_handles; EFI_STATUS rc; _cleanup_free EFI_HANDLE *partitions = NULL; EFI_GUID pip = PARTITION_INFO_PROTOCOL; rc = uefi_call_wrapper(BS->LocateHandleBuffer, 5, ByProtocol, &pip, NULL, &n_handles, (EFI_HANDLE **)&partitions); if (EFI_ERROR(rc)) { log(L"Could not find partition info"); return rc; } EFI_HANDLE found_partition = 0; for (UINTN i = 0; i < n_handles; i++) { EFI_HANDLE partition = partitions[i]; EFI_PARTITION_INFO_PROTOCOL *info; _cleanup_protocol Protocol info_p = PROTOCOL_INIT; rc = efi_open_protocol_exclusive(partition, &pip, loaded_image, &info_p); if (EFI_ERROR(rc)) { log(L"Could not open partition info protocol"); continue; } info = info_p.iface; if (info->Revision == EFI_PARTITION_INFO_PROTOCOL_REVISION) { if (info->Type == PARTITION_TYPE_GPT) { EFI_PARTITION_ENTRY *gpt = &info->Info.Gpt; if (CompareGuid(&gpt->PartitionTypeGUID, partition_type) == 0 && StrCmp(name, gpt->PartitionName) == 0) { found_partition = partition; break; } } else if (info->Type == PARTITION_TYPE_MBR) { MBR_PARTITION_RECORD *mbr = &info->Info.Mbr; if (mbr->OSIndicator == mbr_partition_type) { found_partition = partition; break; } } } } if (found_partition) { *partition_out = found_partition; return EFI_SUCCESS; } return EFI_NOT_FOUND; } UINT32 round_up_to_blocksize(UINT32 size, UINT32 block_size) { UINT32 n_blocks = (size + (block_size - 1)) / block_size; return n_blocks * block_size; } VOID * allocate_aligned_buffer(UINT32 buf_size, EFI_MEMORY_TYPE mem_type) { EFI_STATUS rc; EFI_PHYSICAL_ADDRESS addr = 0; rc = uefi_call_wrapper(BS->AllocatePages, 4, AllocateAnyPages, mem_type, (buf_size + EFI_PAGE_SIZE - 1) / EFI_PAGE_SIZE, &addr); if (EFI_ERROR(rc)) return NULL; return (VOID *)addr; } EFI_STATUS find_active_slot(EFI_HANDLE loaded_image, UINT32 *slot_out) { EFI_STATUS rc; EFI_HANDLE bootctl_partition; _cleanup_protocol Protocol proto = PROTOCOL_INIT; EFI_GUID partition_type = UKIBOOTCTL_PARTITION_TYPE_UUID; EFI_BLOCK_IO_PROTOCOL *blockio; rc = find_partition(loaded_image, &partition_type, L"ukibootctl", UKIBOOTCTL_PARTITION_TYPE_MBR_ID, &bootctl_partition); if (EFI_ERROR(rc)) { log(L"Unable to find ukibootctl partition"); return rc; } rc = efi_open_protocol_exclusive(bootctl_partition, &BlockIoProtocol, loaded_image, &proto); if (EFI_ERROR(rc)) { log(L"Unable to open partition blockio"); return rc; } blockio = proto.iface; UINT32 block_size = blockio->Media->BlockSize; UINT32 buf_size = round_up_to_blocksize(sizeof(UkiBootCtrl), block_size); VOID *buffer = allocate_aligned_buffer(buf_size, EfiLoaderData); if (buffer == NULL) { log(L"Unable to allocate memory to read ukibootctl data"); return EFI_OUT_OF_RESOURCES; } rc = efi_read_blocks(blockio, 0, buf_size, buffer); if (EFI_ERROR(rc)) { log(L"Unable to read ukibootctl partition"); return rc; } UkiBootCtrl *bootctl = (UkiBootCtrl *)buffer; rc = bootctl_validate(bootctl); if (EFI_ERROR(rc)) { log(L"Uninitialized uki_bootctl partition, reseting to default"); rc = bootctl_init(bootctl); if (EFI_ERROR(rc)) { log(L"Unable to init ukibootctl partition"); return rc; } rc = efi_write_blocks(blockio, 0, buf_size, buffer); if (EFI_ERROR(rc)) { log(L"Unable to write initialized ukibootctl partition"); return rc; } } UINT32 active_slot; rc = bootctl_find_active_slot(bootctl, &active_slot); if (EFI_ERROR(rc)) { log(L"Unable to find active slot"); return rc; } if (bootctl->slots[active_slot].successful_boot == 0) { log(L"Test booting slot %s, tries_remaining: %d", slot_names[active_slot], bootctl->slots[active_slot].tries_remaining); bootctl->slots[active_slot].tries_remaining -= 1; rc = bootctl_update_crc32(bootctl); if (EFI_ERROR(rc)) { log(L"Unable to update tries_remaining"); return rc; } rc = efi_write_blocks(blockio, 0, buf_size, buffer); if (EFI_ERROR(rc)) { log(L"Unable to write updated ukibootctl partition"); return rc; } } *slot_out = active_slot; return EFI_SUCCESS; } UINTN get_filepath_size(EFI_DEVICE_PATH_PROTOCOL *dp_root) { UINTN total_size = 0; EFI_DEVICE_PATH_PROTOCOL *dp; UINT8 *ptr = (UINT8 *)dp_root; do { dp = (EFI_DEVICE_PATH_PROTOCOL *)ptr; UINTN size = DevicePathNodeLength(dp); total_size += size; ptr += size; } while (!IsDevicePathEndType(dp)); return total_size; } INT32 find_last_separator(CHAR16 *path) { INT32 last_separator = -1; INT32 i = 0; while (path[i] != 0) { if (path[i] == L'\\') { last_separator = i; } i++; } if (last_separator >= 0) return last_separator; /* No separator, return after path end */ return i; } EFI_STATUS get_fake_device_path_for_slot(EFI_HANDLE loaded_image, UINT32 active_slot, EFI_DEVICE_PATH **path_out) { EFI_STATUS rc; _cleanup_protocol Protocol proto = PROTOCOL_INIT; EFI_GUID lidpp = EFI_LOADED_IMAGE_DEVICE_PATH_PROTOCOL_GUID; CHAR16 *fake_filename = slot_efi_name[active_slot]; rc = efi_open_protocol_exclusive(loaded_image, &lidpp, loaded_image, &proto); if (EFI_ERROR(rc)) { log(L"Could not open loaded_image devicepath protocol"); return rc; } EFI_DEVICE_PATH_PROTOCOL *dp_root = proto.iface; /* We should have at least non-end node */ if (IsDevicePathEndType(dp_root)) { log(L"Invalid loaded image device path"); return EFI_INVALID_PARAMETER; } UINTN orig_size = get_filepath_size(dp_root); /* Ensure we have space for the original filepath + modified basename */ _cleanup_free VOID *new_dp = AllocatePool(orig_size + (1 + StrLen(fake_filename) + 1) * sizeof(CHAR16)); if (new_dp == NULL) { log(L"Unable to allocate memory for device path"); return EFI_OUT_OF_RESOURCES; } UINT8 *ptr = (UINT8 *)dp_root; UINT8 *dst_ptr = (UINT8 *)new_dp; EFI_DEVICE_PATH_PROTOCOL *src_dp; src_dp = (EFI_DEVICE_PATH_PROTOCOL *)ptr; while (!IsDevicePathEndType(src_dp)) { UINTN src_size = DevicePathNodeLength(src_dp); EFI_DEVICE_PATH_PROTOCOL *next_src_dp = (EFI_DEVICE_PATH_PROTOCOL *)(ptr + src_size); EFI_DEVICE_PATH_PROTOCOL *dst_dp = (EFI_DEVICE_PATH_PROTOCOL *)dst_ptr; if (IsDevicePathEndType(next_src_dp)) { /* This is the last (non-end) node, rewrite it */ if (DevicePathType(src_dp) != MEDIA_DEVICE_PATH || DevicePathSubType(src_dp) != MEDIA_FILEPATH_DP) { log(L"Final device path element is not a file path node. Type=0x%x SubType=0x%x", DevicePathType(src_dp), DevicePathSubType(src_dp)); return EFI_INVALID_PARAMETER; } FILEPATH_DEVICE_PATH *dst_fp = (FILEPATH_DEVICE_PATH *)dst_dp; dst_dp->Type = src_dp->Type; dst_dp->SubType = src_dp->SubType; UINT32 new_path_len = (StrLen(ESP_DIR) + 1 + StrLen(fake_filename) + 1) * sizeof(CHAR16); SetDevicePathNodeLength(dst_dp, new_path_len + DEVICE_PATH_HEADER_SIZE); dst_ptr += new_path_len + DEVICE_PATH_HEADER_SIZE; StrCpy(dst_fp->PathName, ESP_DIR); StrCat(dst_fp->PathName, L"/"); StrCat(dst_fp->PathName, fake_filename); log(L"Using uki pathname: %s", dst_fp->PathName); } else { CopyMem(dst_dp, src_dp, src_size); dst_ptr += src_size; } ptr += src_size; src_dp = (EFI_DEVICE_PATH_PROTOCOL *)ptr; } /* This is the end of device path node */ EFI_DEVICE_PATH_PROTOCOL *end_dp = (EFI_DEVICE_PATH_PROTOCOL *)dst_ptr; end_dp->Type = END_DEVICE_PATH_TYPE; end_dp->SubType = END_ENTIRE_DEVICE_PATH_SUBTYPE; SetDevicePathNodeLength(end_dp, DEVICE_PATH_HEADER_SIZE); *path_out = (EFI_DEVICE_PATH *)_steal_pointer(&new_dp); return EFI_SUCCESS; } EFI_STATUS boot(EFI_HANDLE loaded_image) { EFI_STATUS rc; UINT32 active_slot; EFI_GUID partition_type = UKIBOOT_PARTITION_TYPE_UUID; UINT8 mbr_partition_ids[] = UKIBOOT_PARTITION_TYPE_MBR_IDS; rc = bootloader_interface_init(loaded_image); if (EFI_ERROR(rc)) { log(L"Warning: Unable to initialize bootloader interface: %d", rc); } rc = find_active_slot(loaded_image, &active_slot); if (EFI_ERROR(rc)) { log(L"Unable to find active slot"); return rc; } CHAR16 *partition_name = slot_partition_names[active_slot]; UINT8 mbr_partition_id = mbr_partition_ids[active_slot]; EFI_HANDLE boot_partition; rc = find_partition(loaded_image, &partition_type, partition_name, mbr_partition_id, &boot_partition); if (EFI_ERROR(rc)) { log(L"Unable to find %s partition", partition_name); return rc; } _cleanup_protocol Protocol proto = PROTOCOL_INIT; EFI_BLOCK_IO_PROTOCOL *blockio; rc = efi_open_protocol_exclusive(boot_partition, &BlockIoProtocol, loaded_image, &proto); if (EFI_ERROR(rc)) { log(L"Unable to open partition blockio"); return rc; } blockio = proto.iface; UINT32 block_size = blockio->Media->BlockSize; UINT32 buf_size = round_up_to_blocksize(PE_FILE_HEADER_BUFFER_SIZE, block_size); VOID *buffer = allocate_aligned_buffer(buf_size, EfiLoaderData); if (buffer == NULL) { log(L"Unable to allocate memory to read pe header"); return EFI_OUT_OF_RESOURCES; } rc = efi_read_blocks(blockio, 0, buf_size, buffer); if (EFI_ERROR(rc)) { log(L"Unable to read pe header"); return rc; } UINTN pe_size; rc = get_pe_size(buffer, buf_size, &pe_size); if (EFI_ERROR(rc)) { log(L"Unable to parse pe header"); return rc; } buf_size = round_up_to_blocksize(pe_size, block_size); VOID *image_buf = allocate_aligned_buffer(buf_size, EfiLoaderCode); if (image_buf == NULL) { log(L"Unable to allocate memory for uki image"); return EFI_OUT_OF_RESOURCES; } log(L"Loading UKI from partition %s", partition_name); rc = efi_read_blocks(blockio, 0, buf_size, image_buf); if (EFI_ERROR(rc)) { log(L"Unable to read uki partition"); return rc; } _cleanup_free EFI_DEVICE_PATH *fake_path = NULL; rc = get_fake_device_path_for_slot(loaded_image, active_slot, &fake_path); if (EFI_ERROR(rc)) { log(L"Unable to construct device path for slot %d: %r", active_slot, rc); return rc; } log(L"Calling LoadImage"); EFI_HANDLE image; rc = uefi_call_wrapper(BS->LoadImage, 6, FALSE, loaded_image, fake_path, image_buf, pe_size, &image); if (EFI_ERROR(rc)) { log(L"Unable to load uki image: %d", rc); return rc; } log(L"Starting UKI"); rc = uefi_call_wrapper(BS->StartImage, 3, image, 0, NULL); if (EFI_ERROR(rc)) { log(L"Unable to load uki image: %d", rc); return rc; } /* Unexpected error if StartImage returns */ return EFI_LOAD_ERROR; } EFI_STATUS efi_main(EFI_HANDLE loaded_image, UNUSED EFI_SYSTEM_TABLE *SystemTable) { EFI_STATUS rc; log(L"Starting ukiboot version %s", PACKAGE_VERSION_L); rc = boot(loaded_image); if (EFI_ERROR(rc)) { log(L"Error: Unable to boot (%r)", rc); } return rc; } ukiboot-0.2.1+git20260604.ec869c7/gpt_parser.c000066400000000000000000000101401521024602400201620ustar00rootroot00000000000000/* Minimal GPT parser Copyright (C) 2026 Alexander Larsson This file is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This file 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ #include "config.h" #include "gpt_parser.h" #include "utils.h" #include #include #include #ifdef HAVE_ENDIAN_H #include #endif #ifdef HAVE_SYS_ENDIAN_H #include #endif #ifdef HAVE_MACHINE_ENDIAN_H #include #endif #define GPT_SECTOR_SIZE 512 #define GPT_HEADER_OFFSET GPT_SECTOR_SIZE #define GPT_SIGNATURE 0x5452415020494645ULL /* "EFI PART" */ #define GPT_ENTRY_NAME_CHARS 36 typedef struct attr_packed { uint64_t signature; uint32_t revision; uint32_t header_size; uint32_t header_crc32; uint32_t reserved; uint64_t my_lba; uint64_t alternate_lba; uint64_t first_usable_lba; uint64_t last_usable_lba; uint8_t disk_guid[16]; uint64_t partition_entry_lba; uint32_t num_partition_entries; uint32_t partition_entry_size; uint32_t partition_entry_crc32; } GptHeader; typedef struct attr_packed { uint8_t type_guid[16]; uint8_t unique_guid[16]; uint64_t first_lba; uint64_t last_lba; uint64_t attributes; uint16_t name[GPT_ENTRY_NAME_CHARS]; } GptEntry; static bool is_zero_guid(const uint8_t *guid) { for (int i = 0; i < 16; i++) { if (guid[i] != 0) return false; } return true; } static void utf16le_to_ascii(const uint16_t *src, char *dst, size_t max_chars) { for (size_t i = 0; i < max_chars; i++) { uint16_t c = le16toh(src[i]); if (c == 0) { dst[i] = '\0'; return; } dst[i] = (c < 128) ? (char)c : '?'; } dst[max_chars] = '\0'; } bool gpt_parse(int fd, GptPartitionTable *out) { GptHeader header; if (!full_pread(fd, &header, sizeof(header), GPT_HEADER_OFFSET)) return false; if (le64toh(header.signature) != GPT_SIGNATURE) { error("Invalid GPT signature\n"); return false; } uint32_t num_entries = le32toh(header.num_partition_entries); uint32_t entry_size = le32toh(header.partition_entry_size); uint64_t entries_offset = le64toh(header.partition_entry_lba) * GPT_SECTOR_SIZE; if (entry_size < sizeof(GptEntry)) { error("GPT entry size too small\n"); return false; } autofree uint8_t *entry_buf = xmalloc(entry_size); autofree GptPartition *parts = NULL; uint32_t count = 0; for (uint32_t i = 0; i < num_entries; i++) { if (!full_pread(fd, entry_buf, entry_size, entries_offset + (uint64_t)i * entry_size)) return false; GptEntry *entry = (GptEntry *)entry_buf; if (is_zero_guid(entry->type_guid)) continue; parts = xrealloc(parts, (count + 1) * sizeof(GptPartition)); uint16_t name_copy[GPT_ENTRY_NAME_CHARS]; memcpy(name_copy, entry->name, sizeof(name_copy)); utf16le_to_ascii(name_copy, parts[count].name, GPT_ENTRY_NAME_CHARS); uint64_t first = le64toh(entry->first_lba); uint64_t last = le64toh(entry->last_lba); parts[count].offset = first * GPT_SECTOR_SIZE; parts[count].size = (last - first + 1) * GPT_SECTOR_SIZE; count++; } out->partitions = steal_pointer(&parts); out->n_partitions = count; return true; } GptPartition * gpt_find_partition(GptPartitionTable *table, const char *name) { for (uint32_t i = 0; i < table->n_partitions; i++) { if (strcmp(table->partitions[i].name, name) == 0) return &table->partitions[i]; } return NULL; } void gpt_partition_table_free(GptPartitionTable *table) { free(table->partitions); table->partitions = NULL; table->n_partitions = 0; } ukiboot-0.2.1+git20260604.ec869c7/gpt_parser.h000066400000000000000000000023061521024602400201740ustar00rootroot00000000000000/* Minimal GPT parser Copyright (C) 2026 Alexander Larsson This file is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This file 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ #include #include #define GPT_NAME_MAX 36 typedef struct { char name[GPT_NAME_MAX + 1]; uint64_t offset; uint64_t size; } GptPartition; typedef struct { uint32_t n_partitions; GptPartition *partitions; } GptPartitionTable; extern bool gpt_parse(int fd, GptPartitionTable *out); extern GptPartition * gpt_find_partition(GptPartitionTable *table, const char *name); extern void gpt_partition_table_free(GptPartitionTable *table); ukiboot-0.2.1+git20260604.ec869c7/meson.build000066400000000000000000000076361521024602400200320ustar00rootroot00000000000000project('ukiboot', 'c', version: '0.2.1', license : 'LGPL-2.1+', meson_version : '>=0.62.0', default_options : ['warning_level=2', 'c_std=c99'], ) cc = meson.get_compiler('c') add_project_arguments( cc.get_supported_arguments([ '-Werror=shadow', '-Werror=empty-body', '-Werror=strict-prototypes', '-Werror=missing-prototypes', '-Werror=implicit-function-declaration', '-Werror=format=2 -Werror=format-security -Werror=format-nonliteral', '-Werror=pointer-arith', '-Werror=init-self', '-Werror=missing-declarations', '-Werror=return-type', '-Werror=switch', '-Werror=overflow', '-Werror=int-conversion', '-Werror=parentheses', '-Werror=undef', '-Werror=incompatible-pointer-types', '-Werror=misleading-indentation', '-Werror=missing-include-dirs', '-Wstrict-aliasing=2', '-Werror=unused-result', ]), language: 'c' ) conf = configuration_data() conf.set_quoted('PACKAGE_VERSION', meson.project_version()) conf.set('PACKAGE_VERSION_L', 'L"@0@"'.format(meson.project_version())) conf.set('_GNU_SOURCE', 1) efi_ldsdir = get_option('efi-ldsdir') efi_incdir = get_option('efi-includedir') efi_libdir = get_option('efi-libdir') if cc.check_header('endian.h') conf.set('HAVE_ENDIAN_H', '1') endif if cc.check_header('sys/endian.h') conf.set('HAVE_SYS_ENDIAN_H', 1) endif if cc.check_header('machine/endian.h') conf.set('HAVE_MACHINE_ENDIAN_H', 1) endif esp_dir = get_option('esp-dir') conf.set('ESP_DIR', 'L"' + esp_dir + '"') cc = meson.get_compiler('c') objcopy = find_program('objcopy') objcopy_version = run_command(objcopy, '--version', check: true).stdout().split('\n')[0].split(' ')[-1] gnuefi = dependency('gnu-efi', required: false) if not gnuefi.found() gnuefi_dirs = [] if efi_libdir != '' gnuefi_dirs = gnuefi_dirs + [efi_libdir] endif gnuefi_lib = cc.find_library('efi', dirs: gnuefi_dirs, header_include_directories: [include_directories(efi_incdir)], has_headers: ['efiapi.h'], required: true) endif prefix = get_option('prefix') libdir = join_paths(prefix, get_option('libdir')) libexecdir = join_paths(prefix, get_option('libexecdir')) python3path = get_option('python') if python3path == '' python3 = import('python').find_installation('python3') else python3 = find_program(python3path) endif systemd = dependency('systemd') systemd_system_unit_dir = systemd.get_variable(pkgconfig : 'systemdsystemunitdir') unit_files = [ 'ukiboot-set-success.service' ] efi_app_location = join_paths(libexecdir, 'ukiboot', 'efi') ukify = find_program('ukify') custom_target('slot_a_addon', output: 'slot_a.addon.efi', command: [ukify, 'build', '--output=slot_a.addon.efi', '--cmdline', 'androidboot.slot_suffix=_a'], install: true, install_dir: efi_app_location, ) custom_target('slot_b_addon', output: 'slot_b.addon.efi', command: [ukify, 'build', '--output=slot_b.addon.efi', '--cmdline', 'androidboot.slot_suffix=_b'], install: true, install_dir: efi_app_location, ) libcrypto_dep = dependency('libcrypto', required: get_option('openssl')) if libcrypto_dep.found() conf.set('HAVE_OPENSSL', 1) endif configure_file( output : 'config.h', configuration : conf ) ukiboot_efi_dep = declare_dependency() ukibootctl = executable('ukibootctl', sources: ['ukibootctl.c', 'utils.c'], install: true, ) ukibootimg_deps = [] if libcrypto_dep.found() ukibootimg_deps += [libcrypto_dep] endif ukibootimg = executable('ukibootimg', sources: ['ukibootimg.c', 'utils.c', 'pe_parser_posix.c', 'gpt_parser.c'], dependencies: ukibootimg_deps, install: true, ) foreach u : unit_files configure_file( copy: true, input: u, install: true, install_dir: systemd_system_unit_dir, output: u, ) endforeach subdir('efi') subdir('test') ukiboot-0.2.1+git20260604.ec869c7/meson_options.txt000066400000000000000000000011251521024602400213100ustar00rootroot00000000000000option('efi-libdir', type : 'string', description : 'path to the EFI lib directory') option('efi-ldsdir', type : 'string', description : 'path to the EFI lds directory') option('efi-includedir', type : 'string', value : '/usr/include/efi', description : 'path to the EFI header directory') option('python', type : 'string', description : 'the absolute path of the python3 binary') option('esp-dir', type : 'string', value : 'EFI/BOOT', description : 'Directory on ESP for slot files') option('openssl', type : 'feature', value : 'auto', description : 'OpenSSL support for signature verification') ukiboot-0.2.1+git20260604.ec869c7/pe_parser_posix.c000066400000000000000000000461211521024602400212260ustar00rootroot00000000000000/* PE parser for POSIX Copyright (C) 2026 Alexander Larsson This file is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This file 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ #include "config.h" #include "pe_parser_posix.h" #include "utils.h" #include #include #include #ifdef HAVE_ENDIAN_H #include #endif #ifdef HAVE_SYS_ENDIAN_H #include #endif #ifdef HAVE_MACHINE_ENDIAN_H #include #endif #define IMAGE_DOS_SIGNATURE 0x5A4D #define IMAGE_NT_SIGNATURE 0x00004550 typedef struct attr_packed { uint16_t e_magic; uint16_t e_cblp; uint16_t e_cp; uint16_t e_crlc; uint16_t e_cparhdr; uint16_t e_minalloc; uint16_t e_maxalloc; uint16_t e_ss; uint16_t e_sp; uint16_t e_csum; uint16_t e_ip; uint16_t e_cs; uint16_t e_lfarlc; uint16_t e_ovno; uint16_t e_res[4]; uint16_t e_oemid; uint16_t e_oeminfo; uint16_t e_res2[10]; int32_t e_lfanew; } ImageDosHeader; typedef struct attr_packed { uint16_t Machine; uint16_t NumberOfSections; uint32_t TimeDateStamp; uint32_t PointerToSymbolTable; uint32_t NumberOfSymbols; uint16_t SizeOfOptionalHeader; uint16_t Characteristics; } ImageFileHeader; typedef struct attr_packed { uint32_t Signature; ImageFileHeader FileHeader; } ImageNtHeaders; typedef struct attr_packed { uint8_t Name[PE_SECTION_NAME_SIZE]; union { uint32_t PhysicalAddress; uint32_t VirtualSize; } Misc; uint32_t VirtualAddress; uint32_t SizeOfRawData; uint32_t PointerToRawData; uint32_t PointerToRelocations; uint32_t PointerToLinenumbers; uint16_t NumberOfRelocations; uint16_t NumberOfLinenumbers; uint32_t Characteristics; } ImageSectionHeader; #define IMAGE_NT_OPTIONAL_HDR32_MAGIC 0x10b #define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b static bool pe_read_headers(int fd, off_t base_offset, uint32_t *nt_offset_out, ImageNtHeaders *nt_out, uint16_t *opt_magic_out) { ImageDosHeader dos_header; if (!full_pread(fd, &dos_header, sizeof(dos_header), base_offset)) return false; if (le16toh(dos_header.e_magic) != IMAGE_DOS_SIGNATURE) { error("Invalid DOS header magic\n"); return false; } uint32_t nt_offset = (uint32_t)le32toh(dos_header.e_lfanew); ImageNtHeaders nt_header; if (!full_pread(fd, &nt_header, sizeof(nt_header), base_offset + nt_offset)) return false; if (le32toh(nt_header.Signature) != IMAGE_NT_SIGNATURE) { error("Invalid PE signature\n"); return false; } uint16_t opt_magic; if (!full_pread(fd, &opt_magic, sizeof(opt_magic), base_offset + nt_offset + sizeof(ImageNtHeaders))) return false; opt_magic = le16toh(opt_magic); if (opt_magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC && opt_magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) { error("Unsupported PE optional header magic: 0x%x\n", opt_magic); return false; } *nt_offset_out = nt_offset; *nt_out = nt_header; *opt_magic_out = opt_magic; return true; } bool pe_parse_sections(int fd, off_t base_offset, PeSectionInfo **sections_out, uint32_t *n_sections_out) { uint32_t nt_offset; ImageNtHeaders nt_header; uint16_t opt_magic; if (!pe_read_headers(fd, base_offset, &nt_offset, &nt_header, &opt_magic)) return false; uint16_t opt_header_size = le16toh(nt_header.FileHeader.SizeOfOptionalHeader); uint32_t num_sections = le16toh(nt_header.FileHeader.NumberOfSections); uint32_t sections_offset = nt_offset + sizeof(ImageNtHeaders) + opt_header_size; autofree ImageSectionHeader *raw_sections = xcalloc(num_sections, sizeof(ImageSectionHeader)); if (!full_pread(fd, raw_sections, num_sections * sizeof(ImageSectionHeader), base_offset + sections_offset)) return false; autofree PeSectionInfo *sections = xcalloc(num_sections, sizeof(PeSectionInfo)); for (uint32_t i = 0; i < num_sections; i++) { memcpy(sections[i].name, raw_sections[i].Name, PE_SECTION_NAME_SIZE); sections[i].name[PE_SECTION_NAME_SIZE] = '\0'; sections[i].file_offset = le32toh(raw_sections[i].PointerToRawData); sections[i].size = le32toh(raw_sections[i].Misc.VirtualSize); } *sections_out = steal_pointer(§ions); *n_sections_out = num_sections; return true; } /* Authenticode signature verification */ #ifdef HAVE_OPENSSL #include #include #include #include #include #include #include #include #define WIN_CERT_REVISION_2_0 0x0200 #define WIN_CERT_TYPE_PKCS7 0x0002 #define HASH_BUF_SIZE (64 * 1024) static inline void cleanup_x509_storep(X509_STORE **p) { if (*p) X509_STORE_free(*p); } static inline void cleanup_x509_store_ctxp(X509_STORE_CTX **p) { if (*p) X509_STORE_CTX_free(*p); } static inline void cleanup_evp_md_ctxp(EVP_MD_CTX **p) { if (*p) EVP_MD_CTX_free(*p); } static inline void cleanup_pkcs7p(PKCS7 **p) { if (*p) PKCS7_free(*p); } #define auto_x509_store __attribute__((cleanup(cleanup_x509_storep))) #define auto_x509_store_ctx __attribute__((cleanup(cleanup_x509_store_ctxp))) #define auto_evp_md_ctx __attribute__((cleanup(cleanup_evp_md_ctxp))) #define auto_pkcs7 __attribute__((cleanup(cleanup_pkcs7p))) typedef struct attr_packed { uint32_t dwLength; uint16_t wRevision; uint16_t wCertificateType; } WinCertificate; typedef struct { off_t base_offset; off_t opt_header_offset; bool is_pe32plus; off_t checksum_offset; off_t security_dir_offset; uint32_t cert_table_rva; uint32_t cert_table_size; uint32_t size_of_headers; uint16_t num_sections; off_t sections_offset; } PeLayout; static bool pe_read_layout(int fd, off_t base_offset, PeLayout *layout) { uint32_t nt_offset; ImageNtHeaders nt_header; uint16_t opt_magic; if (!pe_read_headers(fd, base_offset, &nt_offset, &nt_header, &opt_magic)) return false; layout->base_offset = base_offset; layout->opt_header_offset = base_offset + nt_offset + sizeof(ImageNtHeaders); layout->num_sections = le16toh(nt_header.FileHeader.NumberOfSections); uint16_t opt_size = le16toh(nt_header.FileHeader.SizeOfOptionalHeader); layout->sections_offset = layout->opt_header_offset + opt_size; layout->is_pe32plus = (opt_magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC); layout->checksum_offset = layout->opt_header_offset + 64; uint32_t security_dir_table_offset = layout->is_pe32plus ? 144 : 128; layout->security_dir_offset = layout->opt_header_offset + security_dir_table_offset; uint32_t sec_dir[2]; if (!full_pread(fd, sec_dir, sizeof(sec_dir), layout->security_dir_offset)) return false; layout->cert_table_rva = le32toh(sec_dir[0]); layout->cert_table_size = le32toh(sec_dir[1]); uint32_t size_of_headers; if (!full_pread(fd, &size_of_headers, sizeof(size_of_headers), layout->opt_header_offset + 60)) return false; layout->size_of_headers = le32toh(size_of_headers); return true; } static int section_raw_ptr_cmp(const void *a, const void *b) { const ImageSectionHeader *sa = a; const ImageSectionHeader *sb = b; uint32_t pa = le32toh(sa->PointerToRawData); uint32_t pb = le32toh(sb->PointerToRawData); return (pa > pb) - (pa < pb); } static bool hash_file_range(EVP_MD_CTX *ctx, int fd, off_t offset, size_t length) { autofree uint8_t *buf = xmalloc(HASH_BUF_SIZE); while (length > 0) { size_t chunk = length < HASH_BUF_SIZE ? length : HASH_BUF_SIZE; if (!full_pread(fd, buf, chunk, offset)) return false; if (!EVP_DigestUpdate(ctx, buf, chunk)) return false; offset += chunk; length -= chunk; } return true; } static bool compute_authenticode_hash(int fd, PeLayout *layout, const EVP_MD *md, uint8_t *hash_out, unsigned int *hash_len) { auto_evp_md_ctx EVP_MD_CTX *ctx = EVP_MD_CTX_new(); if (!ctx) return false; if (!EVP_DigestInit_ex(ctx, md, NULL)) return false; off_t base = layout->base_offset; off_t checksum_off = layout->checksum_offset; off_t secdir_off = layout->security_dir_offset; off_t after_checksum = checksum_off + 4; off_t after_secdir = secdir_off + 8; off_t headers_end = base + layout->size_of_headers; /* Hash headers in three ranges, skipping the CheckSum field (4 bytes) and the Security Directory entry (8 bytes). */ if (!hash_file_range(ctx, fd, base, checksum_off - base)) return false; if (!hash_file_range(ctx, fd, after_checksum, secdir_off - after_checksum)) return false; if (after_secdir < headers_end) { if (!hash_file_range(ctx, fd, after_secdir, headers_end - after_secdir)) return false; } autofree ImageSectionHeader *shdrs = xcalloc(layout->num_sections, sizeof(ImageSectionHeader)); if (!full_pread(fd, shdrs, layout->num_sections * sizeof(ImageSectionHeader), layout->sections_offset)) return false; qsort(shdrs, layout->num_sections, sizeof(ImageSectionHeader), section_raw_ptr_cmp); off_t last_section_end = 0; for (uint16_t i = 0; i < layout->num_sections; i++) { uint32_t raw_ptr = le32toh(shdrs[i].PointerToRawData); uint32_t raw_size = le32toh(shdrs[i].SizeOfRawData); if (raw_size == 0) continue; if (!hash_file_range(ctx, fd, base + raw_ptr, raw_size)) return false; off_t sec_end = raw_ptr + raw_size; if (sec_end > last_section_end) last_section_end = sec_end; } if (layout->cert_table_rva > 0 && layout->cert_table_rva > last_section_end) { if (!hash_file_range(ctx, fd, base + last_section_end, layout->cert_table_rva - last_section_end)) return false; } if (!EVP_DigestFinal_ex(ctx, hash_out, hash_len)) return false; return true; } /* Extract the file hash from a DER-encoded SpcIndirectDataContent: SEQUENCE { SpcAttributeTypeAndOptionalValue, DigestInfo } where DigestInfo = SEQUENCE { AlgorithmIdentifier, OCTET STRING } */ static bool extract_spc_file_hash(const uint8_t *data, int data_len, uint8_t *hash_out, unsigned int *hash_len_out, unsigned int hash_max) { const uint8_t *p = data; long len; int tag, cls, ret; /* Outer SEQUENCE */ ret = ASN1_get_object(&p, &len, &tag, &cls, data_len); if (ret & 0x80 || tag != V_ASN1_SEQUENCE) return false; const uint8_t *seq_end = p + len; /* Skip SpcAttributeTypeAndOptionalValue SEQUENCE */ ret = ASN1_get_object(&p, &len, &tag, &cls, seq_end - p); if (ret & 0x80 || tag != V_ASN1_SEQUENCE) return false; p += len; /* DigestInfo SEQUENCE */ ret = ASN1_get_object(&p, &len, &tag, &cls, seq_end - p); if (ret & 0x80 || tag != V_ASN1_SEQUENCE) return false; const uint8_t *di_end = p + len; /* Skip AlgorithmIdentifier SEQUENCE */ ret = ASN1_get_object(&p, &len, &tag, &cls, di_end - p); if (ret & 0x80 || tag != V_ASN1_SEQUENCE) return false; p += len; /* OCTET STRING: the file hash */ ret = ASN1_get_object(&p, &len, &tag, &cls, di_end - p); if (ret & 0x80 || tag != V_ASN1_OCTET_STRING) return false; if (len <= 0 || (unsigned int)len > hash_max) return false; memcpy(hash_out, p, len); *hash_len_out = len; return true; } static bool verify_pkcs7_signature(PKCS7 *p7, PKCS7_SIGNER_INFO *si, const EVP_MD *md, const uint8_t *content_data, int content_len, const char *cert_path) { FILE *cert_file = fopen(cert_path, "r"); if (!cert_file) { error("Failed to open certificate %s: %s\n", cert_path, strerror(errno)); return false; } X509 *trusted = PEM_read_X509(cert_file, NULL, NULL, NULL); fclose(cert_file); if (!trusted) { error("Failed to parse PEM certificate %s\n", cert_path); return false; } auto_x509_store X509_STORE *store = X509_STORE_new(); if (!store) { X509_free(trusted); return false; } X509_STORE_add_cert(store, trusted); X509_free(trusted); /* Match EFI firmware behavior: don't check cert expiry, since there is no reliable clock at early boot. */ X509_STORE_set_flags(store, X509_V_FLAG_NO_CHECK_TIME); /* We can't use PKCS7_verify() because it doesn't handle the Authenticode SpcIndirectDataContent content type. Instead we verify the cert chain, messageDigest, and signature manually. */ /* Verify signer cert against trusted store */ X509 *signer = PKCS7_cert_from_signer_info(p7, si); if (!signer) { error("Cannot find signer certificate in PKCS#7\n"); return false; } auto_x509_store_ctx X509_STORE_CTX *store_ctx = X509_STORE_CTX_new(); if (!store_ctx) return false; if (!X509_STORE_CTX_init(store_ctx, store, signer, p7->d.sign->cert)) return false; if (X509_verify_cert(store_ctx) != 1) { error("Signer certificate verification failed\n"); return false; } verbose("Signer certificate trusted\n"); /* Verify the messageDigest attribute matches hash of content */ ASN1_OCTET_STRING *msg_digest = PKCS7_digest_from_attributes(si->auth_attr); if (!msg_digest) { error("No messageDigest attribute in signer info\n"); return false; } uint8_t computed_md[EVP_MAX_MD_SIZE]; unsigned int computed_md_len; if (!EVP_Digest(content_data, content_len, computed_md, &computed_md_len, md, NULL)) { error("Failed to compute content digest\n"); return false; } if (msg_digest->length != (int)computed_md_len || CRYPTO_memcmp(msg_digest->data, computed_md, computed_md_len) != 0) { error("Content digest mismatch\n"); return false; } /* Verify the RSA/ECDSA signature over the authenticated attributes */ EVP_PKEY *pkey = X509_get0_pubkey(signer); if (!pkey) { error("Cannot get signer public key\n"); return false; } int attr_der_len = ASN1_item_i2d((ASN1_VALUE *)si->auth_attr, NULL, ASN1_ITEM_rptr(PKCS7_ATTR_VERIFY)); if (attr_der_len <= 0) { error("Failed to encode authenticated attributes\n"); return false; } autofree uint8_t *attr_der = xmalloc(attr_der_len); uint8_t *attr_p = attr_der; ASN1_item_i2d((ASN1_VALUE *)si->auth_attr, &attr_p, ASN1_ITEM_rptr(PKCS7_ATTR_VERIFY)); auto_evp_md_ctx EVP_MD_CTX *md_ctx = EVP_MD_CTX_new(); if (!md_ctx) return false; if (!EVP_DigestVerifyInit(md_ctx, NULL, md, NULL, pkey) || !EVP_DigestVerify(md_ctx, si->enc_digest->data, si->enc_digest->length, attr_der, attr_der_len)) { error("Signature verification failed\n"); return false; } return true; } bool pe_verify_signature(int fd, off_t base_offset, const char *cert_path) { PeLayout layout; if (!pe_read_layout(fd, base_offset, &layout)) return false; if (layout.cert_table_size == 0) { error("PE file has no embedded signature\n"); return false; } off_t cert_offset = base_offset + layout.cert_table_rva; WinCertificate win_cert; if (!full_pread(fd, &win_cert, sizeof(win_cert), cert_offset)) return false; if (le16toh(win_cert.wRevision) != WIN_CERT_REVISION_2_0) { error("Unsupported certificate revision: 0x%04x\n", le16toh(win_cert.wRevision)); return false; } if (le16toh(win_cert.wCertificateType) != WIN_CERT_TYPE_PKCS7) { error("Unsupported certificate type: 0x%04x\n", le16toh(win_cert.wCertificateType)); return false; } uint32_t dwLength = le32toh(win_cert.dwLength); if (dwLength < sizeof(WinCertificate) || dwLength > layout.cert_table_size) { error("Invalid certificate length: %u\n", dwLength); return false; } uint32_t pkcs7_size = dwLength - sizeof(WinCertificate); autofree uint8_t *pkcs7_buf = xmalloc(pkcs7_size); if (!full_pread(fd, pkcs7_buf, pkcs7_size, cert_offset + sizeof(win_cert))) return false; BIO *bio = BIO_new_mem_buf(pkcs7_buf, pkcs7_size); if (!bio) { error("Failed to create BIO\n"); return false; } auto_pkcs7 PKCS7 *p7 = d2i_PKCS7_bio(bio, NULL); BIO_free(bio); if (!p7) { error("Failed to parse PKCS#7 signature\n"); return false; } if (!PKCS7_type_is_signed(p7)) { error("PKCS#7 is not SignedData\n"); return false; } STACK_OF(PKCS7_SIGNER_INFO) *sinfos = PKCS7_get_signer_info(p7); if (!sinfos || sk_PKCS7_SIGNER_INFO_num(sinfos) != 1) { error("Expected exactly one signer in PKCS#7\n"); return false; } PKCS7_SIGNER_INFO *si = sk_PKCS7_SIGNER_INFO_value(sinfos, 0); const EVP_MD *md = EVP_get_digestbyobj(si->digest_alg->algorithm); if (!md) { error("Unknown digest algorithm in signature\n"); return false; } verbose("Signature digest algorithm: %s\n", EVP_MD_get0_name(md)); /* Extract expected file hash from SpcIndirectDataContent */ ASN1_TYPE *content_val = p7->d.sign->contents->d.other; if (!content_val || content_val->type != V_ASN1_SEQUENCE) { error("Missing or invalid SpcIndirectDataContent\n"); return false; } ASN1_OCTET_STRING *content_os = content_val->value.sequence; if (!content_os || !content_os->data) { error("Empty SpcIndirectDataContent\n"); return false; } uint8_t expected_hash[EVP_MAX_MD_SIZE]; unsigned int expected_hash_len; if (!extract_spc_file_hash(content_os->data, content_os->length, expected_hash, &expected_hash_len, sizeof(expected_hash))) { error("Failed to extract file hash from signature\n"); return false; } /* Compute Authenticode hash and compare */ uint8_t computed_hash[EVP_MAX_MD_SIZE]; unsigned int computed_hash_len; if (!compute_authenticode_hash(fd, &layout, md, computed_hash, &computed_hash_len)) return false; if (computed_hash_len != expected_hash_len || CRYPTO_memcmp(computed_hash, expected_hash, computed_hash_len) != 0) { error("Authenticode hash mismatch\n"); return false; } verbose("Authenticode hash matches\n"); /* Verify the PKCS#7 signature and certificate chain. The messageDigest attribute hashes the content value bytes (inside the outer SEQUENCE tag, not including it). */ const uint8_t *content_inner = content_os->data; int content_inner_len = content_os->length; long inner_len; int tag, cls; int ret = ASN1_get_object(&content_inner, &inner_len, &tag, &cls, content_inner_len); if (ret & 0x80 || tag != V_ASN1_SEQUENCE) { error("Invalid SpcIndirectDataContent encoding\n"); return false; } return verify_pkcs7_signature(p7, si, md, content_inner, inner_len, cert_path); } #else /* !HAVE_OPENSSL */ bool pe_verify_signature(arg_unused int fd, arg_unused off_t base_offset, arg_unused const char *cert_path) { error("Signature verification not available (built without OpenSSL)\n"); return false; } #endif /* HAVE_OPENSSL */ ukiboot-0.2.1+git20260604.ec869c7/pe_parser_posix.h000066400000000000000000000022271521024602400212320ustar00rootroot00000000000000/* PE parser for POSIX Copyright (C) 2026 Alexander Larsson This file is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This file 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ #include #include #include #define PE_SECTION_NAME_SIZE 8 typedef struct { char name[PE_SECTION_NAME_SIZE + 1]; uint32_t file_offset; uint32_t size; } PeSectionInfo; extern bool pe_parse_sections(int fd, off_t base_offset, PeSectionInfo **sections_out, uint32_t *n_sections_out); extern bool pe_verify_signature(int fd, off_t base_offset, const char *cert_path); ukiboot-0.2.1+git20260604.ec869c7/test/000077500000000000000000000000001521024602400166335ustar00rootroot00000000000000ukiboot-0.2.1+git20260604.ec869c7/test/ctltest.py000077500000000000000000000271411521024602400206770ustar00rootroot00000000000000#!/usr/bin/env python3 # Copyright (C) 2025 Alberto Ruiz # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA import tempfile import subprocess import os import struct import zlib import unittest # --- Configuration --- UKIBOOTCTL_BINARY = os.environ.get("UKIBOOTCTL_PATH", default = "./ukibootctl") # --- Constants from C Source --- # UKI_BOOT_CTRL_MAGIC as defined in the C code UKI_BOOT_CTRL_MAGIC = 1420550408 # This is 0x544C4342 in hex, representing 'BTCL' (little-endian) # --- Structure Definitions (Python equivalent using struct) --- # UkiBootSlotInfo: priority (uint8_t), tries_remaining (uint8_t), successful_boot (uint8_t), reserved (uint8_t) # Format: &2 exit 1; ;; esac mcopy -i $ESPPARTIMG efi/ukiboot${UEFI_ARCH_EXT,,}.efi ::EFI/BOOT/BOOT$UEFI_ARCH_EXT.EFI # Generate ukibootctrl.bin touch $UKIBOOTPARTIMG ukibootctl_path_init () { $UKIBOOTCTL_PATH init --partition=$UKIBOOTPARTIMG } load_ctl_part () { dd of=$DISK_FILE conv=notrunc if=$UKIBOOTPARTIMG seek=${CTL_SEEK[${LABEL_ID}]} } copy_to_partitions () { dd of=$DISK_FILE conv=notrunc if=$ESPPARTIMG seek=2048 dd of=$DISK_FILE conv=notrunc if=test/SLOTA.EFI seek=${UKI1_SEEK[${LABEL_ID}]} dd of=$DISK_FILE conv=notrunc if=test/SLOTB.EFI seek=${UKI2_SEEK[${LABEL_ID}]} load_ctl_part ${LABEL_ID} ${DISK_FILE} } test_qemu_output () { SEARCH_STRING=$1 # Run the program with a timeout, and pipe its output to grep if [ -c /dev/kvm ]; then QEMU_ACCEL_ARGS="-accel kvm" CPU=host else QEMU_ACCEL_ARGS="-accel tcg,thread=multi" CPU=$QEMU_CPU fi if $QEMU_CMD $QEMU_ACCEL_ARGS -M $QEMU_MTYPE -bios $OVMF -cpu $CPU -drive if=virtio,id=system,format=raw,file=$DISK_FILE -display none -serial stdio | grep -q "##$SEARCH_STRING" ; then echo "String '##$SEARCH_STRING' found! Exiting." else # Check the exit status of timeout to differentiate between string not found and actual timeout TIMEOUT_EXIT_STATUS=$? if [ $TIMEOUT_EXIT_STATUS -eq 124 ]; then echo "Timeout: String '$SEARCH_STRING' not found within $TIMEOUT_SECONDS seconds. Exiting with error." exit 1 elif [ $TIMEOUT_EXIT_STATUS -eq 1 ]; then echo "String '$SEARCH_STRING' not found, and program completed before timeout. Exiting." exit 2 else echo "An unexpected error occurred (exit status: $TIMEOUT_EXIT_STATUS)." exit 3 fi fi } run_test () { LABEL_ID=$1 DISK_FILE=$2 ukibootctl_path_init copy_to_partitions $LABEL_ID $DISK_FILE test_qemu_output "SLOT A" $DISK_FILE $UKIBOOTCTL_PATH --partition=$UKIBOOTPARTIMG prepare-switch 1 $UKIBOOTCTL_PATH --partition=$UKIBOOTPARTIMG finalize-switch 1 load_ctl_part $LABEL_ID $DISK_FILE test_qemu_output "SLOT B" $DISK_FILE } echo ***Test: GPT*** run_test "gpt" $GPTDISKFILE echo ***Test: DOS*** run_test "dos" $DOSDISKFILE ukiboot-0.2.1+git20260604.ec869c7/test/imgtest.py000066400000000000000000000335221521024602400206660ustar00rootroot00000000000000#!/usr/bin/env python3 # Copyright (C) 2026 Alexander Larsson # # This library is free software; you can redistribute it and/or # modify it under the terms of the GNU Lesser General Public # License as published by the Free Software Foundation; either # version 2.1 of the License, or (at your option) any later version. # # This library 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 # Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public # License along with this library; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA import os import shutil import struct import subprocess import tempfile import unittest UKIBOOTIMG_BINARY = os.environ.get("UKIBOOTIMG_PATH", "./ukibootimg") UKIBOOTCTL_BINARY = os.environ.get("UKIBOOTCTL_PATH", "./ukibootctl") HAS_SBSIGN = shutil.which('sbsign') is not None and shutil.which('openssl') is not None def create_pe(sections): """Create a minimal PE32+ file with the given sections. sections: list of (name, content_bytes) tuples """ nt_offset = 64 opt_header_size = 240 num_sections = len(sections) headers_size = nt_offset + 4 + 20 + opt_header_size + num_sections * 40 aligned_headers = (headers_size + 511) & ~511 # DOS header dos = bytearray(64) struct.pack_into(' /dev/null && pwd ) UKIFY=ukify FIRMWARE=ovmf UBOOT=u-boot.rom DUMP=disk.dump DISK_LABEL=gpt declare -A UKI1_SEEK UKI1_SEEK["gpt"]=22528 UKI1_SEEK["dos"]=22530 declare -A UKI2_SEEK UKI2_SEEK["gpt"]=327328 UKI2_SEEK["dos"]=327332 declare -A CTL_SEEK CTL_SEEK["gpt"]=632128 CTL_SEEK["dos"]=632134 while [[ $# -gt 0 ]]; do case "$1" in --firmware=*) FIRMWARE="${1#*=}" shift ;; --firmware) if [[ $# -gt 1 ]]; then FIRMWARE="$2" shift 2 else echo "Error: --firmware requires an argument (e.g., --firmware=u-boot)" exit 1 fi ;; --disk_label=*) DUMP="${1#*=}.dump" DISK_LABEL="${1#*=}" shift ;; *) echo "Unknown option: $1" exit 1 ;; esac done generate_uki() { local OUT=$1 local CMDLINE=$2 local KVER=$(uname --kernel-release) if [ $(sudo bootctl is-installed) == "yes" ]; then BOOT=$(bootctl --print-esp-path) MACHINE_ID=$(cat /etc/machine-id) LINUX=${BOOT}/${MACHINE_ID}/${KVER}/linux INITRD=${BOOT}/${MACHINE_ID}/${KVER}/initrd else BOOT="/boot" LINUX=${BOOT}/vmlinuz-${KVER} INITRD=${BOOT}/initramfs-${KVER}.img fi sudo $UKIFY build --output=$OUT --linux ${LINUX} --initrd ${INITRD} \ --uname `uname --kernel-release` \ --cmdline "console=ttyS0 $CMDLINE rd.shell rd.break=pre-mount" } create_disk() { if [ ! -f uki1.efi ]; then generate_uki uki1.efi example=1 fi if [ ! -f uki2.efi ]; then generate_uki uki2.efi example=2 fi fallocate -l 400M disk.img sfdisk disk.img < ${TEST_DIR}/${DUMP} dd if=uki1.efi of=disk.img seek=${UKI1_SEEK[${DISK_LABEL}]} conv=notrunc dd if=uki2.efi of=disk.img seek=${UKI2_SEEK[${DISK_LABEL}]} conv=notrunc } update_ukiboot() { fallocate -l 10M esp.img mkfs.vfat esp.img mmd -i esp.img ::/EFI mmd -i esp.img ::/EFI/BOOT mmd -i esp.img ::/EFI/BOOT/ukiboot_a.efi.extra.d mmd -i esp.img ::/EFI/BOOT/ukiboot_b.efi.extra.d mcopy -i esp.img slot_a.addon.efi ::/EFI/BOOT/ukiboot_a.efi.extra.d/slot_a.addon.efi mcopy -i esp.img slot_b.addon.efi ::/EFI/BOOT/ukiboot_b.efi.extra.d/slot_b.addon.efi if test -f efi/ukibootx64.efi; then mcopy -i esp.img efi/ukibootx64.efi ::/EFI/BOOT/BOOTX64.EFI fi if test -f efi/ukibootaa64.efi; then mcopy -i esp.img efi/ukibootaa64.efi ::/EFI/BOOT/BOOTAA64.EFI fi dd if=esp.img of=disk.img seek=2048 conv=notrunc } reset_ukibootctl() { dd if=/dev/zero of=disk.img seek=${CTL_SEEK[${DISK_LABEL}]} bs=512 count=4 conv=notrunc # Reset boot counters, etc } if [ ! -f disk.img ]; then create_disk fi update_ukiboot reset_ukibootctl ARCH=$(arch) QEMU_ARGS="\ -m 1G \ -device virtio-blk-pci,drive=virtiodisk \ -drive file=disk.img,if=none,id=virtiodisk,format=raw \ -nographic \ -serial mon:stdio " if [ "$ARCH" == "aarch64" ]; then if [ "$FIRMWARE" == "u-boot" ]; then QEMU_ARGS+=" -bios u-boot.rom" else QEMU_ARGS+=" -bios /usr/share/edk2/aarch64/QEMU_EFI.fd" fi QEMU_ARGS+="\ -cpu cortex-a57 \ -machine virt \ -boot efi \ " fi if [ "$ARCH" == "x86_64" ]; then if [ "$FIRMWARE" == "u-boot" ]; then QEMU_ARGS+=" -bios u-boot.rom" else cp /usr/share/OVMF/OVMF_VARS.fd . QEMU_ARGS+="\ -drive if=pflash,format=raw,readonly,file=/usr/share/OVMF/OVMF_CODE.fd \ -drive if=pflash,format=raw,file=OVMF_VARS.fd \ " fi QEMU_ARGS+="\ -accel kvm \ -cpu host \ -debugcon file:log.txt \ -vga std \ -nodefaults \ " fi qemu-system-$(arch) ${QEMU_ARGS} ukiboot-0.2.1+git20260604.ec869c7/test/slota.c000066400000000000000000000003721521024602400201230ustar00rootroot00000000000000#include EFI_STATUS efi_main(EFI_HANDLE ImageHandle, EFI_SYSTEM_TABLE *ST) { EFI_STATUS Status; ST->ConOut->OutputString(ST->ConOut, L"##SLOT A\r\n"); ST->RuntimeServices->ResetSystem(EfiResetShutdown, 0, 0, 0); return 0; } ukiboot-0.2.1+git20260604.ec869c7/test/slotb.c000066400000000000000000000003721521024602400201240ustar00rootroot00000000000000#include EFI_STATUS efi_main(EFI_HANDLE ImageHandle, EFI_SYSTEM_TABLE *ST) { EFI_STATUS Status; ST->ConOut->OutputString(ST->ConOut, L"##SLOT B\r\n"); ST->RuntimeServices->ResetSystem(EfiResetShutdown, 0, 0, 0); return 0; } ukiboot-0.2.1+git20260604.ec869c7/ukiboot-set-success.service000066400000000000000000000005531521024602400231540ustar00rootroot00000000000000[Unit] Description=Mark boot as successful in ukibootctl partition Requires=boot-complete.target After=boot-complete.target ConditionVirtualization=!container [Service] Type=oneshot RemainAfterExit=yes Environment=UKIBOOTCTL="/dev/disk/by-partlabel/ukibootctl" ExecStart=ukibootctl --partition=${UKIBOOTCTL} mark-successful [Install] WantedBy=multi-user.target ukiboot-0.2.1+git20260604.ec869c7/ukibootctl.c000066400000000000000000000256331521024602400202100ustar00rootroot00000000000000/* ukibootctl Copyright (C) 2025 Alexander Larsson This file is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This file 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ #include "config.h" #include "bootctl.h" #include #include #include char *slot_partition_names[] = { "ukiboot_a", "ukiboot_b", }; static uint32_t bootctl_slot_other(uint32_t slot) { if (slot == 0) { return 1; } return 0; } static void bootctl_update_crc32(UkiBootCtrl *bootctl) { uint32_t crc = crc32((uint8_t *)bootctl, sizeof(UkiBootCtrl) - sizeof(uint32_t)); bootctl->CRC32 = htole32(crc); } static void bootctl_prepare_switch(UkiBootCtrl *bootctl, uint32_t new_slot) { uint32_t old_slot = bootctl_slot_other(new_slot); // Ensure old slot is bootable bootctl->slots[old_slot].successful_boot = 1; bootctl->slots[old_slot].tries_remaining = 0; // Mark new slot non-bootable bootctl->slots[new_slot].successful_boot = 0; bootctl->slots[new_slot].tries_remaining = 0; bootctl->slots[new_slot].priority = 0; bootctl_update_crc32(bootctl); } static void bootctl_finalize_switch(UkiBootCtrl *bootctl, uint32_t new_slot) { uint32_t old_slot = bootctl_slot_other(new_slot); // Ensure old slot lower prio bootctl->slots[old_slot].priority = 14; // Mark new slot as active for 7 tries bootctl->slots[new_slot].successful_boot = 0; bootctl->slots[new_slot].tries_remaining = 7; bootctl->slots[new_slot].priority = 15; bootctl_update_crc32(bootctl); } static void bootctl_mark_successful(UkiBootCtrl *bootctl, uint32_t slot) { bootctl->slots[slot].successful_boot = 1; bootctl->slots[slot].tries_remaining = 0; bootctl_update_crc32(bootctl); } static bool bootctl_read(UkiBootCtrl *bootctl, const char *path) { autoclose int fd = open(path, O_RDONLY | O_CLOEXEC); if (fd < 0) { error("Failed to open %s: %s\n", path, strerror(errno)); return false; } ssize_t res = read(fd, (void *)bootctl, sizeof(UkiBootCtrl)); if (res < 0) { error("Failed to read %s: %s\n", path, strerror(errno)); return false; } if (res != sizeof(UkiBootCtrl)) { error("Failed to read %s: short read\n", path); return false; } return true; } static bool bootctl_read_and_validate(UkiBootCtrl *bootctl, const char *path) { if (!bootctl_read(bootctl, path)) { return false; } if (!bootctl_validate(bootctl)) { error("Bootctl partition is invalid\n"); return false; } return true; } static bool bootctl_write(UkiBootCtrl *bootctl, const char *path) { autoclose int fd = open(path, O_WRONLY | O_CLOEXEC); if (fd < 0) { error("Failed to open %s: %s\n", path, strerror(errno)); return false; } ssize_t res = write(fd, (void *)bootctl, sizeof(UkiBootCtrl)); if (res < 0) { error("Failed to write %s: %s\n", path, strerror(errno)); return false; } if (res != sizeof(UkiBootCtrl)) { error("Failed to write %s: short write\n", path); return false; } return true; } #define OPT_VERSION 102 #define OPT_VERBOSE 103 #define OPT_PARTITION 104 #define OPT_HELP 105 const char *opt_partition = "/dev/disk/by-partlabel/ukibootctl"; static int cmd_init(int argc, arg_unused char **argv) { if (argc != 1) { error("Unexpected arguments to init\n"); return 1; } UkiBootCtrl bootctl; memset(&bootctl, 0, sizeof(UkiBootCtrl)); bootctl.magic = htole32(UKI_BOOT_CTRL_MAGIC); bootctl.slots[0].priority = 15; bootctl.slots[0].tries_remaining = 7; bootctl.slots[0].successful_boot = 0; bootctl.slots[1].priority = 14; bootctl.slots[1].tries_remaining = 7; bootctl.slots[1].successful_boot = 0; bootctl_update_crc32(&bootctl); if (!bootctl_write(&bootctl, opt_partition)) { return 1; } return 0; } static int cmd_dump(int argc, arg_unused char **argv) { if (argc != 1) { error("Unexpected arguments to dump\n"); return 1; } UkiBootCtrl bootctl; if (!bootctl_read_and_validate(&bootctl, opt_partition)) { return 1; } for (int i = 0; i < 2; i++) { UkiBootSlotInfo *slot = &bootctl.slots[i]; printf("Slot %d: prio: %d, tries_remaining: %d, successful_boot: %d\n", i, slot->priority, slot->tries_remaining, slot->successful_boot); } return 0; } static int cmd_get_active(int argc, arg_unused char **argv) { if (argc != 1) { error("Unexpected arguments to get-active\n"); return 1; } UkiBootCtrl bootctl; if (!bootctl_read_and_validate(&bootctl, opt_partition)) { return 1; } uint32_t slot; if (!bootctl_find_active_slot(&bootctl, &slot)) { error("No active slot\n"); return 1; } printf("%d\n", slot); return 0; } static int get_booted_slot(void) { int slot = 0; autofree char *cmdline = read_proc_cmdline(); if (cmdline == NULL) fatal("Failed to read /proc/cmdline\n"); autofree char *slot_suffix = find_proc_cmdline_key(cmdline, "androidboot.slot_suffix"); if (slot_suffix == NULL) { error("No slot suffix in command line, assuming slot 0\n"); } else { if (strcmp(slot_suffix, "_a") == 0) slot = 0; else if (strcmp(slot_suffix, "_b") == 0) slot = 1; else fatal("androidboot.slot_suffix invalid: %s\n", slot_suffix); } return slot; } static int cmd_get_booted(int argc, arg_unused char **argv) { if (argc != 1) { error("Unexpected arguments to get-booted\n"); return 1; } int slot = get_booted_slot(); printf("%d\n", slot); return 0; } static int parse_slot(const char *slot_s) { char *slot_s_end; uint32_t slot = strtol(slot_s, &slot_s_end, 10); if (*slot_s == 0 || *slot_s_end != 0) { return -1; } if (slot != 0 && slot != 1) return -1; return slot; } static int cmd_prepare_switch(int argc, arg_unused char **argv) { if (argc < 2) { error("No slot specified\n"); return 1; } if (argc > 2) { error("Unexpected arguments to prepare-switch\n"); return 1; } char *slot_s = argv[1]; int32_t slot = parse_slot(slot_s); if (slot < 0) { error("Invalid slot %s\n", slot_s); return 1; } UkiBootCtrl bootctl; if (!bootctl_read_and_validate(&bootctl, opt_partition)) { return 1; } bootctl_prepare_switch(&bootctl, slot); if (!bootctl_write(&bootctl, opt_partition)) { return 1; } return 0; } static int cmd_finalize_switch(int argc, arg_unused char **argv) { if (argc < 2) { error("No slot specified\n"); return 1; } if (argc > 2) { error("Unexpected arguments to finalize-switch\n"); return 1; } char *slot_s = argv[1]; int32_t slot = parse_slot(slot_s); if (slot < 0) { error("Invalid slot %s\n", slot_s); return 1; } UkiBootCtrl bootctl; if (!bootctl_read_and_validate(&bootctl, opt_partition)) { return 1; } bootctl_finalize_switch(&bootctl, slot); if (!bootctl_write(&bootctl, opt_partition)) { return 1; } return 0; } static int cmd_mark_successful(int argc, arg_unused char **argv) { int32_t slot = 0; if (argc < 2) { /* No slot specified, use the booted */ slot = get_booted_slot(); } else if (argc == 2) { char *slot_s = argv[1]; slot = parse_slot(slot_s); if (slot < 0) { error("Invalid slot %s\n", slot_s); return 1; } } else { error("Unexpected arguments to mark-successful\n"); return 1; } UkiBootCtrl bootctl; if (!bootctl_read_and_validate(&bootctl, opt_partition)) { return 1; } bootctl_mark_successful(&bootctl, slot); if (!bootctl_write(&bootctl, opt_partition)) { return 1; } return 0; } typedef struct { char *name; int (*fn)(int argc, char **argv); } CmdHandler; CmdHandler commands[] = { {"init", cmd_init}, {"dump", cmd_dump}, {"get-active", cmd_get_active}, {"get-booted", cmd_get_booted}, {"prepare-switch", cmd_prepare_switch}, {"finalize-switch", cmd_finalize_switch}, {"mark-successful", cmd_mark_successful}, }; static CmdHandler * find_command_handler(const char *name) { for (size_t i = 0; i < N_ELEMENTS(commands); i++) { CmdHandler *handler = &commands[i]; if (strcmp(name, handler->name) == 0) return handler; } return NULL; } static void usage(const char *argv0) { const char *bin = gnu_basename(argv0); fprintf(stderr, "Usage: %s [OPTIONS] COMMAND [...]\n" "Options:\n" " --verbose Show verbose output\n" " --help Show help\n" " --partition=PATH Path to ukibootctrl partition\n" " Default: /dev/disk/by-partlabel/ukibootctl\n" "Commands:\n" " init Initialize boot options with default values\n" " dump Dump current boot options\n" " get-active Show current active slot (on disk)\n" " get-booted Show current booted slot\n" " prepare-switch SLOT Prepare to switch to SLOT (before update)\n" " finalize-switch SLOT Finalize switch to SLOT (after update)\n" " mark-successful [SLOT] Mark boot successful (after update & boot)\n", bin); } int main(int argc, char **argv) { const char *bin = argv[0]; const struct option longopts[] = { {.name = "help", .has_arg = no_argument, .flag = NULL, .val = OPT_HELP}, {.name = "version", .has_arg = no_argument, .flag = NULL, .val = OPT_VERSION}, {.name = "verbose", .has_arg = no_argument, .flag = NULL, .val = OPT_VERBOSE}, {.name = "partition", .has_arg = required_argument, .flag = NULL, .val = OPT_PARTITION}, {}, }; int opt; while ((opt = getopt_long(argc, argv, "", longopts, NULL)) != -1) { switch (opt) { case OPT_HELP: usage(bin); exit(0); break; case OPT_VERSION: printf("ukibootctl %s\n", PACKAGE_VERSION); exit(0); break; case OPT_VERBOSE: opt_verbose = true; break; case OPT_PARTITION: opt_partition = optarg; break; case ':': fprintf(stderr, "option needs a value\n"); exit(EXIT_FAILURE); default: usage(bin); exit(1); } } argv += optind; argc -= optind; if (argc < 1) { error("No command specified\n"); usage(bin); exit(1); } const char *command = argv[0]; CmdHandler *handler = find_command_handler(command); if (handler == NULL) { error("Unknown command '%s'\n", command); usage(bin); return 1; } if (handler->fn(argc, argv)) { return 1; } return 0; } ukiboot-0.2.1+git20260604.ec869c7/ukibootimg.c000066400000000000000000000361321521024602400201760ustar00rootroot00000000000000/* ukibootimg Copyright (C) 2025 Alexander Larsson This file is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This file 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ #include "config.h" #include "bootctl.h" #include "gpt_parser.h" #include "pe_parser_posix.h" #include #include #include #include #include #define OPT_HELP 256 #define OPT_VERSION 257 #define OPT_VERBOSE 258 #define OPT_IMAGE 259 #define OPT_BOOTCTL 260 #define OPT_BOOT_A 261 #define OPT_BOOT_B 262 #define OPT_SLOT 263 #define OPT_OUTPUT_DIR 264 #define OPT_CERT 265 #define OPT_VERIFY 266 static const char *opt_image = NULL; static const char *opt_bootctl_path = NULL; static const char *opt_boot_a = NULL; static const char *opt_boot_b = NULL; static const char *opt_output_dir = "."; static const char *opt_cert = NULL; static bool opt_verify = false; static int opt_slot = -1; static bool read_section_content(int fd, off_t base_offset, PeSectionInfo *section, char **out, size_t *out_len) { autofree char *buf = xmalloc(section->size + 1); if (!full_pread(fd, buf, section->size, base_offset + section->file_offset)) return false; buf[section->size] = '\0'; *out = steal_pointer(&buf); if (out_len) *out_len = section->size; return true; } static PeSectionInfo * find_section(PeSectionInfo *sections, uint32_t n_sections, const char *name) { for (uint32_t i = 0; i < n_sections; i++) { if (strcmp(sections[i].name, name) == 0) return §ions[i]; } return NULL; } static char * find_osrel_value(const char *osrel, const char *key) { size_t key_len = strlen(key); for (const char *line = osrel; line;) { if (strncmp(line, key, key_len) == 0 && line[key_len] == '=') { const char *val = line + key_len + 1; const char *end = strchr(val, '\n'); if (!end) end = val + strlen(val); if (end > val && val[0] == '"' && end[-1] == '"') return strndup(val + 1, end - val - 2); return strndup(val, end - val); } const char *next = strchr(line, '\n'); line = next ? next + 1 : NULL; } return NULL; } static int cmd_status(int argc, arg_unused char **argv, int uki_fd, off_t uki_offset, uint32_t active_slot, const char *uki_path, PeSectionInfo *sections, uint32_t n_sections) { if (argc > 0) { error("Unexpected arguments to status\n"); return 1; } printf("Active slot: %c\n", active_slot == 0 ? 'a' : 'b'); PeSectionInfo *osrel_sec = find_section(sections, n_sections, ".osrel"); if (osrel_sec) { autofree char *osrel = NULL; if (read_section_content(uki_fd, uki_offset, osrel_sec, &osrel, NULL)) { autofree char *name = find_osrel_value(osrel, "NAME"); autofree char *version = find_osrel_value(osrel, "VERSION"); if (name && version) printf("OS: %s %s\n", name, version); else if (name) printf("OS: %s\n", name); } } PeSectionInfo *uname_sec = find_section(sections, n_sections, ".uname"); if (uname_sec) { autofree char *uname = NULL; if (read_section_content(uki_fd, uki_offset, uname_sec, &uname, NULL)) printf("Kernel version: %s\n", uname); } PeSectionInfo *cmdline_sec = find_section(sections, n_sections, ".cmdline"); if (cmdline_sec) { autofree char *cmdline = NULL; if (read_section_content(uki_fd, uki_offset, cmdline_sec, &cmdline, NULL)) printf("Command line: %s androidboot.slot_suffix=_%c\n", cmdline, active_slot == 0 ? 'a' : 'b'); } PeSectionInfo *linux_sec = find_section(sections, n_sections, ".linux"); if (linux_sec) printf("Kernel: %s offset=0x%" PRIx64 " size=%u\n", uki_path, (uint64_t)(uki_offset + linux_sec->file_offset), linux_sec->size); PeSectionInfo *initrd_sec = find_section(sections, n_sections, ".initrd"); if (initrd_sec) printf("Initrd: %s offset=0x%" PRIx64 " size=%u\n", uki_path, (uint64_t)(uki_offset + initrd_sec->file_offset), initrd_sec->size); return 0; } static int cmd_list(int argc, arg_unused char **argv, arg_unused int uki_fd, arg_unused off_t uki_offset, arg_unused uint32_t active_slot, arg_unused const char *uki_path, PeSectionInfo *sections, uint32_t n_sections) { if (argc > 0) { error("Unexpected arguments to list\n"); return 1; } printf("%-16s %10s %10s\n", "Name", "Offset", "Size"); for (uint32_t i = 0; i < n_sections; i++) { printf("%-16s 0x%08x %10u\n", sections[i].name, sections[i].file_offset, sections[i].size); } return 0; } #define COPY_BUF_SIZE (64 * 1024) static bool extract_section(int fd, off_t base_offset, PeSectionInfo *section, const char *output_dir, uint32_t active_slot) { const char *name = section->name; if (name[0] == '.') name++; autofree char *path = NULL; if (asprintf(&path, "%s/%s", output_dir, name) < 0) oom(); autoclose int out_fd = open(path, O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644); if (out_fd < 0) { error("Failed to create %s: %s\n", path, strerror(errno)); return false; } autofree uint8_t *buf = xmalloc(COPY_BUF_SIZE); uint32_t remaining = section->size; off_t offset = base_offset + section->file_offset; while (remaining > 0) { size_t chunk = remaining < COPY_BUF_SIZE ? remaining : COPY_BUF_SIZE; ssize_t n = pread(fd, buf, chunk, offset); if (n <= 0) { error("Failed to read section %s: %s\n", section->name, n < 0 ? strerror(errno) : "unexpected end of file"); return false; } if (!full_write(out_fd, buf, n)) return false; remaining -= n; offset += n; } if (strcmp(section->name, ".cmdline") == 0) { const char *suffix = active_slot == 0 ? " androidboot.slot_suffix=_a" : " androidboot.slot_suffix=_b"; if (!full_write(out_fd, suffix, strlen(suffix))) return false; } verbose("Extracted %s (%u bytes)\n", path, section->size); return true; } static int cmd_verify(int argc, arg_unused char **argv, int uki_fd, off_t uki_offset, arg_unused uint32_t active_slot, arg_unused const char *uki_path, arg_unused PeSectionInfo *sections, arg_unused uint32_t n_sections) { if (argc > 0) { error("Unexpected arguments to verify\n"); return 1; } if (!opt_cert) fatal("--cert is required for verify\n"); if (!pe_verify_signature(uki_fd, uki_offset, opt_cert)) return 1; printf("Signature verification successful\n"); return 0; } static int cmd_extract(int argc, char **argv, int uki_fd, off_t uki_offset, uint32_t active_slot, arg_unused const char *uki_path, PeSectionInfo *sections, uint32_t n_sections) { if (opt_verify) { if (!opt_cert) fatal("--cert is required with --verify\n"); if (!pe_verify_signature(uki_fd, uki_offset, opt_cert)) fatal("Signature verification failed, aborting extract\n"); verbose("Signature verified\n"); } bool extract_all = (argc == 0); for (uint32_t i = 0; i < n_sections; i++) { bool should_extract = extract_all; if (!extract_all) { for (int a = 0; a < argc; a++) { const char *want = argv[a]; if (strcmp(sections[i].name, want) == 0 || (want[0] != '.' && sections[i].name[0] == '.' && strcmp(sections[i].name + 1, want) == 0)) { should_extract = true; break; } } } if (should_extract) { if (!extract_section(uki_fd, uki_offset, §ions[i], opt_output_dir, active_slot)) return 1; } } return 0; } static bool resolve_active_slot(int bootctl_fd, off_t bootctl_offset, uint32_t *slot_out) { UkiBootCtrl ctrl; ssize_t n = pread(bootctl_fd, &ctrl, sizeof(ctrl), bootctl_offset); if (n < (ssize_t)sizeof(ctrl)) { error("Failed to read bootctl: %s\n", n < 0 ? strerror(errno) : "short read"); return false; } if (!bootctl_validate(&ctrl)) { verbose("Bootctl invalid, using default initialization\n"); bootctl_init_default(&ctrl); } if (!bootctl_find_active_slot(&ctrl, slot_out)) { error("No valid active slot found\n"); return false; } return true; } typedef int (*CmdFn)(int argc, char **argv, int uki_fd, off_t uki_offset, uint32_t active_slot, const char *uki_path, PeSectionInfo *sections, uint32_t n_sections); typedef struct { const char *name; CmdFn fn; } CmdHandler; static CmdHandler commands[] = { {"extract", cmd_extract}, {"list", cmd_list}, {"status", cmd_status}, {"verify", cmd_verify}, }; static CmdHandler * find_command_handler(const char *name) { for (size_t i = 0; i < N_ELEMENTS(commands); i++) { if (strcmp(name, commands[i].name) == 0) return &commands[i]; } return NULL; } static void usage(const char *argv0) { const char *bin = gnu_basename(argv0); fprintf(stderr, "Usage: %s [OPTIONS] COMMAND [...]\n" "\n" "Extract and inspect UKI sections from ukiboot partitions.\n" "\n" "Input modes:\n" " --image PATH GPT disk image\n" " --bootctl PATH Path to ukibootctl partition/file\n" " --boot-a PATH Path to ukiboot_a partition/file\n" " --boot-b PATH Path to ukiboot_b partition/file\n" "\n" "Options:\n" " --output-dir DIR Output directory (default: current dir)\n" " --slot a|b Force slot selection\n" " --cert PATH Trusted certificate (PEM) for verification\n" " --verify Verify signature before extracting\n" " --verbose Verbose output\n" " --help Show this help\n" " --version Show version\n" "\n" "Commands:\n" " extract [SECTION...] Extract sections (all if none specified)\n" " list List PE sections with offsets and sizes\n" " status Print active slot, kernel version, cmdline,\n" " and kernel/initrd offset+size\n" " verify Verify UKI Authenticode signature\n", bin); } int main(int argc, char **argv) { const char *bin = argv[0]; const struct option longopts[] = { {.name = "help", .has_arg = no_argument, .val = OPT_HELP}, {.name = "version", .has_arg = no_argument, .val = OPT_VERSION}, {.name = "verbose", .has_arg = no_argument, .val = OPT_VERBOSE}, {.name = "image", .has_arg = required_argument, .val = OPT_IMAGE}, {.name = "bootctl", .has_arg = required_argument, .val = OPT_BOOTCTL}, {.name = "boot-a", .has_arg = required_argument, .val = OPT_BOOT_A}, {.name = "boot-b", .has_arg = required_argument, .val = OPT_BOOT_B}, {.name = "slot", .has_arg = required_argument, .val = OPT_SLOT}, {.name = "output-dir", .has_arg = required_argument, .val = OPT_OUTPUT_DIR}, {.name = "cert", .has_arg = required_argument, .val = OPT_CERT}, {.name = "verify", .has_arg = no_argument, .val = OPT_VERIFY}, {}, }; int opt; while ((opt = getopt_long(argc, argv, "", longopts, NULL)) != -1) { switch (opt) { case OPT_HELP: usage(bin); return 0; case OPT_VERSION: printf("ukibootimg %s\n", PACKAGE_VERSION); return 0; case OPT_VERBOSE: opt_verbose = true; break; case OPT_IMAGE: opt_image = optarg; break; case OPT_BOOTCTL: opt_bootctl_path = optarg; break; case OPT_BOOT_A: opt_boot_a = optarg; break; case OPT_BOOT_B: opt_boot_b = optarg; break; case OPT_SLOT: if (strcmp(optarg, "a") == 0 || strcmp(optarg, "0") == 0) opt_slot = 0; else if (strcmp(optarg, "b") == 0 || strcmp(optarg, "1") == 0) opt_slot = 1; else fatal("Invalid slot '%s', expected 'a' or 'b'\n", optarg); break; case OPT_OUTPUT_DIR: opt_output_dir = optarg; break; case OPT_CERT: opt_cert = optarg; break; case OPT_VERIFY: opt_verify = true; break; default: usage(bin); return 1; } } argv += optind; argc -= optind; if (argc < 1) { error("No command specified\n"); usage(bin); return 1; } const char *command = argv[0]; argv++; argc--; CmdHandler *handler = find_command_handler(command); if (!handler) { error("Unknown command '%s'\n", command); usage(bin); return 1; } if (opt_image && (opt_bootctl_path || opt_boot_a || opt_boot_b)) fatal("Cannot combine --image with --bootctl/--boot-a/--boot-b\n"); if (!opt_image && !opt_boot_a && !opt_boot_b) fatal("Must specify --image or at least one of --boot-a/--boot-b\n"); autoclose int image_fd = -1; autoclose int bootctl_fd = -1; autoclose int uki_fd = -1; GptPartitionTable gpt = {0}; uint32_t active_slot; if (opt_image) { image_fd = open(opt_image, O_RDONLY | O_CLOEXEC); if (image_fd < 0) fatal("Failed to open %s: %s\n", opt_image, strerror(errno)); if (!gpt_parse(image_fd, &gpt)) fatal("Failed to parse GPT from %s\n", opt_image); } if (opt_slot >= 0) { active_slot = opt_slot; } else { int bctl_fd; off_t bctl_offset = 0; if (opt_image) { GptPartition *p = gpt_find_partition(&gpt, "ukibootctl"); if (!p) fatal("No ukibootctl partition found in image\n"); bctl_fd = image_fd; bctl_offset = p->offset; } else if (opt_bootctl_path) { bootctl_fd = open(opt_bootctl_path, O_RDONLY | O_CLOEXEC); if (bootctl_fd < 0) fatal("Failed to open %s: %s\n", opt_bootctl_path, strerror(errno)); bctl_fd = bootctl_fd; } else { verbose("No bootctl source, defaulting to slot a\n"); active_slot = 0; goto have_slot; } if (!resolve_active_slot(bctl_fd, bctl_offset, &active_slot)) fatal("Failed to determine active slot\n"); } have_slot: verbose("Active slot: %c\n", active_slot == 0 ? 'a' : 'b'); const char *slot_names[] = {"ukiboot_a", "ukiboot_b"}; int u_fd; off_t u_offset = 0; const char *uki_path = NULL; if (opt_image) { GptPartition *p = gpt_find_partition(&gpt, slot_names[active_slot]); if (!p) fatal("No %s partition found in image\n", slot_names[active_slot]); u_fd = image_fd; u_offset = p->offset; uki_path = opt_image; } else { const char *path = (active_slot == 0) ? opt_boot_a : opt_boot_b; if (!path) fatal("No --%s specified for active slot\n", active_slot == 0 ? "boot-a" : "boot-b"); uki_fd = open(path, O_RDONLY | O_CLOEXEC); if (uki_fd < 0) fatal("Failed to open %s: %s\n", path, strerror(errno)); u_fd = uki_fd; uki_path = path; } autofree PeSectionInfo *sections = NULL; uint32_t n_sections; if (!pe_parse_sections(u_fd, u_offset, §ions, &n_sections)) fatal("Failed to parse PE sections\n"); int ret = handler->fn(argc, argv, u_fd, u_offset, active_slot, uki_path, sections, n_sections); gpt_partition_table_free(&gpt); return ret; } ukiboot-0.2.1+git20260604.ec869c7/utils.c000066400000000000000000000042171521024602400171640ustar00rootroot00000000000000#include "config.h" #include #include "utils.h" /* Global state */ bool opt_verbose = 0; __attribute__((__format__(printf, 1, 2))) void verbose(const char *format, ...) { if (opt_verbose) { va_list args; va_start(args, format); vprintf(format, args); va_end(args); } } __attribute__((__format__(printf, 1, 2))) void error(const char *format, ...) { va_list args; va_start(args, format); vfprintf(stderr, format, args); va_end(args); } __attribute__((__noreturn__)) __attribute__((__format__(printf, 1, 2))) void fatal(const char *format, ...) { va_list args; va_start(args, format); vfprintf(stderr, format, args); va_end(args); exit(1); } __attribute__((__noreturn__)) void oom() { fatal("Out of memory"); } uint32_t crc32(const uint8_t *data, size_t len) { size_t i; ssize_t j; uint32_t byte, crc, mask; i = 0; crc = 0xFFFFFFFF; while (i < len) { byte = data[i]; // Get next byte. crc = crc ^ byte; for (j = 7; j >= 0; j--) { // Do eight times. mask = -(crc & 1); crc = (crc >> 1) ^ (0xEDB88320 & mask); } i = i + 1; } return ~crc; } char * read_proc_cmdline(void) { FILE *f = fopen("/proc/cmdline", "r"); char *cmdline = NULL; size_t len; if (!f) goto out; /* Note that /proc/cmdline will not end in a newline, so getline * will fail unelss we provide a length. */ if (getline(&cmdline, &len, f) < 0) goto out; /* ... but the length will be the size of the malloc buffer, not * strlen(). Fix that. */ len = strlen(cmdline); if (cmdline[len - 1] == '\n') cmdline[len - 1] = '\0'; out: if (f) fclose(f); return cmdline; } char * find_proc_cmdline_key(const char *cmdline, const char *key) { const size_t key_len = strlen(key); for (const char *iter = cmdline; iter;) { const char *next = strchr(iter, ' '); if (strncmp(iter, key, key_len) == 0 && iter[key_len] == '=') { const char *start = iter + key_len + 1; if (next) return strndup(start, next - start); return strdup(start); } if (next) next += strspn(next, " "); iter = next; } return NULL; } ukiboot-0.2.1+git20260604.ec869c7/utils.h000066400000000000000000000105001521024602400171610ustar00rootroot00000000000000/* ukibootctl Copyright (C) 2025 Alexander Larsson This file is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This file 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ #include "config.h" #include #include #include #include #include #include #include #include #include #ifdef HAVE_MACHINE_ENDIAN_H #include #endif #ifdef HAVE_SYS_ENDIAN_H #include #endif #ifdef HAVE_ENDIAN_H #include #endif extern bool opt_verbose; #define N_ELEMENTS(arr) (sizeof(arr) / sizeof((arr)[0])) static inline void _lcfs_reset_errno_(int *saved_errno) { if (*saved_errno < 0) return; errno = *saved_errno; } // This helper was taken from systemd; it ensures that the value of errno // is reset. #define PROTECT_ERRNO \ __attribute__((cleanup(_lcfs_reset_errno_))) __attribute__((unused)) int _saved_errno_ = errno static inline void cleanup_freep(void *p) { void **pp = (void **)p; if (*pp) free(*pp); } // A wrapper around close() that takes a pointer to a file descriptor (integer): // - Never returns an error (and preserves errno) // - Sets the value to -1 after closing to make cleanup idempotent static inline void cleanup_fdp(int *fdp) { PROTECT_ERRNO; int fd; assert(fdp); fd = *fdp; if (fd != -1) (void)close(fd); *fdp = -1; } #define arg_unused __attribute__((unused)) #define attr_packed __attribute__((packed)) #define autofree __attribute__((cleanup(cleanup_freep))) #define autoclose __attribute__((cleanup(cleanup_fdp))) __attribute__((__format__(printf, 1, 2))) extern void verbose(const char *format, ...); __attribute__((__format__(printf, 1, 2))) extern void error(const char *format, ...); __attribute__((__noreturn__)) __attribute__((__format__(printf, 1, 2))) extern void fatal(const char *format, ...); __attribute__((__noreturn__)) extern void oom(void); #define attr_malloc __attribute__((__malloc__)) #define attr_alloc_size(...) __attribute__((__alloc_size__(__VA_ARGS__))) attr_malloc attr_alloc_size(1) static inline void *xmalloc(size_t size) { void *p = malloc(size); if (!p) oom(); return p; } attr_malloc attr_alloc_size(1, 2) static inline void *xcalloc(size_t nmemb, size_t size) { void *p = calloc(nmemb, size); if (!p) oom(); return p; } attr_alloc_size(2) static inline void *xrealloc(void *ptr, size_t size) { void *p = realloc(ptr, size); if (!p) oom(); return p; } static inline bool full_pread(int fd, void *buf, size_t count, off_t offset) { uint8_t *p = buf; while (count > 0) { ssize_t n = pread(fd, p, count, offset); if (n < 0) { error("pread failed: %s\n", strerror(errno)); return false; } if (n == 0) { error("Unexpected end of file\n"); return false; } p += n; count -= n; offset += n; } return true; } static inline bool full_write(int fd, const void *buf, size_t count) { const uint8_t *p = buf; while (count > 0) { ssize_t n = write(fd, p, count); if (n < 0) { error("write failed: %s\n", strerror(errno)); return false; } p += n; count -= n; } return true; } static inline void * steal_pointer(void *pp) { void **ptr = (void **)pp; void *ref; ref = *ptr; *ptr = NULL; return ref; } /* type safety */ #define steal_pointer(pp) (0 ? (*(pp)) : (steal_pointer)(pp)) static inline const char * gnu_basename(const char *filename) { const char *p = strrchr(filename, '/'); return p ? p + 1 : filename; } extern uint32_t crc32(const uint8_t *buffer, size_t len); extern char * read_proc_cmdline(void); extern char * find_proc_cmdline_key(const char *cmdline, const char *key);