diff --git a/.gitignore b/.gitignore index 90a3288..3ed7656 100644 --- a/.gitignore +++ b/.gitignore @@ -1,18 +1,24 @@ *.iso *.ird *.gz +*.db +*.zip +*.rar PS3_GAME/ PS3_UPDATE/ PS3_DISC.SFB +*/PS3_GAME +*/PS3_UPDATE +*PS3_DISC.SFB + tools/keys/* tools/*/* tools/*.db tools/*.dat -libra/data/*.db -*.db +libray/data/*.db # Byte-compiled / optimized / DLL files __pycache__/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..d4a6357 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,37 @@ +# LibRay — Agent Quick Reference +# Important +Make sure to use the virtual environment in `~/.venv/libray` (activate with `source ~/.venv/libray/bin/activate`) and not global pip. + +## Repo +- Python 3 CLI tool for decrypting/encrypting/examining PS3 Blu-Ray ISOs +- Entry point: `libray/libray.py` (defines `main()`); installed console script is `libray=libray.libray:main` (see `setup.py`). `libray/libray` is a symlink to `libray.py` for running from a source checkout. +- Package: `libray/` — modules: `core.py` (main logic), `iso.py` (ISO parsing), `ird.py` (IRD parsing), `sfo.py` (PARAM.SFO) +- Tests: `tests/` — `test_iso.py`, `test_interface.py` (interface test is currently skipped/broken) +- Tools: `tools/keys2db.py` (builds `libray/data/keys.db` from redump keys), `tools/rpcs3.py` (fetches compat data) + +## Commands +- Install deps: `pip install -r requirements.txt` +- Run tests: `python -m unittest discover -b` +- Build sdist + wheel: `python3 setup.py sdist bdist_wheel` +- Publish: `twine upload dist/*` + +## Parallelization +- Decrypt and re-encrypt support multiprocessing via `-p`/`--threads` CLI argument +- Default: auto-detects CPU core count via `os.cpu_count()` +- Each sector is independently decrypted (per-sector IV in AES-CBC), making it embarrassingly parallel +- Uses `concurrent.futures.ProcessPoolExecutor` — true multi-core parallelism by spawning OS processes +- Each process gets its own Python interpreter (own GIL), so pycryptodome's partial GIL release is irrelevant +- Unencrypted regions are always copied sequentially (no crypto needed) +- Module-level `_process_sector_chunk_mp()` function is picklable for use with ProcessPoolExecutor; it processes a contiguous run of sectors per task to amortise IPC cost +- A bounded window of chunks is kept in flight (memory stays bounded for large ISOs); results are written back to their absolute offsets in the output file as they complete + +## Gotchas +- **Crypto package conflict**: `pycrypto`/`crypto` will break `pycryptodome`. If `ImportError: No module named Crypto.Cipher`, run: + ``` + pip uninstall crypto pycrypto && pip install pycryptodome + ``` +- **keys.db is generated**, not committed. Build it with `python3 tools/keys2db.py` (requires keys in `tools/keys/`). It's listed in `.gitignore` via `libray/data/*.db`. +- **`libray/__init__.py`** dynamically imports submodules via `pkgutil.walk_packages` + `importlib.import_module` (skips the `libray` entry-point module to avoid shadowing the package) — don't expect explicit imports. +- **`test_interface.py`** is skipped (`@unittest.skip('currently broken')`) — the interface test won't run. +- `.editorconfig` enforces 4-space indent for `.py`, 2-space for `.yml`/`.yaml`. +- No linting/typechecking config exists — plain `unittest`, no pytest, no pre-commit. diff --git a/CHANGELOG.md b/CHANGELOG.md index 69a39d6..22cd21a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,45 @@ All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). +## [0.0.10] - 2024-03-07 + +### Fixed +- Issue #17: find_module removed in Python 3.12, replaced with find_spec + +### Added +- PR #14: Add tests +- PR #14: Add option to calculate CRC32 with -c / --checksum +- Add --info for both -i and -k. Will print info about either .iso or .ird. +- Added title_id to keys.db + +### Changed +- PR #14: Reworked disc-key lookup logic +- Added searching for title_id to disc-key lookup logic + +## [0.0.9] - 2022-02-19 +### Fixed +- Issue #11: fix read_regions bug which caused incorrect encryption/decryption + +### Changed +- A little more lenient requirements using ~= + +## [0.0.8] - 2021-11-27 +### Fixed +- Issue #7: fix manually supplied .ird files not being used. + +## [0.0.7] - 2021-06-29 +### Added +- PARAM.SFO reader (sfo.py) +- Now searches for PARAM.SFO first and uses game title from there instead of crc32. +- To identify keys, checks if .iso has a unique size, then if it has the name from PARAM.SFO in it + size, then downloads .ird +- long_description in setup.py for description on PyPI + +### Changed +- Multiman styling by default if PARAM.SFO is found + +### Removed +- No longer checks crc32, see Added. Might re-add as last fallback later. + ## [0.0.6] - 2021-06-05 ### Fixed - Issue #6: fix decrypting using disc key not working diff --git a/LICENSE.txt b/LICENSE.txt deleted file mode 120000 index d24842f..0000000 --- a/LICENSE.txt +++ /dev/null @@ -1 +0,0 @@ -COPYING \ No newline at end of file diff --git a/LICENSE.txt b/LICENSE.txt new file mode 100644 index 0000000..810fce6 --- /dev/null +++ b/LICENSE.txt @@ -0,0 +1,621 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS diff --git a/PKG-INFO b/PKG-INFO new file mode 100644 index 0000000..bc3db7b --- /dev/null +++ b/PKG-INFO @@ -0,0 +1,204 @@ +Metadata-Version: 2.1 +Name: libray +Version: 0.0.10 +Summary: A Libre (FLOSS) Python application for unencrypting, extracting, repackaging, and encrypting PS3 ISOs +Home-page: https://notabug.org/necklace/libray +Author: Nichlas Severinsen +Author-email: ns@nsz.no +Description-Content-Type: text/markdown +License-File: LICENSE.txt +License-File: COPYING +Requires-Dist: tqdm~=4.66.2 +Requires-Dist: pycryptodome~=3.20.0 +Requires-Dist: requests~=2.31.0 +Requires-Dist: beautifulsoup4~=4.12.3 +Requires-Dist: html5lib~=1.1 +Requires-Dist: setuptools~=69.1.1 + +# Libray + +Libray: A portmanteau of Libre and Blu-Ray + +Libray aims to be a Libre (FLOSS) Python application for unencrypting, +extracting, repackaging, and encrypting PS3 ISOs. + +A hackable, crossplatform, alternative to ISOTools and ISO-Rebuilder. + +## How to install + +Note: You will need Python 3, so you might want to use `python3` and `pip3` instead of `python` and `pip` depending on your system. + +### From PyPi: + +1. `sudo pip install libray` + +### Manually: + +1. Clone this repository ```git clone https://notabug.org/necklace/libray``` + +2. Install dependencies with ```sudo pip install -r requirements.txt``` + +3. Run ```sudo python setup.py install``` + +### From AUR: + +For Arch or Arch-based GNU/Linux distributions there's an option to [install libray from the AUR](https://aur.archlinux.org/packages/libray-git/) (Arch User Repository). + +You will need an [AUR helper](https://wiki.archlinux.org/index.php/AUR_helpers) (of which there are many). + +Then you will need to run the appropriate install command for that AUR helper using `libray` as package name. + +This will essentially automatically do the manual method for you. + +### With pipx: + +- PyPi version: `pipx install libray` + +### Done! + +`libray` is now installed to your path. + +## How do I use it? + +``` +usage: libray [-h] (-i ISO | -k IRD) [-o OUTPUT] [-d DECRYPTION_KEY] [-v] [-q] [-r] [-c] [-t CHECKSUM_TIMEOUT] [--info] + +A Libre (FLOSS) Python application for unencrypting, extracting, repackaging, and encrypting PS3 ISOs + +options: + -h, --help show this help message and exit + -i ISO, --iso ISO Path to .iso file or stream + -k IRD, --ird IRD Path to .ird file + +optional arguments: + -o OUTPUT, --output OUTPUT + Output filename + -d DECRYPTION_KEY, --decryption-key DECRYPTION_KEY + Manually specify key + -v, --verbose Increase verbosity + -q, --quiet Quiet mode, only prints on error + -r, --re-encrypt Re-encrypt .iso + -c, --checksum Allow fallback to CRC32 checksum (disabled by default) + -t CHECKSUM_TIMEOUT, --checksum-timeout CHECKSUM_TIMEOUT + How many seconds to wait for CRC32 checksum (default 15) + --info Print info about .iso or .ird, then quit. +``` + +First off, even before you install libray, you will need a compatible Blu-Ray drive that can read PS3 discs. + +There's a compiled list of compatible drives here: [https://rpcs3.net/quickstart](https://rpcs3.net/quickstart#compatible_drives) ([archive](https://web.archive.org/web/20190801060739/https://rpcs3.net/quickstart])) (see "Compatible Blu-ray disc drives section"). + +### 1. Decrypt + +On some systems (eg. Linux), you can decrypt directly from the disc: + +``` +libray -i /dev/sr0 -o ps3_game_decrypted.iso +``` + +Libray is bundled with redump keys and will automatically try to decrypt the .iso if it finds a compatible key. If not, it will try to download an IRD decryption file for your iso. If you don't have internet connection, but you do have an .ird file you can specify that: + +``` +libray -i /dev/sr0 -k game_ird_file.ird -o ps3_game_decrypted.iso +``` + +Alternatively, you can first rip the disc to an ISO file and then decrypt from the ISO file: + +``` +libray -i ps3_game.iso -o ps3_game_decrypted.iso +``` + +If libray is unable to download an .ird for your game, you could manually give it the key, if you have it: + +``` +libray -i ps3_game.iso -d DECRYPTION_KEY -o ps3_game_decrypted.iso +``` + +### 2. Extract decrypted ISO + +Then, if you want to feed it into RPCS3 just extract the contents of the .ISO: + +``` +7z x nfs_ps3_decrypted.iso +``` + +And move the resulting folders into a folder named after the game ID into the appropriate folder for RPCS3, for example: + +- Linux: /home/username/.config/rpcs3/dev_hdd0/disc/BLUS0000 +- macOS: ~/Library/Application Support/rpcs3/dev_hdd0/disc/BLUS0000 + +### 3. (Optional) Print info about .iso or .ird: + +Get info from .iso without decrypting + +``` +libray -i ps3_game.iso --info +``` + +Get info from .ird + +``` +libray -k game_ird_file.ird --info +``` + +## License + +This project is Free, Libre, and Open Source Software; FLOSS, licensed under the GNU General Public License version 3. GPLv3. + +See also COPYING or LICENSE.txt + +Copyright © 2018 - 2024 Nichlas Severinsen + +## Error! + +Help! I get + +> ImportError: No module named Crypto.Cipher + +or + +> ImportError: cannot import name 'byte_string' from 'Crypto.Util.py3compat' (/usr/lib/python3.7/site-packages/Crypto/Util/py3compat.py) + +This is due to multiple similarly named python crypto packages, one way to fix it is: + +``` +sudo pip uninstall crypto +sudo pip uninstall pycrypto +sudo pip install pycryptodome +``` + +If you get any other errors, or have any other problem with libray, please [create an issue](https://notabug.org/necklace/libray/issues/new)! + +## Development + +[Bluray disc encryption](http://www.psdevwiki.com/ps3/Bluray_disc#Encryption) ([archive.fo](https://archive.fo/hN1E6)) + +[.SFO](https://www.psdevwiki.com/ps3/PARAM.SFO) ([archive.fo](https://archive.fo/HLJZG)) + +[TITLE_ID for Physical Media](https://www.psdevwiki.com/ps3/Template:TITLE_ID_for_Physical_Media) ([archive.fo](https://archive.fo/R8tCz)) + +[7bit encoded int / RLE / CLP](https://github.com/microsoft/referencesource/blob/1acafe20a789a55daa17aac6bb47d1b0ec04519f/mscorlib/system/io/binaryreader.cs#L582-L600) + +clp = compressed length prefix + +## Tests + +`python -m unittest discover -b` + +## Deployment + +0. `pip3 install wheel twine` +1. Place redump keys in tools/keys and .dat in tools/ +2. Run keys2db.py, ensure it made a file in libray/data/keys.db +3. Run `python3 setup.py sdist bdist_wheel` +4. Run `twine upload dist/*` + +## Todo + +- Extract ISO (currently doable with `7z x output.iso`) +- Repackage (unextract) iso +- Test .irds with version < 9 +- Custom command to backup all irds available +- Unit tests +- Download .irds from vimm.net? +- Parallelization? diff --git a/README.md b/README.md index db8e5ff..047dfbf 100644 --- a/README.md +++ b/README.md @@ -1,14 +1,12 @@ -# LibRay +# Libray -LibRay: A portmanteau of Libre and Blu-Ray +Libray: A portmanteau of Libre and Blu-Ray -LibRay aims to be a Libre (FLOSS) Python application for unencrypting, +Libray aims to be a Libre (FLOSS) Python application for unencrypting, extracting, repackaging, and encrypting PS3 ISOs. A hackable, crossplatform, alternative to ISOTools and ISO-Rebuilder. -**Note: this is still a very beta project, report any bug you see!** - ## How to install Note: You will need Python 3, so you might want to use `python3` and `pip3` instead of `python` and `pip` depending on your system. @@ -35,6 +33,10 @@ Then you will need to run the appropriate install command for that AUR helper us This will essentially automatically do the manual method for you. +### With pipx: + +- PyPi version: `pipx install libray` + ### Done! `libray` is now installed to your path. @@ -42,22 +44,27 @@ This will essentially automatically do the manual method for you. ## How do I use it? ``` -usage: libray [-h] -i ISO [-o OUTPUT] [-k IRD] [-d DECRYPTION_KEY] [-v] [-q] [-r] +usage: libray [-h] (-i ISO | -k IRD) [-o OUTPUT] [-d DECRYPTION_KEY] [-v] [-q] [-r] [-c] [-t CHECKSUM_TIMEOUT] [--info] A Libre (FLOSS) Python application for unencrypting, extracting, repackaging, and encrypting PS3 ISOs -required arguments: +options: + -h, --help show this help message and exit -i ISO, --iso ISO Path to .iso file or stream + -k IRD, --ird IRD Path to .ird file optional arguments: -o OUTPUT, --output OUTPUT Output filename - -k IRD, --ird IRD Path to .ird file -d DECRYPTION_KEY, --decryption-key DECRYPTION_KEY Manually specify key -v, --verbose Increase verbosity -q, --quiet Quiet mode, only prints on error -r, --re-encrypt Re-encrypt .iso + -c, --checksum Allow fallback to CRC32 checksum (disabled by default) + -t CHECKSUM_TIMEOUT, --checksum-timeout CHECKSUM_TIMEOUT + How many seconds to wait for CRC32 checksum (default 15) + --info Print info about .iso or .ird, then quit. ``` First off, even before you install libray, you will need a compatible Blu-Ray drive that can read PS3 discs. @@ -98,9 +105,24 @@ Then, if you want to feed it into RPCS3 just extract the contents of the .ISO: 7z x nfs_ps3_decrypted.iso ``` -And move the resulting folders into a folder named after the game ID into the appropriate folder for RPCS3: +And move the resulting folders into a folder named after the game ID into the appropriate folder for RPCS3, for example: - Linux: /home/username/.config/rpcs3/dev_hdd0/disc/BLUS0000 +- macOS: ~/Library/Application Support/rpcs3/dev_hdd0/disc/BLUS0000 + +### 3. (Optional) Print info about .iso or .ird: + +Get info from .iso without decrypting + +``` +libray -i ps3_game.iso --info +``` + +Get info from .ird + +``` +libray -k game_ird_file.ird --info +``` ## License @@ -108,7 +130,7 @@ This project is Free, Libre, and Open Source Software; FLOSS, licensed under the See also COPYING or LICENSE.txt -Copyright © 2018 - 2021 Nichlas Severinsen +Copyright © 2018 - 2024 Nichlas Severinsen ## Error! @@ -132,14 +154,23 @@ If you get any other errors, or have any other problem with libray, please [crea ## Development -[see also](http://www.psdevwiki.com/ps3/Bluray_disc#Encryption) ([archive.fo](https://archive.fo/hN1E6)) +[Bluray disc encryption](http://www.psdevwiki.com/ps3/Bluray_disc#Encryption) ([archive.fo](https://archive.fo/hN1E6)) + +[.SFO](https://www.psdevwiki.com/ps3/PARAM.SFO) ([archive.fo](https://archive.fo/HLJZG)) + +[TITLE_ID for Physical Media](https://www.psdevwiki.com/ps3/Template:TITLE_ID_for_Physical_Media) ([archive.fo](https://archive.fo/R8tCz)) [7bit encoded int / RLE / CLP](https://github.com/microsoft/referencesource/blob/1acafe20a789a55daa17aac6bb47d1b0ec04519f/mscorlib/system/io/binaryreader.cs#L582-L600) clp = compressed length prefix -## Building and Deployment +## Tests +`python -m unittest discover -b` + +## Deployment + +0. `pip3 install wheel twine` 1. Place redump keys in tools/keys and .dat in tools/ 2. Run keys2db.py, ensure it made a file in libray/data/keys.db 3. Run `python3 setup.py sdist bdist_wheel` diff --git a/app.yaml b/app.yaml index 9f602d5..ba452f6 100644 --- a/app.yaml +++ b/app.yaml @@ -1,9 +1,13 @@ libraries: -- name: pycrypto - version: "2.6.1" +- name: pycryptodome + version: "3.20.0" - name: tqdm - version: "4.23.4" + version: "4.66.2" - name: requests - version: "2.19.1" + version: "2.31.0" - name: beautifulsoup4 - version: "4.6.0" + version: "4.12.3" +- name: html5lib + version: "1.1" +- name: setuptools + version: "69.1.1" diff --git a/docs/.gitignore b/docs/.gitignore new file mode 100644 index 0000000..756b22f --- /dev/null +++ b/docs/.gitignore @@ -0,0 +1 @@ +*.svg diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..aba91ce --- /dev/null +++ b/docs/README.md @@ -0,0 +1,53 @@ +# LibRay 1.0.0 Specification + +**Note** +This specification has not been implemented yet. + +**Note** +Work in progress. + +## User interaction + +Here is a flow diagram to explain the different ways a user can interact with LibRay: + +![LiBray flow][flow] + +As you can see there are three main routes: + +1. The user has a key (in hex) +2. The user has an .ird +3. The user has nothing + +It is assumed that no. 3 is the most common way to use LibRay, simply give it your .iso file and let LibRay decrypt it. + + +## Database + +LiBray bundles a database containing two tables: + +- ird: containing parsed data from various .ird dumps +- redump: containing parsed data from redump + +![LibRay DB tables][tables] + + +## Dependencies + +- crypto: `pycryptodomex` +- progressbar: `tqdm` +- http/https: `requests` +- html: `beautifulsoup4` + +In previous versions there were problems where dependencies interfered with eachother (notably, `crypto` vs `pycrypto` vs `pycryptodome`), so 1.0.0 and above uses `pycryptodomex` which is standalone from the previously mentioned packages. + +## Packaging + +- [Poetry](https://python-poetry.org/) + + + + + +[flow]: flow.png "LibRay user interaction flowchart" +[tables]: tables.png "LibRay database tables" + diff --git a/docs/flow.d2 b/docs/flow.d2 new file mode 100644 index 0000000..f9c227e --- /dev/null +++ b/docs/flow.d2 @@ -0,0 +1,81 @@ +direction: down + +Start: { + Ird: libray -i encrypted.iso -d game.ird + Manual: libray -i encrypted.iso -d supplied_key + Automatic: libray -i encrypted.iso + Info: libray -i game.iso --info +} + +End: { + Dead: { shape: circle } + Success?: { shape: circle } +} + + +PrintInfo: Print info about .iso + +Start.Info -> PrintInfo + +Process: decrypt or re-encrypt + +VerifyIrd: Verify \n title ID { shape: diamond } + +Key: "" { + + NoVerify: No verification, \n use given key + IrdKey: Use .ird key + UseBundled: Use bundled key + UseSelected: Use selected key + +} + + +Start.Manual -> Key.NoVerify -> Process -> End.Success? + + +Start.Ird -> VerifyIrd +VerifyIrd -> End.Dead: Wrong ID +VerifyIrd -> Key.IrdKey: Same ID in .ird and .iso +Key.IrdKey -> Process + +Bundled: "" { + + CheckIrd: Check for \n bundled .ird { shape: diamond } + CheckKeys: Check for \n bundled key { shape: diamond } + Size: Size { shape: diamond } + SCN: Size \n Country \n Name { shape: diamond } + Choose: Let user \n Choose { shape: diamond } + + CheckKeys -> Size + Size -> SCN: Multiple keys + SCN -> Choose: Multiple keys + + +} + +Net: "" { + Search: Search for .ird online with title ID + Jonny: jonnysp { shape: diamond } + Aldos: aldostools { shape: diamond } +} + +Bundled.Size -> Key.UseBundled: Single key +Bundled.SCN -> Key.UseBundled: Single key +Bundled.Choose -> Key.UseSelected +Bundled.SCN -> Net.Search: No keys +Key.UseSelected -> Process +Key.UseBundled -> Process +Bundled.Choose -> Net.Search: Not opted in \n None selected + +Start.Automatic -> Bundled.CheckIrd +Bundled.CheckIrd -> Key.IrdKey: Title ID Match +Bundled.CheckIrd -> Bundled.CheckKeys: No keys / No match +Bundled.CheckKeys -> Net.Search: No keys +Net.Search -> Net.Jonny +Net.Jonny -> Net.Aldos: no .ird / \n is down +Net.Aldos -> End.Dead: no .ird +Net.Jonny -> Key.IrdKey: .ird found +Net.Aldos -> Key.IrdKey: .ird found + + diff --git a/docs/flow.png b/docs/flow.png new file mode 100644 index 0000000..8b35b71 Binary files /dev/null and b/docs/flow.png differ diff --git a/docs/tables.d2 b/docs/tables.d2 new file mode 100644 index 0000000..6958ffb --- /dev/null +++ b/docs/tables.d2 @@ -0,0 +1,20 @@ + + +ird: { + shape: sql_table + title_id TEXT + name TEXT + size BIGINT + key BLOB +} + +redump: { + shape: sql_table + name TEXT + size BIGINT + crc32 TEXT + md5 TEXT + sha1 TEXT + key BLOB +} + diff --git a/docs/tables.png b/docs/tables.png new file mode 100644 index 0000000..8cc5de0 Binary files /dev/null and b/docs/tables.png differ diff --git a/libray/__init__.py b/libray/__init__.py index e69de29..35a8408 100644 --- a/libray/__init__.py +++ b/libray/__init__.py @@ -0,0 +1,33 @@ +# -*- coding: utf8 -*- + +# libray - Libre Blu-Ray PS3 ISO Tool +# Copyright © 2018 - 2024 Nichlas Severinsen +# +# This file is part of libray. +# +# libray is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# libray is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with libray. If not, see . + +import pkgutil +import importlib + +__all__ = [] +for loader, module_name, is_pkg in pkgutil.walk_packages(__path__): + # Skip the entry-point script (libray/libray.py) which would pollute + # the package namespace with a 'libray' submodule that shadows the + # package itself when imported via 'importlib.import_module'. + if module_name == 'libray': + continue + __all__.append(module_name) + _module = importlib.import_module(f'.{module_name}', __name__) + globals()[module_name] = _module diff --git a/libray/core.py b/libray/core.py index b30e73c..2b173bc 100644 --- a/libray/core.py +++ b/libray/core.py @@ -1,7 +1,7 @@ # -*- coding: utf8 -*- # libray - Libre Blu-Ray PS3 ISO Tool -# Copyright © 2018 - 2021 Nichlas Severinsen +# Copyright © 2018 - 2024 Nichlas Severinsen # # This file is part of libray. # @@ -24,14 +24,18 @@ import sys import stat import zlib import shutil +import threading import requests from bs4 import BeautifulSoup +from typing import Any, Optional try: - from libray import iso + from libray import iso + from libray import ird except ImportError: - import iso + import iso + import ird # Magic numbers / Constant variables @@ -42,146 +46,206 @@ GET_IRD_NET_LOC = 'http://jonnysp.bplaced.net/ird/' # Utility functions -def to_int(data, byteorder='big'): - """Convert bytes to integer""" - if isinstance(data, bytes): - return int.from_bytes(data, byteorder) +def to_int(data: bytes, byteorder: str = 'big') -> int: + """Convert bytes to integer""" + if isinstance(data, bytes): + return int.from_bytes(data, byteorder) + return 0 -def to_bytes(data): - """Convert a string of HEX to bytes""" - if isinstance(data, str): - return bytes(bytearray.fromhex(data)) +def to_bytes(data: str) -> Optional[bytes]: + """Convert a string of HEX to bytes""" + if isinstance(data, str): + return bytes(bytearray.fromhex(data)) + return None ISO_SECRET = to_bytes("380bcf0b53455b3c7817ab4fa3ba90ed") ISO_IV = to_bytes("69474772af6fdab342743aefaa186287") -def size(path): - """Get size of a file or block device in bytes""" - pathstat = os.stat(path) +def size(path: str) -> int: + """Get size of a file or block device in bytes""" + pathstat = os.stat(path) - # Check if it's a block device + # Check if it's a block device - if stat.S_ISBLK(pathstat.st_mode): - return open(path, 'rb').seek(0, os.SEEK_END) + if stat.S_ISBLK(pathstat.st_mode): + return open(path, 'rb').seek(0, os.SEEK_END) - # Otherwise, it's hopefully a file + # Otherwise, it's hopefully a file - return pathstat.st_size + return pathstat.st_size -def read_seven_bit_encoded_int(fileobj, order): - """Read an Int32, 7 bits at a time.""" - # The highest bit of the byte, when on, means to continue reading more bytes. - count = 0 - shift = 0 - byte = -1 - while (byte & 0x80) != 0 or byte == -1: - # Check for a corrupted stream. Read a max of 5 bytes. - if shift == (5 * 7): - raise ValueError - byte = to_int(fileobj.read(1), order) - count |= (byte & 0x7F) << shift - shift += 7 - return count +def read_seven_bit_encoded_int(fileobj, order: str) -> int: + """Read an Int32, 7 bits at a time.""" + # The highest bit of the byte, when on, means to continue reading more bytes. + count = 0 + shift = 0 + byte = -1 + while (byte & 0x80) != 0 or byte == -1: + # Check for a corrupted stream. Read a max of 5 bytes. + if shift == (5 * 7): + raise ValueError + byte = to_int(fileobj.read(1), order) + count |= (byte & 0x7F) << shift + shift += 7 + return count -def error(msg): - """Print fatal error message and terminate""" - print('[ERROR] %s' % msg) - sys.exit(1) +def error(msg: str) -> None: + """Print fatal error message and terminate""" + print(f'[ERROR] {msg}', file=sys.stderr) + sys.exit(1) -def warning(msg, args): - """Print a warning message. Warning messages can be silenced with --quiet""" +def warning(msg: str, args: Any) -> None: + """Print a warning message. Warning messages can be silenced with --quiet""" - if not args.quiet: - print('[WARNING] %s. Continuing regardless.' % msg) + if not args.quiet: + print(f'[WARNING] {msg}. Continuing regardless.', file=sys.stderr) -def vprint(msg, args): - """Vprint, verbose print, can be silenced with --quiet""" +def vprint(msg: str, args: Any) -> None: + """Vprint, verbose print, can be silenced with --quiet""" - if not args.quiet: - print('[*] ' + msg) + if not args.quiet: + print(f'[*] {msg}') -def download_ird(ird_name): - """Download an .ird from GET_IRD_NET_LOC""" +def download_ird(ird_name: str) -> None: + """Download an .ird from GET_IRD_NET_LOC""" - # Check if file already exists and skip if it does - if os.path.exists(ird_name): # TODO: might want to check that the file is valid first, could do a HEAD agains the url - return + # Check if file already exists and skip if it does + if os.path.exists(ird_name): # TODO: might want to check that the file is valid first, could do a HEAD agains the url + return - ird_link = GET_IRD_NET_LOC + ird_name - r = requests.get(ird_link, stream=True) + ird_link = GET_IRD_NET_LOC + ird_name + r = requests.get(ird_link, stream=True, timeout=30) - with open(ird_name, 'wb') as ird_file: - r.raw.decode_content = True - shutil.copyfileobj(r.raw, ird_file) + with open(ird_name, 'wb') as ird_file: + r.raw.decode_content = True + shutil.copyfileobj(r.raw, ird_file) -def ird_by_game_id(game_id): - """Using a game_id, download the responding .ird from ALL_IRD_NET_LOC""" - gameid = game_id.replace('-','') - try: - r = requests.get(ALL_IRD_NET_LOC, headers = {'User-Agent': 'Anonymous (You)' }, timeout=5) - except requests.exceptions.ReadTimeout: - error('Server timed out, fix your connection or manually specify a key/ird.') - soup = BeautifulSoup(r.text, "html.parser") +def ird_by_game_id(game_id: str) -> Optional[str]: + """Using a game_id, download the responding .ird from ALL_IRD_NET_LOC""" + gameid = game_id.replace('-', '') + try: + r = requests.get(ALL_IRD_NET_LOC, headers={'User-Agent': 'Anonymous (You)'}, timeout=5) + except requests.exceptions.ReadTimeout: + error('Server timed out, fix your connection or manually specify a key/ird.') + soup = BeautifulSoup(r.text, "html.parser") - ird_name = False - for elem in soup.find_all("a"): - url = elem.get('href').split('/')[-1].replace('\\"','') - if gameid in url: - ird_name = url + ird_name = False + for elem in soup.find_all("a"): + url = elem.get('href').split('/')[-1].replace('\\"', '') + if gameid in url: + ird_name = url - if not ird_name: - error("Unable to download IRD, couldn't find link. You could specify the decryption key with -d if you have it.") + if not ird_name: + error("Unable to download IRD, couldn't find link. You could specify the decryption key with -d if you have it.") - download_ird(ird_name) + download_ird(ird_name) - return(ird_name) + return (ird_name) -def crc32(filename): - """Calculate crc32 for file""" +def crc32(filename: str, cancel: Optional[threading.Event] = None) -> Optional[str]: + """Calculate crc32 for file. - with open(filename, 'rb') as infile: + If *cancel* is provided, the computation can be aborted from another + thread by calling ``cancel.set()``. Returns ``None`` when cancelled. + """ + if cancel is None: + cancel = threading.Event() - crc32 = 0 + with open(filename, 'rb') as infile: + crc_val = 0 + while not cancel.is_set(): + data = infile.read(65536) + if not data: + break + crc_val = zlib.crc32(data, crc_val) - while True: - data = infile.read(65536) - if not data: - break - crc32 = zlib.crc32(data, crc32) + if cancel.is_set(): + return None - return "%08X" % (crc32 & 0xFFFFFFFF) + return f"{crc_val & 0xFFFFFFFF:08X}" + + +def serial_country(title: str) -> str: + """Get country from disc serial / productcode / title_id""" + + if title[2] == 'A': + return 'Asia' + if title[2] == 'C': + return 'China' + if title[2] == 'E': + return 'Europe' + if title[2] == 'H': + return 'Hong Kong' + if title[2] == 'J' or title[2] == 'P': + return 'Japan' + if title[2] == 'K': + return 'Korea' + if title[2] == 'U' or title[2] == 'T': + return 'USA' + + raise ValueError('Unknown country?!') + + +def multiman_title(title: str) -> str: + """Fix special characters in title for Multiman style""" + + replace = { + ':': ' -', + '/': '-', + '™': '', + '®': '', + } + + for key, val in replace.items(): + title = title.replace(key, val) + + return title # Main functions +def info(args: Any) -> None: + """Print information about .iso and then quit.""" -def decrypt(args): - """Try to decrypt a given .iso using relevant .ird or encryption key from argparse + if args.iso: + input_iso = iso.ISO(args) + input_iso.print_info() + sys.exit() - If no .ird is given this will try to automatically download an .ird file with the encryption/decryption key for the given game .iso - """ - - input_iso = iso.ISO(args) - - input_iso.decrypt(args) + if args.ird: + input_ird = ird.IRD(args.ird) + input_ird.print_info(regions=True) + sys.exit() -def encrypt(args): - """Try to re-encrypt a decrypted .iso using relevant .ird or encryption key from argparse +def decrypt(args: Any) -> None: + """Try to decrypt a given .iso using relevant .ird or encryption key from argparse - If no .ird is given this will try to automatically download an .ird file with the encryption/decryption key for the given game .iso - """ + If no .ird is given this will try to automatically download an .ird file with the encryption/decryption key for the given game .iso + """ - input_iso = iso.ISO(args) + input_iso = iso.ISO(args) - input_iso.encrypt(args) + # TODO: some of the logic should probably be moved up here instead of residing in the decrypt function + input_iso.decrypt(args) + + +def encrypt(args: Any) -> None: + """Try to re-encrypt a decrypted .iso using relevant .ird or encryption key from argparse + + If no .ird is given this will try to automatically download an .ird file with the encryption/decryption key for the given game .iso + """ + + input_iso = iso.ISO(args) + + input_iso.encrypt(args) diff --git a/libray/ird.py b/libray/ird.py index fbcc1db..6af748c 100644 --- a/libray/ird.py +++ b/libray/ird.py @@ -1,7 +1,7 @@ # -*- coding: utf8 -*- # libray - Libre Blu-Ray PS3 ISO Tool -# Copyright © 2018 - 2021 Nichlas Severinsen +# Copyright © 2018 - 2024 Nichlas Severinsen # # This file is part of libray. # @@ -23,126 +23,134 @@ import os import sys import zlib import shutil +import tempfile try: - from libray import core + from libray import core except ImportError: - import core + import core class IRD: - """Class for handling .ird files + """Class for handling .ird files - Attributes: - version: IRD version number - game_id: PS3 game identifier - game_name: Name of PS3 game - update_version: PS3 firmware update version - game_version: PS3 game version - app_version: PS3 app version - region_count: How many encrypted regions are in the .iso - file_count: How many files are supposed to be in the .iso - data1: Encryption key - """ + Attributes: + version: IRD version number + game_id: PS3 game identifier + game_name: Name of PS3 game + update_version: PS3 firmware update version + game_version: PS3 game version + app_version: PS3 app version + region_count: How many encrypted regions are in the .iso + file_count: How many files are supposed to be in the .iso + data1: Encryption key + """ - ORDER = 'little' - TEMP_FILE = 'ird' - MAGIC_STRING = b'3IRD' + ORDER = 'little' + MAGIC_STRING = b'3IRD' + def __init__(self, ird_path, verbose=False): + """IRD constructor using args from argparse.""" - def __init__(self, args): - """IRD constructor using args from argparse.""" + temp_path = self._prepare_temp(ird_path) - self.uncompress(args.ird) # TODO: Try/Except? + try: + self.size = core.size(temp_path) - self.size = core.size(self.TEMP_FILE) + if not self.size: + core.error('IRD file is empty!') - if not self.size: - core.error('IRD file is empty!') + with open(temp_path, 'rb') as input_ird: + if input_ird.read(4) != self.MAGIC_STRING: + core.error('Either not an IRD file, corruped IRD file, or unknown IRD format') - with open(self.TEMP_FILE, 'rb') as input_ird: - if input_ird.read(4) != self.MAGIC_STRING: - core.error('Either not an IRD file, corruped IRD file, or unknown IRD format') + self.version = core.to_int(input_ird.read(1), self.ORDER) + self.game_id = input_ird.read(9) + name_length = core.read_seven_bit_encoded_int(input_ird, self.ORDER) + self.game_name = input_ird.read(name_length).decode('utf8') + self.update_version = input_ird.read(4) + self.game_version = input_ird.read(5) + self.app_version = input_ird.read(5) - self.version = core.to_int(input_ird.read(1), self.ORDER) - self.game_id = input_ird.read(9) - name_length = core.read_seven_bit_encoded_int(input_ird, self.ORDER) - self.game_name = input_ird.read(name_length).decode('utf8') - self.update_version = input_ird.read(4) - self.game_version = input_ird.read(5) - self.app_version = input_ird.read(5) + if self.version == 7: + self.identifier = input_ird.read(4) - if self.version == 7: - self.identifier = input_ird.read(4) + header_length = (core.to_int(input_ird.read(4), self.ORDER)) + self.header = input_ird.read(header_length) + footer_length = (core.to_int(input_ird.read(4), self.ORDER)) + self.footer = input_ird.read(footer_length) - header_length = (core.to_int(input_ird.read(4), self.ORDER)) - self.header = input_ird.read(header_length) - footer_length = (core.to_int(input_ird.read(4), self.ORDER)) - self.footer = input_ird.read(footer_length) + self.region_count = core.to_int(input_ird.read(1), self.ORDER) + self.region_hashes = [] + for _ in range(0, self.region_count): + self.region_hashes.append(input_ird.read(16)) - self.region_count = core.to_int(input_ird.read(1), self.ORDER) - self.region_hashes = [] - for _ in range(0, self.region_count): - self.region_hashes.append(input_ird.read(16)) + self.file_count = core.to_int(input_ird.read(4), self.ORDER) + self.file_hashes = [] + for _ in range(0, self.file_count): + key = core.to_int(input_ird.read(8), self.ORDER) + val = input_ird.read(16) + self.file_hashes.append({'key': key, 'val': val}) - self.file_count = core.to_int(input_ird.read(4), self.ORDER) - self.file_hashes = [] - for _ in range(0, self.file_count): - key = core.to_int(input_ird.read(8), self.ORDER) - val = input_ird.read(16) - self.file_hashes.append({'key': key, 'val': val}) + if self.version >= 9: + self.pic = input_ird.read(115) - if self.version >= 9: - self.pic = input_ird.read(115) + input_ird.seek(input_ird.tell() + 4) # ? - input_ird.seek(input_ird.tell() + 4) # ? + self.data1 = input_ird.read(16) + self.data2 = input_ird.read(16) - self.data1 = input_ird.read(16) - self.data2 = input_ird.read(16) + if self.version < 9: + self.pic = input_ird.read(115) - if self.version < 9: - self.pic = input_ird.read(115) + if self.version < 7: + self.uid = core.to_int(input_ird.read(4), self.ORDER) - if self.version < 7: - self.uid = core.to_int(input_ird.read(4), self.ORDER) + if verbose: + self.print_info() + finally: + os.remove(temp_path) - if args.verbose: - self.print_info() + def _prepare_temp(self, filename): + """Decompress (if needed) and copy an IRD file to a unique temp file. - os.remove(self.TEMP_FILE) + Returns the path to the temp file. The caller is responsible for + deleting it (use a ``try / finally`` block). + """ + with open(filename, 'rb') as f: + magic = f.read(4) + fd, tmp_path = tempfile.mkstemp(suffix='.ird') + os.close(fd) - def uncompress(self, filename): - """Uncompress IRD. Assumes given .ird file is not compressed, but then tries to decompress it with zlib/gzfile if it was not uncompressed.""" + if magic != self.MAGIC_STRING: + # Compressed — decompress to the temp file + with open(filename, 'rb') as gzfile, open(tmp_path, 'wb') as tmpfile: + tmpfile.write(zlib.decompress(gzfile.read(), zlib.MAX_WBITS | 16)) + else: + # Uncompressed — copy to the temp file + shutil.copyfile(filename, tmp_path) - uncompress = False - with open(filename, 'rb') as input_ird: - if input_ird.read(4) != self.MAGIC_STRING: - uncompress = True + return tmp_path - if uncompress: - with open(filename, 'rb') as gzfile: - with open(self.TEMP_FILE, 'wb') as tmpfile: - tmpfile.write(zlib.decompress(gzfile.read(), zlib.MAX_WBITS|16)) - else: - shutil.copyfile(filename, self.TEMP_FILE) + def print_info(self, regions=False): + # TODO: This could probably have been a __str__? Who cares? + """Print some info about the IRD.""" + print('Info from IRD:') + print('Version: %s' % self.version) + print('Game ID: %s' % self.game_id) + print('Game Name: %s' % self.game_name) + print('Update Version: %s' % self.update_version) + print('Game Version: %s' % self.game_version) + print('App Version: %s' % self.app_version) + print('Region Count: %s' % self.region_count) - def print_info(self): - # TODO: This could probably have been a __str__? Who cares? - """Print some info about the IRD.""" - - print('Info from IRD:') - print('Version: %s' % self.version) - print('Game ID: %s' % self.game_id) - print('Game Name: %s' % self.game_name) - print('Update Version: %s' % self.update_version) - print('Game Version: %s' % self.game_version) - print('App Version: %s' % self.app_version) - print('Region Count: %s' % self.region_count) - print('File Count: %s' % self.file_count) - print('Data1: %s' % self.data1.hex()) - print('Data2: %s' % self.data2.hex()) - + if regions: + for i, region_hash in enumerate(self.region_hashes): + print('\tRegion Hash %s: %s' % (i, region_hash.hex())) + print('File Count: %s' % self.file_count) + print('Data1: %s' % self.data1.hex()) + print('Data2: %s' % self.data2.hex()) diff --git a/libray/iso.py b/libray/iso.py index a243bf2..690067e 100644 --- a/libray/iso.py +++ b/libray/iso.py @@ -1,7 +1,7 @@ # -*- coding: utf8 -*- # libray - Libre Blu-Ray PS3 ISO Tool -# Copyright © 2018 -2021 Nichlas Severinsen +# Copyright © 2018 - 2024 Nichlas Severinsen # # This file is part of libray. # @@ -19,269 +19,403 @@ # along with libray. If not, see . +import os import sys import sqlite3 -import pkg_resources +import concurrent.futures +import threading +from collections import deque +from threading import Thread +from importlib import resources from tqdm import tqdm from Crypto.Cipher import AES try: - from libray import core - from libray import ird + from libray import core + from libray import ird + from libray import sfo except ImportError: - import core - import ird + import core + import ird + import sfo + + +def _make_iv(sector_number): + """Build a 16-byte IV from a sector number (little-endian).""" + iv = bytearray(16) + num = sector_number + for j in range(16): + iv[15 - j] = num & 0xFF + num >>= 8 + return bytes(iv) + + +def _process_sector_chunk_mp(args): + """Multiprocessing worker: (de/en)crypt a contiguous run of sectors. + + Picklable, module-level function for use with ProcessPoolExecutor. Takes a + single ``bytes`` blob of one or more whole sectors and returns the processed + blob, so only one (large) object is pickled per task instead of many small + ones — this is what makes the multiprocessing worthwhile. + """ + disc_key, sector_blob, sector_start_number, encrypt_mode = args + out = bytearray() + for offset in range(0, len(sector_blob), core.SECTOR): + sector = sector_blob[offset:offset + core.SECTOR] + iv = _make_iv(sector_start_number + offset // core.SECTOR) + cipher = AES.new(disc_key, AES.MODE_CBC, iv) + out += cipher.encrypt(sector) if encrypt_mode else cipher.decrypt(sector) + return bytes(out) class ISO: - """Class for handling PS3 .iso files. + """Class for handling PS3 .iso files. - Attributes: - size: Size of .iso in bytes - number_of_regions: Number of regions in the .iso - regions: List with info of every region - game_id: PS3 game id - ird: IRD object (see ird.py) - disc_key: data1 from .ird, encrypted - """ - - - NUM_INFO_BYTES = 4 - - - def read_regions(self, input_iso, filename): - """List with info dict (start, end, whether it's encrypted) for every region. - - Basically, every other (odd numbered) region is encrypted. + Attributes: + size: Size of .iso in bytes + number_of_regions: Number of regions in the .iso + regions: List with info of every region + game_id: PS3 game id + ird: IRD object (see ird.py) + disc_key: data1 from .ird, encrypted """ - regions = [] - encrypted = False - for _ in range(0, self.number_of_regions): + NUM_INFO_BYTES = 4 - regions.append({ - 'start': core.to_int(input_iso.read(self.NUM_INFO_BYTES)) * core.SECTOR, - 'end': core.to_int(input_iso.read(self.NUM_INFO_BYTES)) * core.SECTOR, - 'enc': encrypted - }) + def read_regions(self, input_iso): + """List with info dict (start, end, whether it's encrypted) for every region. - input_iso.seek(input_iso.tell() - self.NUM_INFO_BYTES) + Basically, every other (odd numbered) region is encrypted. + """ - encrypted = not encrypted + # The first region is always unencrypted - # Last region might not actually be 2048 bytes, so we'll just cheat - regions[-1]['end'] = self.size + encrypted = False - return regions + regions = [{ + 'start': core.to_int(input_iso.read(self.NUM_INFO_BYTES)) * core.SECTOR, # Should always be 0? + 'end': core.to_int(input_iso.read(self.NUM_INFO_BYTES)) * core.SECTOR + core.SECTOR, + 'enc': encrypted + }] + # We'll read 4 bytes until we hit a non-size (<=0) - def __init__(self, args): - """ISO constructor using args from argparse.""" + while True: - self.size = core.size(args.iso) + encrypted = not encrypted - if not self.size: - core.error('looks like ISO file/mount is empty?') + end = core.to_int(input_iso.read(self.NUM_INFO_BYTES)) * core.SECTOR - with open(args.iso, 'rb') as input_iso: - # Get number of regions (times two as the number represents both encrypted and decrypted regions ) - self.number_of_regions = core.to_int(input_iso.read(self.NUM_INFO_BYTES)) * 2 + if not end: + break - # Skip unused bytes - input_iso.seek(input_iso.tell() + self.NUM_INFO_BYTES) + regions.append({ + 'start': regions[-1]['end'], + 'end': end + core.SECTOR - (core.SECTOR if encrypted else 0), + 'enc': encrypted + }) - self.regions = self.read_regions(input_iso, args.iso) + return regions - # Seek to the start of region 2, '+ 16' skips a section containing some 'playstation' - input_iso.seek(core.SECTOR + 16) + def __init__(self, args): + """ISO constructor using args from argparse.""" - self.game_id = input_iso.read(16).decode('utf8').strip() + self.size = core.size(args.iso) - cipher = AES.new(core.ISO_SECRET, AES.MODE_CBC, core.ISO_IV) + if not self.size: + core.error('looks like ISO file/mount is empty?') + + with open(args.iso, 'rb') as input_iso: + # Get number of unencrypted regions + self.number_of_unencrypted_regions = core.to_int(input_iso.read(self.NUM_INFO_BYTES)) + + # Skip unused bytes + input_iso.seek(input_iso.tell() + self.NUM_INFO_BYTES) + + self.regions = self.read_regions(input_iso) + + # Seek to the start of sector 2, '+ 16' skips a section containing some 'playstation' + input_iso.seek(core.SECTOR + 16) + + self.game_id = input_iso.read(16).decode('utf8').strip() + + # Find PARAM.SFO + + core.vprint('Searching for PARAM.SFO', args) + + input_iso.seek(0) + counter = 1 + found_param = False + + while True: + + data = input_iso.read(8) + + if not data: + break + + # if data == b'PS3LICDA': + # print(data) + + if data[0:4] == b'\x00\x50\x53\x46': + found_param = True + + # input_iso.seek(input_iso.tell() - 8) + # param = sfo.SFO(input_iso) + # print(param['TITLE']) + # print(param['TITLE_ID']) + break + + input_iso.seek((core.SECTOR * counter)) + + counter += 1 + + game_title = '' + + if found_param: + input_iso.seek(input_iso.tell() - 8) + try: + param = sfo.SFO(input_iso) + core.vprint('PARAM.SFO found', args) + + game_title = core.multiman_title(param['TITLE']) + + if args.verbose and not args.quiet: + param.print_info() + + # Set output to multiman style + if not args.output: + args.output = f'{game_title} [{param["TITLE_ID"]}].iso' + + except (UnicodeDecodeError, KeyError, IndexError, ValueError): + core.warning('Failed reading SFO', args) + + self.disc_key = self.get_key_from_args(game_title, args) + if args.verbose and not args.quiet: + self.print_info() + + def decrypt(self, args): + """Decrypt self using args from argparse.""" + self._process_iso(args, encrypt_mode=False) + + def encrypt(self, args): + """Encrypt self using args from argparse.""" + self._process_iso(args, encrypt_mode=True) + + def _process_iso(self, args, encrypt_mode): + """Shared driver for decrypt/encrypt. ``encrypt_mode`` selects direction.""" + + core.vprint(f'{"Re-encrypting" if encrypt_mode else "Decrypting"} with disc key: {self.disc_key.hex()}', args) + + num_workers = args.threads if args.threads and args.threads > 0 else (os.cpu_count() or 1) + + if args.output: + output_name = args.output + else: + output_name = f'{self.game_id}_e.iso' if encrypt_mode else f'{self.game_id}.iso' + + core.vprint(f'{"Re-encrypted" if encrypt_mode else "Decrypted"} .iso is output to: {output_name}', args) + + total_sectors = self.size // core.SECTOR + pbar = tqdm(total=total_sectors, file=sys.stdout, disable=args.quiet, leave=True) + + if num_workers > 1: + core.vprint(f'Using {num_workers} processes for parallel {"re-encryption" if encrypt_mode else "decryption"}', args) + self._process_parallel(args, output_name, encrypt_mode, num_workers, pbar) + else: + self._process_sequential(args, output_name, encrypt_mode, pbar) + + pbar.close() + core.vprint(f'{"Re-encryption" if encrypt_mode else "Decryption"} complete!', args) + + def _process_sequential(self, args, output_name, encrypt_mode, pbar): + """Single-process path: read, optionally (de/en)crypt, and write per sector.""" + with open(args.iso, 'rb') as input_iso, open(output_name, 'wb') as output_file: + for region in self.regions: + region_sectors = (region['end'] - region['start']) // core.SECTOR + base_sector = region['start'] // core.SECTOR + input_iso.seek(region['start']) + + for i in range(region_sectors): + data = input_iso.read(core.SECTOR) + if not data: + core.warning('Trying to read past the end of the file', args) + break + if region['enc']: + cipher = AES.new(self.disc_key, AES.MODE_CBC, _make_iv(base_sector + i)) + data = cipher.encrypt(data) if encrypt_mode else cipher.decrypt(data) + output_file.write(data) + pbar.update(1) + + def _process_parallel(self, args, output_name, encrypt_mode, num_workers, pbar): + """Multi-process path: one process pool for the whole operation. + + The output file is pre-sized so every region can be written to its + absolute offset; this also clears any stale file from a previous run. + """ + # Pre-create the output at its final size and write to absolute offsets. + total_bytes = self.regions[-1]['end'] + with open(output_name, 'wb') as f: + f.truncate(total_bytes) + + with concurrent.futures.ProcessPoolExecutor(max_workers=num_workers) as executor, \ + open(args.iso, 'rb') as input_iso, \ + open(output_name, 'r+b') as out: + for region in self.regions: + if region['enc']: + self._process_region_parallel(input_iso, out, region, executor, num_workers, encrypt_mode, pbar) + else: + # Unencrypted region — copy straight through to its offset. + region_sectors = (region['end'] - region['start']) // core.SECTOR + input_iso.seek(region['start']) + out.seek(region['start']) + for _ in range(region_sectors): + data = input_iso.read(core.SECTOR) + if not data: + core.warning('Trying to read past the end of the file', args) + break + out.write(data) + pbar.update(1) + + def _process_region_parallel(self, input_iso, out, region, executor, num_workers, encrypt_mode, pbar): + """(De/en)crypt one encrypted region across worker processes. + + Reads the region in bounded-size chunks and keeps only a small window of + chunks in flight, so peak memory stays bounded even for huge ISOs. + Results are written back to their absolute offsets as they complete. + """ + num_sectors = (region['end'] - region['start']) // core.SECTOR + base_sector = region['start'] // core.SECTOR + + # Sectors per task: large enough to amortise IPC, small enough to keep + # every worker busy and bound peak memory. + sectors_per_chunk = max(1, min(512, (num_sectors // (num_workers * 4)) or 1)) + max_in_flight = num_workers * 4 + + input_iso.seek(region['start']) + next_sector = base_sector + sectors_left = num_sectors + pending = deque() + + def submit_more(): + nonlocal next_sector, sectors_left + while sectors_left > 0 and len(pending) < max_in_flight: + count = min(sectors_per_chunk, sectors_left) + blob = input_iso.read(count * core.SECTOR) + future = executor.submit(_process_sector_chunk_mp, + (self.disc_key, blob, next_sector, encrypt_mode)) + pending.append((next_sector, count, future)) + next_sector += count + sectors_left -= count + + submit_more() + while pending: + start_sector, count, future = pending.popleft() + out.seek(start_sector * core.SECTOR) + out.write(future.result()) + pbar.update(count) + submit_more() + + def get_key_from_args(self, game_title, args): + # key provided with -d / --decryption-key + if args.decryption_key: + return core.to_bytes(args.decryption_key) + + def get_key_from_ird(i): + self.ird = ird.IRD(i) + if self.ird.region_count != len(self.regions): + core.error( + f'Corrupt ISO or error in IRD. Expected {self.ird.region_count} regions, found {len(self.regions)} regions') + + if self.regions[-1]['start'] > self.size: + core.error( + f'Corrupt ISO or error in IRD. Expected filesize larger than {self.regions[-1]["start"]/1024**3:.2f} GiB, actual size is {self.size/1024**3:.2f} GiB') + cipher = AES.new(core.ISO_SECRET, AES.MODE_CBC, core.ISO_IV) + return cipher.encrypt(self.ird.data1) + + # .ird file given with -k / --ird + if args.ird: + return get_key_from_ird(args.ird) - if not args.decryption_key: - if not args.ird: # No key or .ird specified. Let's first check if keys.db is packaged with this release - - redump = False - core.vprint('Checking for bundled redump keys', args) + db_path = resources.files(__name__).joinpath('data', 'keys.db') + db = sqlite3.connect(str(db_path)) + c = db.cursor() + + # UPDATE: 2024 - New database now has game/title ids. See if we have that. + + core.vprint('Searching using TITLE_ID', args) try: - db = sqlite3.connect(pkg_resources.resource_filename(__name__, 'data/keys.db')) - c = db.cursor() + keys = c.execute('SELECT name, key FROM games WHERE title_id = ?', [self.game_id.replace('-', '')]).fetchall() + except sqlite3.OperationalError: + core.error('keys.db not found or invalid. Build it with: python3 tools/keys2db.py') + if len(keys) == 1: + core.vprint(f'Found potential redump key: "{keys[0][0]}"', args) + return keys[0][1] - core.vprint('Calculating crc32', args) + # Then check if there's only one game with this exact size + core.vprint('Trying to find redump key based on size', args) + keys = c.execute('SELECT name, key FROM games WHERE size = ?', [str(self.size)]).fetchall() + if len(keys) == 1: + core.vprint(f'Found potential redump key: "{keys[0][0]}"', args) + return keys[0][1] - crc32 = core.crc32(args.iso) + # If not, see if we can filter it out based on name and size + core.vprint('Trying to find redump key based on size, game title, and country', args) + if not game_title: + core.error('Could not determine game title from PARAM.SFO. Specify a decryption key with -d or provide an IRD file with -k.') - keys = c.execute('SELECT * FROM games WHERE crc32=?', [crc32.lower()]).fetchall() + try: + country = core.serial_country(self.game_id) + except ValueError: + core.error(f'Unknown country code in game ID "{self.game_id}". Specify a decryption key with -d or provide an IRD file with -k.') - if keys: + keys = c.execute('SELECT name, key FROM games WHERE lower(name) LIKE ? AND size = ?', [ + '%' + '%'.join(game_title.lower().split(' ')) + '%' + country.lower() + '%', str(self.size)]).fetchall() + if keys: + core.vprint(f'Found potential redump key: "{keys[0][0]}"', args) + return keys[0][1] - self.disc_key = keys[0][-1] + # since checksums can take a while to calculate, bail here unless the + # user has specifically indicated they want to try the CRC32 fallback + if not args.checksum: + core.error('could not find disc key') - core.vprint('.ISO identified as "%s"' % keys[0][0], args) + # Okay, searching has failed us, but maaaybe the checksum works? + core.vprint('Trying to find redump key based on CRC32', args) + cancel = threading.Event() + crc_done = threading.Event() + if args.checksum_timeout > 0: + def timeout(): + # Abort the CRC32 calculation if it hasn't finished in time. + if not crc_done.wait(timeout=float(args.checksum_timeout)): + core.vprint(f'could not calculate CRC32 before {args.checksum_timeout}-second timeout', args) + cancel.set() - redump = True + crc_thread = Thread(target=timeout, daemon=True) + crc_thread.start() - else: - raise ValueError + calculated_crc = core.crc32(args.iso, cancel) + crc_done.set() + if calculated_crc is None: + raise TimeoutError - except: - core.vprint('No keys found', args) + keys = c.execute('SELECT name, key FROM games WHERE crc32=?', [calculated_crc.lower()]).fetchall() + if len(keys) == 1: + core.vprint(f'Found potential redump key: "{keys[0][0]}" (CRC32={calculated_crc.lower()})', args) + return keys[0][1] - if not redump: - - # Fallback to checking if an .ird exists - - core.warning('No IRD file specified, finding required file', args) - args.ird = core.ird_by_game_id(self.game_id) # Download ird - - self.ird = ird.IRD(args) - - if self.ird.region_count != len(self.regions)-1: - core.error('Corrupt ISO or error in IRD. Expected %s regions, found %s regions' % (self.ird.region_count, len(self.regions)-1)) - - if self.regions[-1]['start'] > self.size: - core.error('Corrupt ISO or error in IRD. Expected filesize larger than %.2f GiB, actual size is %.2f GiB' % (self.regions[-1]['start'] / 1024**3, self.size / 1024**3 ) ) - - self.disc_key = cipher.encrypt(self.ird.data1) - else: - self.disc_key = core.to_bytes(args.decryption_key) - - if args.verbose and not args.quiet: - self.print_info() - - - def decrypt(self, args): - """Decrypt self using args from argparse.""" - - core.vprint('Decrypting with disc key: %s' % self.disc_key.hex(), args) - - with open(args.iso, 'rb') as input_iso: - - if not args.output: - output_name = '%s.iso' % self.game_id - else: - output_name = args.output - - with open(output_name, 'wb') as output_iso: - - if not args.quiet: - pbar = tqdm(total= (self.size // 2048) ) - - for region in self.regions: - input_iso.seek(region['start']) - - # Unencrypted region, just copy it - if not region['enc']: - while input_iso.tell() < region['end']: - data = input_iso.read(core.SECTOR) - if not data: - core.warning('Trying to read past the end of the file', args) - break - output_iso.write(data) - - if not args.quiet: - pbar.update(1) - continue - # Encrypted region, decrypt then write - else: - while input_iso.tell() < region['end']: - num = input_iso.tell() // 2048 - iv = bytearray([0 for i in range(0,16)]) - for j in range(0,16): - iv[16 - j - 1] = (num & 0xFF) - num >>= 8 - - data = input_iso.read(core.SECTOR) - if not data: - core.warning('Trying to read past the end of the file', args) - break - - cipher = AES.new(self.disc_key, AES.MODE_CBC, bytes(iv)) - decrypted = cipher.decrypt(data) - - output_iso.write(decrypted) - - if not args.quiet: - pbar.update(1) - - if not args.quiet: - pbar.close() - - core.vprint('Decryption complete!', args) - - - def encrypt(self, args): - """Encrypt self using args from argparse.""" - - core.vprint('Re-encrypting with disc key: %s' % self.disc_key.hex(), args) - - with open(args.iso, 'rb') as input_iso: - - if not args.output: - output_name = '%s_e.iso' % self.game_id - else: - output_name = args.output - - with open(output_name, 'wb') as output_iso: - - if not args.quiet: - pbar = tqdm(total= (self.size // 2048) ) - - for region in self.regions: - input_iso.seek(region['start']) - - # Unencrypted region, just copy it - if not region['enc']: - while input_iso.tell() < region['end']: - data = input_iso.read(core.SECTOR) - if not data: - core.warning('Trying to read past the end of the file', args) - break - output_iso.write(data) - - if not args.quiet: - pbar.update(1) - continue - # Decrypted region, re-encrypt it - else: - while input_iso.tell() < region['end']: - num = input_iso.tell() // 2048 - iv = bytearray([0 for i in range(0,16)]) - for j in range(0,16): - iv[16 - j - 1] = (num & 0xFF) - num >>= 8 - - data = input_iso.read(core.SECTOR) - if not data: - core.warning('Trying to read past the end of the file', args) - break - - cipher = AES.new(self.disc_key, AES.MODE_CBC, bytes(iv)) - encrypted = cipher.encrypt(data) - - output_iso.write(encrypted) - - if not args.quiet: - pbar.update(1) - - if not args.quiet: - pbar.close() - - core.vprint('Re-encryption complete!', args) - - - def print_info(self): - # TODO: This could probably have been a __str__? Who cares? - """Print some info about the ISO.""" - print('Game ID: %s' % self.game_id) - print('Key: %s' % self.disc_key.hex()) - print('Info from ISO:') - print('Regions: %s' % self.number_of_regions) - for i, region in enumerate(self.regions): - print(i, region) + core.error('could not find disc key') + def print_info(self): + # TODO: This could probably have been a __str__? Who cares? + """Print some info about the ISO.""" + print(f'Game ID: {self.game_id}') + print(f'Key: {self.disc_key.hex()}') + print(f'Info from ISO:') + print(f'Unencrypted regions: {self.number_of_unencrypted_regions}') + for i, region in enumerate(self.regions): + print(i, region, region['start'] // core.SECTOR, region['end'] // core.SECTOR) diff --git a/libray/libray.py b/libray/libray.py index 86bbf05..fe061e6 100755 --- a/libray/libray.py +++ b/libray/libray.py @@ -2,7 +2,7 @@ # -*- coding: utf8 -*- # libray - Libre Blu-Ray PS3 ISO Tool -# Copyright © 2018 - 2021 Nichlas Severinsen +# Copyright © 2018 - 2024 Nichlas Severinsen # # This file is part of libray. # @@ -19,39 +19,56 @@ # You should have received a copy of the GNU General Public License # along with libray. If not, see . +import multiprocessing + +try: + multiprocessing.set_start_method('spawn') +except RuntimeError: + pass import argparse +import sys try: - from libray import core + from libray import core except ImportError: - import core + import core + + +def main(): + parser = argparse.ArgumentParser( + description='A Libre (FLOSS) Python application for unencrypting, extracting, repackaging, and encrypting PS3 ISOs') + + required = parser.add_mutually_exclusive_group(required=True) + required.add_argument('-i', '--iso', dest='iso', type=str, help='Path to .iso file or stream') + required.add_argument('-k', '--ird', dest='ird', type=str, help='Path to .ird file', default='') + + optional = parser.add_argument_group('optional arguments') + optional.add_argument('-o', '--output', dest='output', type=str, help='Output filename', default='') + optional.add_argument('-d', '--decryption-key', dest='decryption_key', type=str, help='Manually specify key', default='') + optional.add_argument('-v', '--verbose', dest='verbose', help='Increase verbosity', action='count') + optional.add_argument('-q', '--quiet', dest='quiet', help='Quiet mode, only prints on error', action='store_true') + # -e is reserved for "extract" so re-encrypt is "-r" + optional.add_argument('-r', '--re-encrypt', dest='reencrypt', help='Re-encrypt .iso', action='store_true') + optional.add_argument('-c', '--checksum', dest='checksum', help='Allow fallback to CRC32 checksum (disabled by default)', action='store_true') + optional.add_argument('-t', '--checksum-timeout', dest='checksum_timeout', type=int, help='How many seconds to wait for CRC32 checksum (default 15)', default=15) + optional.add_argument('-p', '--threads', dest='threads', type=int, help='Number of threads for parallel decryption/encryption (default: number of CPU cores)', default=0) + optional.add_argument('--info', dest='info', action='store_true', help='Print info about .iso or .ird, then quit.') + + args = parser.parse_args() + + if args.info: + core.info(args) + + if not args.iso: + core.error('No .iso file given. Use -i/--iso path/to/file.iso') + + if args.reencrypt: + core.encrypt(args) + else: + core.decrypt(args) if __name__ == '__main__': - - parser = argparse.ArgumentParser(description='A Libre (FLOSS) Python application for unencrypting, extracting, repackaging, and encrypting PS3 ISOs') - parser._action_groups.pop() - - required = parser.add_argument_group('required arguments') - required.add_argument('-i', '--iso', dest='iso', type=str, help='Path to .iso file or stream', required=True) - - optional = parser.add_argument_group('optional arguments') - optional.add_argument('-o', '--output', dest='output', type=str, help='Output filename', default='') - optional.add_argument('-k', '--ird', dest='ird', type=str, help='Path to .ird file', default='') - optional.add_argument('-d', '--decryption-key', dest='decryption_key', type=str, help='Manually specify key', default='') - optional.add_argument('-v', '--verbose', dest='verbose', help='Increase verbosity', action='count') - optional.add_argument('-q', '--quiet', dest='quiet', help='Quiet mode, only prints on error', action='store_true') - # -e is reserved for "extract" so re-encrypt is "-r" - optional.add_argument('-r', '--re-encrypt', dest='reencrypt', help='Re-encrypt .iso', action='store_true') - - args = parser.parse_args() - - if args.reencrypt: - - core.encrypt(args) - - else: - - core.decrypt(args) + main() diff --git a/libray/py.typed b/libray/py.typed new file mode 100644 index 0000000..e69de29 diff --git a/libray/sfo.py b/libray/sfo.py new file mode 100644 index 0000000..0141935 --- /dev/null +++ b/libray/sfo.py @@ -0,0 +1,123 @@ +# -*- coding: utf8 -*- + +# libray - Libre Blu-Ray PS3 ISO Tool +# Copyright © 2018 - 2024 Nichlas Severinsen +# +# This file is part of libray. +# +# libray is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# libray is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with libray. If not, see . + + +try: + from libray import core +except ImportError: + import core + + +class SFO: + """Class for handling .sfo files + + Attributes: + magic: Magic header + version: .SFO version + key_table_start: Absolute offset for key_table in .SFO + data_table_start: Absolute offset for index_table in .SFO + tables_entries: Number of entries in index_table and key_table + key_data: Parsed keys and data tables from .SFO transformed into dict + """ + + def __init__(self, fp): + + self.file_start = fp.tell() + + # Header + + self.magic = fp.read(4) + self.version = fp.read(4) + self.key_table_start = core.to_int(fp.read(4), 'little') + self.data_table_start = core.to_int(fp.read(4), 'little') + self.tables_entries = core.to_int(fp.read(4), 'little') + + # Index table + + index_table = [] + + for _ in range(0, self.tables_entries): + index_table.append({ + 'key_offset': core.to_int(fp.read(2), 'little'), + 'data_fmt': fp.read(2), + 'data_len': core.to_int(fp.read(4), 'little'), + 'data_max_len': core.to_int(fp.read(4), 'little'), + 'data_offset': core.to_int(fp.read(4), 'little'), + }) + + # Key table + + key_table = [] + + for i in range(0, self.tables_entries): + + # Seek to absolute offset + relative offset of key + + fp.seek(self.file_start + self.key_table_start + + index_table[i]['key_offset']) + + # Read key string until nullbyte + + key = '' + + while True: + + data = fp.read(1) + + if data == b'\x00': + break + + key += data.decode('utf8') + + key_table.append(key) + + # Data table + + self.key_data = {} + + for i in range(0, self.tables_entries): + + # Seek to absolute offset + relative offset of data + + fp.seek(self.file_start + self.data_table_start + index_table[i]['data_offset']) + + if index_table[i]['data_fmt'] == b'\x04\x02': # UTF8 + data = fp.read(index_table[i]['data_len'] - 1).decode('utf8') + elif index_table[i]['data_fmt'] == b'\x04\x04': # int32 + data = core.to_int( + fp.read(index_table[i]['data_len']), 'little') + else: # Meh + data = fp.read(index_table[i]['data_len']) + + self.key_data[key_table[i]] = data + + def __getitem__(self, key): + """Overload [] so we can directly select data using key from .SFO""" + return self.key_data[key] + + def print_info(self): + + print('Magic:', self.magic) + print('Version: ', self.version) + print('key_table_start:', self.key_table_start) + print('data_table_start:', self.data_table_start) + print('tables_entries:', self.tables_entries) + + print(self.key_data) diff --git a/requirements.txt b/requirements.txt index f7b6b90..680254f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,4 +1,4 @@ -tqdm==4.32.2 -pycryptodome==3.9.8 -requests==2.22.0 -beautifulsoup4==4.7.1 +tqdm~=4.66.2 +pycryptodome~=3.20.0 +requests~=2.31.0 +beautifulsoup4~=4.12.3 diff --git a/setup.cfg b/setup.cfg index b88034e..9f88734 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,2 +1,7 @@ [metadata] description-file = README.md + +[egg_info] +tag_build = +tag_date = 0 + diff --git a/setup.py b/setup.py index c45d887..30ee147 100755 --- a/setup.py +++ b/setup.py @@ -1,22 +1,34 @@ #!/usr/bin/env python3 # -*- coding: utf8 -*- + from setuptools import setup + +with open('README.md') as f: + long_description = f.read() + + setup( name="libray", - version="0.0.6", + version="0.0.10", description='A Libre (FLOSS) Python application for unencrypting, extracting, repackaging, and encrypting PS3 ISOs', + long_description=long_description, + long_description_content_type='text/markdown', author="Nichlas Severinsen", author_email="ns@nsz.no", url="https://notabug.org/necklace/libray", packages=['libray'], - scripts=['libray/libray'], + entry_points={ + 'console_scripts': [ + 'libray=libray.libray:main', + ], + }, install_requires=[ - 'tqdm==4.32.2', - 'pycryptodome==3.9.8', - 'requests==2.22.0', - 'beautifulsoup4==4.7.1', + 'tqdm~=4.66.2', + 'pycryptodome~=3.20.0', + 'requests~=2.31.0', + 'beautifulsoup4~=4.12.3', ], include_package_data=True, package_data={'': ['data/keys.db']}, diff --git a/target.md5 b/target.md5 new file mode 100644 index 0000000..b9aabaf --- /dev/null +++ b/target.md5 @@ -0,0 +1 @@ +c16539e7abd6fe851ab2a67c0cbbaa32 diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/tests/test_interface.py b/tests/test_interface.py new file mode 100644 index 0000000..b0338be --- /dev/null +++ b/tests/test_interface.py @@ -0,0 +1,63 @@ +# -*- coding: utf8 -*- + +# libray - Libre Blu-Ray PS3 ISO Tool +# Copyright © 2018 - 2024 Nichlas Severinsen +# +# This file is part of libray. +# +# libray is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# libray is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with libray. If not, see . + +# This is a script to find the redump names and game serial id's using rpcs3's compatibility list. +# It puts the name, serial id, and some other info into an sqlite3 database. +# That database can then be used to harcode serial id to keys into keys.db. +# This script is not included in the release of libray. + + +import io +import argparse +import builtins +import unittest +import unittest.mock + +import libray + + +class TestInterface(unittest.TestCase): + + + @unittest.skip('currently broken') + @unittest.mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace()) + def test_decrypt_with_key(self, mock_args): + os_stat = unittest.mock.Mock() + os_stat.return_value.st_mode = 33188 + + iso_filepath = unittest.mock.Mock() + iso_filepath.open = unittest.mock.mock_open(read_data=b"some initial binary data: \x00\x01") + + iso_filepath.is_file.return_value = True + iso_filepath.stat.return_value = unittest.mock.MagicMock() + iso_filepath.stat.st_size = 1024 + iso_filepath.stat.st_mode = 33188 + iso_filepath.stat.S_ISBLK.return_value = False + + mock_args.iso = 'encrypted_mock.iso' + + #mock_args.iso = iso_filepath + + with unittest.mock.patch('os.stat', os_stat): + + with unittest.mock.patch('builtins.open', iso_filepath.open): + + libray.core.decrypt(mock_args) + diff --git a/tests/test_iso.py b/tests/test_iso.py new file mode 100644 index 0000000..63ad0a0 --- /dev/null +++ b/tests/test_iso.py @@ -0,0 +1,394 @@ +# -*- coding: utf8 -*- + +# libray - Libre Blu-Ray PS3 ISO Tool +# Copyright © 2018 - 2024 Nichlas Severinsen +# +# This file is part of libray. +# +# libray is free software: you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# libray is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with libray. If not, see . + +# This file contains tests to validate the key-retrieval logic for the +# ISO class. +# This script is not included in the release of libray. + + +import argparse +import os +import unittest +import unittest.mock as mock +from Crypto.Cipher import AES + +from libray import core, iso + +class TestISO(unittest.TestCase): + + @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace()) + def test_explicit_decryption_key(self, mock_args): + mock_args.iso = 'fake.iso' + mock_args.decryption_key = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + decryptkey_bytes = core.to_bytes(mock_args.decryption_key) + fake_iso = iso.ISO.__new__(iso.ISO) + returned_key = fake_iso.get_key_from_args('AAA', mock_args) + self.assertEqual(decryptkey_bytes, returned_key) + + @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace()) + def test_explicit_valid_ird(self, mock_args): + mock_args.iso = 'fake.iso' + mock_args.ird = 'aaa.ird' + mock_args.decryption_key = False + mock_args.verbose = True + + ird = mock.Mock() + ird.region_count = 3 + ird.data1 = b'01010101010101010101010101010101' + cipher = AES.new(core.ISO_SECRET, AES.MODE_CBC, core.ISO_IV) + decryptkey_bytes = cipher.encrypt(ird.data1) + + fake_iso = iso.ISO.__new__(iso.ISO) + fake_iso.size = 2048 + fake_iso.regions = [ + {'start': 0, 'end': 512, 'enc': False}, + {'start': 512, 'end': 1024, 'enc': True}, + {'start': 1024, 'end': 2048, 'enc': False} + ] + + with mock.patch('libray.iso.ird.IRD', return_value=ird) as mock_ird: + returned_key = fake_iso.get_key_from_args('AAA', mock_args) + mock_ird.assert_called_once_with('aaa.ird') + self.assertEqual(decryptkey_bytes, returned_key) + + @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace()) + def test_ird_with_region_count_mismatch(self, mock_args): + mock_args.iso = 'fake.iso' + mock_args.ird = 'aaa.ird' + mock_args.decryption_key = False + mock_args.verbose = True + + ird = mock.Mock() + ird.region_count = 3 + ird.data1 = b'01010101010101010101010101010101' + + fake_iso = iso.ISO.__new__(iso.ISO) + fake_iso.size = 512 + fake_iso.regions = [ + {'start': 0, 'end': 512, 'enc': False}, + ] + + with mock.patch('libray.iso.ird.IRD', return_value=ird) as mock_ird: + with self.assertRaises(SystemExit): + fake_iso.get_key_from_args('AAA', mock_args) + + @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace()) + def test_ird_with_invalid_start(self, mock_args): + mock_args.iso = 'fake.iso' + mock_args.ird = 'aaa.ird' + mock_args.decryption_key = False + mock_args.verbose = True + + ird = mock.Mock() + ird.region_count = 3 + ird.data1 = b'01010101010101010101010101010101' + + fake_iso = iso.ISO.__new__(iso.ISO) + fake_iso.size = 512 * 1024 * 1024 + fake_iso.regions = [ + {'start': 0, 'end': 3000000, 'enc': False}, + {'start': 3000000, 'end': 2000000000, 'enc': True}, + {'start': 2000000000, 'end': 2000001000, 'enc': False} + ] + + with mock.patch('libray.iso.ird.IRD', return_value=ird) as mock_ird: + with self.assertRaises(SystemExit): + fake_iso.get_key_from_args('AAA', mock_args) + + @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace()) + def test_keys_db_size_match(self, mock_args): + mock_args.iso = 'fake.iso' + mock_args.ird = '' + mock_args.decryption_key = False + mock_args.verbose = True + + fake_iso = iso.ISO.__new__(iso.ISO) + fake_iso.size = 512 * 1024 * 1024 + fake_iso.game_id = 'TCUS-12345' + + with mock.patch('libray.iso.sqlite3') as mocksql: + decryption_key = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + decryptkey_bytes = core.to_bytes(decryption_key) + mocksql.connect().cursor().execute().fetchall.return_value = [['AAA', decryptkey_bytes]] + returned_key = fake_iso.get_key_from_args('AAA', mock_args) + self.assertEqual(decryptkey_bytes, returned_key) + + @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace()) + def test_keys_db_size_multiple_match_name_lookup(self, mock_args): + mock_args.iso = 'fake.iso' + mock_args.ird = '' + mock_args.decryption_key = False + mock_args.verbose = True + + fake_iso = iso.ISO.__new__(iso.ISO) + fake_iso.size = 512 * 1024 * 1024 + fake_iso.game_id = 'TCUS-12345' + + with mock.patch('libray.iso.sqlite3') as mocksql: + decryption_key = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + decryptkey_bytes = core.to_bytes(decryption_key) + mocksql.connect().cursor().execute().fetchall.side_effect = [[], [['AAA', decryptkey_bytes]]] + returned_key = fake_iso.get_key_from_args('AAA', mock_args) + self.assertEqual(decryptkey_bytes, returned_key) + + @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace()) + def test_keys_db_size_multiple_match_no_game_id(self, mock_args): + mock_args.iso = 'fake.iso' + mock_args.ird = '' + mock_args.decryption_key = False + mock_args.verbose = True + + fake_iso = iso.ISO.__new__(iso.ISO) + fake_iso.size = 512 * 1024 * 1024 + fake_iso.game_id = 'TCUS-12345' + + with mock.patch('libray.iso.sqlite3') as mocksql: + decryption_key = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + decryptkey_bytes = core.to_bytes(decryption_key) + mocksql.connect().cursor().execute().fetchall.return_value = [['AAA', decryptkey_bytes],['BBB', decryptkey_bytes]] + with self.assertRaises(SystemExit): + fake_iso.get_key_from_args(None, mock_args) + + @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace()) + def test_keys_db_no_match_no_checksum(self, mock_args): + mock_args.iso = 'fake.iso' + mock_args.ird = '' + mock_args.decryption_key = False + mock_args.checksum = False + mock_args.verbose = True + + fake_iso = iso.ISO.__new__(iso.ISO) + fake_iso.size = 512 * 1024 * 1024 + fake_iso.game_id = 'TCUS-12345' + + with mock.patch('libray.iso.sqlite3') as mocksql: + mocksql.connect().cursor().execute().fetchall.return_value = [] + with self.assertRaises(SystemExit): + fake_iso.get_key_from_args('AAA', mock_args) + + @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace()) + def test_keys_db_no_match_checksum_fallback(self, mock_args): + mock_args.iso = 'fake.iso' + mock_args.ird = '' + mock_args.decryption_key = False + mock_args.checksum = True + mock_args.checksum_timeout = 15 + mock_args.verbose = True + + fake_iso = iso.ISO.__new__(iso.ISO) + fake_iso.size = 512 * 1024 * 1024 + fake_iso.game_id = 'TCUS-12345' + + with mock.patch('libray.iso.sqlite3') as mocksql: + decryption_key = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa' + decryptkey_bytes = core.to_bytes(decryption_key) + fakeresults = ([], [], [['AAA', decryptkey_bytes]]) + mocksql.connect().cursor().execute().fetchall.side_effect = fakeresults + with mock.patch('libray.iso.core.crc32', return_value='01010101'): + returned_key = fake_iso.get_key_from_args('AAA', mock_args) + self.assertEqual(decryptkey_bytes, returned_key) + + @mock.patch('argparse.ArgumentParser.parse_args', return_value=argparse.Namespace()) + def test_keys_db_no_match_checksum_timeout(self, mock_args): + mock_args.iso = 'fake.iso' + mock_args.ird = '' + mock_args.decryption_key = False + mock_args.checksum = True + mock_args.checksum_timeout = 15 + mock_args.verbose = True + + fake_iso = iso.ISO.__new__(iso.ISO) + fake_iso.size = 512 * 1024 * 1024 + fake_iso.game_id = 'TCUS-12345' + + with mock.patch('libray.iso.sqlite3') as mocksql: + mocksql.connect().cursor().execute().fetchall.return_value = [] + with mock.patch('libray.iso.core.crc32', return_value=None): + with self.assertRaises(TimeoutError): + fake_iso.get_key_from_args('AAA', mock_args) + + def _build_fake_iso(self, num_sectors=8, disc_key=None): + """Build a minimal fake ISO binary in a temp file. + + Layout: + [0:4] num_unencrypted_regions (uint32 BE = 1) + [4:8] padding (4 bytes, skipped by constructor) + [8:12] unencrypted region start sector (uint32 BE = 0) + [12:16] unencrypted region end sector (uint32 BE = 2) + [16:20] encrypted region end sector (uint32 BE = 6) + [20:24] terminator (0) + [2048:2064] game_id (16 bytes) + [2064:2072] PARAM.SFO marker (b'\\x00PSF') + Sectors 0-1 = unencrypted header + Sectors 2-5 = encrypted payload (zeros) + Sector 6+ = unencrypted tail + """ + import tempfile + if disc_key is None: + disc_key = b'\xaa' * 16 + + # Region info: constructor reads bytes 0-3, skips 4-7, then + # read_regions() reads bytes 8-11 (start) and 12-15 (end) + region_info = b'\x00\x00\x00\x01' # num_unencrypted_regions (offset 0) + region_info += b'\x00\x00\x00\x00' # padding (offset 4, skipped) + region_info += b'\x00\x00\x00\x00' # unencrypted start = sector 0 (offset 8) + region_info += b'\x00\x00\x00\x02' # unencrypted end = sector 2 (offset 12) + region_info += b'\x00\x00\x00\x06' # encrypted end = sector 6 (offset 16) + region_info += b'\x00\x00\x00\x00' # terminator (offset 20) + + # Sector 1 (offset 2048): unencrypted header with game_id and PARAM.SFO marker + sector1 = bytearray(2048) + # game_id at offset 2048+16=2064 + sector1[16:32] = b'TEST-GAME0000000' + # PARAM.SFO marker at offset 2048+20=2068 + sector1[20:24] = b'\x00PSF' + + # Encrypt sectors 2-5 with AES-CBC per-sector IV + from libray.iso import _make_iv + encrypted_payload = bytearray() + for s in range(2, 6): + iv = _make_iv(s) + cipher = AES.new(disc_key, AES.MODE_CBC, iv) + encrypted_payload.extend(cipher.encrypt(b'\x00' * 2048)) + + # Pad so sector data starts at offset 2048 (PS3 ISO convention) + data = region_info + b'\x00' * (2048 - len(region_info)) + sector1 + encrypted_payload + + # Ensure file is at least as large as the last region end (sector 6 = 12288 bytes) + # The constructor uses size to calculate total_sectors, so file must be >= region end + while len(data) < 12288: + data += b'\x00' * 2048 + + total = len(data) + + fd, path = tempfile.mkstemp(suffix='.iso') + with os.fdopen(fd, 'wb') as f: + f.write(data) + return path, total + + @mock.patch('argparse.ArgumentParser.parse_args') + def test_decrypt_parallel_pipeline(self, mock_args): + """Verify the multi-threaded decrypt pipeline processes all sectors.""" + disc_key = b'\xbb' * 16 + path, size = self._build_fake_iso(disc_key=disc_key) + try: + mock_args.iso = path + mock_args.decryption_key = disc_key.hex() + mock_args.ird = '' + mock_args.output = '' + mock_args.verbose = True + mock_args.quiet = True + mock_args.checksum = False + mock_args.checksum_timeout = 0 + mock_args.threads = 4 + + out_path = path + '.dec' + mock_args.output = out_path + + s = iso.ISO(mock_args) + s.decrypt(mock_args) + + self.assertTrue(os.path.exists(out_path)) + with open(out_path, 'rb') as f: + decrypted = f.read() + # Sectors 2-5 should be decrypted back to zeros + self.assertEqual(len(decrypted), size) + # Encrypted region: start=6144 (region[0].end), end=12288 + self.assertEqual(decrypted[6144:12288], b'\x00' * 6144) + finally: + os.unlink(path) + if os.path.exists(path + '.dec'): + os.unlink(path + '.dec') + + @mock.patch('argparse.ArgumentParser.parse_args') + def test_decrypt_sequential_fallback(self, mock_args): + """Verify single-thread decrypt still works (sequential path).""" + disc_key = b'\xcc' * 16 + path, size = self._build_fake_iso(disc_key=disc_key) + try: + mock_args.iso = path + mock_args.decryption_key = disc_key.hex() + mock_args.ird = '' + mock_args.output = '' + mock_args.verbose = True + mock_args.quiet = True + mock_args.checksum = False + mock_args.checksum_timeout = 0 + mock_args.threads = 1 + + out_path = path + '.dec' + mock_args.output = out_path + + s = iso.ISO(mock_args) + s.decrypt(mock_args) + + self.assertTrue(os.path.exists(out_path)) + with open(out_path, 'rb') as f: + decrypted = f.read() + self.assertEqual(decrypted[6144:12288], b'\x00' * 6144) + finally: + os.unlink(path) + if os.path.exists(path + '.dec'): + os.unlink(path + '.dec') + + @mock.patch('argparse.ArgumentParser.parse_args') + def test_encrypt_parallel_pipeline(self, mock_args): + """Verify the multi-threaded re-encrypt pipeline works.""" + disc_key = b'\xdd' * 16 + path, size = self._build_fake_iso(disc_key=disc_key) + try: + # First decrypt to get a plain ISO + mock_args.iso = path + mock_args.decryption_key = disc_key.hex() + mock_args.ird = '' + mock_args.output = path + '.dec' + mock_args.verbose = True + mock_args.quiet = True + mock_args.checksum = False + mock_args.checksum_timeout = 0 + mock_args.threads = 4 + s = iso.ISO(mock_args) + s.decrypt(mock_args) + + # Now re-encrypt with -r + reenc_path = path + '.reenc' + mock_args.iso = path + '.dec' + mock_args.decryption_key = disc_key.hex() + mock_args.reencrypt = True + mock_args.output = reenc_path + mock_args.threads = 4 + + s2 = iso.ISO(mock_args) + s2.encrypt(mock_args) + + self.assertTrue(os.path.exists(reenc_path)) + with open(reenc_path, 'rb') as f: + reencrypted = f.read() + with open(path, 'rb') as f: + original = f.read() + self.assertEqual(reencrypted, original) + finally: + os.unlink(path) + if os.path.exists(path + '.dec'): + os.unlink(path + '.dec') + if os.path.exists(path + '.reenc'): + os.unlink(path + '.reenc') + + diff --git a/tools/keys2db.py b/tools/keys2db.py index 197340d..1003d7d 100755 --- a/tools/keys2db.py +++ b/tools/keys2db.py @@ -2,7 +2,7 @@ # -*- coding: utf8 -*- # libray - Libre Blu-Ray PS3 ISO Tool -# Copyright © 2018 - 2021 Nichlas Severinsen +# Copyright © 2018 - 2024 Nichlas Severinsen # # This file is part of libray. # @@ -21,32 +21,64 @@ # This script transforms Datfile.dat and keys/*.key keyfiles into a sqlite3 keys.db # Keys.db is then moved to libray/data/keys.db and packaged with libray in setup.py. -# Libray checks if this file is bundled with it and checks if it has a key for the .iso using a crc32 of it. +# Libray checks if this file is bundled with it and has logic to identify the correct key. + # TODO: In theory we could add the game-serials (BLUS-0000) and check that first. import bs4 +import csv import sys import shutil import sqlite3 import pathlib +import argparse + + +import requests if __name__ == '__main__': - db_path = pathlib.Path('keys.db') + parser = argparse.ArgumentParser() + parser.add_argument('-d', '--database', type=pathlib.Path, default='keys.db', help='Path to keys.db') + parser.add_argument('-k', '--keys', type=pathlib.Path, default='keys', help='Path to .key keys') + parser.add_argument('--show-missing', action='store_true', help='Show titles missing keys') + args = parser.parse_args() - if db_path.exists(): - db_path.unlink() + if args.database.exists(): + args.database.unlink() - db = sqlite3.connect(db_path) + # Check if there's a mapping csv that maps the keynames to title IDs + mapping = pathlib.Path('keys.csv') + + title_ids = {} + + if mapping.exists(): + with open(mapping, 'r') as infile: + reader = csv.DictReader(infile, delimiter=',', quotechar='"', ) + for row in reader: + title_ids[row['md5']] = { + 'title_id': row['title_id'], + 'filename': row['filename'], + 'size': row['size'], + 'crc32': row['crc32'], + } + + db = sqlite3.connect(args.database) c = db.cursor() - c.execute('CREATE TABLE games (name TEXT, size TEXT, crc32 TEXT, md5 TEXT, sha1 TEXT, key BLOB)') + c.execute('CREATE TABLE games (title_id TEXT, name TEXT, size TEXT, crc32 TEXT, md5 TEXT, sha1 TEXT, key BLOB)') db.commit() cwd = pathlib.Path(__file__).resolve().parent + keys_path = cwd / 'keys' + + if not keys_path.exists(): + print('Error: No keys/ folder. Place the .key files in a tools/keys/ folder') + sys.exit() + any_dats = [x for x in cwd.glob('*.dat')] if not any_dats: @@ -55,6 +87,8 @@ if __name__ == '__main__': datfile = any_dats[0] + warnings = 0 + with open(datfile, 'r') as infile: soup = bs4.BeautifulSoup(infile.read(), features='html5lib') @@ -64,24 +98,49 @@ if __name__ == '__main__': name = game.find('description').text.strip() attrs = game.find('rom').attrs - entry = [name, attrs['size'], attrs['crc'], attrs['md5'], attrs['sha1']] + try: + + title_map = title_ids[attrs['md5']] + + assert title_map['size'] == attrs['size'] + assert title_map['crc32'] == attrs['crc'] + + title_id = title_map['title_id'] + + except (KeyError, AssertionError): + title_id = None + + # Some of the records are spaces: + if not title_id: + title_id = None + + entry = [title_id, name, attrs['size'], attrs['crc'], attrs['md5'], attrs['sha1']] try: with open(cwd / ('keys/' + name + '.key'), 'rb') as keyfile: entry.append(keyfile.read()) except FileNotFoundError: - print('Warning: key not found for ' + name) - c.execute('INSERT INTO games (name, size, crc32, md5, sha1) VALUES (?, ?, ?, ?, ?)', entry) + warnings += 1 + if args.show_missing: + print('Warning: missing keyfile for %s [%s]' % (name, attrs['crc'])) + + c.execute('INSERT INTO games (title_id, name, size, crc32, md5, sha1) VALUES (?, ?, ?, ?, ?, ?)', entry) continue - c.execute('INSERT INTO games VALUES (?, ?, ?, ?, ?, ?)', entry) + c.execute('INSERT INTO games VALUES (?, ?, ?, ?, ?, ?, ?)', entry) db.commit() db.close() - shutil.copyfile(db_path, ((cwd.parent / 'libray') / 'data/') / db_path.name) - + data_path = (cwd.parent / 'libray') / 'data/' + + if not data_path.exists(): + data_path.mkdir() + + shutil.copyfile(args.database, ((cwd.parent / 'libray') / 'data/') / args.database.name) + + print('Warning: no keyfiles for %s titles' % str(warnings)) diff --git a/tools/rpcs3.py b/tools/rpcs3.py index 45bb146..474fe81 100755 --- a/tools/rpcs3.py +++ b/tools/rpcs3.py @@ -2,7 +2,7 @@ # -*- coding: utf8 -*- # libray - Libre Blu-Ray PS3 ISO Tool -# Copyright © 2018 - 2021 Nichlas Severinsen +# Copyright © 2018 - 2024 Nichlas Severinsen # # This file is part of libray. #