pax_global_header00006660000000000000000000000064152532430600014512gustar00rootroot0000000000000052 comment=b2799409d07d986e73b82c4686fde9c6209115dd rhboot-pesign-612e96c/000077500000000000000000000000001525324306000146335ustar00rootroot00000000000000rhboot-pesign-612e96c/.github/000077500000000000000000000000001525324306000161735ustar00rootroot00000000000000rhboot-pesign-612e96c/.github/workflows/000077500000000000000000000000001525324306000202305ustar00rootroot00000000000000rhboot-pesign-612e96c/.github/workflows/pullrequest.yml000066400000000000000000000042601525324306000233420ustar00rootroot00000000000000name: pull-request on: pull_request: branches: - main jobs: build-pull-request-intel: runs-on: ubuntu-24.04 container: vathpela/efi-ci:${{ matrix.distro }}-x64 name: ${{ matrix.distro }} ${{ matrix.arch }} build strategy: fail-fast: false matrix: include: - arch: amd64 makearch: x86_64 distro: centos9 test_pqc: 0 - arch: amd64 makearch: x86_64 distro: centos10 test_pqc: 1 - arch: amd64 makearch: x86_64 distro: f43 test_pqc: 0 - arch: amd64 makearch: x86_64 distro: f44 test_pqc: 1 - arch: amd64 makearch: x86_64 distro: f45 test_pqc: 1 steps: - name: Checkout uses: actions/checkout@v5 with: # otherwise we are testing target branch instead of the PR branch (see pull_request_target trigger) ref: ${{ github.event.pull_request.head.sha }} fetch-depth: 0 submodules: recursive - name: Work around directory ownership issue id: ignore-ownership run: | git config --global --add safe.directory /__w/shim/shim - name: Install some build requirements id: dnf run: | dnf install -y efivar-devel nss-devel openssl-devel - name: Run tests on ${{ matrix.distro }} for ${{ matrix.arch }} id: test run: | make ARCH=${{ matrix.makearch }} PREFIX=/usr DESTDIR=/destdir ENABLE_PQC_TESTS=${{ matrix.test_pqc }} test - name: Do the build on ${{ matrix.distro }} for ${{ matrix.arch }} id: build run: | make ARCH=${{ matrix.makearch }} PREFIX=/usr DESTDIR=/destdir all - name: Install on ${{ matrix.distro }} for ${{ matrix.arch }} id: install run: | make ARCH=${{ matrix.makearch }} PREFIX=/usr DESTDIR=/destdir install echo 'results:' find /destdir -type f - name: Upload coverage to Codecov uses: codecov/codecov-action@v5 env: CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }} rhboot-pesign-612e96c/.gitignore000066400000000000000000000004721525324306000166260ustar00rootroot00000000000000.cache/ .*.d .*.P .*.sw? .sw? *~ *.1 *.a *.bin *.C *.E *.efi *.o *.so /*.auth /*.crt /*.cer /*.der /*.efi /*.esl /*.log /*.p12 /*.pem /*.pk12 /*.tar.* /*.strace /*.rpm *-8be4df61-93ca-11d2-aa0d-00e098032b8c *-d719b2cb-3d3a-4596-a3bc-dad00e67656f compile_commands.json core.* cov-int/ pwfile scan-results/ vgcore.* rhboot-pesign-612e96c/CODE_OF_CONDUCT.md000066400000000000000000000125661525324306000174440ustar00rootroot00000000000000 # Contributor Covenant Code of Conduct ## Our Pledge We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, caste, color, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community. ## Our Standards Examples of behavior that contributes to a positive environment for our community include: * Demonstrating empathy and kindness toward other people * Being respectful of differing opinions, viewpoints, and experiences * Giving and gracefully accepting constructive feedback * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience * Focusing on what is best not just for us as individuals, but for the overall community Examples of unacceptable behavior include: * The use of sexualized language or imagery, and sexual attention or advances of any kind * Trolling, insulting or derogatory comments, and personal or political attacks * Public or private harassment * Publishing others' private information, such as a physical or email address, without their explicit permission * Other conduct which could reasonably be considered inappropriate in a professional setting ## Enforcement Responsibilities Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful. Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate. ## Scope This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event. ## Enforcement Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at rharwood AT redhat DOT com. All complaints will be reviewed and investigated promptly and fairly. All community leaders are obligated to respect the privacy and security of the reporter of any incident. ## Enforcement Guidelines Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct: ### 1. Correction **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community. **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested. ### 2. Warning **Community Impact**: A violation through a single incident or series of actions. **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban. ### 3. Temporary Ban **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior. **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban. ### 4. Permanent Ban **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals. **Consequence**: A permanent ban from any sort of public interaction within the community. ## Attribution This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.1, available at [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder][Mozilla CoC]. For answers to common questions about this code of conduct, see the FAQ at [https://www.contributor-covenant.org/faq][FAQ]. Translations are available at [https://www.contributor-covenant.org/translations][translations]. [homepage]: https://www.contributor-covenant.org [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html [Mozilla CoC]: https://github.com/mozilla/diversity [FAQ]: https://www.contributor-covenant.org/faq [translations]: https://www.contributor-covenant.org/translations rhboot-pesign-612e96c/COPYING000066400000000000000000000432541525324306000156760ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. rhboot-pesign-612e96c/Make.coverity000066400000000000000000000022071525324306000172770ustar00rootroot00000000000000include $(TOPDIR)/Make.version include $(TOPDIR)/Make.rules include $(TOPDIR)/Make.defaults COV_EMAIL=$(call get-config,coverity.email) COV_TOKEN=$(call get-config,coverity.token) COV_URL=$(call get-config,coverity.url) COV_FILE=$(NAME)-coverity-$(VERSION)-$(COMMIT_ID).tar.bz2 cov-int : clean cov-build --dir cov-int make all cov-clean : @rm -vf $(NAME)-coverity-*.tar.* @if [ -d cov-int ]; then rm -rf cov-int && echo "removed 'cov-int'"; fi cov-file : | $(COV_FILE) $(COV_FILE) : cov-int tar caf $@ cov-int cov-upload : @if [ -n "$(COV_URL)" ] && \ [ -n "$(COV_TOKEN)" ] && \ [ -n "$(COV_EMAIL)" ] ; \ then \ echo curl --form token=$(COV_TOKEN) --form email="$(COV_EMAIL)" --form file=@"$(COV_FILE)" --form version=$(VERSION).1 --form description="$(COMMIT_ID)" "$(COV_URL)" ; \ curl --form token=$(COV_TOKEN) --form email="$(COV_EMAIL)" --form file=@"$(COV_FILE)" --form version=$(VERSION).1 --form description="$(COMMIT_ID)" "$(COV_URL)" ; \ else \ echo Coverity output is in $(COV_FILE) ; \ fi coverity : cov-file cov-upload clean : | cov-clean .PHONY : coverity cov-upload cov-clean cov-file rhboot-pesign-612e96c/Make.defaults000066400000000000000000000075451525324306000172540ustar00rootroot00000000000000NAME = pesign COMMIT_ID ?= $(shell git log -1 --pretty=%H 2>/dev/null || echo master) prefix ?= /usr/ prefix := $(abspath $(prefix))/ libdir ?= $(prefix)lib64/ libdatadir ?= $(prefix)lib/ libexecdir ?= $(prefix)libexec/ datadir ?= $(prefix)share/ mandir ?= $(datadir)man/ includedir ?= $(prefix)include/ bindir ?= $(prefix)bin/ rundir ?= /run/ rundir := $(abspath $(rundir))/ pcdir ?= $(libdir)pkgconfig/ docdir ?= $(prefix)share/doc/ DESTDIR ?= INSTALLROOT = $(DESTDIR) INSTALL ?= install CROSS_COMPILE ?= EFI_ARCHES ?= aa64 ia32 x64 la64 enabled = $(if $(filter undefined,$(origin $(1))),$(3),$(2)) HOSTARCH = $(shell uname -m | sed s,i[3456789]86,ia32,) ARCH := $(shell uname -m | sed 's,i[3456789]86,ia32,;s,arm.*,arm,') PKG_CONFIG ?= $(CROSS_COMPILE)pkg-config CC := $(if $(filter default,$(origin CC)),$(CROSS_COMPILE)gcc,$(CC)) CCLD := $(if $(filter undefined,$(origin CCLD)),$(CC),$(CCLD)) CFLAGS ?= -O2 -g3 -pipe -fPIE -fstack-protector-all \ -fstack-clash-protection \ $(if $(filter x86_64 ia32,$(ARCH)),-fcf-protection=full,) DIAGFLAGS ?= $(call enabled,ENABLE_GCC_ANALYZER,-fmessage-length=0 \ -fdiagnostics-color=always \ -fdiagnostics-format=text \ -fdiagnostics-show-cwe \ -fanalyzer) \ $(call enabled,ENABLE_LEAK_CHECKER,-Wno-analyzer-malloc-leak,) AS ?= $(CROSS_COMPILE)as AR ?= $(CROSS_COMPILE)$(if $(filter $(CC),clang),llvm-ar,$(notdir $(CC))-ar) RANLIB ?= $(CROSS_COMPILE)$(if $(filter $(CC),clang),llvm-ranlib,$(notdir $(CC))-ranlib) OBJCOPY ?= $(CROSS_COMPILE)objcopy LD ?= $(CROSS_COMPILE)ld INSTALL ?= $(CROSS_COMPILE)install PKGS = efivar nspr nss nss-util uuid SOFLAGS ?= -shared clang_cflags = gcc_cflags = -Wmaybe-uninitialized -grecord-gcc-switches \ $(call enabled,ENABLE_LEAK_CHECKER,$(call enabled,ENABLE_LEAK_CHECKER_LTO,-flto,),) \ $(DIAGFLAGS) ifneq (,$(wildcard /usr/lib/gcc/x86_64-redhat-linux/*/plugin/annobin.so)) gcc_cflags += -fplugin=annobin endif cflags = $(CFLAGS) $(ARCH3264) $(ARCH_CFLAGS) \ -Wall -Wextra -Wsign-compare -Wmissing-prototypes -Wstrict-prototypes -Wno-unused-result \ -Wno-unused-function -Wno-missing-field-initializers \ $(call enabled,ENABLE_LEAK_CHECKER,-Wno-analyzer-malloc-leak,) \ -Werror -Wno-error=cpp -Wno-free-nonheap-object \ -std=gnu11 -fshort-wchar -fPIC -fno-strict-aliasing \ -D_GNU_SOURCE -DCONFIG_$(ARCH) -I../include \ '-DRUNDIR="$(rundir)"' \ $(if $(filter $(CC),clang),$(clang_cflags), ) \ $(if $(filter $(CC),gcc),$(gcc_cflags), ) \ $(call pkg-config-cflags) clang_ccldflags = gcc_ccldflags = -fno-merge-constants \ -fvar-tracking -fvar-tracking-assignments -fkeep-inline-functions \ -Wl,--fatal-warnings,--no-allow-shlib-undefined,--default-symver \ -Wl,-O2 -Wl,--no-undefined-version -Wl,-z,relro,-z,now \ -Wl,--no-add-needed,--no-copy-dt-needed-entries,--as-needed -pie ifeq ($(ARCH),arm) gcc_ccldflags += -Wl,--no-wchar-size-warning endif ccldflags = $(cflags) $(CCLDFLAGS) $(LDFLAGS) \ $(if $(filter $(CCLD),clang),$(clang_ccldflags),) \ $(if $(filter $(CCLD),gcc),$(gcc_ccldflags),) \ $(call pkg-config-ccldflags) efi_cflags = $(cflags) ASFLAGS ?= $(ARCH3264) CPPFLAGS ?= -D_FORTIFY_SOURCE=2 -D_GLIBCXX_ASSERTIONS RANLIBFLAGS ?= $(if $(filter $(CC),gcc),-D) ARFLAGS ?= $(if $(filter $(CC),gcc),-Dcvqs)$(if $(filter $(CC),clang),-cqvs) LDLIBS = $(foreach lib,$(LIBS),-l$(lib)) $(call pkg-config-ldlibs) ifeq ($(ARCH),ia64) efi_cflags += -mfixed-range=f32-f127 endif ifeq ($(ARCH), ia32) ifeq ($(HOSTARCH), x86_64) ARCH3264 := -m32 endif endif ifeq ($(ARCH), x86_64) efi_cflags += -mno-red-zone ifeq ($(HOSTARCH), ia32) ARCH3264 := -m64 endif endif ifeq ($(ARCH), aarch64) ARCH_CFLAGS := -mbranch-protection=standard endif # Docs are enabled by default. Set ENABLE_DOCS=0 to disable # building/installing docs. ENABLE_DOCS ?= 1 # PQC testing is enabled by default. Set ENABLE_PQC_TESTS=0 to disable running # them. ENABLE_PQC_TESTS ?= 1 rhboot-pesign-612e96c/Make.deps000066400000000000000000000005421525324306000163660ustar00rootroot00000000000000SRCDIR = $(realpath .) TOPDIR = $(realpath ..) include $(TOPDIR)/Make.version include $(TOPDIR)/Make.rules include $(TOPDIR)/Make.defaults .%.d : %.c $(CC) $(cflags) $(CPPFLAGS) -MM -MG -MF $@ $^ .%.d : %.S $(CC) $(cflags) $(CPPFLAGS) -MM -MG -MF $@ $^ SOURCES ?= deps : echo SOURCES=$(SOURCES) deps : $(call deps-of,$(filter-out %.h,$(SOURCES))) rhboot-pesign-612e96c/Make.efirules000066400000000000000000000007541525324306000172560ustar00rootroot00000000000000default : all .PHONY: default all deps clean install test include $(TOPDIR)/Make.version %.efi : %.so $(OBJCOPY) -j .text -j .sdata -j .data -j .dynamic -j .dynsym -j .rel \ -j .rela -j .reloc --target=$(FORMAT) $*.so $@ %.so: %.o $(LD) $(LDFLAGS) -o $@ $^ $(LIBS) %.o: %.c $(CC) $(INCDIR) $(CFLAGS) $(CPPFLAGS) -D__UEFI__ -c $< -o $@ %.S: %.c $(CC) $(INCDIR) $(CFLAGS) $(CPPFLAGS) -D__UEFI__ -S $< -o $@ %.E: %.c $(CC) $(INCDIR) $(CFLAGS) $(CPPFLAGS) -D__UEFI__ -E $< -o $@ rhboot-pesign-612e96c/Make.rules000066400000000000000000000041121525324306000165620ustar00rootroot00000000000000default : all .PHONY: default all deps clean install install_systemd install_sysvinit test include $(TOPDIR)/Make.version all : deps deps : clean : install : install_systemd : install_sysvinit : test : %.a : $(AR) $(ARFLAGS) $@ $^ $(RANLIB) $(RANLIBFLAGS) $@ % : %.o $(CCLD) $(ccldflags) $(CPPFLAGS) -o $@ $^ $(LDLIBS) %.so : $(CCLD) $(ccldflags) $(CPPFLAGS) $(SOFLAGS) \ -Wl,-soname,$@.0.$(MAJOR_VERSION) \ -o $@ $^ $(LDLIBS) %.o: %.c $(CC) $(cflags) $(CPPFLAGS) -c -o $@ $(filter %.c %.o %.S,$^) %.S: %.c $(CC) $(cflags) $(CPPFLAGS) -S $< -o $@ %.E: %.c $(CC) $(cflags) $(CPPFLAGS) -E $< -o $@ %.c : %.h .%.d : define substitute-version = sed \ -e "s,@@VERSION@@,$(VERSION),g" \ -e "s,@@LIBDIR@@,$(libdir),g" \ -e "s,@@LIBEXECDIR@@,$(libexecdir),g" \ -e "s,@@RUNDIR@@,$(rundir),g" \ -e "s,@@EFI_ARCHES@@,$(EFI_ARCHES),g" \ $(1) > $(2) endef %.1 : %.1.mdoc @mandoc -man -T man -Ios=Linux $^ > $@ % : %.in @$(call substitute-version,$<,$@) %.pc : %.pc.in @$(call substitute-version,$<,$@) %.spec : %.spec.in @$(call substitute-version,$<,$@) %.service : %.service.in @$(call substitute-version,$<,$@) %.sysvinit : %.sysvinit.in @$(call substitute-version,$<,$@) pkg-config-cflags = \ $(shell if [ -n "$(PKGS)" ]; then $(PKG_CONFIG) --cflags $(PKGS); fi) pkg-config-ldflags = \ $(shell if [ -n "$(PKGS)" ]; then $(PKG_CONFIG) --libs-only-L --libs-only-other $(PKGS) ; fi) pkg-config-ldlibs = \ $(shell if [ -n "$(PKGS)" ]; then $(PKG_CONFIG) --libs-only-l $(PKGS) ; fi) objects-of = \ $(patsubst %.c,%.o,$(1)) define deps-of = $(foreach src,$(filter %.c,$(1)),$(patsubst %.c,.%.d,$(src))) \ $(foreach src,$(filter %.S,$(1)),$(patsubst %.S,.%.d,$(src))) endef $(TOPDIR)/libdpe/%.a $(TOPDIR)/libdpe/% : $(MAKE) -C $(TOPDIR)/libdpe $(notdir $@) define get-config = $(shell git config --local --get "$(NAME).$(1)") endef define removes if [ -n "$(TARGETS)" ]; then rm -rfv $(TARGETS) ; fi rm -rfv *.o *.a *.so .*.d rm -rfv {vg,}core.[0123456789]* endef define descend set -e ; for x in $(SUBDIRS) ; do \ $(MAKE) -C $$x $@ ; \ done endef rhboot-pesign-612e96c/Make.scan-build000066400000000000000000000015471525324306000174620ustar00rootroot00000000000000SCAN_BUILD ?= $(shell x=$$(which --skip-alias --skip-functions scan-build 2>/dev/null) ; [ -n "$$x" ] && echo 1) ifeq ($(SCAN_BUILD),) SCAN_BUILD_ERROR = $(error scan-build not found) endif SCAN_CC = $(CROSS_COMPILE)clang SCAN_AR = $(CROSS_COMPILE)llvm-ar SCAN_ARFLAGS=-cqvs SCAN_RANLIB = $(CROSS_COMPILE)llvm-ranlib scan-test : ; $(SCAN_BUILD_ERROR) scan-clean : clean @if [ -d scan-results ]; then rm -rf scan-results && echo "removed 'scan-results'"; fi scan-build : | scan-test scan-build : clean scan-build -o scan-results make $(DASHJ) \ AR=$(SCAN_AR) ARFLAGS=$(SCAN_ARFLAGS) \ RANLIB=$(SCAN_RANLIB) CC=$(SCAN_CC) \ all scan-build-all : | scan-test scan-build-all : clean scan-build -o scan-results make $(DASHJ) \ AR=$(SCAN_AR) ARFLAGS=$(SCAN_ARFLAGS) \ RANLIB=$(SCAN_RANLIB) CC=$(SCAN_CC) \ all .PHONY : scan-build scan-clean # vim:ft=make rhboot-pesign-612e96c/Make.version000066400000000000000000000000571525324306000171210ustar00rootroot00000000000000MAJOR_VERSION = 117 VERSION = $(MAJOR_VERSION) rhboot-pesign-612e96c/Makefile000066400000000000000000000045561525324306000163050ustar00rootroot00000000000000SRCDIR = $(realpath .) TOPDIR = $(realpath .) include $(TOPDIR)/Make.version include $(TOPDIR)/Make.rules include $(TOPDIR)/Make.defaults include $(TOPDIR)/Make.coverity include $(TOPDIR)/Make.scan-build SUBDIRS := include libdpe src install : $(INSTALL) -d -m 755 $(INSTALLROOT)$(docdir)/pesign-$(VERSION)/ $(INSTALL) -pm 644 COPYING $(INSTALLROOT)$(docdir)/pesign-$(VERSION)/ @$(call descend) install_systemd install_sysvinit : install @$(call descend) distclean : | clean clean : @$(call removes) @$(call descend) clean deps all : | Make.version deps all : @$(call descend) $(SUBDIRS) : $(MAKE) -C $@ all .PHONY: $(SUBDIRS) GITTAG = $(VERSION) test-archive: @rm -rf /tmp/pesign-$(VERSION) /tmp/pesign-$(VERSION)-tmp @mkdir -p /tmp/pesign-$(VERSION)-tmp @git archive --format=tar $(shell git branch | awk '/^*/ { print $$2 }') | ( cd /tmp/pesign-$(VERSION)-tmp/ ; tar x ) @git diff | ( cd /tmp/pesign-$(VERSION)-tmp/ ; patch -s -p1 -b -z .gitdiff ) @mv /tmp/pesign-$(VERSION)-tmp/ /tmp/pesign-$(VERSION)/ @dir=$$PWD; cd /tmp; tar -c --bzip2 -f $$dir/pesign-$(VERSION).tar.bz2 pesign-$(VERSION) @rm -rf /tmp/pesign-$(VERSION) @echo "The archive is in pesign-$(VERSION).tar.bz2" tag: git tag -s $(GITTAG) refs/heads/main archive: tag @rm -rf /tmp/pesign-$(VERSION) /tmp/pesign-$(VERSION)-tmp @mkdir -p /tmp/pesign-$(VERSION)-tmp @git archive --format=tar $(GITTAG) | ( cd /tmp/pesign-$(VERSION)-tmp/ ; tar x ) @mv /tmp/pesign-$(VERSION)-tmp/ /tmp/pesign-$(VERSION)/ @dir=$$PWD; cd /tmp; tar -c --bzip2 -f $$dir/pesign-$(VERSION).tar.bz2 pesign-$(VERSION) @rm -rf /tmp/pesign-$(VERSION) @echo "The archive is in pesign-$(VERSION).tar.bz2" valgrind : all valgrind --leak-check=full --track-origins=yes ./src/pesign -f -s -t 'Secure Boot Signer' -c 'Certificate for Digital Signature' -i shimx64.efi -o shimx64.signed.efi --pwfile pwfile strace : all strace -tt -s 1024 -v -f -o pesign.strace -o /dev/stdout ./src/pesign -f -s -t 'Secure Boot Signer' -c 'Certificate for Digital Signature' -i shimx64.efi -o shimx64.signed.efi --pwfile pwfile gdb : all echo run -f -s -t \'Secure Boot Signer\' -c \'Certificate for Digital Signature\' -i shimx64.efi -o shimx64.signed.efi --pwfile pwfile | copy gdb ./src/pesign TESTS=$(wildcard tests/test-*.sh) test : | all test : $(TESTS) $(TESTS) :: % : all @stdbuf -o 0 -e 0 $@ $(if $(filter 0,$(ENABLE_PQC_TESTS)),--disable-pqc) rhboot-pesign-612e96c/README.md000066400000000000000000000015671525324306000161230ustar00rootroot00000000000000# pesign + efikeygen Signing tools for PE-COFF binaries. Compliant with the PE and Authenticode specifications. (These serve a similar purpose to Microsoft's [SignTool.exe](http://msdn.microsoft.com/en-us/library/8s9b9yaz%28v=vs.80%29.aspx), except for Linux.) ## Examples Generate a key for use with pesign, stored on disk: ``` efikeygen -d /etc/pki/pesign -S -TYPE -c 'CN=Your Name Key' -n 'Custom Secureboot' ``` (where TYPE is m if you're only signing kernel modules, and k otherwise). For more complex and secure use cases (e.g., hardware tokens), see efikeygen man page (`man efikeygen`). Sign a UEFI application using that key: ``` pesign -i grubx64.efi -o grubx64.efi.signed -c 'Custom Secureboot' -s ``` Show signatures on a UEFI application: ``` pesign -i grubx64.efi.signed -S ``` For more signing/verification operations, see the pesign man page (`man pesign`). rhboot-pesign-612e96c/TODO000066400000000000000000000015751525324306000153330ustar00rootroot00000000000000Stuff that needs to get done: In no particular order, this stuff still needs to be done (or is in progress): 1) file i/o a) get an in-memory representation via mmap *done* b) render in-memory representation back to disk also via mmap *done-ish* 2) signatures a) read hash from stand-alone file *done* b) write hash to stand-alone file *done* c) verify hash from stand-alone file d) read cert from file *done* e) create hash/digest of file *done* f) create new signature (aka "sign the hash") i) generate SpcContentInfo *done* ii) sign it *done* g) create cert table *done for the very basic (ms-supported) case* h) find cert table *eh* i) implant cert in table *eh* 3) make hash algorithm configurable 4) test suite 5) test suite 6) docs 7) efikeygen - random serial number + check for dupes against local nss db See also: https://github.com/rhboot/pesign/issues/milestones rhboot-pesign-612e96c/include/000077500000000000000000000000001525324306000162565ustar00rootroot00000000000000rhboot-pesign-612e96c/include/Makefile000066400000000000000000000004421525324306000177160ustar00rootroot00000000000000SRCDIR = $(realpath .) TOPDIR = $(realpath ..) include $(TOPDIR)/Make.version include $(TOPDIR)/Make.rules include $(TOPDIR)/Make.defaults SUBDIRS = libdpe clean all install : for x in $(SUBDIRS) ; do \ $(MAKE) -C $$x $@ ; \ done $(SUBDIRS) : $(MAKE) -C $@ all .PHONY: $(SUBDIRS) rhboot-pesign-612e96c/include/libdpe/000077500000000000000000000000001525324306000175155ustar00rootroot00000000000000rhboot-pesign-612e96c/include/libdpe/Makefile000066400000000000000000000004311525324306000211530ustar00rootroot00000000000000SRCDIR = $(realpath .) TOPDIR = $(realpath ../..) include $(TOPDIR)/Make.version include $(TOPDIR)/Make.rules include $(TOPDIR)/Make.defaults #install: # $(INSTALL) -d -m 755 $(INSTALLROOT)$(PREFIX)/include/libdpe/ # $(INSTALL) -m 644 *.h $(INSTALLROOT)$(PREFIX)/include/libdpe/ rhboot-pesign-612e96c/include/libdpe/libdpe.h000066400000000000000000000044511525324306000211310ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * libdpe.h - types for libdpe * Copyright 2011-2020 Peter Jones * Copyright 2011 Red Hat, Inc. */ #ifndef LIBDPE_H #define LIBDPE_H 1 #include #include typedef enum { PE_K_NONE, PE_K_MZ, PE_K_PE_OBJ, PE_K_PE_EXE, PE_K_PE_ROM, PE_K_PE64_OBJ, PE_K_PE64_EXE, PE_K_NUM /* terminating entry */ } Pe_Kind; typedef enum { PE_C_NULL, PE_C_READ, PE_C_RDWR, PE_C_WRITE, PE_C_CLR, PE_C_SET, PE_C_FDDONE, PE_C_FDREAD, PE_C_READ_MMAP, PE_C_RDWR_MMAP, PE_C_WRITE_MMAP, PE_C_READ_MMAP_PRIVATE, PE_C_EMPTY, PE_C_NUM /* last entry */ } Pe_Cmd; typedef enum { PE_DATA_DIR_EXPORTS = 1, PE_DATA_DIR_IMPORTS, PE_DATA_DIR_RESOURCES, PE_DATA_DIR_EXCEPTIONS, PE_DATA_DIR_CERTIFICATES, PE_DATA_DIR_BASE_RELOCATIONS, PE_DATA_DIR_DEBUG, PE_DATA_DIR_ARCH, PE_DATA_DIR_GLOBAL_POINTER, PE_DATA_TLS, PE_DATA_LOAD_CONFIG, PE_DATA_BOUND_IMPORT, PE_DATA_IMPORT_ADDRESS, PE_DATA_DELAY_IMPORTS, PE_DATA_CLR_RUNTIME_HEADER, PE_DATA_RESERVED, PE_DATA_NUM /* last entry */ } Pe_DataDir_Type; typedef struct Pe Pe; typedef struct Pe_Scn Pe_Scn; extern Pe *pe_begin(int fildes, Pe_Cmd cmd, Pe *ref); extern Pe *pe_clone(Pe *pe, Pe_Cmd cmd); extern Pe *pe_memory(char *image, size_t size); extern int pe_end(Pe *pe); extern loff_t pe_update(Pe *pe, Pe_Cmd cmd); extern Pe_Kind pe_kind(Pe *Pe) __attribute__ ((__pure__)); extern Pe_Scn *pe_nextscn(Pe *pe, Pe_Scn *scn); extern Pe_Scn *pe_getscn(Pe *pe, size_t idx); extern struct section_header *pe_getshdr(Pe_Scn *scn, struct section_header *dst); extern struct pe_hdr *pe_getpehdr(Pe *pe, struct pe_hdr *pehdr); extern char *pe_rawfile(Pe *pe, size_t *ptr); extern int pe_getdatadir(Pe *pe, data_directory **dd); extern void *pe_getopthdr(Pe *pe); extern int32_t pe_get_file_alignment(Pe *pe); extern int32_t pe_get_scn_alignment(Pe *pe); extern int pe_set_image_size(Pe *pe); extern int pe_extend_file(Pe *pe, size_t size, uint32_t *new_space, int align); extern int pe_freespace(Pe *pe, uint32_t offset, size_t size); extern int pe_shorten_file(Pe *pe, size_t size); extern int pe_clearcert(Pe *pe); extern int pe_alloccert(Pe *pe, size_t len); extern int pe_populatecert(Pe *pe, void *cert, size_t len); extern int pe_errno(void); extern const char *pe_errmsg(int error); #endif /* LIBDPE_H */ rhboot-pesign-612e96c/include/libdpe/pe.h000066400000000000000000000355761525324306000203120ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * pe.h - types and magic for PE binaries * Copyright 2011-2020 Peter Jones * Copyright 2011 Red Hat, Inc. */ #ifndef PE_H #define PE_H 1 #include #define MZ_MAGIC 0x5a4d /* "MZ" */ struct mz_hdr { uint16_t magic; /* MZ_MAGIC */ uint16_t lbsize; /* size of last used block */ uint16_t blocks; /* pages in file, 0x3 */ uint16_t relocs; /* relocations */ uint16_t hdrsize; /* header size in "paragraphs" */ uint16_t min_extra_pps; /* .bss */ uint16_t max_extra_pps; /* runtime limit for the arena size */ uint16_t ss; /* relative stack segment */ uint16_t sp; /* initial %sp register */ uint16_t checksum; /* word checksum */ uint16_t ip; /* initial %ip register */ uint16_t cs; /* initial %cs relative to load segment */ uint16_t reloc_table_offset; /* offset of the first relocation */ uint16_t overlay_num; /* overlay number. set to 0. */ uint16_t reserved0[4]; /* reserved */ uint16_t oem_id; /* oem identifier */ uint16_t oem_info; /* oem specific */ uint16_t reserved1[10]; /* reserved */ uint32_t peaddr; /* address of pe header */ char message[64]; /* message to print */ }; struct mz_reloc { uint16_t offset; uint16_t segment; }; #define PE_MAGIC 0x00004550 /* "PE\0\0" */ #define PE_OPT_MAGIC_PE32 0x010b #define PE_OPT_MAGIC_PE32_ROM 0x0107 #define PE_OPT_MAGIC_PE32PLUS 0x020b /* machine type */ #define IMAGE_FILE_MACHINE_UNKNOWN 0x0000 #define IMAGE_FILE_MACHINE_AM33 0x01d3 #define IMAGE_FILE_MACHINE_AMD64 0x8664 #define IMAGE_FILE_MACHINE_ARM 0x01c0 #define IMAGE_FILE_MACHINE_ARMV7 0x01c4 #define IMAGE_FILE_MACHINE_EBC 0x0ebc #define IMAGE_FILE_MACHINE_I386 0x014c #define IMAGE_FILE_MACHINE_IA64 0x0200 #define IMAGE_FILE_MACHINE_M32R 0x9041 #define IMAGE_FILE_MACHINE_MIPS16 0x0266 #define IMAGE_FILE_MACHINE_MIPSFPU 0x0366 #define IMAGE_FILE_MACHINE_MIPSFPU16 0x0466 #define IMAGE_FILE_MACHINE_POWERPC 0x01f0 #define IMAGE_FILE_MACHINE_POWERPCFP 0x01f1 #define IMAGE_FILE_MACHINE_R4000 0x0166 #define IMAGE_FILE_MACHINE_SH3 0x01a2 #define IMAGE_FILE_MACHINE_SH3DSP 0x01a3 #define IMAGE_FILE_MACHINE_SH3E 0x01a4 #define IMAGE_FILE_MACHINE_SH4 0x01a6 #define IMAGE_FILE_MACHINE_SH5 0x01a8 #define IMAGE_FILE_MACHINE_THUMB 0x01c2 #define IMAGE_FILE_MACHINE_WCEMIPSV2 0x0169 /* flags */ #define IMAGE_FILE_RELOCS_STRIPPED 0x0001 #define IMAGE_FILE_EXECUTABLE_IMAGE 0x0002 #define IMAGE_FILE_LINE_NUMS_STRIPPED 0x0004 #define IMAGE_FILE_LOCAL_SYMS_STRIPPED 0x0008 #define IMAGE_FILE_AGGRESSIVE_WS_TRIM 0x0010 #define IMAGE_FILE_LARGE_ADDRESS_AWARE 0x0020 #define IMAGE_FILE_16BIT_MACHINE 0x0040 #define IMAGE_FILE_BYTES_REVERSED_LO 0x0080 #define IMAGE_FILE_32BIT_MACHINE 0x0100 #define IMAGE_FILE_DEBUG_STRIPPED 0x0200 #define IMAGE_FILE_REMOVABLE_RUN_FROM_SWAP 0x0400 #define IMAGE_FILE_NET_RUN_FROM_SWAP 0x0800 #define IMAGE_FILE_SYSTEM 0x1000 #define IMAGE_FILE_DLL 0x2000 #define IMAGE_FILE_UP_SYSTEM_ONLY 0x4000 #define IMAGE_FILE_BYTES_REVERSED_HI 0x8000 struct pe_hdr { uint32_t magic; /* PE magic */ uint16_t machine; /* machine type */ uint16_t sections; /* number of sections */ uint32_t timestamp; /* time_t */ uint32_t symbol_table; /* symbol table offset */ uint32_t symbols; /* number of symbols */ uint16_t opt_hdr_size; /* size of optional header */ uint16_t flags; /* flags */ }; struct pe_symtab_entry { uint8_t name[8]; /* symbol name */ uint32_t value; /* depends */ uint16_t section; /* section number */ uint16_t type; /* 0x20 for function, 0x0 for not function */ uint8_t storage_class; /* storage class */ uint8_t n_aux_symbols; /* how many more records this one uses... */ } __attribute__((__packed__)) __attribute__((__aligned__(1))); #define IMAGE_FILE_OPT_ROM_MAGIC 0x107 #define IMAGE_FILE_OPT_PE32_MAGIC 0x10b #define IMAGE_FILE_OPT_PE32_PLUS_MAGIC 0x20b #define IMAGE_SUBSYSTEM_UNKNOWN 0 #define IMAGE_SUBSYSTEM_NATIVE 1 #define IMAGE_SUBSYSTEM_WINDOWS_GUI 2 #define IMAGE_SUBSYSTEM_WINDOWS_CUI 3 #define IMAGE_SUBSYSTEM_POSIX_CUI 7 #define IMAGE_SUBSYSTEM_WINDOWS_CE_GUI 9 #define IMAGE_SUBSYSTEM_EFI_APPLICATION 10 #define IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER 11 #define IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER 12 #define IMAGE_SUBSYSTEM_EFI_ROM_IMAGE 13 #define IMAGE_SUBSYSTEM_XBOX 14 #define IMAGE_DLL_CHARACTERISTICS_DYNAMIC_BASE 0x0040 #define IMAGE_DLL_CHARACTERISTICS_FORCE_INTEGRITY 0x0080 #define IMAGE_DLL_CHARACTERISTICS_NX_COMPAT 0x0100 #define IMAGE_DLL_CHARACTERISTICS_NO_ISOLATION 0x0200 #define IMAGE_DLL_CHARACTERISTICS_NO_SEH 0x0400 #define IMAGE_DLL_CHARACTERISTICS_NO_BIND 0x0800 #define IMAGE_DLL_CHARACTERISTICS_WDM_DRIVER 0x2000 #define IMAGE_DLL_CHARACTERISTICS_TERMINAL_SERVER_AWARE 0x8000 /* the fact that pe32 isn't padded where pe32+ is 64-bit means union won't * work right. vomit. */ struct pe32_opt_hdr { /* "standard" header */ uint16_t magic; /* file type */ uint8_t ld_major; /* linker major version */ uint8_t ld_minor; /* linker minor version */ uint32_t text_size; /* size of text section(s) */ uint32_t data_size; /* size of data section(s) */ uint32_t bss_size; /* size of bss section(s) */ uint32_t entry_point; /* file offset of entry point */ uint32_t code_base; /* relative code addr in ram */ uint32_t data_base; /* relative data addr in ram */ /* "windows" header */ uint32_t image_base; /* preferred load address */ uint32_t section_align; /* alignment in bytes */ uint32_t file_align; /* file alignment in bytes */ uint16_t os_major; /* major OS version */ uint16_t os_minor; /* minor OS version */ uint16_t image_major; /* major image version */ uint16_t image_minor; /* minor image version */ uint16_t subsys_major; /* major subsystem version */ uint16_t subsys_minor; /* minor subsystem version */ uint32_t win32_version; /* reserved, must be 0 */ uint32_t image_size; /* image size */ uint32_t header_size; /* header size rounded up to file_align */ uint32_t csum; /* checksum */ uint16_t subsys; /* subsystem */ uint16_t dll_flags; /* more flags! */ uint32_t stack_size_req;/* amt of stack requested */ uint32_t stack_size; /* amt of stack required */ uint32_t heap_size_req; /* amt of heap requested */ uint32_t heap_size; /* amt of heap required */ uint32_t loader_flags; /* reserved, must be 0 */ uint32_t data_dirs; /* number of data dir entries */ }; struct pe32plus_opt_hdr { uint16_t magic; /* file type */ uint8_t major; /* linker major version */ uint8_t minor; /* linker minor version */ uint32_t text_size; /* size of text section(s) */ uint32_t data_size; /* size of data section(s) */ uint32_t bss_size; /* size of bss section(s) */ uint32_t entry_point; /* file offset of entry point */ uint32_t code_base; /* relative code addr in ram */ /* "windows" header */ uint64_t image_base; /* preferred load address */ uint32_t section_align; /* alignment in bytes */ uint32_t file_align; /* file alignment in bytes */ uint16_t os_major; /* major OS version */ uint16_t os_minor; /* minor OS version */ uint16_t image_major; /* major image version */ uint16_t image_minor; /* minor image version */ uint16_t subsys_major; /* major subsystem version */ uint16_t subsys_minor; /* minor subsystem version */ uint32_t win32_version; /* reserved, must be 0 */ uint32_t image_size; /* image size */ uint32_t header_size; /* header size rounded up to file_align */ uint32_t csum; /* checksum */ uint16_t subsys; /* subsystem */ uint16_t dll_flags; /* more flags! */ uint64_t stack_size_req;/* amt of stack requested */ uint64_t stack_size; /* amt of stack required */ uint64_t heap_size_req; /* amt of heap requested */ uint64_t heap_size; /* amt of heap required */ uint32_t loader_flags; /* reserved, must be 0 */ uint32_t data_dirs; /* number of data dir entries */ }; typedef struct _data_dirent { uint32_t virtual_address; /* relative to load address */ uint32_t size; } data_dirent; typedef struct _data_directory { data_dirent exports; /* .edata */ data_dirent imports; /* .idata */ data_dirent resources; /* .rsrc */ data_dirent exceptions; /* .pdata */ data_dirent certs; /* certs */ data_dirent base_relocations; /* .reloc */ data_dirent debug; /* .debug */ data_dirent arch; /* reservered */ data_dirent global_ptr; /* global pointer reg. Size=0 */ data_dirent tls; /* .tls */ data_dirent load_config; /* load configuration structure */ data_dirent bound_imports; /* no idea */ data_dirent import_addrs; /* import address table */ data_dirent delay_imports; /* delay-load import table */ data_dirent clr_runtime_hdr; /* .cor (object only) */ data_dirent reserved; } data_directory; struct section_header { char name[8]; /* name or "/12\0" string tbl offset */ uint32_t virtual_size; /* size of loaded section in ram */ uint32_t virtual_address; /* relative virtual address */ uint32_t raw_data_size; /* size of the section */ uint32_t data_addr; /* file pointer to first page of sec */ uint32_t relocs; /* file pointer to relocation entries */ uint32_t line_numbers; /* line numbers! */ uint16_t num_relocs; /* number of relocations */ uint16_t num_lin_numbers; /* srsly. */ uint32_t flags; }; /* they actually defined 0x00000000 as well, but I think we'll skip that one. */ #define IMAGE_SCN_RESERVED_0 0x00000001 #define IMAGE_SCN_RESERVED_1 0x00000002 #define IMAGE_SCN_RESERVED_2 0x00000004 #define IMAGE_SCN_TYPE_NO_PAD 0x00000008 /* don't pad - obsolete */ #define IMAGE_SCN_RESERVED_3 0x00000010 #define IMAGE_SCN_CNT_CODE 0x00000020 /* .text */ #define IMAGE_SCN_CNT_INITIALIZED_DATA 0x00000040 /* .data */ #define IMAGE_SCN_CNT_UNINITIALIZED_DATA 0x00000080 /* .bss */ #define IMAGE_SCN_LNK_OTHER 0x00000100 /* reserved */ #define IMAGE_SCN_LNK_INFO 0x00000200 /* .drectve comments */ #define IMAGE_SCN_RESERVED_4 0x00000400 #define IMAGE_SCN_LNK_REMOVE 0x00000800 /* .o only - scn to be rm'd*/ #define IMAGE_SCN_LNK_COMDAT 0x00001000 /* .o only - COMDAT data */ #define IMAGE_SCN_RESERVED_5 0x00002000 /* spec omits this */ #define IMAGE_SCN_RESERVED_6 0x00004000 /* spec omits this */ #define IMAGE_SCN_GPREL 0x00008000 /* global pointer referenced data */ /* spec lists 0x20000 twice, I suspect they meant 0x10000 for one of them */ #define IMAGE_SCN_MEM_PURGEABLE 0x00010000 /* reserved for "future" use */ #define IMAGE_SCN_16BIT 0x00020000 /* reserved for "future" use */ #define IMAGE_SCN_LOCKED 0x00040000 /* reserved for "future" use */ #define IMAGE_SCN_PRELOAD 0x00080000 /* reserved for "future" use */ /* and here they just stuck a 1-byte integer in the middle of a bitfield */ #define IMAGE_SCN_ALIGN_1BYTES 0x00100000 /* it does what it says on the box */ #define IMAGE_SCN_ALIGN_2BYTES 0x00200000 #define IMAGE_SCN_ALIGN_4BYTES 0x00300000 #define IMAGE_SCN_ALIGN_8BYTES 0x00400000 #define IMAGE_SCN_ALIGN_16BYTES 0x00500000 #define IMAGE_SCN_ALIGN_32BYTES 0x00600000 #define IMAGE_SCN_ALIGN_64BYTES 0x00700000 #define IMAGE_SCN_ALIGN_128BYTES 0x00800000 #define IMAGE_SCN_ALIGN_256BYTES 0x00900000 #define IMAGE_SCN_ALIGN_512BYTES 0x00a00000 #define IMAGE_SCN_ALIGN_1024BYTES 0x00b00000 #define IMAGE_SCN_ALIGN_2048BYTES 0x00c00000 #define IMAGE_SCN_ALIGN_4096BYTES 0x00d00000 #define IMAGE_SCN_ALIGN_8192BYTES 0x00e00000 #define IMAGE_SCN_LNK_NRELOC_OVFL 0x01000000 /* extended relocations */ #define IMAGE_SCN_MEM_DISCARDABLE 0x02000000 /* scn can be discarded */ #define IMAGE_SCN_MEM_NOT_CACHED 0x04000000 /* cannot be cached */ #define IMAGE_SCN_MEM_NOT_PAGED 0x08000000 /* not pageable */ #define IMAGE_SCN_MEM_SHARED 0x10000000 /* can be shared */ #define IMAGE_SCN_MEM_EXECUTE 0x20000000 /* can be executed as code */ #define IMAGE_SCN_MEM_READ 0x40000000 /* readable */ #define IMAGE_SCN_MEM_WRITE 0x80000000 /* writeable */ typedef enum { IMAGE_REL_AMD64_ABSOLUTE = 0, IMAGE_REL_AMD64_ADDR64, IMAGE_REL_AMD64_ADDR32, IMAGE_REL_AMD64_ADDR32N, IMAGE_REL_AMD64_REL32, IMAGE_REL_AMD64_REL32_1, IMAGE_REL_AMD64_REL32_2, IMAGE_REL_AMD64_REL32_3, IMAGE_REL_AMD64_REL32_4, IMAGE_REL_AMD64_REL32_5, IMAGE_REL_AMD64_SECTION, IMAGE_REL_AMD64_SECREL, IMAGE_REL_AMD64_SECREL7, IMAGE_REL_AMD64_TOKEN, IMAGE_REL_AMD64_SREL32, IMAGE_REL_AMD64_PAIR, IMAGE_REL_AMD64_SSPAN32, } x64_coff_reloc_type; typedef enum { IMAGE_REL_ARM_ABSOLUTE, IMAGE_REL_ARM_ADDR32, IMAGE_REL_ARM_ADDR32N, IMAGE_REL_ARM_BRANCH2, IMAGE_REL_ARM_BRANCH1, IMAGE_REL_ARM_SECTION, IMAGE_REL_ARM_SECREL, } arm_coff_reloc_type; typedef enum { IMAGE_REL_SH3_ABSOLUTE, IMAGE_REL_SH3_DIRECT16, IMAGE_REL_SH3_DIRECT32, IMAGE_REL_SH3_DIRECT8, IMAGE_REL_SH3_DIRECT8_WORD, IMAGE_REL_SH3_DIRECT8_LONG, IMAGE_REL_SH3_DIRECT4, IMAGE_REL_SH3_DIRECT4_WORD, IMAGE_REL_SH3_DIRECT4_LONG, IMAGE_REL_SH3_PCREL8_WORD, IMAGE_REL_SH3_PCREL8_LONG, IMAGE_REL_SH3_PCREL12_WORD, IMAGE_REL_SH3_STARTOF_SECTION, IMAGE_REL_SH3_SIZEOF_SECTION, IMAGE_REL_SH3_SECTION, IMAGE_REL_SH3_SECREL, IMAGE_REL_SH3_DIRECT32_NB, IMAGE_REL_SH3_GPREL4_LONG, IMAGE_REL_SH3_TOKEN, IMAGE_REL_SHM_PCRELPT, IMAGE_REL_SHM_REFLO, IMAGE_REL_SHM_REFHALF, IMAGE_REL_SHM_RELLO, IMAGE_REL_SHM_RELHALF, IMAGE_REL_SHM_PAIR, IMAGE_REL_SHM_NOMODE, } sh_coff_reloc_type; typedef enum { IMAGE_REL_PPC_ABSOLUTE, IMAGE_REL_PPC_ADDR64, IMAGE_REL_PPC_ADDR32, IMAGE_REL_PPC_ADDR24, IMAGE_REL_PPC_ADDR16, IMAGE_REL_PPC_ADDR14, IMAGE_REL_PPC_REL24, IMAGE_REL_PPC_REL14, IMAGE_REL_PPC_ADDR32N, IMAGE_REL_PPC_SECREL, IMAGE_REL_PPC_SECTION, IMAGE_REL_PPC_SECREL16, IMAGE_REL_PPC_REFHI, IMAGE_REL_PPC_REFLO, IMAGE_REL_PPC_PAIR, IMAGE_REL_PPC_SECRELLO, IMAGE_REL_PPC_GPREL, IMAGE_REL_PPC_TOKEN, } ppc_coff_reloc_type; typedef enum { IMAGE_REL_I386_ABSOLUTE, IMAGE_REL_I386_DIR16, IMAGE_REL_I386_REL16, IMAGE_REL_I386_DIR32, IMAGE_REL_I386_DIR32NB, IMAGE_REL_I386_SEG12, IMAGE_REL_I386_SECTION, IMAGE_REL_I386_SECREL, IMAGE_REL_I386_TOKEN, IMAGE_REL_I386_SECREL7, IMAGE_REL_I386_REL32, } x86_coff_reloc_type; typedef enum { IMAGE_REL_IA64_ABSOLUTE, IMAGE_REL_IA64_IMM14, IMAGE_REL_IA64_IMM22, IMAGE_REL_IA64_IMM64, IMAGE_REL_IA64_DIR32, IMAGE_REL_IA64_DIR64, IMAGE_REL_IA64_PCREL21B, IMAGE_REL_IA64_PCREL21M, IMAGE_REL_IA64_PCREL21F, IMAGE_REL_IA64_GPREL22, IMAGE_REL_IA64_LTOFF22, IMAGE_REL_IA64_SECTION, IMAGE_REL_IA64_SECREL22, IMAGE_REL_IA64_SECREL64I, IMAGE_REL_IA64_SECREL32, IMAGE_REL_IA64_DIR32NB, IMAGE_REL_IA64_SREL14, IMAGE_REL_IA64_SREL22, IMAGE_REL_IA64_SREL32, IMAGE_REL_IA64_UREL32, IMAGE_REL_IA64_PCREL60X, IMAGE_REL_IA64_PCREL60B, IMAGE_REL_IA64_PCREL60F, IMAGE_REL_IA64_PCREL60I, IMAGE_REL_IA64_PCREL60M, IMAGE_REL_IA64_IMMGPREL6, IMAGE_REL_IA64_TOKEN, IMAGE_REL_IA64_GPREL32, IMAGE_REL_IA64_ADDEND, } ia64_coff_reloc_type; struct coff_reloc { uint32_t virtual_address; uint32_t symbol_table_index; union { x64_coff_reloc_type x64_type; arm_coff_reloc_type arm_type; sh_coff_reloc_type sh_type; ppc_coff_reloc_type ppc_type; x86_coff_reloc_type x86_type; ia64_coff_reloc_type ia64_type; uint16_t data; }; }; #endif /* PE_H */ rhboot-pesign-612e96c/libdpe/000077500000000000000000000000001525324306000160725ustar00rootroot00000000000000rhboot-pesign-612e96c/libdpe/.gitignore000066400000000000000000000000421525324306000200560ustar00rootroot00000000000000*~ *.o *.so *.a *.sw? .*.P core.* rhboot-pesign-612e96c/libdpe/Makefile000066400000000000000000000023231525324306000175320ustar00rootroot00000000000000SRCDIR = $(realpath .) TOPDIR = $(realpath ..) include $(TOPDIR)/Make.version include $(TOPDIR)/Make.rules include $(TOPDIR)/Make.defaults LIBTARGETS=libdpe.so STATICLIBTARGETS=libdpe.a TARGETS=$(LIBTARGETS) $(STATICLIBTARGETS) LIBDPE_SOURCES = $(sort $(wildcard *.c)) ALL_SOURCES=$(LIBDPE_SOURCES) -include $(call deps-of,$(ALL_SOURCES)) all : deps $(TARGETS) libdpe.a : $(call objects-of,$(LIBDPE_SOURCES)) libdpe.a : LIBS=pthread # libdpe.a : | $(wildcard *.h) $(wildcard $(TOPDIR)/include/libdpe/*.h) libdpe.so : $(call objects-of,$(LIBDPE_SOURCES)) libdpe.so : LIBS=pthread # libdpe.so : | $(wildcard *.h) $(wildcard $(TOPDIR)/include/libdpe/*.h) deps : $(ALL_SOURCES) $(MAKE) -f $(TOPDIR)/Make.deps deps SOURCES="$(ALL_SOURCES)" clean : @rm -rfv *~ *.o *.a *.so *.so.* .*.d #install : # $(INSTALL) -d -m 755 $(DESTDIR)$(libdir) # $(foreach x,$(LIBTARGETS), \ # $(INSTALL) -m 755 $(x) $(DESTDIR)$(libdir)/$(x).$(VERSION) ;\ # ln -fs $(x).$(VERSION) $(DESTDIR)$(libdir)/$(x).$(MAJOR_VERSION) ;\ # ln -fs $(x).$(VERSION) $(DESTDIR)$(libdir)/$(x); ) # $(foreach x,$(STATICLIBTARGETS), \ # $(INSTALL) -m 644 $(x) $(DESTDIR)$(libdir)/$(x); ) .SECONDARY : $(foreach x,$(LIBTARGETS),$(x).$(VERSION) $(x).$(MAJOR_VERSION)) rhboot-pesign-612e96c/libdpe/common.h000066400000000000000000000071551525324306000175430ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * common.h - common types and helpers * Copyright Peter Jones * Copyright Red Hat, Inc. */ #ifndef LIBDPE_COMMON_H #define LIBDPE_COMMON_H 1 #include "fix_coverity.h" #include #include #define pwrite_retry(fd, buf, len, off) \ TEMP_FAILURE_RETRY (pwrite (fd, buf, len, off)) #define write_retry(fd, buf, n) \ TEMP_FAILURE_RETRY (write (fd, buf, n)) #define pread_retry(fd, buf, len, off) \ TEMP_FAILURE_RETRY (pread (fd, buf, len, off)) #define is_64_bit(pe) ((pe)->flags & IMAGE_FILE_32BIT_MACHINE) #define xfree(x) ({if (x) { free(x); x = NULL; }}) #define xmunmap(addr, size) ({if (addr) { munmap(addr,size); addr = NULL; }}) #include static inline void * UNUSED compute_mem_addr(Pe *pe, off_t offset) { /* XXX this might not work when we're not mmapped */ return (char *)pe->map_address + le32_to_cpu(offset); } static inline uint32_t UNUSED compute_file_addr(Pe *pe, void *addr) { /* XXX this might not work when we're not mmapped */ return cpu_to_le32((char *)addr - ((char *)pe->map_address)); } static inline size_t UNUSED get_shnum(void *map_address, size_t maxsize UNUSED) { size_t result = 0; void *buf = (void *)map_address; struct mz_hdr *mz = (struct mz_hdr *)buf; if (mz == NULL) return (size_t)-1l; off_t hdr = (off_t)le32_to_cpu(mz->peaddr); struct pe_hdr *pe = (struct pe_hdr *)(buf + hdr); uint16_t sections = pe->sections; result = le16_to_cpu(sections); return result; } static inline Pe_Kind UNUSED determine_kind(void *buf, size_t len UNUSED) { Pe_Kind retval = PE_K_NONE; uint16_t mz_magic = MZ_MAGIC; struct mz_hdr *mz = (struct mz_hdr *)buf; if (cmp_le16(&mz->magic, &mz_magic)) return retval; retval = PE_K_MZ; off_t hdr = (off_t)le32_to_cpu(mz->peaddr); struct pe_hdr *pe = (struct pe_hdr *)(buf + hdr); uint32_t pe_magic = PE_MAGIC; if (cmp_le32(&pe->magic, &pe_magic)) return retval; if (pe->flags & IMAGE_FILE_EXECUTABLE_IMAGE) { if (le32_to_cpu(pe->opt_hdr_size) == 0) { /* this PE header is invalid, so return PE_K_MZ */ return retval; } struct pe32_opt_hdr *peo = (struct pe32_opt_hdr *)(buf + hdr + sizeof(*pe)); /* if we don't have an optional header, fall back to testing * our machine type list... */ switch (le16_to_cpu(peo->magic)) { case PE_OPT_MAGIC_PE32: retval = PE_K_PE_EXE; break; case PE_OPT_MAGIC_PE32_ROM: retval = PE_K_PE_ROM; break; case PE_OPT_MAGIC_PE32PLUS: retval = PE_K_PE64_EXE; break; default: /* some magic we don't know? Guess based on * machine type */ retval = is_64_bit(pe) ? PE_K_PE64_EXE : PE_K_PE_EXE; break; } } else { /* this is an object file */ retval = is_64_bit(pe) ? PE_K_PE64_OBJ : PE_K_PE_OBJ; } return retval; } #undef choose_kind #undef is_64_bit static inline Pe * UNUSED allocate_pe(int fildes, void *map_address, size_t maxsize, Pe_Cmd cmd, Pe *parent, Pe_Kind kind, size_t extra) { Pe *result = (Pe *) calloc(1, sizeof (Pe) + extra); if (result == NULL) { __libpe_seterrno(PE_E_NOMEM); } else { result->kind = kind; result->ref_count = 1; result->cmd = cmd; result->fildes = fildes; result->maximum_size = maxsize; result->map_address = map_address; result->parent = parent; } return result; } /* We often have to update a flag iff a value changed. Make this * convenient. */ #define update_if_changed(var, exp, flag) \ ({ \ __typeof__ (var) *_var = &(var); \ __typeof__ (exp) _exp = (exp); \ if (*_var != _exp) { \ *_var = _exp; \ (flag) |= PE_F_DIRTY; \ } \ }) #endif /* LIBDPE_COMMON_H */ rhboot-pesign-612e96c/libdpe/compiler.h000066400000000000000000000004311525324306000200530ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * compiler.h - borrow the compiler.h from pesign * Copyright Peter Jones */ #ifndef LIBDPE_COMPILER_H_ #define LIBDPE_COMPILER_H_ #include "../src/compiler.h" #endif /* !LIBDPE_COMPILER_H_ */ // vim:fenc=utf-8:tw=75:et rhboot-pesign-612e96c/libdpe/endian.h000066400000000000000000000031511525324306000175010ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * endian.h - helpers for cross-endian data access * Copyright Peter Jones * Copyright Red Hat, Inc. */ #ifndef ENDIAN_H #define ENDIAN_H #include #include #include #if __BYTE_ORDER == __LITTLE_ENDIAN #define cpu_to_le16(x) (x) #define cpu_to_le32(x) (x) #define cpu_to_le64(x) (x) #define le16_to_cpu(x) (x) #define le32_to_cpu(x) (x) #define le64_to_cpu(x) (x) #define cpu_to_be16(x) __builtin_bswap16(x) #define cpu_to_be32(x) __builtin_bswap32(x) #define cpu_to_be64(x) __builtin_bswap64(x) #define be16_to_cpu(x) __builtin_bswap16(x) #define be32_to_cpu(x) __builtin_bswap32(x) #define be64_to_cpu(x) __builtin_bswap64(x) #else #define cpu_to_be16(x) (x) #define cpu_to_be32(x) (x) #define cpu_to_be64(x) (x) #define be16_to_cpu(x) (x) #define be32_to_cpu(x) (x) #define be64_to_cpu(x) (x) #define cpu_to_le16(x) __builtin_bswap16(x) #define cpu_to_le32(x) __builtin_bswap32(x) #define cpu_to_le64(x) __builtin_bswap64(x) #define le16_to_cpu(x) __builtin_bswap16(x) #define le32_to_cpu(x) __builtin_bswap32(x) #define le64_to_cpu(x) __builtin_bswap64(x) #endif static inline uint32_t UNUSED SwapBytes32(uint32_t x) { return __builtin_bswap32(x); } static inline int UNUSED cmp_le16(uint16_t *ledata, uint16_t *cpudata) { uint16_t tmp = le16_to_cpu(*ledata); return memcmp(&tmp, cpudata, sizeof(*cpudata)); } static inline int UNUSED cmp_le32(uint32_t *ledata, uint32_t *cpudata) { uint32_t tmp = le32_to_cpu(*ledata); return memcmp(&tmp, cpudata, sizeof(*cpudata)); } #endif /* ENDIAN_H */ /* vim:set shiftwidth=8 softtabstop=8: */ rhboot-pesign-612e96c/libdpe/fix_coverity.h000066400000000000000000000061551525324306000207640ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * fix_coverity.h - coverity is a piece of junk and this helps * Copyright Peter Jones */ #ifndef FIX_COVERITY_H #define FIX_COVERITY_H #ifndef _GNU_SOURCE #define _GNU_SOURCE #endif #ifndef __COVERITY_GCC_VERSION_AT_LEAST #define __COVERITY_GCC_VERSION_AT_LEAST(x, y) 0 #define FAKE__COVERITY_GCC_VERSION_AT_LEAST__ #endif /* __COVERITY_GCC_VERSION_AT_LEAST */ /* With gcc 7 on x86_64 (at least), coverity pretends to be GCC but * accidentally doesn't create all of the types GCC would. * * In glibc's headers, bits/floatn.h has: * * #if (defined __x86_64__ \ * ? __GNUC_PREREQ (4, 3) \ * : (defined __GNU__ ? __GNUC_PREREQ (4, 5) : __GNUC_PREREQ (4, 4))) * # define __HAVE_FLOAT128 1 * #else * # define __HAVE_FLOAT128 0 * #endif * * and stdlib.h has: * * #if __HAVE_FLOAT128 && __GLIBC_USE (IEC_60559_TYPES_EXT) * slash* Likewise for the '_Float128' format *slash * extern _Float128 strtof128 (const char *__restrict __nptr, * char **__restrict __endptr) * __THROW __nonnull ((1)); * #endif * * Which then causes cov-emit to lose its shit: * * "/usr/include/stdlib.h", line 133: error #20: identifier "_Float128" is * undefined * extern _Float128 strtof128 (const char *__restrict __nptr, * ^ * "/usr/include/stdlib.h", line 190: error #20: identifier "_Float128" is * undefined * _Float128 __f) * ^ * "/usr/include/stdlib.h", line 236: error #20: identifier "_Float128" is * undefined * extern _Float128 strtof128_l (const char *__restrict __nptr, * ^ * * And then you'll notice something like this later on: * [WARNING] Emitted 0 C/C++ compilation units (0%) successfully * * 0 C/C++ compilation units (0%) are ready for analysis * For more details, please look at: * /home/pjones/devel/github.com/dbxtool/master/cov-int/build-log.txt * * You would think that if you're writing something that pretends to be * gcc, and you've got a "build a configuration by running shit through gcc * and looking at the output" stage (which they do), you would run "gcc -da * -fdump-tree-all -c -o foo.o foo.c" on an empty file and snarf up all the * types defined in the foo.c.001t.tu output. Apparently, they do not. * * Anyway, even just defining the type doesn't always work in the face of * how _Complex is defined, so we cheat a bit here. Be prepared to vomit. */ #ifdef __x86_64__ #if __COVERITY_GCC_VERSION_AT_LEAST(7, 0) #if 0 typedef float _Float128 __attribute__((__mode__(__TF__))); typedef __complex__ float __cfloat128 __attribute__ ((__mode__ (__TC__))); typedef _Complex float __cfloat128 __attribute__ ((__mode__ (__TC__))); #else #include #define __cplusplus 201103L #include #undef __cplusplus #endif #endif #endif #ifdef FAKE__COVERITY_GCC_VERSION_AT_LEAST__ #undef FAKE__COVERITY_GCC_VERSION_AT_LEAST #undef __COVERITY_GCC_VERSION_AT_LEAST #endif #endif /* !FIX_COVERITY_H */ // vim:fenc=utf-8:tw=75 rhboot-pesign-612e96c/libdpe/libdpe.c000066400000000000000000000006551525324306000175030ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * libdpe.c - miscelanious PE access functions * Copyright Peter Jones * Copyright Red Hat, Inc. */ #include #include "libdpe_priv.h" Pe *pe_clone(Pe *pe UNUSED, Pe_Cmd cmd UNUSED) { return NULL; } Pe *pe_memory(char *image UNUSED, size_t size UNUSED) { return NULL; } Pe_Kind pe_kind(Pe *pe) { return pe == NULL ? PE_K_NONE : pe->kind; } rhboot-pesign-612e96c/libdpe/libdpe_priv.h000066400000000000000000000056421525324306000205510ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * libdpe_priv.h - private types and helpers * Copyright Peter Jones * Copyright Red Hat, Inc. */ #ifndef LIBDPE_PRIV_H #define LIBDPE_PRIV_H 1 #include #include #include "compiler.h" #include "endian.h" enum { PE_F_DIRTY = 0x1, PE_F_MMAPPED = 0x40, PE_F_MALLOCED = 0x80, PE_F_FILEDATA = 0x100, }; enum { PE_E_NOERROR = 0, PE_E_UNKNOWN_ERROR, PE_E_INVALID_HANDLE, PE_E_NOMEM, PE_E_INVALID_FILE, PE_E_WRITE_ERROR, PE_E_INVALID_INDEX, PE_E_INVALID_OP, PE_E_INVALID_CMD, PE_E_INVALID_OPERAND, PE_E_WRONG_ORDER_PEHDR, PE_E_FD_DISABLED, PE_E_FD_MISMATCH, PE_E_UPDATE_RO, PE_E_NUM /* terminating entry */ }; extern void __libpe_seterrno(int value); struct Pe_Scn { size_t index; struct Pe *pe; struct section_header *shdr; unsigned int shdr_flags; unsigned int flags; char *rawdata_base; char *data_base; struct Pe_ScnList *list; }; typedef struct Pe_ScnList { unsigned int cnt; unsigned int max; struct Pe_ScnList *next; struct Pe_Scn data[0]; } Pe_ScnList; struct Pe { /* Address to which the file was mapped. NULL if not mapped. */ char *map_address; Pe *parent; Pe *next; /* command used to create this object */ Pe_Cmd cmd; Pe_Kind kind; int fildes; size_t maximum_size; int flags; int ref_count; union { struct { struct mz_hdr *mzhdr; struct pe_hdr *pehdr; void *reserved0; void *reserved1; struct section_header *shdr; Pe_ScnList *scns_last; unsigned int scnincr; Pe_ScnList scns; } pe; struct { struct mz_hdr *mzhdr; struct pe_hdr *pehdr; void *reserved0; void *reserved1; struct section_header *shdr; Pe_ScnList *scns_last; unsigned int scnincr; Pe_ScnList scns; } pe32_obj; struct { struct mz_hdr *mzhdr; struct pe_hdr *pehdr; void *reserved0; void *reserved1; struct section_header *shdr; Pe_ScnList *scns_last; unsigned int scnincr; Pe_ScnList scns; } pe32_rom; struct { struct mz_hdr *mzhdr; struct pe_hdr *pehdr; struct pe32_opt_hdr *opthdr; data_directory *datadir; struct section_header *shdr; Pe_ScnList *scns_last; unsigned int scnincr; Pe_ScnList scns; } pe32_exe; struct { struct mz_hdr *mzhdr; struct pe_hdr *pehdr; void *reserved0; void *reserved1; struct section_header *shdr; Pe_ScnList *scns_last; unsigned int scnincr; Pe_ScnList scns; } pe32plus_obj; struct { struct mz_hdr *mzhdr; struct pe_hdr *pehdr; struct pe32plus_opt_hdr *opthdr; data_directory *datadir; struct section_header *shdr; Pe_ScnList *scns_last; unsigned int scnincr; Pe_ScnList scns; } pe32plus_exe; } state; }; #include "common.h" extern off_t __pe_updatemmap(Pe *pe, size_t shnum); extern int __pe_updatefile(Pe *pe, size_t shnum); extern off_t __pe_updatenull(Pe *pe, size_t shnum); extern char *__libpe_readall(Pe *pe); #endif /* LIBDPE_PRIV_H */ rhboot-pesign-612e96c/libdpe/pe_addcert.c000066400000000000000000000042041525324306000203300ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * pe_addcert.c - helpers to manage the PE cert directory * Copyright Peter Jones * Copyright Red Hat, Inc. */ #include #include "libdpe_priv.h" // IWYU pragma: keep int pe_clearcert(Pe *pe) { int rc; data_directory *dd = NULL; if (!pe) { errno = EINVAL; return -1; } rc = pe_getdatadir(pe, &dd); if (rc < 0) return rc; if (dd->certs.virtual_address != 0 && dd->certs.size != 0) { uint64_t pos = le32_to_cpu(dd->certs.virtual_address); uint64_t size = le32_to_cpu(dd->certs.size); uint64_t end; if (__builtin_add_overflow(pos, size, &end) || pos >= pe->maximum_size || end > pe->maximum_size) { __libpe_seterrno(PE_E_INVALID_FILE); return -1; } rc = pe_freespace(pe, dd->certs.virtual_address, dd->certs.size); if (rc < 0) return rc; memset(&dd->certs, '\0', sizeof (dd->certs)); } return 0; } int pe_alloccert(Pe *pe, size_t size) { int rc; data_directory *dd = NULL; if (!pe) { errno = EINVAL; return -1; } rc = pe_clearcert(pe); if (rc < 0) return rc; uint32_t new_space = 0; rc = pe_extend_file(pe, size, &new_space, 8); if (rc < 0) return rc; rc = pe_getdatadir(pe, &dd); if (rc < 0) return rc; void *addr = compute_mem_addr(pe, new_space); /* We leave the whole list empty until finalize...*/ memset(addr, '\0', size); dd->certs.virtual_address = compute_file_addr(pe, addr); dd->certs.size += size; return 0; } int pe_populatecert(Pe *pe, void *cert, size_t size) { int rc; data_directory *dd = NULL; if (!pe) { errno = EINVAL; return -1; } rc = pe_getdatadir(pe, &dd); if (rc < 0) return rc; if (size != dd->certs.size) return -1; void *mem = compute_mem_addr(pe, dd->certs.virtual_address); if (!mem) return -1; memcpy(mem, cert, size); uint64_t max_size = pe->maximum_size; uint32_t new_space; uint32_t page_size = sysconf(_SC_PAGESIZE); pe_extend_file(pe, 0, &new_space, page_size); uint64_t new_max_size = pe->maximum_size; mem = compute_mem_addr(pe, 0); msync(mem, new_max_size, MS_SYNC); new_max_size -= max_size; pe_shorten_file(pe, new_max_size); return 0; } rhboot-pesign-612e96c/libdpe/pe_allocspace.c000066400000000000000000000066661525324306000210460ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * pe_allocspace.c - allocate space in the PE binary * Copyright Peter Jones * Copyright Red Hat, Inc. */ #include "libdpe_priv.h" #include #include #include #define adjust(x,y) ((x) = (typeof (x))(((uint8_t *)(x)) + (y))) static void pe_fix_addresses(Pe *pe, int64_t offset) { pe->map_address += offset; adjust(pe->state.pe.mzhdr, offset); adjust(pe->state.pe.pehdr, offset); adjust(pe->state.pe.reserved0, offset); adjust(pe->state.pe.reserved1, offset); adjust(pe->state.pe.shdr, offset); size_t scncnt = get_shnum(pe->map_address, pe->maximum_size); /* in general this means we couldn't identify any sections, so * they must not need to be fixed up. */ if (scncnt == (size_t)-1l) return; for (size_t cnt = 0; cnt < scncnt; cnt++) { pe->state.pe.scns.data[cnt].shdr = &pe->state.pe.shdr[cnt]; adjust(pe->state.pe.scns.data[cnt].rawdata_base, offset); adjust(pe->state.pe.scns.data[cnt].data_base, offset); } } #undef adjust #define align(val, align) (((val) + (align) -1 ) & (- (align))) int pe_set_image_size(Pe *pe) { if (!pe) { errno = EINVAL; return -1; } uint32_t image_size = 0; struct pe_hdr *pehdr = pe->state.pe.pehdr; struct pe32plus_opt_hdr *opthdr = pe->state.pe32plus_exe.opthdr; Pe_Scn *scn = NULL; struct section_header shdr = { "", 0, }, tmp_shdr; if (pehdr->sections < 1) return -1; for (int i = 0; i < pehdr->sections; i++) { scn = pe_nextscn(pe, scn); if (scn == NULL) break; pe_getshdr(scn, &tmp_shdr); if (tmp_shdr.virtual_size > 0) memcpy (&shdr, &tmp_shdr, sizeof(shdr)); } int falign = pe_get_file_alignment(pe); int salign = pe_get_scn_alignment(pe); image_size = shdr.virtual_address - opthdr->image_base + align(align(shdr.virtual_size, falign), salign); pe->state.pe32plus_exe.opthdr->image_size = image_size; return 0; } int pe_extend_file(Pe *pe, size_t size, uint32_t *new_space, int align) { if (!pe) { errno = EINVAL; return -1; } void *new = NULL; if (align) align = ALIGNMENT_PADDING(pe->maximum_size, align); int extra = size + align; int rc = ftruncate(pe->fildes, pe->maximum_size + extra); if (rc < 0) return -1; new = mremap(pe->map_address, pe->maximum_size, pe->maximum_size + extra, MREMAP_MAYMOVE); if (new == MAP_FAILED) { __libpe_seterrno (PE_E_NOMEM); return -1; } if (new != pe->map_address) pe_fix_addresses(pe, (uint8_t *)new-(uint8_t *)pe->map_address); char *addr = compute_mem_addr(pe, pe->maximum_size); memset(addr, '\0', extra); *new_space = compute_file_addr(pe, addr + align); pe->maximum_size = pe->maximum_size + extra; return 0; } int pe_shorten_file(Pe *pe, size_t size) { void *new = NULL; if (!pe) { errno = EINVAL; return -1; } new = mremap(pe->map_address, pe->maximum_size, pe->maximum_size - size, 0); if (new == MAP_FAILED) { __libpe_seterrno (PE_E_NOMEM); return -1; } int rc = ftruncate(pe->fildes, pe->maximum_size - size); if (rc < 0) return -1; pe->maximum_size -= size; return 0; } int pe_freespace(Pe *pe, uint32_t offset, size_t size) { if (!pe) { errno = EINVAL; return -1; } void *addr = compute_mem_addr(pe, offset); memset(addr, '\0', size); if (offset + size == pe->maximum_size) pe_shorten_file(pe, size); /* XXX PJFIX TODO: this should actually de-allocate the space, *if* * it's the certificate list, when it isn't at the end of the file, * too. */ return 0; } rhboot-pesign-612e96c/libdpe/pe_begin.c000066400000000000000000000211631525324306000200110ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * pe_begin.c - read the PE objects from the media * Copyright Peter Jones * Copyright Red Hat, Inc. */ #include #include #include #include #include #include #include #include #include #include "libdpe_priv.h" static inline Pe * file_read_pe_obj(int fildes UNUSED, void *map_address UNUSED, unsigned char *p_ident UNUSED, size_t maxsize UNUSED, Pe_Cmd cmd UNUSED, Pe *parent UNUSED) { return NULL; } static inline Pe * file_read_pe_exe(int fildes, void *map_address, unsigned char *p_ident, size_t maxsize, Pe_Cmd cmd UNUSED, Pe *parent) { Pe_Kind kind = determine_kind(p_ident, maxsize); size_t scncnt = get_shnum(map_address, maxsize); if (scncnt == (size_t) -1l) { /* Could not determine the number of sections. */ return NULL; } if (scncnt > SIZE_MAX / sizeof(Pe_Scn) + sizeof (struct section_header)) return NULL; const size_t scnmax = (scncnt ?: (cmd == PE_C_RDWR || cmd == PE_C_RDWR_MMAP) ? 1: 0); Pe *pe = allocate_pe(fildes, map_address, maxsize, cmd, parent, kind, scnmax * sizeof (Pe_Scn)); if (pe == NULL) return NULL; pe->state.pe32_obj.mzhdr = (struct mz_hdr *) ((char *)map_address); pe->state.pe32_obj.pehdr = (struct pe_hdr *)((char *)map_address + (off_t)le32_to_cpu(pe->state.pe32_obj.mzhdr->peaddr)); assert((unsigned int)scncnt == scncnt); pe->state.pe32_obj.scns.cnt = scncnt; pe->state.pe32_obj.scns.max = scnmax; pe->state.pe32_obj.scnincr = 10; size_t ddsize = 0; switch (kind) { case PE_K_PE_OBJ: pe->state.pe32_obj.shdr = (struct section_header *) ((char *)pe->state.pe32_obj.pehdr + sizeof (struct pe_hdr)); break; case PE_K_PE_EXE: pe->state.pe32_exe.opthdr = (struct pe32_opt_hdr *) ((char *)pe->state.pe32_exe.pehdr + sizeof (struct pe_hdr)); pe->state.pe32_exe.datadir = (data_directory *) ((char *)pe->state.pe32_exe.opthdr + sizeof (struct pe32_opt_hdr)); ddsize = le32_to_cpu( pe->state.pe32_exe.opthdr->data_dirs); pe->state.pe32_exe.shdr = (struct section_header *) ((char *)pe->state.pe32_exe.datadir + (sizeof (data_dirent) * ddsize)); break; case PE_K_PE64_OBJ: pe->state.pe32plus_obj.shdr = (struct section_header *) ((char *)pe->state.pe32plus_obj.pehdr + sizeof (struct pe_hdr)); break; case PE_K_PE64_EXE: pe->state.pe32plus_exe.opthdr = (struct pe32plus_opt_hdr *) ((char *)pe->state.pe32plus_exe.pehdr + sizeof (struct pe_hdr)); pe->state.pe32plus_exe.datadir = (data_directory *) ((char *)pe->state.pe32plus_exe.opthdr + sizeof (struct pe32plus_opt_hdr)); ddsize = le32_to_cpu( pe->state.pe32plus_exe.opthdr->data_dirs); pe->state.pe32plus_exe.shdr = (struct section_header *) ((char *)pe->state.pe32plus_exe.datadir + (sizeof (data_dirent) * ddsize)); break; default: break; } for (size_t cnt = 0; cnt < scncnt; cnt++) { pe->state.pe.scns.data[cnt].index = cnt; pe->state.pe.scns.data[cnt].pe = pe; pe->state.pe.scns.data[cnt].shdr = &pe->state.pe.shdr[cnt]; uint32_t raw_data_size = le32_to_cpu(pe->state.pe.shdr[cnt].raw_data_size); uint32_t data_addr = le32_to_cpu(pe->state.pe.shdr[cnt].data_addr); if (data_addr < maxsize && maxsize - data_addr <= raw_data_size) pe->state.pe.scns.data[cnt].rawdata_base = pe->state.pe.scns.data[cnt].data_base = ((char *)map_address + data_addr); pe->state.pe.scns.data[cnt].list = &pe->state.pe.scns; } return pe; } static Pe * __libpe_read_mmapped_file(int fildes, void *map_address, size_t maxsize, Pe_Cmd cmd, Pe *parent) { unsigned char *p_ident = (unsigned char *) map_address; Pe_Kind kind = determine_kind (p_ident, maxsize); switch (kind) { case PE_K_PE_OBJ: case PE_K_PE64_OBJ: return file_read_pe_obj(fildes, map_address, p_ident, maxsize, cmd, parent); case PE_K_PE64_EXE: case PE_K_PE_EXE: return file_read_pe_exe(fildes, map_address, p_ident, maxsize, cmd, parent); case PE_K_MZ: errno = ENOSYS; return NULL; default: break; } return allocate_pe(fildes, map_address, maxsize, cmd, parent, PE_K_NONE, 0); } static Pe * read_unmmapped_file(int fildes, size_t maxsize, Pe_Cmd cmd, Pe *parent) { union { struct { struct mz_hdr mz; struct pe_hdr pe; union { struct pe32_opt_hdr opt_hdr_32; struct pe32plus_opt_hdr opt_hdr_64; }; }; unsigned char raw[sizeof(struct mz_hdr) + sizeof(struct pe_hdr) + sizeof(struct pe32plus_opt_hdr)]; } mem; ssize_t nread = pread_retry (fildes, &mem.mz, sizeof(mem.mz), 0); if (nread == -1) return NULL; /* this handles MZ-only binaries wrong, but who cares, really? */ off_t peaddr = le32_to_cpu(mem.mz.peaddr); ssize_t prev_nread = nread; nread += pread_retry (fildes, &mem.pe, sizeof(mem.pe), peaddr); if (nread == prev_nread) return NULL; mem.mz.peaddr = cpu_to_le32(offsetof(typeof(mem), pe)); Pe_Kind kind = determine_kind(&mem, nread); switch (kind) { case PE_K_PE_OBJ: return file_read_pe_obj(fildes, NULL, mem.raw, maxsize, cmd, parent); case PE_K_PE_EXE: return file_read_pe_exe(fildes, NULL, mem.raw, maxsize, cmd, parent); default: break; } return allocate_pe(fildes, NULL, maxsize, cmd, parent, PE_K_NONE, 0); } static Pe * read_file(int fildes, size_t maxsize, Pe_Cmd cmd, Pe *parent) { void *map_address = NULL; int use_mmap = (cmd == PE_C_READ_MMAP || cmd == PE_C_RDWR_MMAP || cmd == PE_C_WRITE_MMAP || cmd == PE_C_READ_MMAP_PRIVATE); if (use_mmap) { if (parent == NULL) { if (maxsize == ~((size_t) 0)) { struct stat st; if (fstat(fildes, &st) == 0 && (sizeof(size_t) >= sizeof(st.st_size)|| st.st_size <= ~((size_t)0))) maxsize = (size_t) st.st_size; } map_address = mmap(NULL, maxsize, cmd == PE_C_READ_MMAP ? PROT_READ : PROT_READ|PROT_WRITE, cmd == PE_C_READ_MMAP_PRIVATE || cmd == PE_C_READ_MMAP ? MAP_PRIVATE : MAP_SHARED, fildes, 0); if (map_address == MAP_FAILED) map_address = NULL; } else { assert (maxsize != ~((size_t)0)); map_address = parent->map_address; } } if (map_address != NULL) { assert(map_address != MAP_FAILED); struct Pe *result = __libpe_read_mmapped_file(fildes, map_address, maxsize, cmd, parent); if (result == NULL && (parent == NULL || parent->map_address != map_address)) munmap(map_address, maxsize); else if (parent == NULL) result->flags |= PE_F_MMAPPED; return result; } return read_unmmapped_file(fildes, maxsize, cmd, parent); } static struct Pe * write_file (int fd, Pe_Cmd cmd) { #define NSCNSALLOC 10 Pe *result = allocate_pe(fd, NULL, 0, cmd, NULL, PE_K_PE_EXE, NSCNSALLOC * sizeof (Pe_Scn)); if (result != NULL) { result->flags = PE_F_DIRTY; result->state.pe.scnincr = NSCNSALLOC; result->state.pe.scns_last = &result->state.pe.scns; result->state.pe.scns.max = NSCNSALLOC; } return result; } static Pe * dup_pe(int fildes, Pe_Cmd cmd UNUSED, Pe *ref) { if (fildes == -1) { fildes = ref->fildes; } if (ref->fildes != -1 && fildes != ref->fildes) { __libpe_seterrno(PE_E_FD_MISMATCH); return NULL; } if (ref->cmd != PE_C_READ && ref->cmd != PE_C_READ_MMAP && ref->cmd != PE_C_WRITE && ref->cmd != PE_C_WRITE_MMAP && ref->cmd != PE_C_RDWR && ref->cmd != PE_C_RDWR_MMAP && ref->cmd != PE_C_READ_MMAP_PRIVATE) { __libpe_seterrno(PE_E_INVALID_OP); return NULL; } /* for now, just increment the refcount and return the same object */ ref->ref_count++; return ref; } Pe * pe_begin(int fildes, Pe_Cmd cmd, Pe *ref) { Pe *retval = NULL; if (fcntl(fildes, F_GETFL) == -1 && errno == EBADF) { __libpe_seterrno(PE_E_INVALID_FILE); return NULL; } switch (cmd) { case PE_C_NULL: break; case PE_C_READ_MMAP_PRIVATE: if (ref != NULL && ref->cmd != PE_C_READ_MMAP_PRIVATE) { __libpe_seterrno(PE_E_INVALID_CMD); break; } /* fall through */ case PE_C_READ: case PE_C_READ_MMAP: if (ref != NULL) retval = dup_pe(fildes, cmd, ref); else retval = read_file(fildes, ~((size_t)0), cmd, NULL); break; case PE_C_RDWR: case PE_C_RDWR_MMAP: if (ref != NULL) { if (ref->cmd != PE_C_RDWR && ref->cmd != PE_C_RDWR_MMAP && ref->cmd != PE_C_WRITE && ref->cmd != PE_C_WRITE_MMAP) { __libpe_seterrno(PE_E_INVALID_CMD); retval = NULL; } } else { retval = read_file(fildes, ~((size_t) 0), cmd, NULL); } break; case PE_C_WRITE: case PE_C_WRITE_MMAP: retval = write_file(fildes, cmd); break; default: __libpe_seterrno(PE_E_INVALID_CMD); break; } return retval; } rhboot-pesign-612e96c/libdpe/pe_end.c000066400000000000000000000027371525324306000175010ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * pe_end.c - save our results and finalize the PE binary * Copyright Peter Jones * Copyright Red Hat, Inc. */ #include #include "libdpe_priv.h" int pe_end(Pe *pe) { Pe *parent = NULL; if (pe == NULL) { /* This is allowed and is a no-op. */ return 0; } if (pe->ref_count != 0 && --pe->ref_count != 0) { int result = pe->ref_count; return result; } parent = pe->parent; switch (pe->kind) { case PE_K_NONE: case PE_K_MZ: break; case PE_K_PE_OBJ: case PE_K_PE_EXE: case PE_K_PE_ROM: case PE_K_PE64_OBJ: case PE_K_PE64_EXE: { Pe_ScnList *list = &pe->state.pe.scns; do { size_t cnt = list->max; while (cnt-- > 0) { Pe_Scn *scn = &list->data[cnt]; if ((scn->shdr_flags & PE_F_MALLOCED)) xfree(scn->shdr); if (scn->data_base != scn->rawdata_base) xfree(scn->data_base); if (pe->map_address == NULL) xfree(scn->rawdata_base); } Pe_ScnList *oldp = list; list = list->next; assert(list == NULL || oldp->cnt == oldp->max); if (oldp != &pe->state.pe.scns) xfree(oldp); } while (list); } break; case PE_K_NUM: default: break; } if (pe->map_address != NULL && parent == NULL) { if (pe->flags & PE_F_MALLOCED) xfree(pe->map_address); else if (pe->flags & PE_F_MMAPPED) xmunmap(pe->map_address, pe->maximum_size); } xfree(pe); return (parent != NULL && parent->ref_count ? pe_end(parent) : 0); } rhboot-pesign-612e96c/libdpe/pe_error.c000066400000000000000000000062541525324306000200620ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * pe_error.c - error handling for libdpe * Copyright Peter Jones * Copyright Red Hat, Inc. */ #include #include #include "libdpe_priv.h" static int global_error; int pe_errno (void) { int result = global_error; global_error = PE_E_NOERROR; return result; } static const char msgstr[] = { #define PE_E_NOERROR_IDX 0 "no error" "\0" #define PE_E_UNKNOWN_ERROR_IDX \ (PE_E_NOERROR_IDX + sizeof "no error") "unknown error" "\0" #define PE_E_INVALID_HANDLE_IDX \ (PE_E_UNKNOWN_ERROR_IDX + sizeof "unknown error") "invalid 'Pe' handle" "\0" #define PE_E_NOMEM_IDX \ (PE_E_INVALID_HANDLE_IDX + sizeof "invalid 'Pe' handle") "out of memory" "\0" #define PE_E_INVALID_FILE_IDX \ (PE_E_NOMEM_IDX + sizeof "out of memory") "invalid file descriptor" "\0" #define PE_E_WRITE_ERROR_IDX \ (PE_E_INVALID_FILE_IDX + sizeof "invalid file descriptor") "cannot write data to file" "\0" #define PE_E_INVALID_INDEX_IDX \ (PE_E_WRITE_ERROR_IDX + sizeof "cannot write data to file") "invalid section index" "\0" #define PE_E_INVALID_OP_IDX \ (PE_E_INVALID_INDEX_IDX + sizeof "invalid section index") "invalid operation" "\0" #define PE_E_INVALID_CMD_IDX \ (PE_E_INVALID_OP_IDX + sizeof "invalid operation") "invalid command" "\0" #define PE_E_INVALID_OPERAND_IDX \ (PE_E_INVALID_CMD_IDX + sizeof "invalid command") "invalid operand" "\0" #define PE_E_WRONG_ORDER_PEHDR_IDX \ (PE_E_INVALID_OPERAND_IDX + sizeof "invalid operand") "executable header not created first" "\0" #define PE_E_FD_DISABLED_IDX \ (PE_E_WRONG_ORDER_PEHDR_IDX + sizeof "executable header not created first") "file descriptor disabled" "\0" #define PE_E_FD_MISMATCH_IDX \ (PE_E_FD_DISABLED_IDX + sizeof "file descriptor disabled") "file descriptor mismatch" "\0" #define PE_E_UPDATE_RO_IDX \ (PE_E_FD_MISMATCH_IDX + sizeof "file descriptor mismatch") "update() for write on read-only file" }; static const uint16_t msgidx[PE_E_NUM] = { [PE_E_NOERROR] = PE_E_NOERROR_IDX, [PE_E_UNKNOWN_ERROR] = PE_E_UNKNOWN_ERROR_IDX, [PE_E_INVALID_HANDLE] = PE_E_INVALID_HANDLE_IDX, [PE_E_NOMEM] = PE_E_NOMEM_IDX, [PE_E_INVALID_FILE] = PE_E_INVALID_FILE_IDX, [PE_E_WRITE_ERROR] = PE_E_WRITE_ERROR_IDX, [PE_E_INVALID_INDEX] = PE_E_INVALID_INDEX_IDX, [PE_E_INVALID_OP] = PE_E_INVALID_OP_IDX, [PE_E_INVALID_CMD] = PE_E_INVALID_CMD_IDX, [PE_E_INVALID_OPERAND] = PE_E_INVALID_OPERAND_IDX, [PE_E_WRONG_ORDER_PEHDR] = PE_E_WRONG_ORDER_PEHDR_IDX, [PE_E_FD_DISABLED] = PE_E_FD_DISABLED_IDX, [PE_E_FD_MISMATCH] = PE_E_FD_MISMATCH_IDX, [PE_E_UPDATE_RO] = PE_E_UPDATE_RO_IDX, }; #define nmsgidx ((int) (sizeof (msgidx) / sizeof (msgidx[0]))) void __libpe_seterrno(int value) { global_error = value >= 0 && value <= nmsgidx ? value : PE_E_UNKNOWN_ERROR; } const char * pe_errmsg(int error) { int last_error = global_error; if (error == 0) { assert(msgidx[last_error] < sizeof(msgstr)); return last_error != 0 ? msgstr + msgidx[last_error] : NULL; } else if (error < -1 || error >= nmsgidx) { return msgstr + PE_E_UNKNOWN_ERROR_IDX; } assert (msgidx[error == -1 ? last_error : error] < sizeof (msgstr)); return msgstr + msgidx[error == -1 ? last_error : error]; } rhboot-pesign-612e96c/libdpe/pe_getdatadir.c000066400000000000000000000017371525324306000210420ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * pe_getdatadir.c - find the data directory * Copyright Peter Jones * Copyright Red Hat, Inc. */ #include "libdpe_priv.h" int pe_getdatadir(Pe *pe, data_directory **ddp) { int rc = -1; data_directory *dd = NULL; uint64_t dd_pos, dd_size, dd_end; if (!pe || !ddp) { __libpe_seterrno(PE_E_INVALID_INDEX); return rc; } switch (pe->kind) { case PE_K_PE_EXE: { dd = pe->state.pe32_exe.datadir; rc = 0; break; } case PE_K_PE64_EXE: { dd = pe->state.pe32plus_exe.datadir; rc = 0; break; } case PE_K_PE_OBJ: case PE_K_PE64_OBJ: case PE_K_PE_ROM: default: break; } if (!dd) return rc; dd_pos = le32_to_cpu(dd->certs.virtual_address); dd_size = le32_to_cpu(dd->certs.size); if (__builtin_add_overflow(dd_pos, dd_size, &dd_end) || dd_pos >= pe->maximum_size || dd_end > pe->maximum_size) { __libpe_seterrno(PE_E_INVALID_FILE); rc = -1; } if (rc >= 0) *ddp = dd; return rc; } rhboot-pesign-612e96c/libdpe/pe_getpehdr.c000066400000000000000000000005341525324306000205260ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * pe_getpehdr - helpers to find the PE file header * Copyright Peter Jones * Copyright Red Hat, Inc. */ #include "libdpe_priv.h" struct pe_hdr * pe_getpehdr(Pe *pe, struct pe_hdr *dest) { if (pe == NULL) return NULL; memcpy(dest, pe->state.pe.pehdr, sizeof(*dest)); return dest; } rhboot-pesign-612e96c/libdpe/pe_getscn.c000066400000000000000000000014541525324306000202110ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * pe_getscn.c - PE section access * Copyright Peter Jones * Copyright Red Hat, Inc. */ #include "libdpe_priv.h" Pe_Scn * pe_getscn(Pe *pe, size_t idx) { if (pe == NULL) return NULL; switch (pe->kind) { case PE_K_PE_OBJ: case PE_K_PE_EXE: case PE_K_PE_ROM: case PE_K_PE64_OBJ: case PE_K_PE64_EXE: break; default: __libpe_seterrno(PE_E_INVALID_HANDLE); return NULL; } Pe_Scn *result = NULL; Pe_ScnList *runp = &pe->state.pe.scns; while (1) { if (idx < runp->max) { if (idx < runp->cnt) result = &runp->data[idx]; else __libpe_seterrno(PE_E_INVALID_INDEX); break; } idx -= runp->max; runp = runp->next; if (runp == NULL) { __libpe_seterrno(PE_E_INVALID_INDEX); break; } } return result; } rhboot-pesign-612e96c/libdpe/pe_getshdr.c000066400000000000000000000007461525324306000203710ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * pe_getshdr - helpers for PE section headers * Copyright Peter Jones * Copyright Red Hat, Inc. */ #include "libdpe_priv.h" struct section_header * pe_getshdr(Pe_Scn *scn, struct section_header *dst) { struct section_header *result = NULL; if (scn == NULL) return NULL; if (dst == NULL) { __libpe_seterrno(PE_E_INVALID_OPERAND); return NULL; } result = memcpy(dst, scn->shdr, sizeof(*dst)); return result; } rhboot-pesign-612e96c/libdpe/pe_nextscn.c000066400000000000000000000012301525324306000204000ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * pe_nextscn.c - PE section iteration * Copyright Peter Jones * Copyright Red Hat, Inc. */ #include #include "libdpe_priv.h" Pe_Scn * pe_nextscn(Pe *pe, Pe_Scn *scn) { Pe_Scn *result = NULL; if (pe == NULL) return NULL; if (scn == NULL) { if (pe->state.pe.scns.cnt > 0) result = &pe->state.pe.scns.data[0]; } else { Pe_ScnList *list = scn->list; if (scn + 1 < &list->data[list->cnt]) { result = scn + 1; } else if (scn + 1 == &list->data[list->max] && (list = list->next) != NULL) { assert(list->cnt > 0); result = &list->data[0]; } } return result; } rhboot-pesign-612e96c/libdpe/pe_opthdr.c000066400000000000000000000025241525324306000202250ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * pe_opthdr.c - helpers for the PE optional headers * Copyright Peter Jones * Copyright Red Hat, Inc. */ #include "libdpe_priv.h" void * pe_getopthdr(Pe *pe) { switch (pe_kind(pe)) { case PE_K_PE_EXE: return pe->state.pe32_exe.opthdr; case PE_K_PE64_EXE: return pe->state.pe32plus_exe.opthdr; default: return NULL; } } int32_t pe_get_file_alignment(Pe *pe) { struct pe32_opt_hdr *pe32opthdr = NULL; struct pe32plus_opt_hdr *pe64opthdr = NULL; switch (pe_kind(pe)) { case PE_K_PE_EXE: { void *opthdr = pe_getopthdr(pe); pe32opthdr = opthdr; return pe32opthdr ? (int32_t)pe32opthdr->file_align : -1; } case PE_K_PE64_EXE: { void *opthdr = pe_getopthdr(pe); pe64opthdr = opthdr; return pe64opthdr ? (int32_t)pe64opthdr->file_align : -1; break; } default: break; } return -1; } int32_t pe_get_scn_alignment(Pe *pe) { struct pe32_opt_hdr *pe32opthdr = NULL; struct pe32plus_opt_hdr *pe64opthdr = NULL; switch (pe_kind(pe)) { case PE_K_PE_EXE: { void *opthdr = pe_getopthdr(pe); pe32opthdr = opthdr; return pe32opthdr ? (int32_t)pe32opthdr->section_align : -1; } case PE_K_PE64_EXE: { void *opthdr = pe_getopthdr(pe); pe64opthdr = opthdr; return pe64opthdr ? (int32_t)pe64opthdr->section_align : -1; break; } default: break; } return -1; } rhboot-pesign-612e96c/libdpe/pe_rawfile.c000066400000000000000000000010421525324306000203500ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * pe_rawfile.c - I really don't remember. * Copyright Peter Jones * Copyright Red Hat, Inc. */ #include "libdpe_priv.h" char * pe_rawfile(Pe *pe, size_t *size) { char *result; if (pe == NULL) { __libpe_seterrno(PE_E_INVALID_HANDLE); error_out: if (size != NULL) *size = 0; return NULL; } if (pe->map_address == NULL && __libpe_readall(pe) == NULL) goto error_out; if (size != NULL) *size = pe->maximum_size; result = (char *)pe->map_address; return result; } rhboot-pesign-612e96c/libdpe/pe_readall.c000066400000000000000000000003451525324306000203300ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * pe_readall.c - not implemented * Copyright Peter Jones * Copyright Red Hat, Inc. */ #include "libdpe_priv.h" char * __libpe_readall(Pe *pe UNUSED) { return NULL; } rhboot-pesign-612e96c/libdpe/pe_update.c000066400000000000000000000046021525324306000202060ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * pe_update.c - routes to update the PE binary * Copyright Peter Jones * Copyright Red Hat, Inc. */ #include "libdpe_priv.h" #include #include #include static off_t write_file(Pe *pe, off_t size, size_t shnum) { struct stat st; if (fstat(pe->fildes, &st) != 0) { __libpe_seterrno(PE_E_WRITE_ERROR); return -1; } if (pe->parent == NULL && (pe->maximum_size == ~((size_t)0) || (size_t)size > pe->maximum_size) && ftruncate(pe->fildes, size) != 0) { __libpe_seterrno(PE_E_WRITE_ERROR); return -1; } if (pe->map_address == NULL && pe->cmd == PE_C_WRITE_MMAP) { pe->map_address = mmap(NULL, size, PROT_READ|PROT_WRITE, MAP_SHARED, pe->fildes, 0); if (pe->map_address == MAP_FAILED) pe->map_address = NULL; } if (pe->map_address != NULL) { if (__pe_updatemmap(pe, shnum) != 0) size = -1; } else { if (__pe_updatefile(pe, shnum) != 0) size = -1; } if (size != -1 && pe->parent == NULL && pe->maximum_size != ~((size_t)0) && (size_t)size < pe->maximum_size && ftruncate(pe->fildes, size) != 0) { __libpe_seterrno(PE_E_WRITE_ERROR); size = -1; } if (size != -1 && (st.st_mode & (S_ISUID | S_ISGID)) && (fchmod(pe->fildes, st.st_mode) != 0)) { __libpe_seterrno(PE_E_WRITE_ERROR); size = -1; } if (size != -1 && pe->parent == NULL) pe->maximum_size = size; return size; } loff_t pe_update(Pe *pe, Pe_Cmd cmd) { if (cmd != PE_C_NULL && cmd != PE_C_WRITE && cmd != PE_C_WRITE_MMAP) { __libpe_seterrno(PE_E_INVALID_CMD); return -1; } if (pe == NULL) return -1; if (pe->kind != PE_K_PE_EXE && pe->kind != PE_K_PE64_EXE && pe->kind != PE_K_PE_OBJ && pe->kind != PE_K_PE64_OBJ && pe->kind != PE_K_PE_ROM) { __libpe_seterrno(PE_E_INVALID_HANDLE); return -1; } size_t shnum = (pe->state.pe.scns_last->cnt == 0 ? 0 : 1 + pe->state.pe.scns_last->data[ pe->state.pe.scns_last->cnt - 1].index); off_t size = __pe_updatenull(pe, shnum); if (size != -1 && (cmd == PE_C_WRITE || cmd == PE_C_WRITE_MMAP)) { if (pe->cmd != PE_C_RDWR && pe->cmd != PE_C_RDWR_MMAP && pe->cmd != PE_C_WRITE && pe->cmd != PE_C_WRITE_MMAP) { __libpe_seterrno(PE_E_UPDATE_RO); size = -1; } else if (pe->fildes == -1) { __libpe_seterrno(PE_E_FD_DISABLED); size = -1; } else { size = write_file(pe, size, shnum); } } return size; } rhboot-pesign-612e96c/libdpe/pe_updatefile.c000066400000000000000000000063021525324306000210450ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * pe_updatefile.c * Copyright Peter Jones * Copyright Red Hat, Inc. */ #include "fix_coverity.h" #include "libdpe_priv.h" #include #include #include static struct section_header * UNUSED __get_last_section(Pe *pe) { Pe_Scn *scn = NULL; Pe_Scn *ret = NULL; while ((scn = pe_nextscn(pe, scn)) != NULL) { if (!ret) { ret = scn; continue; } if (ret->shdr->virtual_address < scn->shdr->virtual_address) ret = scn; } if (ret) return ret->shdr; return NULL; } static int compare_sections (const void *a, const void *b) { const Pe_Scn **scna = (const Pe_Scn **)a; const Pe_Scn **scnb = (const Pe_Scn **)b; int rc; if ((*scna)->shdr->virtual_address > (*scnb)->shdr->virtual_address) return 1; if ((*scnb)->shdr->virtual_address > (*scna)->shdr->virtual_address) return -1; if ((*scna)->shdr->data_addr > (*scnb)->shdr->data_addr) return 1; if ((*scnb)->shdr->data_addr > (*scna)->shdr->data_addr) return -1; rc = strcmp((*scna)->shdr->name, (*scnb)->shdr->name); if (rc != 0) return rc; if ((*scna)->shdr->virtual_size > (*scnb)->shdr->virtual_size) return 1; if ((*scnb)->shdr->virtual_size > (*scna)->shdr->virtual_size) return -1; if ((*scna)->shdr->raw_data_size > (*scnb)->shdr->raw_data_size) return 1; if ((*scnb)->shdr->raw_data_size > (*scna)->shdr->raw_data_size) return -1; return 0; } static void UNUSED sort_sections (Pe_Scn **scns, Pe_ScnList *list) { Pe_Scn **scnp = scns; do { for (size_t cnt = 0; cnt < list->cnt; ++cnt) *scnp++ = &list->data[cnt]; } while ((list = list->next) != NULL); qsort(scns, scnp-scns, sizeof(*scns), compare_sections); } off_t __pe_updatemmap(Pe *pe, size_t shnum UNUSED) { /* This needs to write back the whole file: * 1) mz/pe/pe-o headers * 2) section headers and sections * 3) data directory table and data directories * * We also need to check if the signature is valid and if not, * make sure it's not in the data directory. */ struct mz_hdr *mzhdr = pe->state.pe.mzhdr; struct pe_hdr *pehdr = pe->state.pe.pehdr; if (pe->flags & PE_F_DIRTY) { off_t offset = 0; memcpy(pe->map_address + offset, mzhdr, sizeof(*mzhdr)); offset += le32_to_cpu(mzhdr->peaddr); memcpy(pe->map_address + offset, pehdr, sizeof(*pehdr)); } /* it's not dirty any more, so clear the flag. */ pe->flags &= ~PE_F_DIRTY; /* flush back to disk */ char *msync_start = ((char *) pe->map_address + (~(sysconf(_SC_PAGESIZE) -1 ))); data_directory *dd = NULL; int rc = pe_getdatadir(pe, &dd); if (rc < 0) { /* XXX set an error here */ return -1; } char *msync_end = (char *)dd + sizeof(*dd); msync(msync_start, msync_end - msync_start, MS_SYNC); /* TODO: this is not done yet. */ //struct section_header *sh = __get_last_section(pe); size_t dd_size = sizeof (*dd) / sizeof (dd->exports); data_dirent *dde = &dd->exports; for (unsigned int i = 0; i < dd_size; i++, dde++) { if (dde->size != 0) { char *addr = compute_mem_addr(pe, dde->virtual_address); msync(addr, dde->size, MS_SYNC); } } return 0; } int __pe_updatefile(Pe *pe UNUSED, size_t shnum UNUSED) { __libpe_seterrno(PE_E_UNKNOWN_ERROR); return 1; } rhboot-pesign-612e96c/libdpe/pe_updatenull.c000066400000000000000000000014351525324306000211020ustar00rootroot00000000000000/// SPDX-License-Identifier: GPLv2 /* * pe_updatenull.c - not implemented, really. * Copyright Peter Jones * Copyright Red Hat, Inc. */ #include "libdpe_priv.h" static int pe_default_mzhdr(Pe *pe, struct mz_hdr *mzhdr) { /* Always write the mz magic */ uint16_t mz_magic = cpu_to_le16(MZ_MAGIC); update_if_changed(mzhdr->magic, mz_magic, pe->flags); /* XXX FIXME: write a real MZ header */ /* print "the only way to win is not to play" */ return 0; } static int pe_default_pehdr(Pe *pe, struct pe_hdr *pehdr, size_t shnum UNUSED) { /* Always write the pe magic */ uint32_t pe_magic = cpu_to_le32(PE_MAGIC); update_if_changed(pehdr->magic, pe_magic, pe->flags); return 0; } off_t __pe_updatenull(Pe *pe UNUSED, size_t shnum UNUSED) { return 0; } rhboot-pesign-612e96c/src/000077500000000000000000000000001525324306000154225ustar00rootroot00000000000000rhboot-pesign-612e96c/src/.gitignore000066400000000000000000000002131525324306000174060ustar00rootroot00000000000000pesign authvar ms client efikeygen efidbtool pesigcheck pesum peverify pesign.service pesign.sysvinit pesign-rpmbuild-helper tmpfiles.conf rhboot-pesign-612e96c/src/Makefile000066400000000000000000000100521525324306000170600ustar00rootroot00000000000000SRCDIR = $(realpath .) TOPDIR = $(realpath ..) include $(TOPDIR)/Make.version include $(TOPDIR)/Make.rules include $(TOPDIR)/Make.defaults BINTARGETS=authvar client efikeygen pesigcheck pesign \ pesign-rpmbuild-helper pesum CFGTARGETS=tmpfiles.conf SVCTARGETS=pesign.sysvinit pesign.service MAN1TARGETS=authvar.1 efikeygen.1 pesigcheck.1 pesign-client.1 pesign.1 TARGETS=$(BINTARGETS) $(SVCTARGETS) $(CFGTARGETS) ifeq ($(ENABLE_DOCS), 1) TARGETS += $(MAN1TARGETS) endif all : deps $(TARGETS) COMMON_SOURCES = cms_common.c content_info.c \ errno-guard.c \ oid.c \ password.c \ signed_data.c signer_info.c \ text.c \ ucs2.c util.c COMMON_PE_SOURCES = wincert.c cms_pe_common.c AUTHVAR_SOURCES = authvar.c authvar_context.c CLIENT_SOURCES = pesign_context.c actions.c client.c EFIKEYGEN_SOURCES = efikeygen.c PESIGCHECK_SOURCES = pesigcheck.c pesigcheck_context.c certdb.c PESIGN_SOURCES = pesign.c pesign_context.c actions.c daemon.c \ file_pe.c file_kmod.c pesign_kmod.c PESUM_SOURCES = pesum.c pesign_context.c actions.c \ file_pe.c file_kmod.c pesign_kmod.c ALL_SOURCES=$(COMMON_SOURCES) $(AUTHVAR_SORUCES) $(CLIENT_SOURCES) \ $(EFIKEYGEN_SOURCES) $(PESIGCHECK_SOURCES) $(PESIGN_SOURCES) \ $(PESUM_SOURCES) -include $(call deps-of,$(ALL_SOURCES)) authvar : $(call objects-of,$(AUTHVAR_SOURCES) $(COMMON_SOURCES)) # authvar : LDLIBS+=$(TOPDIR)/libdpe/libdpe.a authvar : PKGS=efivar nss nspr popt client : $(call objects-of,$(CLIENT_SOURCES) $(COMMON_SOURCES) $(COMMON_PE_SOURCES)) client : LDLIBS+=$(TOPDIR)/libdpe/libdpe.a client : PKGS=efivar nss nspr popt efikeygen : $(call objects-of,$(EFIKEYGEN_SOURCES) $(COMMON_SOURCES)) efikeygen : PKGS=efivar nss nspr popt uuid pesigcheck : $(call objects-of,$(PESIGCHECK_SOURCES) $(COMMON_SOURCES) $(COMMON_PE_SOURCES)) pesigcheck : LDLIBS+=$(TOPDIR)/libdpe/libdpe.a pesigcheck : PKGS=efivar nss nspr popt pesign : $(call objects-of,$(PESIGN_SOURCES) $(COMMON_SOURCES) $(COMMON_PE_SOURCES)) pesign : LDLIBS+=$(TOPDIR)/libdpe/libdpe.a pesign : PKGS=efivar nss nspr popt pesum : $(call objects-of,$(PESUM_SOURCES) $(COMMON_SOURCES) $(COMMON_PE_SOURCES)) pesum : LDLIBS+=$(TOPDIR)/libdpe/libdpe.a pesum : PKGS=efivar nss nspr popt deps : PKGS=efivar nss nspr popt uuid deps : $(ALL_SOURCES) $(MAKE) -f $(TOPDIR)/Make.deps \ SOURCES="$(ALL_SOURCES)" \ PKGS="$(PKGS)" \ deps clean : @rm -rfv $(TARGETS) @$(call removes) install_systemd: pesign.service $(INSTALL) -d -m 755 $(INSTALLROOT)$(libdatadir)tmpfiles.d/ $(INSTALL) -m 644 tmpfiles.conf $(INSTALLROOT)$(libdatadir)tmpfiles.d/pesign.conf $(INSTALL) -d -m 755 $(INSTALLROOT)$(libdatadir)systemd/system/ $(INSTALL) -m 644 pesign.service $(INSTALLROOT)$(libdatadir)systemd/system/ install_sysvinit: pesign.sysvinit $(INSTALL) -d -m 755 $(INSTALLROOT)/etc/rc.d/init.d/ $(INSTALL) -m 755 pesign.sysvinit $(INSTALLROOT)/etc/rc.d/init.d/pesign install : $(INSTALL) -d -m 700 $(INSTALLROOT)/etc/pki/pesign/ $(INSTALL) -d -m 700 $(INSTALLROOT)/etc/pki/pesign-rh-test/ $(INSTALL) -d -m 770 $(INSTALLROOT)$(rundir)pesign/ $(INSTALL) -d -m 755 $(INSTALLROOT)$(bindir) $(INSTALL) -m 755 authvar $(INSTALLROOT)$(bindir) $(INSTALL) -m 755 pesign $(INSTALLROOT)$(bindir) $(INSTALL) -m 755 pesum $(INSTALLROOT)$(bindir) $(INSTALL) -m 755 client $(INSTALLROOT)$(bindir)pesign-client $(INSTALL) -m 755 efikeygen $(INSTALLROOT)$(bindir) $(INSTALL) -m 755 pesigcheck $(INSTALLROOT)$(bindir) $(INSTALL) -d -m 755 $(INSTALLROOT)/etc/popt.d/ $(INSTALL) -m 644 pesign.popt $(INSTALLROOT)/etc/popt.d/ ifeq ($(ENABLE_DOCS), 1) $(INSTALL) -d -m 755 $(INSTALLROOT)$(mandir)man1/ $(INSTALL) -m 644 $(MAN1TARGETS) $(INSTALLROOT)$(mandir)man1/ endif $(INSTALL) -d -m 755 $(INSTALLROOT)/etc/rpm/ $(INSTALL) -m 644 macros.pesign $(INSTALLROOT)/etc/rpm/ $(INSTALL) -d -m 755 $(INSTALLROOT)$(libexecdir)/pesign/ $(INSTALL) -m 755 pesign-rpmbuild-helper $(INSTALLROOT)$(libexecdir)/pesign/ $(INSTALL) -d -m 700 $(INSTALLROOT)/etc/pesign $(INSTALL) -m 600 pesign-users $(INSTALLROOT)/etc/pesign/users $(INSTALL) -m 600 pesign-groups $(INSTALLROOT)/etc/pesign/groups .PHONY: all deps clean install rhboot-pesign-612e96c/src/actions.c000066400000000000000000000233151525324306000172320ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * actions.c - pesign's main actions * Copyright Peter Jones * Copyright Red Hat, Inc. */ #include "fix_coverity.h" #include #include #include #include #include #include #include #include "pesign.h" #include #include #include #include #include #include #include #include static int saw_content; static void handle_bytes(void *arg UNUSED, const char *buf UNUSED, unsigned long len UNUSED) { saw_content = 1; } static PRBool decryption_allowed(SECAlgorithmID *algid UNUSED, PK11SymKey *key UNUSED) { return PR_TRUE; } void insert_signature(cms_context *cms, int signum) { SECItem *sig = &cms->newsig; if (signum == -1) signum = cms->num_signatures; SECItem **signatures = realloc(cms->signatures, sizeof (SECItem *) * (cms->num_signatures + 1)); if (!signatures) { err: cms->log(cms, LOG_ERR, "insert signature: could not allocate memory: %m"); exit(1); } cms->signatures = signatures; if (signum != cms->num_signatures) { memmove(cms->signatures[signum+1], cms->signatures[signum], sizeof(SECItem) * (cms->num_signatures - signum)); } SECItem *newsig = malloc(sizeof (*newsig)); if (!newsig) goto err; memcpy(newsig, sig, sizeof (*newsig)); newsig->data = malloc(sig->len); if (!newsig->data) goto err; memcpy(newsig->data, sig->data, newsig->len); cms->signatures[signum] = newsig; cms->num_signatures++; free(cms->newsig.data); memset(&cms->newsig, '\0', sizeof (cms->newsig)); } int list_signatures(pesign_context *ctx) { cert_iter iter; int rc = cert_iter_init(&iter, ctx->inpe); if (rc < 0) { printf("No certificate list found.\n"); return rc; } void *data; ssize_t datalen; int nsigs = 0; while (1) { rc = next_cert(&iter, &data, &datalen); if (rc <= 0) break; SEC_PKCS7DecoderContext *dc = NULL; saw_content = 0; dc = SEC_PKCS7DecoderStart(handle_bytes, NULL, NULL, NULL, NULL, NULL, decryption_allowed); if (dc == NULL) { fprintf(stderr, "SEC_PKCS7DecoderStart failed\n"); exit(1); } SECStatus status = SEC_PKCS7DecoderUpdate(dc, data, datalen); if (status != SECSuccess) { fprintf(stderr, "Found invalid certificate\n"); continue; } SEC_PKCS7ContentInfo *cinfo = SEC_PKCS7DecoderFinish(dc); if (cinfo == NULL) { fprintf(stderr, "Found invalid certificate\n"); continue; } nsigs++; printf("---------------------------------------------\n"); printf("certificate address is %p\n", data); printf("Content was%s encrypted.\n", SEC_PKCS7ContentIsEncrypted(cinfo) ? "" : " not"); if (SEC_PKCS7ContentIsSigned(cinfo)) { char *signer_cname, *signer_ename; SECItem *signing_time; if (saw_content) { printf("Signature is "); PORT_SetError(0); if (SEC_PKCS7VerifySignature(cinfo, certUsageEmailSigner, PR_FALSE)) { printf("valid.\n"); } else { printf("invalid (Reason: 0x%08x).\n", (uint32_t)PORT_GetError()); } } else { printf("Content is detached; signature cannot " "be verified.\n"); } signer_cname = SEC_PKCS7GetSignerCommonName(cinfo); if (signer_cname != NULL) { printf("The signer's common name is %s\n", signer_cname); PORT_Free(signer_cname); } else { printf("No signer common name.\n"); } signer_ename = SEC_PKCS7GetSignerEmailAddress(cinfo); if (signer_ename != NULL) { printf("The signer's email address is %s\n", signer_ename); PORT_Free(signer_ename); } else { printf("No signer email address.\n"); } signing_time = SEC_PKCS7GetSigningTime(cinfo); if (signing_time != NULL) { char *signing_time_str = DER_TimeChoiceDayToAscii(signing_time); printf("Signing time: %s\n", signing_time_str); PORT_Free(signing_time_str); } else { printf("No signing time included.\n"); } printf("There were%s certs or crls included.\n", SEC_PKCS7ContainsCertsOrCrls(cinfo) ? "" : " no"); SEC_PKCS7DestroyContentInfo(cinfo); } } if (nsigs) { printf("---------------------------------------------\n"); } else { printf("No signatures found.\n"); } return rc; } static const char *sig_begin_marker ="-----BEGIN AUTHENTICODE SIGNATURE-----\n"; static const char *sig_end_marker = "\n-----END AUTHENTICODE SIGNATURE-----\n"; void export_pubkey(pesign_context *p_ctx) { cms_context *ctx = p_ctx->cms_ctx; int rc; SECItem derPublicKey = ctx->cert->derPublicKey; rc = write(p_ctx->outkeyfd, derPublicKey.data, derPublicKey.len); close(p_ctx->outkeyfd); if (rc >= 0 && (unsigned long)rc == derPublicKey.len) exit(0); exit(1); } void export_cert(pesign_context *p_ctx) { cms_context *ctx = p_ctx->cms_ctx; int rc; SECItem derCert = ctx->cert->derCert; rc = write(p_ctx->outcertfd, derCert.data, derCert.len); close(p_ctx->outcertfd); if (rc >= 0 && (unsigned long)rc == derCert.len) exit(0); exit(1); } ssize_t export_signature(cms_context *cms, int fd, int ascii_armor) { ssize_t ret = 0; int rc = 0; SECItem *sig = &cms->newsig; unsigned char *data = sig->data; int datalen = sig->len; if (ascii_armor) { char *ascii = BTOA_DataToAscii(data, datalen); if (!ascii) { cms->log(cms, LOG_ERR, "error exporting signature"); failure: close(fd); return -1; } rc = write(fd, sig_begin_marker, strlen(sig_begin_marker)); if (rc < 0) { cms->log(cms, LOG_ERR, "error exporting signature: %m"); goto failure; } ret += rc; rc = write(fd, ascii, strlen(ascii)); if (rc < 0) { cms->log(cms, LOG_ERR, "error exporting signature: %m"); goto failure; } ret += rc; rc = write(fd, sig_end_marker, strlen(sig_end_marker)); if (rc < 0) { cms->log(cms, LOG_ERR, "error exporting signature: %m"); goto failure; } ret += rc; PORT_Free(ascii); } else { rc = write(fd, data, datalen); if (rc < 0) { cms->log(cms, LOG_ERR, "error exporting signature: %m"); goto failure; } ret += rc; } return ret; } void parse_signature(pesign_context *ctx) { int rc; char *sig; size_t siglen = 0; rc = read_file(ctx->insigfd, &sig, &siglen); if (rc < 0) liberr(1, "pesign: could not read signature"); unsigned char *der; unsigned int derlen; /* XXX FIXME: ignoring length for now */ char *base64 = strstr(sig, sig_begin_marker); if (base64) { base64 += strlen(sig_begin_marker); char *end = strstr(base64, sig_end_marker); if (!end) liberr(1, "pesign: Invalid signature"); derlen = end - base64; base64[derlen] = '\0'; unsigned char *dertmp; dertmp = ATOB_AsciiToData(base64, &derlen); der = xcalloc(1, derlen); memmove(der, dertmp, derlen); PORT_Free(dertmp); } else { der = xcalloc(1, siglen); memmove(der, sig, siglen); derlen = siglen; } free(sig); ctx->cms_ctx->newsig.data = der; ctx->cms_ctx->newsig.len = derlen; #if 0 SEC_PKCS7DecoderContext *dc = NULL; saw_content = 0; dc = SEC_PKCS7DecoderStart(handle_bytes, NULL, NULL, NULL, NULL, NULL, decryption_allowed); if (dc == NULL) { decoder_error: fprintf(stderr, "pesign: Invalid signature.\n"); PORT_Free(der); exit(1); } SECStatus status = SEC_PKCS7DecoderUpdate(dc, (char *)der, derlen); if (status != SECSuccess) goto decoder_error; SEC_PKCS7ContentInfo *cinfo = SEC_PKCS7DecoderFinish(dc); if (!cinfo) goto decoder_error; ctx->cinfo = cinfo; PORT_Free(der); #endif } void import_raw_signature(pesign_context *pctx) { if (pctx->rawsigfd < 0 || pctx->insattrsfd < 0) { fprintf(stderr, "pesign: raw signature and signed attributes " "must both be imported.\n"); exit(1); } cms_context *ctx = pctx->cms_ctx; ctx->raw_signature = SECITEM_AllocItem(ctx->arena, NULL, 0); ctx->raw_signature->type = siBuffer; int rc = read_file(pctx->rawsigfd, (char **)&ctx->raw_signature->data, (size_t *)&ctx->raw_signature->len); if (rc < 0) { fprintf(stderr, "pesign: could not read raw signature: %m\n"); exit(1); } ctx->raw_signed_attrs = SECITEM_AllocItem(ctx->arena, NULL, 0); ctx->raw_signed_attrs->type = siBuffer; rc = read_file(pctx->insattrsfd, (char **)&ctx->raw_signed_attrs->data, (size_t *)&ctx->raw_signed_attrs->len); if (rc < 0) { fprintf(stderr, "pesign: could not read raw signed attributes" ": %m\n"); exit(1); } } int generate_sattr_blob(pesign_context *ctx) { int rc; SECItem sa; SpcContentInfo ci; memset(&ci, '\0', sizeof (ci)); rc = generate_spc_content_info(ctx->cms_ctx, &ci); if (rc < 0) { fprintf(stderr, "Could not generate content info: %s\n", PORT_ErrorToString(PORT_GetError())); exit(1); } rc = generate_signed_attributes(ctx->cms_ctx, &sa); if (rc < 0) { fprintf(stderr, "Could not generate signed attributes: %s\n", PORT_ErrorToString(PORT_GetError())); exit(1); } return write(ctx->outsattrsfd, sa.data, sa.len); } void check_signature_space(pesign_context *ctx) { ssize_t available = available_cert_space(ctx->outpe); ssize_t target = ctx->cms_ctx->newsig.len + sizeof (win_certificate_header_t); target += ALIGNMENT_PADDING(target, 8); if (available >= target) return; fprintf(stderr, "Could not add new signature: insufficient space.\n"); exit(1); } void allocate_signature_space(Pe *pe, ssize_t sigspace) { int rc; rc = pe_alloccert(pe, sigspace); if (rc < 0) { fprintf(stderr, "Could not allocate space for signature: %m\n"); exit(1); } } void remove_signature(pesign_context *p_ctx) { cms_context *ctx = p_ctx->cms_ctx; free(ctx->signatures[p_ctx->signum]->data); free(ctx->signatures[p_ctx->signum]); if (p_ctx->signum != ctx->num_signatures - 1) memmove(&ctx->signatures[p_ctx->signum], &ctx->signatures[p_ctx->signum+1], sizeof(SECItem*) * (ctx->num_signatures - p_ctx->signum - 1)); ctx->num_signatures--; } rhboot-pesign-612e96c/src/actions.h000066400000000000000000000016251525324306000172370ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * actions.h - helpers for our high-level actions * Copyright Peter Jones * Copyright Red Hat, Inc. */ #ifndef PESIGN_CRYPTO_H #define PESIGN_CRYPTO_H 1 #include #include #include "wincert.h" extern int list_signatures(pesign_context *ctx); extern void check_signature_space(pesign_context *ctx); extern void allocate_signature_space(Pe *pe, ssize_t sigspace); extern ssize_t export_signature(cms_context *cms, int fd, int ascii_armor); extern void import_raw_signature(pesign_context *pctx); extern void remove_signature(pesign_context *ctx); extern void export_pubkey(pesign_context *ctx); extern void export_cert(pesign_context *ctx); extern int generate_sattr_blob(pesign_context *pctx); extern void parse_signature(pesign_context *ctx); extern void insert_signature(cms_context *cms, int signum); #endif /* PESIGN_CRYPTO_H */ rhboot-pesign-612e96c/src/authvar.1.mdoc000066400000000000000000000045451525324306000201070ustar00rootroot00000000000000.Dd $Mdocdate: Jun 4 2020$ .Dt AUTHVAR 1 .Os Linux .Sh NAME .Nm authvar .Nd handles authenticated variables for pesign .Sh SYNOPSIS .Nm .Bk -words .Ao .Fl a | .Fl c | .Fl s .Ac .Ek .Bk -words .Cm Fl N Ar {guid} .Cm Fl n Ar name .Ek .Bk -words .Ao .Fl v Ar value | .Fl f Ar file .Ac .Ek .Bk -words .Op Fl t Ar time .Op Fl d Ar directory .Op Fl S Ar nickname .Op Fl i Ar file .Op Fl e Ar file .Ek .Sh DESCRIPTION .Nm is a command line utility for handling authenticated UEFI variables. .Sh OPTIONS .Bl -tag .It Fl a | Fl Fl append Append to variable .It Fl c | Fl Fl clear Clear variable .It Fl s | Fl Fl set set variable .It Fl N Ao {guid} | namespace Ac | Fl Fl namespace Ao {guid} | namespace Ac Variable is in .Ar namespace or .Ar {guid} .Po default: .Pa global .Pc Use .Fl N Ar help to list namespaces. .It Fl n Ar name | Fl Fl name Ar name Variable .Ar name .It Fl v Ar value | Fl Fl value Ar value Set or append .Ar value to variable .It Fl f Ar file | Fl Fl valuefile Ar file Read value from .Ar file .It Fl t Ar time | Fl Fl timestamp Ar time Timestamp for the variable .Po default: .Pa now .Pc .It Fl d Ar directory | Fl Fl certdir Ar directory Specify nss certificate database .Ar directory .Po default: .Pa /etc/pki/pesign .Pc .It Fl S Ar nickname | Fl Fl sign Ar nickname Sign variable with certificate .Ar nickname from the NSS database .It Fl i Ar file | Fl Fl import Ar file Import variable from .Ar file .It Fl e Ar file | Fl Fl export Ar file Export variable to .Ar file instead of setting it in firmware .Sh STANDARDS .Rs .%A B. Kaliski .%R RFC 2315 .%B PKCS #7: Cryptographic Message Syntax v1.5 .%I Internet Engineering Task Force .%D March 1998 .%U https://tools.ietf.org/html/rfc2315\ \& .Re .Rs .%A K. Moriarty .%A M. Nyström .%A S. Parkinson .%A A. Rusch .%A M. Scott .%R RFC 7292 .%B PKCS #12: Personal Information Exchange Syntax v1.1 .%I Internet Engineering Task Force .%D July 2014 .%U https://tools.ietf.org/html/rfc7292\ \& .Re .Rs .%A PKCS11 Technical Committee .%B PKCS#11: Cryptographic Token Interface Standard .%I OASIS .%U https://www.cryptsoft.com/pkcs11doc/\ \& .Re .Rs .%A UEFI Specification Working Group .%B Unified Extensible Firmware Interface (UEFI) Specification Version 2.8 .%I Unified Extensible Firmware Interface Forum .%D March 2019 .%U https://uefi.org/specifications\ \& .Re .Sh "SEE ALSO" .Xr pesign 1 , .Xr certutil 1 .Sh AUTHORS .An Peter Jones rhboot-pesign-612e96c/src/authvar.c000066400000000000000000000277101525324306000172470ustar00rootroot00000000000000// SPDX-License-Identifier: GPLv2 /* * authvar.c - main entry for the authvar utility * Copyright Peter Jones * Copyright Red Hat, Inc. */ #include "fix_coverity.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "authvar.h" #define NO_FLAGS 0x00 #define GENERATE_APPEND 0x01 #define GENERATE_CLEAR 0x02 #define GENERATE_SET 0x04 #define SIGN 0x08 #define IMPORT 0x10 #define EXPORT 0x20 #define SET 0x40 #define SHOW_SIGNATURE_SUPPORT 0x80 #define FLAG_LIST_END 0x100 static struct { int flag; const char *name; } flag_names[] = { {GENERATE_APPEND, "append" }, {GENERATE_CLEAR, "clear" }, {GENERATE_SET, "set" }, {SIGN, "sign" }, {IMPORT, "import" }, {EXPORT, "export" }, {SET, "set_firmware" }, {FLAG_LIST_END, NULL }, }; static void print_flag_name(FILE *f, int flag) { for (int i = 0; flag_names[i].flag != FLAG_LIST_END; i++) { if (flag_names[i].flag & flag) fprintf(f, "%s ", flag_names[i].name); } } static void check_name(authvar_context *ctx) { conderrx(!ctx->name || !*ctx->name, 1, "no name specified."); } static void check_value(authvar_context *ctx, int needed) { if ((!ctx->value || !*ctx->value) && (!ctx->valuefile || !*ctx->valuefile)) { if (needed) warnx("no value specified."); else return; exit(1); } if (ctx->value && *ctx->value && ctx->valuefile && *ctx->valuefile) { conderrx(needed, 1, "--value and --valuefile cannot be used together."); errx(1, "command does not take a value."); } if (ctx->value) { ctx->value_size = strlen(ctx->value); } } static void open_input(authvar_context *ctx) { struct stat sb; int rc; if (!ctx->valuefile) return; ctx->valuefd = open(ctx->valuefile, O_RDONLY|O_CLOEXEC); conderr(ctx->valuefd < 0, 1, "Error opening valuefile"); rc = fstat(ctx->valuefd, &sb); conderr(rc < 0, 1, "Error mapping valuefile"); ctx->value_size = sb.st_size; ctx->value = (char *)mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, ctx->valuefd, 0); conderr(ctx->value == MAP_FAILED, 1, "Error mapping valuefile"); } #define EFIVAR_DIR "/sys/firmware/efi/efivars/" static void generate_efivars_filename(authvar_context *ctx) { char *guid = NULL; int rc = efi_guid_to_str(&ctx->guid, &guid); conderr(rc < 0, 1, "Couldn't convert guid to string"); char *filename = NULL; rc = asprintf(&filename, "/sys/firmware/efi/efivars/%s-%s", ctx->name, guid); conderr(rc < 0, 1, "can't make string"); free(guid); ctx->exportfile = filename; } static void open_output(authvar_context *ctx) { int flags; mode_t mode; if (!ctx->exportfile) { generate_efivars_filename(ctx); ctx->to_firmware = 1; } else if (access(ctx->exportfile, F_OK) == 0) { errx(1, "\"%s\" exists", ctx->exportfile); } flags = O_CREAT|O_RDWR|O_CLOEXEC; mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH; ctx->exportfd = open(ctx->exportfile, flags, mode); conderr(ctx->exportfd < 0, 1, "Error opening exportfile"); } static int find_namespace_guid(authvar_context *ctx) { int rc; efi_guid_t guid; rc = efi_name_to_guid(ctx->namespace, &guid); if (rc < 0) return rc; memcpy(&ctx->guid, &guid, sizeof (guid)); return 0; } static void set_timestamp(authvar_context *ctx, const char *time_str) { time_t t; struct tm tm; memset(&tm, 0, sizeof(struct tm)); if (time_str) { /* Accept the string like "2001-11-12 18:31:01" */ strptime(time_str, "%Y-%m-%d %H:%M:%S", &tm); } else { time(&t); gmtime_r(&t, &tm); } ctx->timestamp.year = tm.tm_year + 1900; ctx->timestamp.month = tm.tm_mon + 1; ctx->timestamp.day = tm.tm_mday; ctx->timestamp.hour = tm.tm_hour; ctx->timestamp.minute = tm.tm_min; ctx->timestamp.second = tm.tm_sec; ctx->timestamp.pad1 = 0; ctx->timestamp.nanosecond = 0; ctx->timestamp.timezone = 0; ctx->timestamp.daylight = 0; ctx->timestamp.pad2 = 0; } static int show_signature_support(void) { int rc; uint8_t *data = NULL; size_t data_size = 0; uint32_t attrs = 0; efi_guid_t *guids; rc = efi_get_variable(efi_guid_global, "SignatureSupport", &data, &data_size, &attrs); if (rc < 0) { warn("Could not read \"SignatureSupport\" variable"); return rc; } if (data_size == 0) return 0; if (data_size % sizeof(efi_guid_t) != 0) { warnx("Invalid size %zd for \"SignatureSupport\" variable", data_size); errno = EINVAL; return -1; } guids = (efi_guid_t *)data; for (size_t i = 0; i < data_size / sizeof(efi_guid_t); i++) { char *id_guid = NULL; rc = efi_guid_to_id_guid(&guids[i], &id_guid); if (rc < 0) continue; printf("%s\n", id_guid); free(id_guid); } free(data); return 0; } static long *verbose; long verbosity(void) { if (!verbose) return 0; return *verbose; } int main(int argc, char *argv[]) { int rc; authvar_context ctx = { 0, }; authvar_context *ctxp = &ctx; char *time_str = NULL; char *tokenname = "NSS Certificate DB"; char *origtoken = tokenname; char *certdir = "/etc/pki/pesign"; SECStatus status; int action = 0; setenv("NSS_DEFAULT_DB_TYPE", "sql", 0); rc = authvar_context_init(ctxp); conderr(rc < 0, 1, "Could not initialize context"); poptContext optCon; struct poptOption options[] = { {.argInfo = POPT_ARG_INTL_DOMAIN, .arg = "pesign" }, {.longName = "append", .shortName = 'a', .argInfo = POPT_ARG_VAL|POPT_ARGFLAG_OR, .arg = &action, .val = GENERATE_APPEND, .descrip = "append to variable" }, {.longName = "certdir", .shortName = 'd', .argInfo = POPT_ARG_STRING|POPT_ARGFLAG_SHOW_DEFAULT, .arg = &certdir, .descrip = "specify nss certificate database directory", .argDescrip = "" }, {.longName = "clear", .shortName = 'c', .argInfo = POPT_ARG_VAL|POPT_ARGFLAG_OR, .arg = &action, .val = GENERATE_CLEAR, .descrip = "clear variable" }, {.longName = "set", .shortName = 's', .argInfo = POPT_ARG_VAL|POPT_ARGFLAG_OR, .arg = &action, .val = GENERATE_SET, .descrip = "set variable" }, {.longName = "namespace", .shortName = 'N', .argInfo = POPT_ARG_STRING|POPT_ARGFLAG_SHOW_DEFAULT, .arg = &ctx.namespace, .descrip = "specified variable is in or " , .argDescrip = "{|}" }, {.longName = "list-supported-sigs", .shortName = 'l', .argInfo = POPT_ARG_VAL|POPT_ARGFLAG_OR, .arg = &action, .val = SHOW_SIGNATURE_SUPPORT, .descrip = "list supported signature types" }, {.longName = "guid", .shortName = 'g', .argInfo = POPT_ARG_STRING|POPT_ARGFLAG_DOC_HIDDEN, .arg = &ctx.namespace, .descrip = "specified variable is in or ", .argDescrip = "{|}" }, {.longName = "name", .shortName = 'n', .argInfo = POPT_ARG_STRING, .arg = &ctx.name, .descrip = "variable name", .argDescrip = "" }, {.longName = "token", .shortName = 'T', .argInfo = POPT_ARG_STRING|POPT_ARGFLAG_SHOW_DEFAULT, .arg = &tokenname, .descrip = "NSS token holding signing key", .argDescrip = "", }, {.longName = "timestamp", .shortName = 't', .argInfo = POPT_ARG_STRING, .arg = &time_str, .descrip = "timestamp for the variable", .argDescrip = "